9f6d34f1fe22a461a17e5c8d9592ebdb4fe59295
[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   info_ptr += 2;
6312   if (cu_header->version < 5)
6313     switch (section_kind)
6314       {
6315       case rcuh_kind::COMPILE:
6316         cu_header->unit_type = DW_UT_compile;
6317         break;
6318       case rcuh_kind::TYPE:
6319         cu_header->unit_type = DW_UT_type;
6320         break;
6321       default:
6322         internal_error (__FILE__, __LINE__,
6323                         _("read_comp_unit_head: invalid section_kind"));
6324       }
6325   else
6326     {
6327       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6328                                                  (read_1_byte (abfd, info_ptr));
6329       info_ptr += 1;
6330       switch (cu_header->unit_type)
6331         {
6332         case DW_UT_compile:
6333           if (section_kind != rcuh_kind::COMPILE)
6334             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6335                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6336                    filename);
6337           break;
6338         case DW_UT_type:
6339           section_kind = rcuh_kind::TYPE;
6340           break;
6341         default:
6342           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6343                  "(is %d, should be %d or %d) [in module %s]"),
6344                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6345         }
6346
6347       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6348       info_ptr += 1;
6349     }
6350   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6351                                                           cu_header,
6352                                                           &bytes_read);
6353   info_ptr += bytes_read;
6354   if (cu_header->version < 5)
6355     {
6356       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6357       info_ptr += 1;
6358     }
6359   signed_addr = bfd_get_sign_extend_vma (abfd);
6360   if (signed_addr < 0)
6361     internal_error (__FILE__, __LINE__,
6362                     _("read_comp_unit_head: dwarf from non elf file"));
6363   cu_header->signed_addr_p = signed_addr;
6364
6365   if (section_kind == rcuh_kind::TYPE)
6366     {
6367       LONGEST type_offset;
6368
6369       cu_header->signature = read_8_bytes (abfd, info_ptr);
6370       info_ptr += 8;
6371
6372       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6373       info_ptr += bytes_read;
6374       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6375       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6376         error (_("Dwarf Error: Too big type_offset in compilation unit "
6377                "header (is %s) [in module %s]"), plongest (type_offset),
6378                filename);
6379     }
6380
6381   return info_ptr;
6382 }
6383
6384 /* Helper function that returns the proper abbrev section for
6385    THIS_CU.  */
6386
6387 static struct dwarf2_section_info *
6388 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6389 {
6390   struct dwarf2_section_info *abbrev;
6391   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6392
6393   if (this_cu->is_dwz)
6394     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6395   else
6396     abbrev = &dwarf2_per_objfile->abbrev;
6397
6398   return abbrev;
6399 }
6400
6401 /* Subroutine of read_and_check_comp_unit_head and
6402    read_and_check_type_unit_head to simplify them.
6403    Perform various error checking on the header.  */
6404
6405 static void
6406 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6407                             struct comp_unit_head *header,
6408                             struct dwarf2_section_info *section,
6409                             struct dwarf2_section_info *abbrev_section)
6410 {
6411   const char *filename = get_section_file_name (section);
6412
6413   if (header->version < 2 || header->version > 5)
6414     error (_("Dwarf Error: wrong version in compilation unit header "
6415            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6416            filename);
6417
6418   if (to_underlying (header->abbrev_sect_off)
6419       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6420     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6421            "(offset %s + 6) [in module %s]"),
6422            sect_offset_str (header->abbrev_sect_off),
6423            sect_offset_str (header->sect_off),
6424            filename);
6425
6426   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6427      avoid potential 32-bit overflow.  */
6428   if (((ULONGEST) header->sect_off + get_cu_length (header))
6429       > section->size)
6430     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6431            "(offset %s + 0) [in module %s]"),
6432            header->length, sect_offset_str (header->sect_off),
6433            filename);
6434 }
6435
6436 /* Read in a CU/TU header and perform some basic error checking.
6437    The contents of the header are stored in HEADER.
6438    The result is a pointer to the start of the first DIE.  */
6439
6440 static const gdb_byte *
6441 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6442                                struct comp_unit_head *header,
6443                                struct dwarf2_section_info *section,
6444                                struct dwarf2_section_info *abbrev_section,
6445                                const gdb_byte *info_ptr,
6446                                rcuh_kind section_kind)
6447 {
6448   const gdb_byte *beg_of_comp_unit = info_ptr;
6449
6450   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6451
6452   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6453
6454   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6455
6456   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6457                               abbrev_section);
6458
6459   return info_ptr;
6460 }
6461
6462 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6463
6464 static sect_offset
6465 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6466                     struct dwarf2_section_info *section,
6467                     sect_offset sect_off)
6468 {
6469   bfd *abfd = get_section_bfd_owner (section);
6470   const gdb_byte *info_ptr;
6471   unsigned int initial_length_size, offset_size;
6472   uint16_t version;
6473
6474   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6475   info_ptr = section->buffer + to_underlying (sect_off);
6476   read_initial_length (abfd, info_ptr, &initial_length_size);
6477   offset_size = initial_length_size == 4 ? 4 : 8;
6478   info_ptr += initial_length_size;
6479
6480   version = read_2_bytes (abfd, info_ptr);
6481   info_ptr += 2;
6482   if (version >= 5)
6483     {
6484       /* Skip unit type and address size.  */
6485       info_ptr += 2;
6486     }
6487
6488   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6489 }
6490
6491 /* Allocate a new partial symtab for file named NAME and mark this new
6492    partial symtab as being an include of PST.  */
6493
6494 static void
6495 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6496                                struct objfile *objfile)
6497 {
6498   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6499
6500   if (!IS_ABSOLUTE_PATH (subpst->filename))
6501     {
6502       /* It shares objfile->objfile_obstack.  */
6503       subpst->dirname = pst->dirname;
6504     }
6505
6506   subpst->textlow = 0;
6507   subpst->texthigh = 0;
6508
6509   subpst->dependencies
6510     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6511   subpst->dependencies[0] = pst;
6512   subpst->number_of_dependencies = 1;
6513
6514   subpst->globals_offset = 0;
6515   subpst->n_global_syms = 0;
6516   subpst->statics_offset = 0;
6517   subpst->n_static_syms = 0;
6518   subpst->compunit_symtab = NULL;
6519   subpst->read_symtab = pst->read_symtab;
6520   subpst->readin = 0;
6521
6522   /* No private part is necessary for include psymtabs.  This property
6523      can be used to differentiate between such include psymtabs and
6524      the regular ones.  */
6525   subpst->read_symtab_private = NULL;
6526 }
6527
6528 /* Read the Line Number Program data and extract the list of files
6529    included by the source file represented by PST.  Build an include
6530    partial symtab for each of these included files.  */
6531
6532 static void
6533 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6534                                struct die_info *die,
6535                                struct partial_symtab *pst)
6536 {
6537   line_header_up lh;
6538   struct attribute *attr;
6539
6540   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6541   if (attr)
6542     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6543   if (lh == NULL)
6544     return;  /* No linetable, so no includes.  */
6545
6546   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6547   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6548 }
6549
6550 static hashval_t
6551 hash_signatured_type (const void *item)
6552 {
6553   const struct signatured_type *sig_type
6554     = (const struct signatured_type *) item;
6555
6556   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6557   return sig_type->signature;
6558 }
6559
6560 static int
6561 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6562 {
6563   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6564   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6565
6566   return lhs->signature == rhs->signature;
6567 }
6568
6569 /* Allocate a hash table for signatured types.  */
6570
6571 static htab_t
6572 allocate_signatured_type_table (struct objfile *objfile)
6573 {
6574   return htab_create_alloc_ex (41,
6575                                hash_signatured_type,
6576                                eq_signatured_type,
6577                                NULL,
6578                                &objfile->objfile_obstack,
6579                                hashtab_obstack_allocate,
6580                                dummy_obstack_deallocate);
6581 }
6582
6583 /* A helper function to add a signatured type CU to a table.  */
6584
6585 static int
6586 add_signatured_type_cu_to_table (void **slot, void *datum)
6587 {
6588   struct signatured_type *sigt = (struct signatured_type *) *slot;
6589   std::vector<signatured_type *> *all_type_units
6590     = (std::vector<signatured_type *> *) datum;
6591
6592   all_type_units->push_back (sigt);
6593
6594   return 1;
6595 }
6596
6597 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6598    and fill them into TYPES_HTAB.  It will process only type units,
6599    therefore DW_UT_type.  */
6600
6601 static void
6602 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6603                               struct dwo_file *dwo_file,
6604                               dwarf2_section_info *section, htab_t &types_htab,
6605                               rcuh_kind section_kind)
6606 {
6607   struct objfile *objfile = dwarf2_per_objfile->objfile;
6608   struct dwarf2_section_info *abbrev_section;
6609   bfd *abfd;
6610   const gdb_byte *info_ptr, *end_ptr;
6611
6612   abbrev_section = (dwo_file != NULL
6613                     ? &dwo_file->sections.abbrev
6614                     : &dwarf2_per_objfile->abbrev);
6615
6616   if (dwarf_read_debug)
6617     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6618                         get_section_name (section),
6619                         get_section_file_name (abbrev_section));
6620
6621   dwarf2_read_section (objfile, section);
6622   info_ptr = section->buffer;
6623
6624   if (info_ptr == NULL)
6625     return;
6626
6627   /* We can't set abfd until now because the section may be empty or
6628      not present, in which case the bfd is unknown.  */
6629   abfd = get_section_bfd_owner (section);
6630
6631   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6632      because we don't need to read any dies: the signature is in the
6633      header.  */
6634
6635   end_ptr = info_ptr + section->size;
6636   while (info_ptr < end_ptr)
6637     {
6638       struct signatured_type *sig_type;
6639       struct dwo_unit *dwo_tu;
6640       void **slot;
6641       const gdb_byte *ptr = info_ptr;
6642       struct comp_unit_head header;
6643       unsigned int length;
6644
6645       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6646
6647       /* Initialize it due to a false compiler warning.  */
6648       header.signature = -1;
6649       header.type_cu_offset_in_tu = (cu_offset) -1;
6650
6651       /* We need to read the type's signature in order to build the hash
6652          table, but we don't need anything else just yet.  */
6653
6654       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6655                                            abbrev_section, ptr, section_kind);
6656
6657       length = get_cu_length (&header);
6658
6659       /* Skip dummy type units.  */
6660       if (ptr >= info_ptr + length
6661           || peek_abbrev_code (abfd, ptr) == 0
6662           || header.unit_type != DW_UT_type)
6663         {
6664           info_ptr += length;
6665           continue;
6666         }
6667
6668       if (types_htab == NULL)
6669         {
6670           if (dwo_file)
6671             types_htab = allocate_dwo_unit_table (objfile);
6672           else
6673             types_htab = allocate_signatured_type_table (objfile);
6674         }
6675
6676       if (dwo_file)
6677         {
6678           sig_type = NULL;
6679           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6680                                    struct dwo_unit);
6681           dwo_tu->dwo_file = dwo_file;
6682           dwo_tu->signature = header.signature;
6683           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6684           dwo_tu->section = section;
6685           dwo_tu->sect_off = sect_off;
6686           dwo_tu->length = length;
6687         }
6688       else
6689         {
6690           /* N.B.: type_offset is not usable if this type uses a DWO file.
6691              The real type_offset is in the DWO file.  */
6692           dwo_tu = NULL;
6693           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6694                                      struct signatured_type);
6695           sig_type->signature = header.signature;
6696           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6697           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6698           sig_type->per_cu.is_debug_types = 1;
6699           sig_type->per_cu.section = section;
6700           sig_type->per_cu.sect_off = sect_off;
6701           sig_type->per_cu.length = length;
6702         }
6703
6704       slot = htab_find_slot (types_htab,
6705                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6706                              INSERT);
6707       gdb_assert (slot != NULL);
6708       if (*slot != NULL)
6709         {
6710           sect_offset dup_sect_off;
6711
6712           if (dwo_file)
6713             {
6714               const struct dwo_unit *dup_tu
6715                 = (const struct dwo_unit *) *slot;
6716
6717               dup_sect_off = dup_tu->sect_off;
6718             }
6719           else
6720             {
6721               const struct signatured_type *dup_tu
6722                 = (const struct signatured_type *) *slot;
6723
6724               dup_sect_off = dup_tu->per_cu.sect_off;
6725             }
6726
6727           complaint (_("debug type entry at offset %s is duplicate to"
6728                        " the entry at offset %s, signature %s"),
6729                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6730                      hex_string (header.signature));
6731         }
6732       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6733
6734       if (dwarf_read_debug > 1)
6735         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6736                             sect_offset_str (sect_off),
6737                             hex_string (header.signature));
6738
6739       info_ptr += length;
6740     }
6741 }
6742
6743 /* Create the hash table of all entries in the .debug_types
6744    (or .debug_types.dwo) section(s).
6745    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6746    otherwise it is NULL.
6747
6748    The result is a pointer to the hash table or NULL if there are no types.
6749
6750    Note: This function processes DWO files only, not DWP files.  */
6751
6752 static void
6753 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6754                                struct dwo_file *dwo_file,
6755                                VEC (dwarf2_section_info_def) *types,
6756                                htab_t &types_htab)
6757 {
6758   int ix;
6759   struct dwarf2_section_info *section;
6760
6761   if (VEC_empty (dwarf2_section_info_def, types))
6762     return;
6763
6764   for (ix = 0;
6765        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6766        ++ix)
6767     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6768                                   types_htab, rcuh_kind::TYPE);
6769 }
6770
6771 /* Create the hash table of all entries in the .debug_types section,
6772    and initialize all_type_units.
6773    The result is zero if there is an error (e.g. missing .debug_types section),
6774    otherwise non-zero.  */
6775
6776 static int
6777 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6778 {
6779   htab_t types_htab = NULL;
6780
6781   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6782                                 &dwarf2_per_objfile->info, types_htab,
6783                                 rcuh_kind::COMPILE);
6784   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6785                                  dwarf2_per_objfile->types, types_htab);
6786   if (types_htab == NULL)
6787     {
6788       dwarf2_per_objfile->signatured_types = NULL;
6789       return 0;
6790     }
6791
6792   dwarf2_per_objfile->signatured_types = types_htab;
6793
6794   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6795   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6796
6797   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6798                           &dwarf2_per_objfile->all_type_units);
6799
6800   return 1;
6801 }
6802
6803 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6804    If SLOT is non-NULL, it is the entry to use in the hash table.
6805    Otherwise we find one.  */
6806
6807 static struct signatured_type *
6808 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6809                void **slot)
6810 {
6811   struct objfile *objfile = dwarf2_per_objfile->objfile;
6812
6813   if (dwarf2_per_objfile->all_type_units.size ()
6814       == dwarf2_per_objfile->all_type_units.capacity ())
6815     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6816
6817   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6818                                               struct signatured_type);
6819
6820   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6821   sig_type->signature = sig;
6822   sig_type->per_cu.is_debug_types = 1;
6823   if (dwarf2_per_objfile->using_index)
6824     {
6825       sig_type->per_cu.v.quick =
6826         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6827                         struct dwarf2_per_cu_quick_data);
6828     }
6829
6830   if (slot == NULL)
6831     {
6832       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6833                              sig_type, INSERT);
6834     }
6835   gdb_assert (*slot == NULL);
6836   *slot = sig_type;
6837   /* The rest of sig_type must be filled in by the caller.  */
6838   return sig_type;
6839 }
6840
6841 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6842    Fill in SIG_ENTRY with DWO_ENTRY.  */
6843
6844 static void
6845 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6846                                   struct signatured_type *sig_entry,
6847                                   struct dwo_unit *dwo_entry)
6848 {
6849   /* Make sure we're not clobbering something we don't expect to.  */
6850   gdb_assert (! sig_entry->per_cu.queued);
6851   gdb_assert (sig_entry->per_cu.cu == NULL);
6852   if (dwarf2_per_objfile->using_index)
6853     {
6854       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6855       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6856     }
6857   else
6858       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6859   gdb_assert (sig_entry->signature == dwo_entry->signature);
6860   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6861   gdb_assert (sig_entry->type_unit_group == NULL);
6862   gdb_assert (sig_entry->dwo_unit == NULL);
6863
6864   sig_entry->per_cu.section = dwo_entry->section;
6865   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6866   sig_entry->per_cu.length = dwo_entry->length;
6867   sig_entry->per_cu.reading_dwo_directly = 1;
6868   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6869   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6870   sig_entry->dwo_unit = dwo_entry;
6871 }
6872
6873 /* Subroutine of lookup_signatured_type.
6874    If we haven't read the TU yet, create the signatured_type data structure
6875    for a TU to be read in directly from a DWO file, bypassing the stub.
6876    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6877    using .gdb_index, then when reading a CU we want to stay in the DWO file
6878    containing that CU.  Otherwise we could end up reading several other DWO
6879    files (due to comdat folding) to process the transitive closure of all the
6880    mentioned TUs, and that can be slow.  The current DWO file will have every
6881    type signature that it needs.
6882    We only do this for .gdb_index because in the psymtab case we already have
6883    to read all the DWOs to build the type unit groups.  */
6884
6885 static struct signatured_type *
6886 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6887 {
6888   struct dwarf2_per_objfile *dwarf2_per_objfile
6889     = cu->per_cu->dwarf2_per_objfile;
6890   struct objfile *objfile = dwarf2_per_objfile->objfile;
6891   struct dwo_file *dwo_file;
6892   struct dwo_unit find_dwo_entry, *dwo_entry;
6893   struct signatured_type find_sig_entry, *sig_entry;
6894   void **slot;
6895
6896   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6897
6898   /* If TU skeletons have been removed then we may not have read in any
6899      TUs yet.  */
6900   if (dwarf2_per_objfile->signatured_types == NULL)
6901     {
6902       dwarf2_per_objfile->signatured_types
6903         = allocate_signatured_type_table (objfile);
6904     }
6905
6906   /* We only ever need to read in one copy of a signatured type.
6907      Use the global signatured_types array to do our own comdat-folding
6908      of types.  If this is the first time we're reading this TU, and
6909      the TU has an entry in .gdb_index, replace the recorded data from
6910      .gdb_index with this TU.  */
6911
6912   find_sig_entry.signature = sig;
6913   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6914                          &find_sig_entry, INSERT);
6915   sig_entry = (struct signatured_type *) *slot;
6916
6917   /* We can get here with the TU already read, *or* in the process of being
6918      read.  Don't reassign the global entry to point to this DWO if that's
6919      the case.  Also note that if the TU is already being read, it may not
6920      have come from a DWO, the program may be a mix of Fission-compiled
6921      code and non-Fission-compiled code.  */
6922
6923   /* Have we already tried to read this TU?
6924      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6925      needn't exist in the global table yet).  */
6926   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6927     return sig_entry;
6928
6929   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6930      dwo_unit of the TU itself.  */
6931   dwo_file = cu->dwo_unit->dwo_file;
6932
6933   /* Ok, this is the first time we're reading this TU.  */
6934   if (dwo_file->tus == NULL)
6935     return NULL;
6936   find_dwo_entry.signature = sig;
6937   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6938   if (dwo_entry == NULL)
6939     return NULL;
6940
6941   /* If the global table doesn't have an entry for this TU, add one.  */
6942   if (sig_entry == NULL)
6943     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6944
6945   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6946   sig_entry->per_cu.tu_read = 1;
6947   return sig_entry;
6948 }
6949
6950 /* Subroutine of lookup_signatured_type.
6951    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6952    then try the DWP file.  If the TU stub (skeleton) has been removed then
6953    it won't be in .gdb_index.  */
6954
6955 static struct signatured_type *
6956 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6957 {
6958   struct dwarf2_per_objfile *dwarf2_per_objfile
6959     = cu->per_cu->dwarf2_per_objfile;
6960   struct objfile *objfile = dwarf2_per_objfile->objfile;
6961   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6962   struct dwo_unit *dwo_entry;
6963   struct signatured_type find_sig_entry, *sig_entry;
6964   void **slot;
6965
6966   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6967   gdb_assert (dwp_file != NULL);
6968
6969   /* If TU skeletons have been removed then we may not have read in any
6970      TUs yet.  */
6971   if (dwarf2_per_objfile->signatured_types == NULL)
6972     {
6973       dwarf2_per_objfile->signatured_types
6974         = allocate_signatured_type_table (objfile);
6975     }
6976
6977   find_sig_entry.signature = sig;
6978   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6979                          &find_sig_entry, INSERT);
6980   sig_entry = (struct signatured_type *) *slot;
6981
6982   /* Have we already tried to read this TU?
6983      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6984      needn't exist in the global table yet).  */
6985   if (sig_entry != NULL)
6986     return sig_entry;
6987
6988   if (dwp_file->tus == NULL)
6989     return NULL;
6990   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
6991                                       sig, 1 /* is_debug_types */);
6992   if (dwo_entry == NULL)
6993     return NULL;
6994
6995   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6996   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6997
6998   return sig_entry;
6999 }
7000
7001 /* Lookup a signature based type for DW_FORM_ref_sig8.
7002    Returns NULL if signature SIG is not present in the table.
7003    It is up to the caller to complain about this.  */
7004
7005 static struct signatured_type *
7006 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7007 {
7008   struct dwarf2_per_objfile *dwarf2_per_objfile
7009     = cu->per_cu->dwarf2_per_objfile;
7010
7011   if (cu->dwo_unit
7012       && dwarf2_per_objfile->using_index)
7013     {
7014       /* We're in a DWO/DWP file, and we're using .gdb_index.
7015          These cases require special processing.  */
7016       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7017         return lookup_dwo_signatured_type (cu, sig);
7018       else
7019         return lookup_dwp_signatured_type (cu, sig);
7020     }
7021   else
7022     {
7023       struct signatured_type find_entry, *entry;
7024
7025       if (dwarf2_per_objfile->signatured_types == NULL)
7026         return NULL;
7027       find_entry.signature = sig;
7028       entry = ((struct signatured_type *)
7029                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7030       return entry;
7031     }
7032 }
7033 \f
7034 /* Low level DIE reading support.  */
7035
7036 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7037
7038 static void
7039 init_cu_die_reader (struct die_reader_specs *reader,
7040                     struct dwarf2_cu *cu,
7041                     struct dwarf2_section_info *section,
7042                     struct dwo_file *dwo_file,
7043                     struct abbrev_table *abbrev_table)
7044 {
7045   gdb_assert (section->readin && section->buffer != NULL);
7046   reader->abfd = get_section_bfd_owner (section);
7047   reader->cu = cu;
7048   reader->dwo_file = dwo_file;
7049   reader->die_section = section;
7050   reader->buffer = section->buffer;
7051   reader->buffer_end = section->buffer + section->size;
7052   reader->comp_dir = NULL;
7053   reader->abbrev_table = abbrev_table;
7054 }
7055
7056 /* Subroutine of init_cutu_and_read_dies to simplify it.
7057    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7058    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7059    already.
7060
7061    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7062    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7063    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7064    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7065    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7066    STUB_COMP_DIR may be non-NULL.
7067    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7068    are filled in with the info of the DIE from the DWO file.
7069    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7070    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7071    kept around for at least as long as *RESULT_READER.
7072
7073    The result is non-zero if a valid (non-dummy) DIE was found.  */
7074
7075 static int
7076 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7077                         struct dwo_unit *dwo_unit,
7078                         struct die_info *stub_comp_unit_die,
7079                         const char *stub_comp_dir,
7080                         struct die_reader_specs *result_reader,
7081                         const gdb_byte **result_info_ptr,
7082                         struct die_info **result_comp_unit_die,
7083                         int *result_has_children,
7084                         abbrev_table_up *result_dwo_abbrev_table)
7085 {
7086   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7087   struct objfile *objfile = dwarf2_per_objfile->objfile;
7088   struct dwarf2_cu *cu = this_cu->cu;
7089   bfd *abfd;
7090   const gdb_byte *begin_info_ptr, *info_ptr;
7091   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7092   int i,num_extra_attrs;
7093   struct dwarf2_section_info *dwo_abbrev_section;
7094   struct attribute *attr;
7095   struct die_info *comp_unit_die;
7096
7097   /* At most one of these may be provided.  */
7098   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7099
7100   /* These attributes aren't processed until later:
7101      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7102      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7103      referenced later.  However, these attributes are found in the stub
7104      which we won't have later.  In order to not impose this complication
7105      on the rest of the code, we read them here and copy them to the
7106      DWO CU/TU die.  */
7107
7108   stmt_list = NULL;
7109   low_pc = NULL;
7110   high_pc = NULL;
7111   ranges = NULL;
7112   comp_dir = NULL;
7113
7114   if (stub_comp_unit_die != NULL)
7115     {
7116       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7117          DWO file.  */
7118       if (! this_cu->is_debug_types)
7119         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7120       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7121       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7122       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7123       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7124
7125       /* There should be a DW_AT_addr_base attribute here (if needed).
7126          We need the value before we can process DW_FORM_GNU_addr_index.  */
7127       cu->addr_base = 0;
7128       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7129       if (attr)
7130         cu->addr_base = DW_UNSND (attr);
7131
7132       /* There should be a DW_AT_ranges_base attribute here (if needed).
7133          We need the value before we can process DW_AT_ranges.  */
7134       cu->ranges_base = 0;
7135       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7136       if (attr)
7137         cu->ranges_base = DW_UNSND (attr);
7138     }
7139   else if (stub_comp_dir != NULL)
7140     {
7141       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7142       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7143       comp_dir->name = DW_AT_comp_dir;
7144       comp_dir->form = DW_FORM_string;
7145       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7146       DW_STRING (comp_dir) = stub_comp_dir;
7147     }
7148
7149   /* Set up for reading the DWO CU/TU.  */
7150   cu->dwo_unit = dwo_unit;
7151   dwarf2_section_info *section = dwo_unit->section;
7152   dwarf2_read_section (objfile, section);
7153   abfd = get_section_bfd_owner (section);
7154   begin_info_ptr = info_ptr = (section->buffer
7155                                + to_underlying (dwo_unit->sect_off));
7156   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7157
7158   if (this_cu->is_debug_types)
7159     {
7160       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7161
7162       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7163                                                 &cu->header, section,
7164                                                 dwo_abbrev_section,
7165                                                 info_ptr, rcuh_kind::TYPE);
7166       /* This is not an assert because it can be caused by bad debug info.  */
7167       if (sig_type->signature != cu->header.signature)
7168         {
7169           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7170                    " TU at offset %s [in module %s]"),
7171                  hex_string (sig_type->signature),
7172                  hex_string (cu->header.signature),
7173                  sect_offset_str (dwo_unit->sect_off),
7174                  bfd_get_filename (abfd));
7175         }
7176       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7177       /* For DWOs coming from DWP files, we don't know the CU length
7178          nor the type's offset in the TU until now.  */
7179       dwo_unit->length = get_cu_length (&cu->header);
7180       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7181
7182       /* Establish the type offset that can be used to lookup the type.
7183          For DWO files, we don't know it until now.  */
7184       sig_type->type_offset_in_section
7185         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7186     }
7187   else
7188     {
7189       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7190                                                 &cu->header, section,
7191                                                 dwo_abbrev_section,
7192                                                 info_ptr, rcuh_kind::COMPILE);
7193       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7194       /* For DWOs coming from DWP files, we don't know the CU length
7195          until now.  */
7196       dwo_unit->length = get_cu_length (&cu->header);
7197     }
7198
7199   *result_dwo_abbrev_table
7200     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7201                                cu->header.abbrev_sect_off);
7202   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7203                       result_dwo_abbrev_table->get ());
7204
7205   /* Read in the die, but leave space to copy over the attributes
7206      from the stub.  This has the benefit of simplifying the rest of
7207      the code - all the work to maintain the illusion of a single
7208      DW_TAG_{compile,type}_unit DIE is done here.  */
7209   num_extra_attrs = ((stmt_list != NULL)
7210                      + (low_pc != NULL)
7211                      + (high_pc != NULL)
7212                      + (ranges != NULL)
7213                      + (comp_dir != NULL));
7214   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7215                               result_has_children, num_extra_attrs);
7216
7217   /* Copy over the attributes from the stub to the DIE we just read in.  */
7218   comp_unit_die = *result_comp_unit_die;
7219   i = comp_unit_die->num_attrs;
7220   if (stmt_list != NULL)
7221     comp_unit_die->attrs[i++] = *stmt_list;
7222   if (low_pc != NULL)
7223     comp_unit_die->attrs[i++] = *low_pc;
7224   if (high_pc != NULL)
7225     comp_unit_die->attrs[i++] = *high_pc;
7226   if (ranges != NULL)
7227     comp_unit_die->attrs[i++] = *ranges;
7228   if (comp_dir != NULL)
7229     comp_unit_die->attrs[i++] = *comp_dir;
7230   comp_unit_die->num_attrs += num_extra_attrs;
7231
7232   if (dwarf_die_debug)
7233     {
7234       fprintf_unfiltered (gdb_stdlog,
7235                           "Read die from %s@0x%x of %s:\n",
7236                           get_section_name (section),
7237                           (unsigned) (begin_info_ptr - section->buffer),
7238                           bfd_get_filename (abfd));
7239       dump_die (comp_unit_die, dwarf_die_debug);
7240     }
7241
7242   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7243      TUs by skipping the stub and going directly to the entry in the DWO file.
7244      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7245      to get it via circuitous means.  Blech.  */
7246   if (comp_dir != NULL)
7247     result_reader->comp_dir = DW_STRING (comp_dir);
7248
7249   /* Skip dummy compilation units.  */
7250   if (info_ptr >= begin_info_ptr + dwo_unit->length
7251       || peek_abbrev_code (abfd, info_ptr) == 0)
7252     return 0;
7253
7254   *result_info_ptr = info_ptr;
7255   return 1;
7256 }
7257
7258 /* Subroutine of init_cutu_and_read_dies to simplify it.
7259    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7260    Returns NULL if the specified DWO unit cannot be found.  */
7261
7262 static struct dwo_unit *
7263 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7264                  struct die_info *comp_unit_die)
7265 {
7266   struct dwarf2_cu *cu = this_cu->cu;
7267   ULONGEST signature;
7268   struct dwo_unit *dwo_unit;
7269   const char *comp_dir, *dwo_name;
7270
7271   gdb_assert (cu != NULL);
7272
7273   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7274   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7275   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7276
7277   if (this_cu->is_debug_types)
7278     {
7279       struct signatured_type *sig_type;
7280
7281       /* Since this_cu is the first member of struct signatured_type,
7282          we can go from a pointer to one to a pointer to the other.  */
7283       sig_type = (struct signatured_type *) this_cu;
7284       signature = sig_type->signature;
7285       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7286     }
7287   else
7288     {
7289       struct attribute *attr;
7290
7291       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7292       if (! attr)
7293         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7294                  " [in module %s]"),
7295                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7296       signature = DW_UNSND (attr);
7297       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7298                                        signature);
7299     }
7300
7301   return dwo_unit;
7302 }
7303
7304 /* Subroutine of init_cutu_and_read_dies to simplify it.
7305    See it for a description of the parameters.
7306    Read a TU directly from a DWO file, bypassing the stub.  */
7307
7308 static void
7309 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7310                            int use_existing_cu, int keep,
7311                            die_reader_func_ftype *die_reader_func,
7312                            void *data)
7313 {
7314   std::unique_ptr<dwarf2_cu> new_cu;
7315   struct signatured_type *sig_type;
7316   struct die_reader_specs reader;
7317   const gdb_byte *info_ptr;
7318   struct die_info *comp_unit_die;
7319   int has_children;
7320   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7321
7322   /* Verify we can do the following downcast, and that we have the
7323      data we need.  */
7324   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7325   sig_type = (struct signatured_type *) this_cu;
7326   gdb_assert (sig_type->dwo_unit != NULL);
7327
7328   if (use_existing_cu && this_cu->cu != NULL)
7329     {
7330       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7331       /* There's no need to do the rereading_dwo_cu handling that
7332          init_cutu_and_read_dies does since we don't read the stub.  */
7333     }
7334   else
7335     {
7336       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7337       gdb_assert (this_cu->cu == NULL);
7338       new_cu.reset (new dwarf2_cu (this_cu));
7339     }
7340
7341   /* A future optimization, if needed, would be to use an existing
7342      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7343      could share abbrev tables.  */
7344
7345   /* The abbreviation table used by READER, this must live at least as long as
7346      READER.  */
7347   abbrev_table_up dwo_abbrev_table;
7348
7349   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7350                               NULL /* stub_comp_unit_die */,
7351                               sig_type->dwo_unit->dwo_file->comp_dir,
7352                               &reader, &info_ptr,
7353                               &comp_unit_die, &has_children,
7354                               &dwo_abbrev_table) == 0)
7355     {
7356       /* Dummy die.  */
7357       return;
7358     }
7359
7360   /* All the "real" work is done here.  */
7361   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7362
7363   /* This duplicates the code in init_cutu_and_read_dies,
7364      but the alternative is making the latter more complex.
7365      This function is only for the special case of using DWO files directly:
7366      no point in overly complicating the general case just to handle this.  */
7367   if (new_cu != NULL && keep)
7368     {
7369       /* Link this CU into read_in_chain.  */
7370       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7371       dwarf2_per_objfile->read_in_chain = this_cu;
7372       /* The chain owns it now.  */
7373       new_cu.release ();
7374     }
7375 }
7376
7377 /* Initialize a CU (or TU) and read its DIEs.
7378    If the CU defers to a DWO file, read the DWO file as well.
7379
7380    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7381    Otherwise the table specified in the comp unit header is read in and used.
7382    This is an optimization for when we already have the abbrev table.
7383
7384    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7385    Otherwise, a new CU is allocated with xmalloc.
7386
7387    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7388    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7389
7390    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7391    linker) then DIE_READER_FUNC will not get called.  */
7392
7393 static void
7394 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7395                          struct abbrev_table *abbrev_table,
7396                          int use_existing_cu, int keep,
7397                          bool skip_partial,
7398                          die_reader_func_ftype *die_reader_func,
7399                          void *data)
7400 {
7401   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7402   struct objfile *objfile = dwarf2_per_objfile->objfile;
7403   struct dwarf2_section_info *section = this_cu->section;
7404   bfd *abfd = get_section_bfd_owner (section);
7405   struct dwarf2_cu *cu;
7406   const gdb_byte *begin_info_ptr, *info_ptr;
7407   struct die_reader_specs reader;
7408   struct die_info *comp_unit_die;
7409   int has_children;
7410   struct attribute *attr;
7411   struct signatured_type *sig_type = NULL;
7412   struct dwarf2_section_info *abbrev_section;
7413   /* Non-zero if CU currently points to a DWO file and we need to
7414      reread it.  When this happens we need to reread the skeleton die
7415      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7416   int rereading_dwo_cu = 0;
7417
7418   if (dwarf_die_debug)
7419     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7420                         this_cu->is_debug_types ? "type" : "comp",
7421                         sect_offset_str (this_cu->sect_off));
7422
7423   if (use_existing_cu)
7424     gdb_assert (keep);
7425
7426   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7427      file (instead of going through the stub), short-circuit all of this.  */
7428   if (this_cu->reading_dwo_directly)
7429     {
7430       /* Narrow down the scope of possibilities to have to understand.  */
7431       gdb_assert (this_cu->is_debug_types);
7432       gdb_assert (abbrev_table == NULL);
7433       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7434                                  die_reader_func, data);
7435       return;
7436     }
7437
7438   /* This is cheap if the section is already read in.  */
7439   dwarf2_read_section (objfile, section);
7440
7441   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7442
7443   abbrev_section = get_abbrev_section_for_cu (this_cu);
7444
7445   std::unique_ptr<dwarf2_cu> new_cu;
7446   if (use_existing_cu && this_cu->cu != NULL)
7447     {
7448       cu = this_cu->cu;
7449       /* If this CU is from a DWO file we need to start over, we need to
7450          refetch the attributes from the skeleton CU.
7451          This could be optimized by retrieving those attributes from when we
7452          were here the first time: the previous comp_unit_die was stored in
7453          comp_unit_obstack.  But there's no data yet that we need this
7454          optimization.  */
7455       if (cu->dwo_unit != NULL)
7456         rereading_dwo_cu = 1;
7457     }
7458   else
7459     {
7460       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7461       gdb_assert (this_cu->cu == NULL);
7462       new_cu.reset (new dwarf2_cu (this_cu));
7463       cu = new_cu.get ();
7464     }
7465
7466   /* Get the header.  */
7467   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7468     {
7469       /* We already have the header, there's no need to read it in again.  */
7470       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7471     }
7472   else
7473     {
7474       if (this_cu->is_debug_types)
7475         {
7476           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7477                                                     &cu->header, section,
7478                                                     abbrev_section, info_ptr,
7479                                                     rcuh_kind::TYPE);
7480
7481           /* Since per_cu is the first member of struct signatured_type,
7482              we can go from a pointer to one to a pointer to the other.  */
7483           sig_type = (struct signatured_type *) this_cu;
7484           gdb_assert (sig_type->signature == cu->header.signature);
7485           gdb_assert (sig_type->type_offset_in_tu
7486                       == cu->header.type_cu_offset_in_tu);
7487           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7488
7489           /* LENGTH has not been set yet for type units if we're
7490              using .gdb_index.  */
7491           this_cu->length = get_cu_length (&cu->header);
7492
7493           /* Establish the type offset that can be used to lookup the type.  */
7494           sig_type->type_offset_in_section =
7495             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7496
7497           this_cu->dwarf_version = cu->header.version;
7498         }
7499       else
7500         {
7501           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7502                                                     &cu->header, section,
7503                                                     abbrev_section,
7504                                                     info_ptr,
7505                                                     rcuh_kind::COMPILE);
7506
7507           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7508           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7509           this_cu->dwarf_version = cu->header.version;
7510         }
7511     }
7512
7513   /* Skip dummy compilation units.  */
7514   if (info_ptr >= begin_info_ptr + this_cu->length
7515       || peek_abbrev_code (abfd, info_ptr) == 0)
7516     return;
7517
7518   /* If we don't have them yet, read the abbrevs for this compilation unit.
7519      And if we need to read them now, make sure they're freed when we're
7520      done (own the table through ABBREV_TABLE_HOLDER).  */
7521   abbrev_table_up abbrev_table_holder;
7522   if (abbrev_table != NULL)
7523     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7524   else
7525     {
7526       abbrev_table_holder
7527         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7528                                    cu->header.abbrev_sect_off);
7529       abbrev_table = abbrev_table_holder.get ();
7530     }
7531
7532   /* Read the top level CU/TU die.  */
7533   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7534   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7535
7536   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7537     return;
7538
7539   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7540      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7541      table from the DWO file and pass the ownership over to us.  It will be
7542      referenced from READER, so we must make sure to free it after we're done
7543      with READER.
7544
7545      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7546      DWO CU, that this test will fail (the attribute will not be present).  */
7547   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7548   abbrev_table_up dwo_abbrev_table;
7549   if (attr)
7550     {
7551       struct dwo_unit *dwo_unit;
7552       struct die_info *dwo_comp_unit_die;
7553
7554       if (has_children)
7555         {
7556           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7557                        " has children (offset %s) [in module %s]"),
7558                      sect_offset_str (this_cu->sect_off),
7559                      bfd_get_filename (abfd));
7560         }
7561       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7562       if (dwo_unit != NULL)
7563         {
7564           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7565                                       comp_unit_die, NULL,
7566                                       &reader, &info_ptr,
7567                                       &dwo_comp_unit_die, &has_children,
7568                                       &dwo_abbrev_table) == 0)
7569             {
7570               /* Dummy die.  */
7571               return;
7572             }
7573           comp_unit_die = dwo_comp_unit_die;
7574         }
7575       else
7576         {
7577           /* Yikes, we couldn't find the rest of the DIE, we only have
7578              the stub.  A complaint has already been logged.  There's
7579              not much more we can do except pass on the stub DIE to
7580              die_reader_func.  We don't want to throw an error on bad
7581              debug info.  */
7582         }
7583     }
7584
7585   /* All of the above is setup for this call.  Yikes.  */
7586   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7587
7588   /* Done, clean up.  */
7589   if (new_cu != NULL && keep)
7590     {
7591       /* Link this CU into read_in_chain.  */
7592       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7593       dwarf2_per_objfile->read_in_chain = this_cu;
7594       /* The chain owns it now.  */
7595       new_cu.release ();
7596     }
7597 }
7598
7599 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7600    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7601    to have already done the lookup to find the DWO file).
7602
7603    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7604    THIS_CU->is_debug_types, but nothing else.
7605
7606    We fill in THIS_CU->length.
7607
7608    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7609    linker) then DIE_READER_FUNC will not get called.
7610
7611    THIS_CU->cu is always freed when done.
7612    This is done in order to not leave THIS_CU->cu in a state where we have
7613    to care whether it refers to the "main" CU or the DWO CU.  */
7614
7615 static void
7616 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7617                                    struct dwo_file *dwo_file,
7618                                    die_reader_func_ftype *die_reader_func,
7619                                    void *data)
7620 {
7621   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7622   struct objfile *objfile = dwarf2_per_objfile->objfile;
7623   struct dwarf2_section_info *section = this_cu->section;
7624   bfd *abfd = get_section_bfd_owner (section);
7625   struct dwarf2_section_info *abbrev_section;
7626   const gdb_byte *begin_info_ptr, *info_ptr;
7627   struct die_reader_specs reader;
7628   struct die_info *comp_unit_die;
7629   int has_children;
7630
7631   if (dwarf_die_debug)
7632     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7633                         this_cu->is_debug_types ? "type" : "comp",
7634                         sect_offset_str (this_cu->sect_off));
7635
7636   gdb_assert (this_cu->cu == NULL);
7637
7638   abbrev_section = (dwo_file != NULL
7639                     ? &dwo_file->sections.abbrev
7640                     : get_abbrev_section_for_cu (this_cu));
7641
7642   /* This is cheap if the section is already read in.  */
7643   dwarf2_read_section (objfile, section);
7644
7645   struct dwarf2_cu cu (this_cu);
7646
7647   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7648   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7649                                             &cu.header, section,
7650                                             abbrev_section, info_ptr,
7651                                             (this_cu->is_debug_types
7652                                              ? rcuh_kind::TYPE
7653                                              : rcuh_kind::COMPILE));
7654
7655   this_cu->length = get_cu_length (&cu.header);
7656
7657   /* Skip dummy compilation units.  */
7658   if (info_ptr >= begin_info_ptr + this_cu->length
7659       || peek_abbrev_code (abfd, info_ptr) == 0)
7660     return;
7661
7662   abbrev_table_up abbrev_table
7663     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7664                                cu.header.abbrev_sect_off);
7665
7666   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7667   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7668
7669   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7670 }
7671
7672 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7673    does not lookup the specified DWO file.
7674    This cannot be used to read DWO files.
7675
7676    THIS_CU->cu is always freed when done.
7677    This is done in order to not leave THIS_CU->cu in a state where we have
7678    to care whether it refers to the "main" CU or the DWO CU.
7679    We can revisit this if the data shows there's a performance issue.  */
7680
7681 static void
7682 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7683                                 die_reader_func_ftype *die_reader_func,
7684                                 void *data)
7685 {
7686   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7687 }
7688 \f
7689 /* Type Unit Groups.
7690
7691    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7692    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7693    so that all types coming from the same compilation (.o file) are grouped
7694    together.  A future step could be to put the types in the same symtab as
7695    the CU the types ultimately came from.  */
7696
7697 static hashval_t
7698 hash_type_unit_group (const void *item)
7699 {
7700   const struct type_unit_group *tu_group
7701     = (const struct type_unit_group *) item;
7702
7703   return hash_stmt_list_entry (&tu_group->hash);
7704 }
7705
7706 static int
7707 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7708 {
7709   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7710   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7711
7712   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7713 }
7714
7715 /* Allocate a hash table for type unit groups.  */
7716
7717 static htab_t
7718 allocate_type_unit_groups_table (struct objfile *objfile)
7719 {
7720   return htab_create_alloc_ex (3,
7721                                hash_type_unit_group,
7722                                eq_type_unit_group,
7723                                NULL,
7724                                &objfile->objfile_obstack,
7725                                hashtab_obstack_allocate,
7726                                dummy_obstack_deallocate);
7727 }
7728
7729 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7730    partial symtabs.  We combine several TUs per psymtab to not let the size
7731    of any one psymtab grow too big.  */
7732 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7733 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7734
7735 /* Helper routine for get_type_unit_group.
7736    Create the type_unit_group object used to hold one or more TUs.  */
7737
7738 static struct type_unit_group *
7739 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7740 {
7741   struct dwarf2_per_objfile *dwarf2_per_objfile
7742     = cu->per_cu->dwarf2_per_objfile;
7743   struct objfile *objfile = dwarf2_per_objfile->objfile;
7744   struct dwarf2_per_cu_data *per_cu;
7745   struct type_unit_group *tu_group;
7746
7747   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7748                              struct type_unit_group);
7749   per_cu = &tu_group->per_cu;
7750   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7751
7752   if (dwarf2_per_objfile->using_index)
7753     {
7754       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7755                                         struct dwarf2_per_cu_quick_data);
7756     }
7757   else
7758     {
7759       unsigned int line_offset = to_underlying (line_offset_struct);
7760       struct partial_symtab *pst;
7761       char *name;
7762
7763       /* Give the symtab a useful name for debug purposes.  */
7764       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7765         name = xstrprintf ("<type_units_%d>",
7766                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7767       else
7768         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
7769
7770       pst = create_partial_symtab (per_cu, name);
7771       pst->anonymous = 1;
7772
7773       xfree (name);
7774     }
7775
7776   tu_group->hash.dwo_unit = cu->dwo_unit;
7777   tu_group->hash.line_sect_off = line_offset_struct;
7778
7779   return tu_group;
7780 }
7781
7782 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7783    STMT_LIST is a DW_AT_stmt_list attribute.  */
7784
7785 static struct type_unit_group *
7786 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7787 {
7788   struct dwarf2_per_objfile *dwarf2_per_objfile
7789     = cu->per_cu->dwarf2_per_objfile;
7790   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7791   struct type_unit_group *tu_group;
7792   void **slot;
7793   unsigned int line_offset;
7794   struct type_unit_group type_unit_group_for_lookup;
7795
7796   if (dwarf2_per_objfile->type_unit_groups == NULL)
7797     {
7798       dwarf2_per_objfile->type_unit_groups =
7799         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7800     }
7801
7802   /* Do we need to create a new group, or can we use an existing one?  */
7803
7804   if (stmt_list)
7805     {
7806       line_offset = DW_UNSND (stmt_list);
7807       ++tu_stats->nr_symtab_sharers;
7808     }
7809   else
7810     {
7811       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7812          We can do various things here like create one group per TU or
7813          spread them over multiple groups to split up the expansion work.
7814          To avoid worst case scenarios (too many groups or too large groups)
7815          we, umm, group them in bunches.  */
7816       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7817                      | (tu_stats->nr_stmt_less_type_units
7818                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7819       ++tu_stats->nr_stmt_less_type_units;
7820     }
7821
7822   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7823   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7824   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7825                          &type_unit_group_for_lookup, INSERT);
7826   if (*slot != NULL)
7827     {
7828       tu_group = (struct type_unit_group *) *slot;
7829       gdb_assert (tu_group != NULL);
7830     }
7831   else
7832     {
7833       sect_offset line_offset_struct = (sect_offset) line_offset;
7834       tu_group = create_type_unit_group (cu, line_offset_struct);
7835       *slot = tu_group;
7836       ++tu_stats->nr_symtabs;
7837     }
7838
7839   return tu_group;
7840 }
7841 \f
7842 /* Partial symbol tables.  */
7843
7844 /* Create a psymtab named NAME and assign it to PER_CU.
7845
7846    The caller must fill in the following details:
7847    dirname, textlow, texthigh.  */
7848
7849 static struct partial_symtab *
7850 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7851 {
7852   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7853   struct partial_symtab *pst;
7854
7855   pst = start_psymtab_common (objfile, name, 0,
7856                               objfile->global_psymbols,
7857                               objfile->static_psymbols);
7858
7859   pst->psymtabs_addrmap_supported = 1;
7860
7861   /* This is the glue that links PST into GDB's symbol API.  */
7862   pst->read_symtab_private = per_cu;
7863   pst->read_symtab = dwarf2_read_symtab;
7864   per_cu->v.psymtab = pst;
7865
7866   return pst;
7867 }
7868
7869 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7870    type.  */
7871
7872 struct process_psymtab_comp_unit_data
7873 {
7874   /* True if we are reading a DW_TAG_partial_unit.  */
7875
7876   int want_partial_unit;
7877
7878   /* The "pretend" language that is used if the CU doesn't declare a
7879      language.  */
7880
7881   enum language pretend_language;
7882 };
7883
7884 /* die_reader_func for process_psymtab_comp_unit.  */
7885
7886 static void
7887 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7888                                   const gdb_byte *info_ptr,
7889                                   struct die_info *comp_unit_die,
7890                                   int has_children,
7891                                   void *data)
7892 {
7893   struct dwarf2_cu *cu = reader->cu;
7894   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7895   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7896   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7897   CORE_ADDR baseaddr;
7898   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7899   struct partial_symtab *pst;
7900   enum pc_bounds_kind cu_bounds_kind;
7901   const char *filename;
7902   struct process_psymtab_comp_unit_data *info
7903     = (struct process_psymtab_comp_unit_data *) data;
7904
7905   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7906     return;
7907
7908   gdb_assert (! per_cu->is_debug_types);
7909
7910   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7911
7912   cu->list_in_scope = &file_symbols;
7913
7914   /* Allocate a new partial symbol table structure.  */
7915   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7916   if (filename == NULL)
7917     filename = "";
7918
7919   pst = create_partial_symtab (per_cu, filename);
7920
7921   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7922   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7923
7924   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7925
7926   dwarf2_find_base_address (comp_unit_die, cu);
7927
7928   /* Possibly set the default values of LOWPC and HIGHPC from
7929      `DW_AT_ranges'.  */
7930   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7931                                          &best_highpc, cu, pst);
7932   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7933     /* Store the contiguous range if it is not empty; it can be empty for
7934        CUs with no code.  */
7935     addrmap_set_empty (objfile->psymtabs_addrmap,
7936                        gdbarch_adjust_dwarf2_addr (gdbarch,
7937                                                    best_lowpc + baseaddr),
7938                        gdbarch_adjust_dwarf2_addr (gdbarch,
7939                                                    best_highpc + baseaddr) - 1,
7940                        pst);
7941
7942   /* Check if comp unit has_children.
7943      If so, read the rest of the partial symbols from this comp unit.
7944      If not, there's no more debug_info for this comp unit.  */
7945   if (has_children)
7946     {
7947       struct partial_die_info *first_die;
7948       CORE_ADDR lowpc, highpc;
7949
7950       lowpc = ((CORE_ADDR) -1);
7951       highpc = ((CORE_ADDR) 0);
7952
7953       first_die = load_partial_dies (reader, info_ptr, 1);
7954
7955       scan_partial_symbols (first_die, &lowpc, &highpc,
7956                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7957
7958       /* If we didn't find a lowpc, set it to highpc to avoid
7959          complaints from `maint check'.  */
7960       if (lowpc == ((CORE_ADDR) -1))
7961         lowpc = highpc;
7962
7963       /* If the compilation unit didn't have an explicit address range,
7964          then use the information extracted from its child dies.  */
7965       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7966         {
7967           best_lowpc = lowpc;
7968           best_highpc = highpc;
7969         }
7970     }
7971   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7972   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7973
7974   end_psymtab_common (objfile, pst);
7975
7976   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7977     {
7978       int i;
7979       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7980       struct dwarf2_per_cu_data *iter;
7981
7982       /* Fill in 'dependencies' here; we fill in 'users' in a
7983          post-pass.  */
7984       pst->number_of_dependencies = len;
7985       pst->dependencies =
7986         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7987       for (i = 0;
7988            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7989                         i, iter);
7990            ++i)
7991         pst->dependencies[i] = iter->v.psymtab;
7992
7993       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7994     }
7995
7996   /* Get the list of files included in the current compilation unit,
7997      and build a psymtab for each of them.  */
7998   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7999
8000   if (dwarf_read_debug)
8001     {
8002       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8003
8004       fprintf_unfiltered (gdb_stdlog,
8005                           "Psymtab for %s unit @%s: %s - %s"
8006                           ", %d global, %d static syms\n",
8007                           per_cu->is_debug_types ? "type" : "comp",
8008                           sect_offset_str (per_cu->sect_off),
8009                           paddress (gdbarch, pst->textlow),
8010                           paddress (gdbarch, pst->texthigh),
8011                           pst->n_global_syms, pst->n_static_syms);
8012     }
8013 }
8014
8015 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8016    Process compilation unit THIS_CU for a psymtab.  */
8017
8018 static void
8019 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8020                            int want_partial_unit,
8021                            enum language pretend_language)
8022 {
8023   /* If this compilation unit was already read in, free the
8024      cached copy in order to read it in again.  This is
8025      necessary because we skipped some symbols when we first
8026      read in the compilation unit (see load_partial_dies).
8027      This problem could be avoided, but the benefit is unclear.  */
8028   if (this_cu->cu != NULL)
8029     free_one_cached_comp_unit (this_cu);
8030
8031   if (this_cu->is_debug_types)
8032     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8033                              build_type_psymtabs_reader, NULL);
8034   else
8035     {
8036       process_psymtab_comp_unit_data info;
8037       info.want_partial_unit = want_partial_unit;
8038       info.pretend_language = pretend_language;
8039       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8040                                process_psymtab_comp_unit_reader, &info);
8041     }
8042
8043   /* Age out any secondary CUs.  */
8044   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8045 }
8046
8047 /* Reader function for build_type_psymtabs.  */
8048
8049 static void
8050 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8051                             const gdb_byte *info_ptr,
8052                             struct die_info *type_unit_die,
8053                             int has_children,
8054                             void *data)
8055 {
8056   struct dwarf2_per_objfile *dwarf2_per_objfile
8057     = reader->cu->per_cu->dwarf2_per_objfile;
8058   struct objfile *objfile = dwarf2_per_objfile->objfile;
8059   struct dwarf2_cu *cu = reader->cu;
8060   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8061   struct signatured_type *sig_type;
8062   struct type_unit_group *tu_group;
8063   struct attribute *attr;
8064   struct partial_die_info *first_die;
8065   CORE_ADDR lowpc, highpc;
8066   struct partial_symtab *pst;
8067
8068   gdb_assert (data == NULL);
8069   gdb_assert (per_cu->is_debug_types);
8070   sig_type = (struct signatured_type *) per_cu;
8071
8072   if (! has_children)
8073     return;
8074
8075   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8076   tu_group = get_type_unit_group (cu, attr);
8077
8078   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8079
8080   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8081   cu->list_in_scope = &file_symbols;
8082   pst = create_partial_symtab (per_cu, "");
8083   pst->anonymous = 1;
8084
8085   first_die = load_partial_dies (reader, info_ptr, 1);
8086
8087   lowpc = (CORE_ADDR) -1;
8088   highpc = (CORE_ADDR) 0;
8089   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8090
8091   end_psymtab_common (objfile, pst);
8092 }
8093
8094 /* Struct used to sort TUs by their abbreviation table offset.  */
8095
8096 struct tu_abbrev_offset
8097 {
8098   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8099   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8100   {}
8101
8102   signatured_type *sig_type;
8103   sect_offset abbrev_offset;
8104 };
8105
8106 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8107
8108 static bool
8109 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8110                           const struct tu_abbrev_offset &b)
8111 {
8112   return a.abbrev_offset < b.abbrev_offset;
8113 }
8114
8115 /* Efficiently read all the type units.
8116    This does the bulk of the work for build_type_psymtabs.
8117
8118    The efficiency is because we sort TUs by the abbrev table they use and
8119    only read each abbrev table once.  In one program there are 200K TUs
8120    sharing 8K abbrev tables.
8121
8122    The main purpose of this function is to support building the
8123    dwarf2_per_objfile->type_unit_groups table.
8124    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8125    can collapse the search space by grouping them by stmt_list.
8126    The savings can be significant, in the same program from above the 200K TUs
8127    share 8K stmt_list tables.
8128
8129    FUNC is expected to call get_type_unit_group, which will create the
8130    struct type_unit_group if necessary and add it to
8131    dwarf2_per_objfile->type_unit_groups.  */
8132
8133 static void
8134 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8135 {
8136   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8137   abbrev_table_up abbrev_table;
8138   sect_offset abbrev_offset;
8139
8140   /* It's up to the caller to not call us multiple times.  */
8141   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8142
8143   if (dwarf2_per_objfile->all_type_units.empty ())
8144     return;
8145
8146   /* TUs typically share abbrev tables, and there can be way more TUs than
8147      abbrev tables.  Sort by abbrev table to reduce the number of times we
8148      read each abbrev table in.
8149      Alternatives are to punt or to maintain a cache of abbrev tables.
8150      This is simpler and efficient enough for now.
8151
8152      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8153      symtab to use).  Typically TUs with the same abbrev offset have the same
8154      stmt_list value too so in practice this should work well.
8155
8156      The basic algorithm here is:
8157
8158       sort TUs by abbrev table
8159       for each TU with same abbrev table:
8160         read abbrev table if first user
8161         read TU top level DIE
8162           [IWBN if DWO skeletons had DW_AT_stmt_list]
8163         call FUNC  */
8164
8165   if (dwarf_read_debug)
8166     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8167
8168   /* Sort in a separate table to maintain the order of all_type_units
8169      for .gdb_index: TU indices directly index all_type_units.  */
8170   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8171   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8172
8173   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8174     sorted_by_abbrev.emplace_back
8175       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8176                                      sig_type->per_cu.section,
8177                                      sig_type->per_cu.sect_off));
8178
8179   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8180              sort_tu_by_abbrev_offset);
8181
8182   abbrev_offset = (sect_offset) ~(unsigned) 0;
8183
8184   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8185     {
8186       /* Switch to the next abbrev table if necessary.  */
8187       if (abbrev_table == NULL
8188           || tu.abbrev_offset != abbrev_offset)
8189         {
8190           abbrev_offset = tu.abbrev_offset;
8191           abbrev_table =
8192             abbrev_table_read_table (dwarf2_per_objfile,
8193                                      &dwarf2_per_objfile->abbrev,
8194                                      abbrev_offset);
8195           ++tu_stats->nr_uniq_abbrev_tables;
8196         }
8197
8198       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8199                                0, 0, false, build_type_psymtabs_reader, NULL);
8200     }
8201 }
8202
8203 /* Print collected type unit statistics.  */
8204
8205 static void
8206 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8207 {
8208   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8209
8210   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8211   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8212                       dwarf2_per_objfile->all_type_units.size ());
8213   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8214                       tu_stats->nr_uniq_abbrev_tables);
8215   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8216                       tu_stats->nr_symtabs);
8217   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8218                       tu_stats->nr_symtab_sharers);
8219   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8220                       tu_stats->nr_stmt_less_type_units);
8221   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8222                       tu_stats->nr_all_type_units_reallocs);
8223 }
8224
8225 /* Traversal function for build_type_psymtabs.  */
8226
8227 static int
8228 build_type_psymtab_dependencies (void **slot, void *info)
8229 {
8230   struct dwarf2_per_objfile *dwarf2_per_objfile
8231     = (struct dwarf2_per_objfile *) info;
8232   struct objfile *objfile = dwarf2_per_objfile->objfile;
8233   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8234   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8235   struct partial_symtab *pst = per_cu->v.psymtab;
8236   int len = VEC_length (sig_type_ptr, tu_group->tus);
8237   struct signatured_type *iter;
8238   int i;
8239
8240   gdb_assert (len > 0);
8241   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8242
8243   pst->number_of_dependencies = len;
8244   pst->dependencies =
8245     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8246   for (i = 0;
8247        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8248        ++i)
8249     {
8250       gdb_assert (iter->per_cu.is_debug_types);
8251       pst->dependencies[i] = iter->per_cu.v.psymtab;
8252       iter->type_unit_group = tu_group;
8253     }
8254
8255   VEC_free (sig_type_ptr, tu_group->tus);
8256
8257   return 1;
8258 }
8259
8260 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8261    Build partial symbol tables for the .debug_types comp-units.  */
8262
8263 static void
8264 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8265 {
8266   if (! create_all_type_units (dwarf2_per_objfile))
8267     return;
8268
8269   build_type_psymtabs_1 (dwarf2_per_objfile);
8270 }
8271
8272 /* Traversal function for process_skeletonless_type_unit.
8273    Read a TU in a DWO file and build partial symbols for it.  */
8274
8275 static int
8276 process_skeletonless_type_unit (void **slot, void *info)
8277 {
8278   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8279   struct dwarf2_per_objfile *dwarf2_per_objfile
8280     = (struct dwarf2_per_objfile *) info;
8281   struct signatured_type find_entry, *entry;
8282
8283   /* If this TU doesn't exist in the global table, add it and read it in.  */
8284
8285   if (dwarf2_per_objfile->signatured_types == NULL)
8286     {
8287       dwarf2_per_objfile->signatured_types
8288         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8289     }
8290
8291   find_entry.signature = dwo_unit->signature;
8292   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8293                          INSERT);
8294   /* If we've already seen this type there's nothing to do.  What's happening
8295      is we're doing our own version of comdat-folding here.  */
8296   if (*slot != NULL)
8297     return 1;
8298
8299   /* This does the job that create_all_type_units would have done for
8300      this TU.  */
8301   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8302   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8303   *slot = entry;
8304
8305   /* This does the job that build_type_psymtabs_1 would have done.  */
8306   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8307                            build_type_psymtabs_reader, NULL);
8308
8309   return 1;
8310 }
8311
8312 /* Traversal function for process_skeletonless_type_units.  */
8313
8314 static int
8315 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8316 {
8317   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8318
8319   if (dwo_file->tus != NULL)
8320     {
8321       htab_traverse_noresize (dwo_file->tus,
8322                               process_skeletonless_type_unit, info);
8323     }
8324
8325   return 1;
8326 }
8327
8328 /* Scan all TUs of DWO files, verifying we've processed them.
8329    This is needed in case a TU was emitted without its skeleton.
8330    Note: This can't be done until we know what all the DWO files are.  */
8331
8332 static void
8333 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8334 {
8335   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8336   if (get_dwp_file (dwarf2_per_objfile) == NULL
8337       && dwarf2_per_objfile->dwo_files != NULL)
8338     {
8339       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8340                               process_dwo_file_for_skeletonless_type_units,
8341                               dwarf2_per_objfile);
8342     }
8343 }
8344
8345 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8346
8347 static void
8348 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8349 {
8350   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8351     {
8352       struct partial_symtab *pst = per_cu->v.psymtab;
8353
8354       if (pst == NULL)
8355         continue;
8356
8357       for (int j = 0; j < pst->number_of_dependencies; ++j)
8358         {
8359           /* Set the 'user' field only if it is not already set.  */
8360           if (pst->dependencies[j]->user == NULL)
8361             pst->dependencies[j]->user = pst;
8362         }
8363     }
8364 }
8365
8366 /* Build the partial symbol table by doing a quick pass through the
8367    .debug_info and .debug_abbrev sections.  */
8368
8369 static void
8370 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8371 {
8372   struct objfile *objfile = dwarf2_per_objfile->objfile;
8373
8374   if (dwarf_read_debug)
8375     {
8376       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8377                           objfile_name (objfile));
8378     }
8379
8380   dwarf2_per_objfile->reading_partial_symbols = 1;
8381
8382   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8383
8384   /* Any cached compilation units will be linked by the per-objfile
8385      read_in_chain.  Make sure to free them when we're done.  */
8386   free_cached_comp_units freer (dwarf2_per_objfile);
8387
8388   build_type_psymtabs (dwarf2_per_objfile);
8389
8390   create_all_comp_units (dwarf2_per_objfile);
8391
8392   /* Create a temporary address map on a temporary obstack.  We later
8393      copy this to the final obstack.  */
8394   auto_obstack temp_obstack;
8395
8396   scoped_restore save_psymtabs_addrmap
8397     = make_scoped_restore (&objfile->psymtabs_addrmap,
8398                            addrmap_create_mutable (&temp_obstack));
8399
8400   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8401     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8402
8403   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8404   process_skeletonless_type_units (dwarf2_per_objfile);
8405
8406   /* Now that all TUs have been processed we can fill in the dependencies.  */
8407   if (dwarf2_per_objfile->type_unit_groups != NULL)
8408     {
8409       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8410                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8411     }
8412
8413   if (dwarf_read_debug)
8414     print_tu_stats (dwarf2_per_objfile);
8415
8416   set_partial_user (dwarf2_per_objfile);
8417
8418   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8419                                                     &objfile->objfile_obstack);
8420   /* At this point we want to keep the address map.  */
8421   save_psymtabs_addrmap.release ();
8422
8423   if (dwarf_read_debug)
8424     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8425                         objfile_name (objfile));
8426 }
8427
8428 /* die_reader_func for load_partial_comp_unit.  */
8429
8430 static void
8431 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8432                                const gdb_byte *info_ptr,
8433                                struct die_info *comp_unit_die,
8434                                int has_children,
8435                                void *data)
8436 {
8437   struct dwarf2_cu *cu = reader->cu;
8438
8439   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8440
8441   /* Check if comp unit has_children.
8442      If so, read the rest of the partial symbols from this comp unit.
8443      If not, there's no more debug_info for this comp unit.  */
8444   if (has_children)
8445     load_partial_dies (reader, info_ptr, 0);
8446 }
8447
8448 /* Load the partial DIEs for a secondary CU into memory.
8449    This is also used when rereading a primary CU with load_all_dies.  */
8450
8451 static void
8452 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8453 {
8454   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8455                            load_partial_comp_unit_reader, NULL);
8456 }
8457
8458 static void
8459 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8460                               struct dwarf2_section_info *section,
8461                               struct dwarf2_section_info *abbrev_section,
8462                               unsigned int is_dwz)
8463 {
8464   const gdb_byte *info_ptr;
8465   struct objfile *objfile = dwarf2_per_objfile->objfile;
8466
8467   if (dwarf_read_debug)
8468     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8469                         get_section_name (section),
8470                         get_section_file_name (section));
8471
8472   dwarf2_read_section (objfile, section);
8473
8474   info_ptr = section->buffer;
8475
8476   while (info_ptr < section->buffer + section->size)
8477     {
8478       struct dwarf2_per_cu_data *this_cu;
8479
8480       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8481
8482       comp_unit_head cu_header;
8483       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8484                                      abbrev_section, info_ptr,
8485                                      rcuh_kind::COMPILE);
8486
8487       /* Save the compilation unit for later lookup.  */
8488       if (cu_header.unit_type != DW_UT_type)
8489         {
8490           this_cu = XOBNEW (&objfile->objfile_obstack,
8491                             struct dwarf2_per_cu_data);
8492           memset (this_cu, 0, sizeof (*this_cu));
8493         }
8494       else
8495         {
8496           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8497                                   struct signatured_type);
8498           memset (sig_type, 0, sizeof (*sig_type));
8499           sig_type->signature = cu_header.signature;
8500           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8501           this_cu = &sig_type->per_cu;
8502         }
8503       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8504       this_cu->sect_off = sect_off;
8505       this_cu->length = cu_header.length + cu_header.initial_length_size;
8506       this_cu->is_dwz = is_dwz;
8507       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8508       this_cu->section = section;
8509
8510       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8511
8512       info_ptr = info_ptr + this_cu->length;
8513     }
8514 }
8515
8516 /* Create a list of all compilation units in OBJFILE.
8517    This is only done for -readnow and building partial symtabs.  */
8518
8519 static void
8520 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8521 {
8522   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8523   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8524                                 &dwarf2_per_objfile->abbrev, 0);
8525
8526   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8527   if (dwz != NULL)
8528     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8529                                   1);
8530 }
8531
8532 /* Process all loaded DIEs for compilation unit CU, starting at
8533    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8534    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8535    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8536    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8537
8538 static void
8539 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8540                       CORE_ADDR *highpc, int set_addrmap,
8541                       struct dwarf2_cu *cu)
8542 {
8543   struct partial_die_info *pdi;
8544
8545   /* Now, march along the PDI's, descending into ones which have
8546      interesting children but skipping the children of the other ones,
8547      until we reach the end of the compilation unit.  */
8548
8549   pdi = first_die;
8550
8551   while (pdi != NULL)
8552     {
8553       pdi->fixup (cu);
8554
8555       /* Anonymous namespaces or modules have no name but have interesting
8556          children, so we need to look at them.  Ditto for anonymous
8557          enums.  */
8558
8559       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8560           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8561           || pdi->tag == DW_TAG_imported_unit
8562           || pdi->tag == DW_TAG_inlined_subroutine)
8563         {
8564           switch (pdi->tag)
8565             {
8566             case DW_TAG_subprogram:
8567             case DW_TAG_inlined_subroutine:
8568               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8569               break;
8570             case DW_TAG_constant:
8571             case DW_TAG_variable:
8572             case DW_TAG_typedef:
8573             case DW_TAG_union_type:
8574               if (!pdi->is_declaration)
8575                 {
8576                   add_partial_symbol (pdi, cu);
8577                 }
8578               break;
8579             case DW_TAG_class_type:
8580             case DW_TAG_interface_type:
8581             case DW_TAG_structure_type:
8582               if (!pdi->is_declaration)
8583                 {
8584                   add_partial_symbol (pdi, cu);
8585                 }
8586               if ((cu->language == language_rust
8587                    || cu->language == language_cplus) && pdi->has_children)
8588                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8589                                       set_addrmap, cu);
8590               break;
8591             case DW_TAG_enumeration_type:
8592               if (!pdi->is_declaration)
8593                 add_partial_enumeration (pdi, cu);
8594               break;
8595             case DW_TAG_base_type:
8596             case DW_TAG_subrange_type:
8597               /* File scope base type definitions are added to the partial
8598                  symbol table.  */
8599               add_partial_symbol (pdi, cu);
8600               break;
8601             case DW_TAG_namespace:
8602               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8603               break;
8604             case DW_TAG_module:
8605               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8606               break;
8607             case DW_TAG_imported_unit:
8608               {
8609                 struct dwarf2_per_cu_data *per_cu;
8610
8611                 /* For now we don't handle imported units in type units.  */
8612                 if (cu->per_cu->is_debug_types)
8613                   {
8614                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8615                              " supported in type units [in module %s]"),
8616                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8617                   }
8618
8619                 per_cu = dwarf2_find_containing_comp_unit
8620                            (pdi->d.sect_off, pdi->is_dwz,
8621                             cu->per_cu->dwarf2_per_objfile);
8622
8623                 /* Go read the partial unit, if needed.  */
8624                 if (per_cu->v.psymtab == NULL)
8625                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8626
8627                 VEC_safe_push (dwarf2_per_cu_ptr,
8628                                cu->per_cu->imported_symtabs, per_cu);
8629               }
8630               break;
8631             case DW_TAG_imported_declaration:
8632               add_partial_symbol (pdi, cu);
8633               break;
8634             default:
8635               break;
8636             }
8637         }
8638
8639       /* If the die has a sibling, skip to the sibling.  */
8640
8641       pdi = pdi->die_sibling;
8642     }
8643 }
8644
8645 /* Functions used to compute the fully scoped name of a partial DIE.
8646
8647    Normally, this is simple.  For C++, the parent DIE's fully scoped
8648    name is concatenated with "::" and the partial DIE's name.
8649    Enumerators are an exception; they use the scope of their parent
8650    enumeration type, i.e. the name of the enumeration type is not
8651    prepended to the enumerator.
8652
8653    There are two complexities.  One is DW_AT_specification; in this
8654    case "parent" means the parent of the target of the specification,
8655    instead of the direct parent of the DIE.  The other is compilers
8656    which do not emit DW_TAG_namespace; in this case we try to guess
8657    the fully qualified name of structure types from their members'
8658    linkage names.  This must be done using the DIE's children rather
8659    than the children of any DW_AT_specification target.  We only need
8660    to do this for structures at the top level, i.e. if the target of
8661    any DW_AT_specification (if any; otherwise the DIE itself) does not
8662    have a parent.  */
8663
8664 /* Compute the scope prefix associated with PDI's parent, in
8665    compilation unit CU.  The result will be allocated on CU's
8666    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8667    field.  NULL is returned if no prefix is necessary.  */
8668 static const char *
8669 partial_die_parent_scope (struct partial_die_info *pdi,
8670                           struct dwarf2_cu *cu)
8671 {
8672   const char *grandparent_scope;
8673   struct partial_die_info *parent, *real_pdi;
8674
8675   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8676      then this means the parent of the specification DIE.  */
8677
8678   real_pdi = pdi;
8679   while (real_pdi->has_specification)
8680     real_pdi = find_partial_die (real_pdi->spec_offset,
8681                                  real_pdi->spec_is_dwz, cu);
8682
8683   parent = real_pdi->die_parent;
8684   if (parent == NULL)
8685     return NULL;
8686
8687   if (parent->scope_set)
8688     return parent->scope;
8689
8690   parent->fixup (cu);
8691
8692   grandparent_scope = partial_die_parent_scope (parent, cu);
8693
8694   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8695      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8696      Work around this problem here.  */
8697   if (cu->language == language_cplus
8698       && parent->tag == DW_TAG_namespace
8699       && strcmp (parent->name, "::") == 0
8700       && grandparent_scope == NULL)
8701     {
8702       parent->scope = NULL;
8703       parent->scope_set = 1;
8704       return NULL;
8705     }
8706
8707   if (pdi->tag == DW_TAG_enumerator)
8708     /* Enumerators should not get the name of the enumeration as a prefix.  */
8709     parent->scope = grandparent_scope;
8710   else if (parent->tag == DW_TAG_namespace
8711       || parent->tag == DW_TAG_module
8712       || parent->tag == DW_TAG_structure_type
8713       || parent->tag == DW_TAG_class_type
8714       || parent->tag == DW_TAG_interface_type
8715       || parent->tag == DW_TAG_union_type
8716       || parent->tag == DW_TAG_enumeration_type)
8717     {
8718       if (grandparent_scope == NULL)
8719         parent->scope = parent->name;
8720       else
8721         parent->scope = typename_concat (&cu->comp_unit_obstack,
8722                                          grandparent_scope,
8723                                          parent->name, 0, cu);
8724     }
8725   else
8726     {
8727       /* FIXME drow/2004-04-01: What should we be doing with
8728          function-local names?  For partial symbols, we should probably be
8729          ignoring them.  */
8730       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8731                  parent->tag, sect_offset_str (pdi->sect_off));
8732       parent->scope = grandparent_scope;
8733     }
8734
8735   parent->scope_set = 1;
8736   return parent->scope;
8737 }
8738
8739 /* Return the fully scoped name associated with PDI, from compilation unit
8740    CU.  The result will be allocated with malloc.  */
8741
8742 static char *
8743 partial_die_full_name (struct partial_die_info *pdi,
8744                        struct dwarf2_cu *cu)
8745 {
8746   const char *parent_scope;
8747
8748   /* If this is a template instantiation, we can not work out the
8749      template arguments from partial DIEs.  So, unfortunately, we have
8750      to go through the full DIEs.  At least any work we do building
8751      types here will be reused if full symbols are loaded later.  */
8752   if (pdi->has_template_arguments)
8753     {
8754       pdi->fixup (cu);
8755
8756       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8757         {
8758           struct die_info *die;
8759           struct attribute attr;
8760           struct dwarf2_cu *ref_cu = cu;
8761
8762           /* DW_FORM_ref_addr is using section offset.  */
8763           attr.name = (enum dwarf_attribute) 0;
8764           attr.form = DW_FORM_ref_addr;
8765           attr.u.unsnd = to_underlying (pdi->sect_off);
8766           die = follow_die_ref (NULL, &attr, &ref_cu);
8767
8768           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8769         }
8770     }
8771
8772   parent_scope = partial_die_parent_scope (pdi, cu);
8773   if (parent_scope == NULL)
8774     return NULL;
8775   else
8776     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8777 }
8778
8779 static void
8780 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8781 {
8782   struct dwarf2_per_objfile *dwarf2_per_objfile
8783     = cu->per_cu->dwarf2_per_objfile;
8784   struct objfile *objfile = dwarf2_per_objfile->objfile;
8785   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8786   CORE_ADDR addr = 0;
8787   const char *actual_name = NULL;
8788   CORE_ADDR baseaddr;
8789   char *built_actual_name;
8790
8791   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8792
8793   built_actual_name = partial_die_full_name (pdi, cu);
8794   if (built_actual_name != NULL)
8795     actual_name = built_actual_name;
8796
8797   if (actual_name == NULL)
8798     actual_name = pdi->name;
8799
8800   switch (pdi->tag)
8801     {
8802     case DW_TAG_inlined_subroutine:
8803     case DW_TAG_subprogram:
8804       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8805       if (pdi->is_external || cu->language == language_ada)
8806         {
8807           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8808              of the global scope.  But in Ada, we want to be able to access
8809              nested procedures globally.  So all Ada subprograms are stored
8810              in the global scope.  */
8811           add_psymbol_to_list (actual_name, strlen (actual_name),
8812                                built_actual_name != NULL,
8813                                VAR_DOMAIN, LOC_BLOCK,
8814                                &objfile->global_psymbols,
8815                                addr, cu->language, objfile);
8816         }
8817       else
8818         {
8819           add_psymbol_to_list (actual_name, strlen (actual_name),
8820                                built_actual_name != NULL,
8821                                VAR_DOMAIN, LOC_BLOCK,
8822                                &objfile->static_psymbols,
8823                                addr, cu->language, objfile);
8824         }
8825
8826       if (pdi->main_subprogram && actual_name != NULL)
8827         set_objfile_main_name (objfile, actual_name, cu->language);
8828       break;
8829     case DW_TAG_constant:
8830       {
8831         std::vector<partial_symbol *> *list;
8832
8833         if (pdi->is_external)
8834           list = &objfile->global_psymbols;
8835         else
8836           list = &objfile->static_psymbols;
8837         add_psymbol_to_list (actual_name, strlen (actual_name),
8838                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8839                              list, 0, cu->language, objfile);
8840       }
8841       break;
8842     case DW_TAG_variable:
8843       if (pdi->d.locdesc)
8844         addr = decode_locdesc (pdi->d.locdesc, cu);
8845
8846       if (pdi->d.locdesc
8847           && addr == 0
8848           && !dwarf2_per_objfile->has_section_at_zero)
8849         {
8850           /* A global or static variable may also have been stripped
8851              out by the linker if unused, in which case its address
8852              will be nullified; do not add such variables into partial
8853              symbol table then.  */
8854         }
8855       else if (pdi->is_external)
8856         {
8857           /* Global Variable.
8858              Don't enter into the minimal symbol tables as there is
8859              a minimal symbol table entry from the ELF symbols already.
8860              Enter into partial symbol table if it has a location
8861              descriptor or a type.
8862              If the location descriptor is missing, new_symbol will create
8863              a LOC_UNRESOLVED symbol, the address of the variable will then
8864              be determined from the minimal symbol table whenever the variable
8865              is referenced.
8866              The address for the partial symbol table entry is not
8867              used by GDB, but it comes in handy for debugging partial symbol
8868              table building.  */
8869
8870           if (pdi->d.locdesc || pdi->has_type)
8871             add_psymbol_to_list (actual_name, strlen (actual_name),
8872                                  built_actual_name != NULL,
8873                                  VAR_DOMAIN, LOC_STATIC,
8874                                  &objfile->global_psymbols,
8875                                  addr + baseaddr,
8876                                  cu->language, objfile);
8877         }
8878       else
8879         {
8880           int has_loc = pdi->d.locdesc != NULL;
8881
8882           /* Static Variable.  Skip symbols whose value we cannot know (those
8883              without location descriptors or constant values).  */
8884           if (!has_loc && !pdi->has_const_value)
8885             {
8886               xfree (built_actual_name);
8887               return;
8888             }
8889
8890           add_psymbol_to_list (actual_name, strlen (actual_name),
8891                                built_actual_name != NULL,
8892                                VAR_DOMAIN, LOC_STATIC,
8893                                &objfile->static_psymbols,
8894                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8895                                cu->language, objfile);
8896         }
8897       break;
8898     case DW_TAG_typedef:
8899     case DW_TAG_base_type:
8900     case DW_TAG_subrange_type:
8901       add_psymbol_to_list (actual_name, strlen (actual_name),
8902                            built_actual_name != NULL,
8903                            VAR_DOMAIN, LOC_TYPEDEF,
8904                            &objfile->static_psymbols,
8905                            0, cu->language, objfile);
8906       break;
8907     case DW_TAG_imported_declaration:
8908     case DW_TAG_namespace:
8909       add_psymbol_to_list (actual_name, strlen (actual_name),
8910                            built_actual_name != NULL,
8911                            VAR_DOMAIN, LOC_TYPEDEF,
8912                            &objfile->global_psymbols,
8913                            0, cu->language, objfile);
8914       break;
8915     case DW_TAG_module:
8916       add_psymbol_to_list (actual_name, strlen (actual_name),
8917                            built_actual_name != NULL,
8918                            MODULE_DOMAIN, LOC_TYPEDEF,
8919                            &objfile->global_psymbols,
8920                            0, cu->language, objfile);
8921       break;
8922     case DW_TAG_class_type:
8923     case DW_TAG_interface_type:
8924     case DW_TAG_structure_type:
8925     case DW_TAG_union_type:
8926     case DW_TAG_enumeration_type:
8927       /* Skip external references.  The DWARF standard says in the section
8928          about "Structure, Union, and Class Type Entries": "An incomplete
8929          structure, union or class type is represented by a structure,
8930          union or class entry that does not have a byte size attribute
8931          and that has a DW_AT_declaration attribute."  */
8932       if (!pdi->has_byte_size && pdi->is_declaration)
8933         {
8934           xfree (built_actual_name);
8935           return;
8936         }
8937
8938       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8939          static vs. global.  */
8940       add_psymbol_to_list (actual_name, strlen (actual_name),
8941                            built_actual_name != NULL,
8942                            STRUCT_DOMAIN, LOC_TYPEDEF,
8943                            cu->language == language_cplus
8944                            ? &objfile->global_psymbols
8945                            : &objfile->static_psymbols,
8946                            0, cu->language, objfile);
8947
8948       break;
8949     case DW_TAG_enumerator:
8950       add_psymbol_to_list (actual_name, strlen (actual_name),
8951                            built_actual_name != NULL,
8952                            VAR_DOMAIN, LOC_CONST,
8953                            cu->language == language_cplus
8954                            ? &objfile->global_psymbols
8955                            : &objfile->static_psymbols,
8956                            0, cu->language, objfile);
8957       break;
8958     default:
8959       break;
8960     }
8961
8962   xfree (built_actual_name);
8963 }
8964
8965 /* Read a partial die corresponding to a namespace; also, add a symbol
8966    corresponding to that namespace to the symbol table.  NAMESPACE is
8967    the name of the enclosing namespace.  */
8968
8969 static void
8970 add_partial_namespace (struct partial_die_info *pdi,
8971                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8972                        int set_addrmap, struct dwarf2_cu *cu)
8973 {
8974   /* Add a symbol for the namespace.  */
8975
8976   add_partial_symbol (pdi, cu);
8977
8978   /* Now scan partial symbols in that namespace.  */
8979
8980   if (pdi->has_children)
8981     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8982 }
8983
8984 /* Read a partial die corresponding to a Fortran module.  */
8985
8986 static void
8987 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8988                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8989 {
8990   /* Add a symbol for the namespace.  */
8991
8992   add_partial_symbol (pdi, cu);
8993
8994   /* Now scan partial symbols in that module.  */
8995
8996   if (pdi->has_children)
8997     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8998 }
8999
9000 /* Read a partial die corresponding to a subprogram or an inlined
9001    subprogram and create a partial symbol for that subprogram.
9002    When the CU language allows it, this routine also defines a partial
9003    symbol for each nested subprogram that this subprogram contains.
9004    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9005    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9006
9007    PDI may also be a lexical block, in which case we simply search
9008    recursively for subprograms defined inside that lexical block.
9009    Again, this is only performed when the CU language allows this
9010    type of definitions.  */
9011
9012 static void
9013 add_partial_subprogram (struct partial_die_info *pdi,
9014                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9015                         int set_addrmap, struct dwarf2_cu *cu)
9016 {
9017   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9018     {
9019       if (pdi->has_pc_info)
9020         {
9021           if (pdi->lowpc < *lowpc)
9022             *lowpc = pdi->lowpc;
9023           if (pdi->highpc > *highpc)
9024             *highpc = pdi->highpc;
9025           if (set_addrmap)
9026             {
9027               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9028               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9029               CORE_ADDR baseaddr;
9030               CORE_ADDR highpc;
9031               CORE_ADDR lowpc;
9032
9033               baseaddr = ANOFFSET (objfile->section_offsets,
9034                                    SECT_OFF_TEXT (objfile));
9035               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9036                                                   pdi->lowpc + baseaddr);
9037               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9038                                                    pdi->highpc + baseaddr);
9039               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9040                                  cu->per_cu->v.psymtab);
9041             }
9042         }
9043
9044       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9045         {
9046           if (!pdi->is_declaration)
9047             /* Ignore subprogram DIEs that do not have a name, they are
9048                illegal.  Do not emit a complaint at this point, we will
9049                do so when we convert this psymtab into a symtab.  */
9050             if (pdi->name)
9051               add_partial_symbol (pdi, cu);
9052         }
9053     }
9054
9055   if (! pdi->has_children)
9056     return;
9057
9058   if (cu->language == language_ada)
9059     {
9060       pdi = pdi->die_child;
9061       while (pdi != NULL)
9062         {
9063           pdi->fixup (cu);
9064           if (pdi->tag == DW_TAG_subprogram
9065               || pdi->tag == DW_TAG_inlined_subroutine
9066               || pdi->tag == DW_TAG_lexical_block)
9067             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9068           pdi = pdi->die_sibling;
9069         }
9070     }
9071 }
9072
9073 /* Read a partial die corresponding to an enumeration type.  */
9074
9075 static void
9076 add_partial_enumeration (struct partial_die_info *enum_pdi,
9077                          struct dwarf2_cu *cu)
9078 {
9079   struct partial_die_info *pdi;
9080
9081   if (enum_pdi->name != NULL)
9082     add_partial_symbol (enum_pdi, cu);
9083
9084   pdi = enum_pdi->die_child;
9085   while (pdi)
9086     {
9087       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9088         complaint (_("malformed enumerator DIE ignored"));
9089       else
9090         add_partial_symbol (pdi, cu);
9091       pdi = pdi->die_sibling;
9092     }
9093 }
9094
9095 /* Return the initial uleb128 in the die at INFO_PTR.  */
9096
9097 static unsigned int
9098 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9099 {
9100   unsigned int bytes_read;
9101
9102   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9103 }
9104
9105 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9106    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9107
9108    Return the corresponding abbrev, or NULL if the number is zero (indicating
9109    an empty DIE).  In either case *BYTES_READ will be set to the length of
9110    the initial number.  */
9111
9112 static struct abbrev_info *
9113 peek_die_abbrev (const die_reader_specs &reader,
9114                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9115 {
9116   dwarf2_cu *cu = reader.cu;
9117   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9118   unsigned int abbrev_number
9119     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9120
9121   if (abbrev_number == 0)
9122     return NULL;
9123
9124   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9125   if (!abbrev)
9126     {
9127       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9128                " at offset %s [in module %s]"),
9129              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9130              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9131     }
9132
9133   return abbrev;
9134 }
9135
9136 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9137    Returns a pointer to the end of a series of DIEs, terminated by an empty
9138    DIE.  Any children of the skipped DIEs will also be skipped.  */
9139
9140 static const gdb_byte *
9141 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9142 {
9143   while (1)
9144     {
9145       unsigned int bytes_read;
9146       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9147
9148       if (abbrev == NULL)
9149         return info_ptr + bytes_read;
9150       else
9151         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9152     }
9153 }
9154
9155 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9156    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9157    abbrev corresponding to that skipped uleb128 should be passed in
9158    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9159    children.  */
9160
9161 static const gdb_byte *
9162 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9163               struct abbrev_info *abbrev)
9164 {
9165   unsigned int bytes_read;
9166   struct attribute attr;
9167   bfd *abfd = reader->abfd;
9168   struct dwarf2_cu *cu = reader->cu;
9169   const gdb_byte *buffer = reader->buffer;
9170   const gdb_byte *buffer_end = reader->buffer_end;
9171   unsigned int form, i;
9172
9173   for (i = 0; i < abbrev->num_attrs; i++)
9174     {
9175       /* The only abbrev we care about is DW_AT_sibling.  */
9176       if (abbrev->attrs[i].name == DW_AT_sibling)
9177         {
9178           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9179           if (attr.form == DW_FORM_ref_addr)
9180             complaint (_("ignoring absolute DW_AT_sibling"));
9181           else
9182             {
9183               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9184               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9185
9186               if (sibling_ptr < info_ptr)
9187                 complaint (_("DW_AT_sibling points backwards"));
9188               else if (sibling_ptr > reader->buffer_end)
9189                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9190               else
9191                 return sibling_ptr;
9192             }
9193         }
9194
9195       /* If it isn't DW_AT_sibling, skip this attribute.  */
9196       form = abbrev->attrs[i].form;
9197     skip_attribute:
9198       switch (form)
9199         {
9200         case DW_FORM_ref_addr:
9201           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9202              and later it is offset sized.  */
9203           if (cu->header.version == 2)
9204             info_ptr += cu->header.addr_size;
9205           else
9206             info_ptr += cu->header.offset_size;
9207           break;
9208         case DW_FORM_GNU_ref_alt:
9209           info_ptr += cu->header.offset_size;
9210           break;
9211         case DW_FORM_addr:
9212           info_ptr += cu->header.addr_size;
9213           break;
9214         case DW_FORM_data1:
9215         case DW_FORM_ref1:
9216         case DW_FORM_flag:
9217           info_ptr += 1;
9218           break;
9219         case DW_FORM_flag_present:
9220         case DW_FORM_implicit_const:
9221           break;
9222         case DW_FORM_data2:
9223         case DW_FORM_ref2:
9224           info_ptr += 2;
9225           break;
9226         case DW_FORM_data4:
9227         case DW_FORM_ref4:
9228           info_ptr += 4;
9229           break;
9230         case DW_FORM_data8:
9231         case DW_FORM_ref8:
9232         case DW_FORM_ref_sig8:
9233           info_ptr += 8;
9234           break;
9235         case DW_FORM_data16:
9236           info_ptr += 16;
9237           break;
9238         case DW_FORM_string:
9239           read_direct_string (abfd, info_ptr, &bytes_read);
9240           info_ptr += bytes_read;
9241           break;
9242         case DW_FORM_sec_offset:
9243         case DW_FORM_strp:
9244         case DW_FORM_GNU_strp_alt:
9245           info_ptr += cu->header.offset_size;
9246           break;
9247         case DW_FORM_exprloc:
9248         case DW_FORM_block:
9249           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9250           info_ptr += bytes_read;
9251           break;
9252         case DW_FORM_block1:
9253           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9254           break;
9255         case DW_FORM_block2:
9256           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9257           break;
9258         case DW_FORM_block4:
9259           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9260           break;
9261         case DW_FORM_sdata:
9262         case DW_FORM_udata:
9263         case DW_FORM_ref_udata:
9264         case DW_FORM_GNU_addr_index:
9265         case DW_FORM_GNU_str_index:
9266           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9267           break;
9268         case DW_FORM_indirect:
9269           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9270           info_ptr += bytes_read;
9271           /* We need to continue parsing from here, so just go back to
9272              the top.  */
9273           goto skip_attribute;
9274
9275         default:
9276           error (_("Dwarf Error: Cannot handle %s "
9277                    "in DWARF reader [in module %s]"),
9278                  dwarf_form_name (form),
9279                  bfd_get_filename (abfd));
9280         }
9281     }
9282
9283   if (abbrev->has_children)
9284     return skip_children (reader, info_ptr);
9285   else
9286     return info_ptr;
9287 }
9288
9289 /* Locate ORIG_PDI's sibling.
9290    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9291
9292 static const gdb_byte *
9293 locate_pdi_sibling (const struct die_reader_specs *reader,
9294                     struct partial_die_info *orig_pdi,
9295                     const gdb_byte *info_ptr)
9296 {
9297   /* Do we know the sibling already?  */
9298
9299   if (orig_pdi->sibling)
9300     return orig_pdi->sibling;
9301
9302   /* Are there any children to deal with?  */
9303
9304   if (!orig_pdi->has_children)
9305     return info_ptr;
9306
9307   /* Skip the children the long way.  */
9308
9309   return skip_children (reader, info_ptr);
9310 }
9311
9312 /* Expand this partial symbol table into a full symbol table.  SELF is
9313    not NULL.  */
9314
9315 static void
9316 dwarf2_read_symtab (struct partial_symtab *self,
9317                     struct objfile *objfile)
9318 {
9319   struct dwarf2_per_objfile *dwarf2_per_objfile
9320     = get_dwarf2_per_objfile (objfile);
9321
9322   if (self->readin)
9323     {
9324       warning (_("bug: psymtab for %s is already read in."),
9325                self->filename);
9326     }
9327   else
9328     {
9329       if (info_verbose)
9330         {
9331           printf_filtered (_("Reading in symbols for %s..."),
9332                            self->filename);
9333           gdb_flush (gdb_stdout);
9334         }
9335
9336       /* If this psymtab is constructed from a debug-only objfile, the
9337          has_section_at_zero flag will not necessarily be correct.  We
9338          can get the correct value for this flag by looking at the data
9339          associated with the (presumably stripped) associated objfile.  */
9340       if (objfile->separate_debug_objfile_backlink)
9341         {
9342           struct dwarf2_per_objfile *dpo_backlink
9343             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9344
9345           dwarf2_per_objfile->has_section_at_zero
9346             = dpo_backlink->has_section_at_zero;
9347         }
9348
9349       dwarf2_per_objfile->reading_partial_symbols = 0;
9350
9351       psymtab_to_symtab_1 (self);
9352
9353       /* Finish up the debug error message.  */
9354       if (info_verbose)
9355         printf_filtered (_("done.\n"));
9356     }
9357
9358   process_cu_includes (dwarf2_per_objfile);
9359 }
9360 \f
9361 /* Reading in full CUs.  */
9362
9363 /* Add PER_CU to the queue.  */
9364
9365 static void
9366 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9367                  enum language pretend_language)
9368 {
9369   struct dwarf2_queue_item *item;
9370
9371   per_cu->queued = 1;
9372   item = XNEW (struct dwarf2_queue_item);
9373   item->per_cu = per_cu;
9374   item->pretend_language = pretend_language;
9375   item->next = NULL;
9376
9377   if (dwarf2_queue == NULL)
9378     dwarf2_queue = item;
9379   else
9380     dwarf2_queue_tail->next = item;
9381
9382   dwarf2_queue_tail = item;
9383 }
9384
9385 /* If PER_CU is not yet queued, add it to the queue.
9386    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9387    dependency.
9388    The result is non-zero if PER_CU was queued, otherwise the result is zero
9389    meaning either PER_CU is already queued or it is already loaded.
9390
9391    N.B. There is an invariant here that if a CU is queued then it is loaded.
9392    The caller is required to load PER_CU if we return non-zero.  */
9393
9394 static int
9395 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9396                        struct dwarf2_per_cu_data *per_cu,
9397                        enum language pretend_language)
9398 {
9399   /* We may arrive here during partial symbol reading, if we need full
9400      DIEs to process an unusual case (e.g. template arguments).  Do
9401      not queue PER_CU, just tell our caller to load its DIEs.  */
9402   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9403     {
9404       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9405         return 1;
9406       return 0;
9407     }
9408
9409   /* Mark the dependence relation so that we don't flush PER_CU
9410      too early.  */
9411   if (dependent_cu != NULL)
9412     dwarf2_add_dependence (dependent_cu, per_cu);
9413
9414   /* If it's already on the queue, we have nothing to do.  */
9415   if (per_cu->queued)
9416     return 0;
9417
9418   /* If the compilation unit is already loaded, just mark it as
9419      used.  */
9420   if (per_cu->cu != NULL)
9421     {
9422       per_cu->cu->last_used = 0;
9423       return 0;
9424     }
9425
9426   /* Add it to the queue.  */
9427   queue_comp_unit (per_cu, pretend_language);
9428
9429   return 1;
9430 }
9431
9432 /* Process the queue.  */
9433
9434 static void
9435 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9436 {
9437   struct dwarf2_queue_item *item, *next_item;
9438
9439   if (dwarf_read_debug)
9440     {
9441       fprintf_unfiltered (gdb_stdlog,
9442                           "Expanding one or more symtabs of objfile %s ...\n",
9443                           objfile_name (dwarf2_per_objfile->objfile));
9444     }
9445
9446   /* The queue starts out with one item, but following a DIE reference
9447      may load a new CU, adding it to the end of the queue.  */
9448   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9449     {
9450       if ((dwarf2_per_objfile->using_index
9451            ? !item->per_cu->v.quick->compunit_symtab
9452            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9453           /* Skip dummy CUs.  */
9454           && item->per_cu->cu != NULL)
9455         {
9456           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9457           unsigned int debug_print_threshold;
9458           char buf[100];
9459
9460           if (per_cu->is_debug_types)
9461             {
9462               struct signatured_type *sig_type =
9463                 (struct signatured_type *) per_cu;
9464
9465               sprintf (buf, "TU %s at offset %s",
9466                        hex_string (sig_type->signature),
9467                        sect_offset_str (per_cu->sect_off));
9468               /* There can be 100s of TUs.
9469                  Only print them in verbose mode.  */
9470               debug_print_threshold = 2;
9471             }
9472           else
9473             {
9474               sprintf (buf, "CU at offset %s",
9475                        sect_offset_str (per_cu->sect_off));
9476               debug_print_threshold = 1;
9477             }
9478
9479           if (dwarf_read_debug >= debug_print_threshold)
9480             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9481
9482           if (per_cu->is_debug_types)
9483             process_full_type_unit (per_cu, item->pretend_language);
9484           else
9485             process_full_comp_unit (per_cu, item->pretend_language);
9486
9487           if (dwarf_read_debug >= debug_print_threshold)
9488             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9489         }
9490
9491       item->per_cu->queued = 0;
9492       next_item = item->next;
9493       xfree (item);
9494     }
9495
9496   dwarf2_queue_tail = NULL;
9497
9498   if (dwarf_read_debug)
9499     {
9500       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9501                           objfile_name (dwarf2_per_objfile->objfile));
9502     }
9503 }
9504
9505 /* Read in full symbols for PST, and anything it depends on.  */
9506
9507 static void
9508 psymtab_to_symtab_1 (struct partial_symtab *pst)
9509 {
9510   struct dwarf2_per_cu_data *per_cu;
9511   int i;
9512
9513   if (pst->readin)
9514     return;
9515
9516   for (i = 0; i < pst->number_of_dependencies; i++)
9517     if (!pst->dependencies[i]->readin
9518         && pst->dependencies[i]->user == NULL)
9519       {
9520         /* Inform about additional files that need to be read in.  */
9521         if (info_verbose)
9522           {
9523             /* FIXME: i18n: Need to make this a single string.  */
9524             fputs_filtered (" ", gdb_stdout);
9525             wrap_here ("");
9526             fputs_filtered ("and ", gdb_stdout);
9527             wrap_here ("");
9528             printf_filtered ("%s...", pst->dependencies[i]->filename);
9529             wrap_here ("");     /* Flush output.  */
9530             gdb_flush (gdb_stdout);
9531           }
9532         psymtab_to_symtab_1 (pst->dependencies[i]);
9533       }
9534
9535   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9536
9537   if (per_cu == NULL)
9538     {
9539       /* It's an include file, no symbols to read for it.
9540          Everything is in the parent symtab.  */
9541       pst->readin = 1;
9542       return;
9543     }
9544
9545   dw2_do_instantiate_symtab (per_cu, false);
9546 }
9547
9548 /* Trivial hash function for die_info: the hash value of a DIE
9549    is its offset in .debug_info for this objfile.  */
9550
9551 static hashval_t
9552 die_hash (const void *item)
9553 {
9554   const struct die_info *die = (const struct die_info *) item;
9555
9556   return to_underlying (die->sect_off);
9557 }
9558
9559 /* Trivial comparison function for die_info structures: two DIEs
9560    are equal if they have the same offset.  */
9561
9562 static int
9563 die_eq (const void *item_lhs, const void *item_rhs)
9564 {
9565   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9566   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9567
9568   return die_lhs->sect_off == die_rhs->sect_off;
9569 }
9570
9571 /* die_reader_func for load_full_comp_unit.
9572    This is identical to read_signatured_type_reader,
9573    but is kept separate for now.  */
9574
9575 static void
9576 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9577                             const gdb_byte *info_ptr,
9578                             struct die_info *comp_unit_die,
9579                             int has_children,
9580                             void *data)
9581 {
9582   struct dwarf2_cu *cu = reader->cu;
9583   enum language *language_ptr = (enum language *) data;
9584
9585   gdb_assert (cu->die_hash == NULL);
9586   cu->die_hash =
9587     htab_create_alloc_ex (cu->header.length / 12,
9588                           die_hash,
9589                           die_eq,
9590                           NULL,
9591                           &cu->comp_unit_obstack,
9592                           hashtab_obstack_allocate,
9593                           dummy_obstack_deallocate);
9594
9595   if (has_children)
9596     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9597                                                   &info_ptr, comp_unit_die);
9598   cu->dies = comp_unit_die;
9599   /* comp_unit_die is not stored in die_hash, no need.  */
9600
9601   /* We try not to read any attributes in this function, because not
9602      all CUs needed for references have been loaded yet, and symbol
9603      table processing isn't initialized.  But we have to set the CU language,
9604      or we won't be able to build types correctly.
9605      Similarly, if we do not read the producer, we can not apply
9606      producer-specific interpretation.  */
9607   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9608 }
9609
9610 /* Load the DIEs associated with PER_CU into memory.  */
9611
9612 static void
9613 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9614                      bool skip_partial,
9615                      enum language pretend_language)
9616 {
9617   gdb_assert (! this_cu->is_debug_types);
9618
9619   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9620                            load_full_comp_unit_reader, &pretend_language);
9621 }
9622
9623 /* Add a DIE to the delayed physname list.  */
9624
9625 static void
9626 add_to_method_list (struct type *type, int fnfield_index, int index,
9627                     const char *name, struct die_info *die,
9628                     struct dwarf2_cu *cu)
9629 {
9630   struct delayed_method_info mi;
9631   mi.type = type;
9632   mi.fnfield_index = fnfield_index;
9633   mi.index = index;
9634   mi.name = name;
9635   mi.die = die;
9636   cu->method_list.push_back (mi);
9637 }
9638
9639 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9640    "const" / "volatile".  If so, decrements LEN by the length of the
9641    modifier and return true.  Otherwise return false.  */
9642
9643 template<size_t N>
9644 static bool
9645 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9646 {
9647   size_t mod_len = sizeof (mod) - 1;
9648   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9649     {
9650       len -= mod_len;
9651       return true;
9652     }
9653   return false;
9654 }
9655
9656 /* Compute the physnames of any methods on the CU's method list.
9657
9658    The computation of method physnames is delayed in order to avoid the
9659    (bad) condition that one of the method's formal parameters is of an as yet
9660    incomplete type.  */
9661
9662 static void
9663 compute_delayed_physnames (struct dwarf2_cu *cu)
9664 {
9665   /* Only C++ delays computing physnames.  */
9666   if (cu->method_list.empty ())
9667     return;
9668   gdb_assert (cu->language == language_cplus);
9669
9670   for (const delayed_method_info &mi : cu->method_list)
9671     {
9672       const char *physname;
9673       struct fn_fieldlist *fn_flp
9674         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9675       physname = dwarf2_physname (mi.name, mi.die, cu);
9676       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9677         = physname ? physname : "";
9678
9679       /* Since there's no tag to indicate whether a method is a
9680          const/volatile overload, extract that information out of the
9681          demangled name.  */
9682       if (physname != NULL)
9683         {
9684           size_t len = strlen (physname);
9685
9686           while (1)
9687             {
9688               if (physname[len] == ')') /* shortcut */
9689                 break;
9690               else if (check_modifier (physname, len, " const"))
9691                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9692               else if (check_modifier (physname, len, " volatile"))
9693                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9694               else
9695                 break;
9696             }
9697         }
9698     }
9699
9700   /* The list is no longer needed.  */
9701   cu->method_list.clear ();
9702 }
9703
9704 /* Go objects should be embedded in a DW_TAG_module DIE,
9705    and it's not clear if/how imported objects will appear.
9706    To keep Go support simple until that's worked out,
9707    go back through what we've read and create something usable.
9708    We could do this while processing each DIE, and feels kinda cleaner,
9709    but that way is more invasive.
9710    This is to, for example, allow the user to type "p var" or "b main"
9711    without having to specify the package name, and allow lookups
9712    of module.object to work in contexts that use the expression
9713    parser.  */
9714
9715 static void
9716 fixup_go_packaging (struct dwarf2_cu *cu)
9717 {
9718   char *package_name = NULL;
9719   struct pending *list;
9720   int i;
9721
9722   for (list = global_symbols; list != NULL; list = list->next)
9723     {
9724       for (i = 0; i < list->nsyms; ++i)
9725         {
9726           struct symbol *sym = list->symbol[i];
9727
9728           if (SYMBOL_LANGUAGE (sym) == language_go
9729               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9730             {
9731               char *this_package_name = go_symbol_package_name (sym);
9732
9733               if (this_package_name == NULL)
9734                 continue;
9735               if (package_name == NULL)
9736                 package_name = this_package_name;
9737               else
9738                 {
9739                   struct objfile *objfile
9740                     = cu->per_cu->dwarf2_per_objfile->objfile;
9741                   if (strcmp (package_name, this_package_name) != 0)
9742                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9743                                (symbol_symtab (sym) != NULL
9744                                 ? symtab_to_filename_for_display
9745                                     (symbol_symtab (sym))
9746                                 : objfile_name (objfile)),
9747                                this_package_name, package_name);
9748                   xfree (this_package_name);
9749                 }
9750             }
9751         }
9752     }
9753
9754   if (package_name != NULL)
9755     {
9756       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9757       const char *saved_package_name
9758         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9759                                         package_name,
9760                                         strlen (package_name));
9761       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9762                                      saved_package_name);
9763       struct symbol *sym;
9764
9765       sym = allocate_symbol (objfile);
9766       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9767       SYMBOL_SET_NAMES (sym, saved_package_name,
9768                         strlen (saved_package_name), 0, objfile);
9769       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9770          e.g., "main" finds the "main" module and not C's main().  */
9771       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9772       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9773       SYMBOL_TYPE (sym) = type;
9774
9775       add_symbol_to_list (sym, &global_symbols);
9776
9777       xfree (package_name);
9778     }
9779 }
9780
9781 /* Allocate a fully-qualified name consisting of the two parts on the
9782    obstack.  */
9783
9784 static const char *
9785 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9786 {
9787   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9788 }
9789
9790 /* A helper that allocates a struct discriminant_info to attach to a
9791    union type.  */
9792
9793 static struct discriminant_info *
9794 alloc_discriminant_info (struct type *type, int discriminant_index,
9795                          int default_index)
9796 {
9797   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9798   gdb_assert (discriminant_index == -1
9799               || (discriminant_index >= 0
9800                   && discriminant_index < TYPE_NFIELDS (type)));
9801   gdb_assert (default_index == -1
9802               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9803
9804   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9805
9806   struct discriminant_info *disc
9807     = ((struct discriminant_info *)
9808        TYPE_ZALLOC (type,
9809                     offsetof (struct discriminant_info, discriminants)
9810                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9811   disc->default_index = default_index;
9812   disc->discriminant_index = discriminant_index;
9813
9814   struct dynamic_prop prop;
9815   prop.kind = PROP_UNDEFINED;
9816   prop.data.baton = disc;
9817
9818   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9819
9820   return disc;
9821 }
9822
9823 /* Some versions of rustc emitted enums in an unusual way.
9824
9825    Ordinary enums were emitted as unions.  The first element of each
9826    structure in the union was named "RUST$ENUM$DISR".  This element
9827    held the discriminant.
9828
9829    These versions of Rust also implemented the "non-zero"
9830    optimization.  When the enum had two values, and one is empty and
9831    the other holds a pointer that cannot be zero, the pointer is used
9832    as the discriminant, with a zero value meaning the empty variant.
9833    Here, the union's first member is of the form
9834    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9835    where the fieldnos are the indices of the fields that should be
9836    traversed in order to find the field (which may be several fields deep)
9837    and the variantname is the name of the variant of the case when the
9838    field is zero.
9839
9840    This function recognizes whether TYPE is of one of these forms,
9841    and, if so, smashes it to be a variant type.  */
9842
9843 static void
9844 quirk_rust_enum (struct type *type, struct objfile *objfile)
9845 {
9846   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9847
9848   /* We don't need to deal with empty enums.  */
9849   if (TYPE_NFIELDS (type) == 0)
9850     return;
9851
9852 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9853   if (TYPE_NFIELDS (type) == 1
9854       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9855     {
9856       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9857
9858       /* Decode the field name to find the offset of the
9859          discriminant.  */
9860       ULONGEST bit_offset = 0;
9861       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9862       while (name[0] >= '0' && name[0] <= '9')
9863         {
9864           char *tail;
9865           unsigned long index = strtoul (name, &tail, 10);
9866           name = tail;
9867           if (*name != '$'
9868               || index >= TYPE_NFIELDS (field_type)
9869               || (TYPE_FIELD_LOC_KIND (field_type, index)
9870                   != FIELD_LOC_KIND_BITPOS))
9871             {
9872               complaint (_("Could not parse Rust enum encoding string \"%s\""
9873                            "[in module %s]"),
9874                          TYPE_FIELD_NAME (type, 0),
9875                          objfile_name (objfile));
9876               return;
9877             }
9878           ++name;
9879
9880           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9881           field_type = TYPE_FIELD_TYPE (field_type, index);
9882         }
9883
9884       /* Make a union to hold the variants.  */
9885       struct type *union_type = alloc_type (objfile);
9886       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9887       TYPE_NFIELDS (union_type) = 3;
9888       TYPE_FIELDS (union_type)
9889         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9890       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9891       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9892
9893       /* Put the discriminant must at index 0.  */
9894       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9895       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9896       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9897       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9898
9899       /* The order of fields doesn't really matter, so put the real
9900          field at index 1 and the data-less field at index 2.  */
9901       struct discriminant_info *disc
9902         = alloc_discriminant_info (union_type, 0, 1);
9903       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9904       TYPE_FIELD_NAME (union_type, 1)
9905         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9906       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9907         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9908                               TYPE_FIELD_NAME (union_type, 1));
9909
9910       const char *dataless_name
9911         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9912                               name);
9913       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9914                                               dataless_name);
9915       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9916       /* NAME points into the original discriminant name, which
9917          already has the correct lifetime.  */
9918       TYPE_FIELD_NAME (union_type, 2) = name;
9919       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9920       disc->discriminants[2] = 0;
9921
9922       /* Smash this type to be a structure type.  We have to do this
9923          because the type has already been recorded.  */
9924       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9925       TYPE_NFIELDS (type) = 1;
9926       TYPE_FIELDS (type)
9927         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9928
9929       /* Install the variant part.  */
9930       TYPE_FIELD_TYPE (type, 0) = union_type;
9931       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9932       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9933     }
9934   else if (TYPE_NFIELDS (type) == 1)
9935     {
9936       /* We assume that a union with a single field is a univariant
9937          enum.  */
9938       /* Smash this type to be a structure type.  We have to do this
9939          because the type has already been recorded.  */
9940       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9941
9942       /* Make a union to hold the variants.  */
9943       struct type *union_type = alloc_type (objfile);
9944       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9945       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9946       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9947       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9948       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9949
9950       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9951       const char *variant_name
9952         = rust_last_path_segment (TYPE_NAME (field_type));
9953       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9954       TYPE_NAME (field_type)
9955         = rust_fully_qualify (&objfile->objfile_obstack,
9956                               TYPE_NAME (type), variant_name);
9957
9958       /* Install the union in the outer struct type.  */
9959       TYPE_NFIELDS (type) = 1;
9960       TYPE_FIELDS (type)
9961         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9962       TYPE_FIELD_TYPE (type, 0) = union_type;
9963       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9964       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9965
9966       alloc_discriminant_info (union_type, -1, 0);
9967     }
9968   else
9969     {
9970       struct type *disr_type = nullptr;
9971       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9972         {
9973           disr_type = TYPE_FIELD_TYPE (type, i);
9974
9975           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9976             {
9977               /* All fields of a true enum will be structs.  */
9978               return;
9979             }
9980           else if (TYPE_NFIELDS (disr_type) == 0)
9981             {
9982               /* Could be data-less variant, so keep going.  */
9983               disr_type = nullptr;
9984             }
9985           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9986                            "RUST$ENUM$DISR") != 0)
9987             {
9988               /* Not a Rust enum.  */
9989               return;
9990             }
9991           else
9992             {
9993               /* Found one.  */
9994               break;
9995             }
9996         }
9997
9998       /* If we got here without a discriminant, then it's probably
9999          just a union.  */
10000       if (disr_type == nullptr)
10001         return;
10002
10003       /* Smash this type to be a structure type.  We have to do this
10004          because the type has already been recorded.  */
10005       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10006
10007       /* Make a union to hold the variants.  */
10008       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10009       struct type *union_type = alloc_type (objfile);
10010       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10011       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10012       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10013       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10014       TYPE_FIELDS (union_type)
10015         = (struct field *) TYPE_ZALLOC (union_type,
10016                                         (TYPE_NFIELDS (union_type)
10017                                          * sizeof (struct field)));
10018
10019       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10020               TYPE_NFIELDS (type) * sizeof (struct field));
10021
10022       /* Install the discriminant at index 0 in the union.  */
10023       TYPE_FIELD (union_type, 0) = *disr_field;
10024       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10025       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10026
10027       /* Install the union in the outer struct type.  */
10028       TYPE_FIELD_TYPE (type, 0) = union_type;
10029       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10030       TYPE_NFIELDS (type) = 1;
10031
10032       /* Set the size and offset of the union type.  */
10033       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10034
10035       /* We need a way to find the correct discriminant given a
10036          variant name.  For convenience we build a map here.  */
10037       struct type *enum_type = FIELD_TYPE (*disr_field);
10038       std::unordered_map<std::string, ULONGEST> discriminant_map;
10039       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10040         {
10041           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10042             {
10043               const char *name
10044                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10045               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10046             }
10047         }
10048
10049       int n_fields = TYPE_NFIELDS (union_type);
10050       struct discriminant_info *disc
10051         = alloc_discriminant_info (union_type, 0, -1);
10052       /* Skip the discriminant here.  */
10053       for (int i = 1; i < n_fields; ++i)
10054         {
10055           /* Find the final word in the name of this variant's type.
10056              That name can be used to look up the correct
10057              discriminant.  */
10058           const char *variant_name
10059             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10060                                                                   i)));
10061
10062           auto iter = discriminant_map.find (variant_name);
10063           if (iter != discriminant_map.end ())
10064             disc->discriminants[i] = iter->second;
10065
10066           /* Remove the discriminant field, if it exists.  */
10067           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10068           if (TYPE_NFIELDS (sub_type) > 0)
10069             {
10070               --TYPE_NFIELDS (sub_type);
10071               ++TYPE_FIELDS (sub_type);
10072             }
10073           TYPE_FIELD_NAME (union_type, i) = variant_name;
10074           TYPE_NAME (sub_type)
10075             = rust_fully_qualify (&objfile->objfile_obstack,
10076                                   TYPE_NAME (type), variant_name);
10077         }
10078     }
10079 }
10080
10081 /* Rewrite some Rust unions to be structures with variants parts.  */
10082
10083 static void
10084 rust_union_quirks (struct dwarf2_cu *cu)
10085 {
10086   gdb_assert (cu->language == language_rust);
10087   for (type *type_ : cu->rust_unions)
10088     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10089   /* We don't need this any more.  */
10090   cu->rust_unions.clear ();
10091 }
10092
10093 /* Return the symtab for PER_CU.  This works properly regardless of
10094    whether we're using the index or psymtabs.  */
10095
10096 static struct compunit_symtab *
10097 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10098 {
10099   return (per_cu->dwarf2_per_objfile->using_index
10100           ? per_cu->v.quick->compunit_symtab
10101           : per_cu->v.psymtab->compunit_symtab);
10102 }
10103
10104 /* A helper function for computing the list of all symbol tables
10105    included by PER_CU.  */
10106
10107 static void
10108 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10109                                 htab_t all_children, htab_t all_type_symtabs,
10110                                 struct dwarf2_per_cu_data *per_cu,
10111                                 struct compunit_symtab *immediate_parent)
10112 {
10113   void **slot;
10114   int ix;
10115   struct compunit_symtab *cust;
10116   struct dwarf2_per_cu_data *iter;
10117
10118   slot = htab_find_slot (all_children, per_cu, INSERT);
10119   if (*slot != NULL)
10120     {
10121       /* This inclusion and its children have been processed.  */
10122       return;
10123     }
10124
10125   *slot = per_cu;
10126   /* Only add a CU if it has a symbol table.  */
10127   cust = get_compunit_symtab (per_cu);
10128   if (cust != NULL)
10129     {
10130       /* If this is a type unit only add its symbol table if we haven't
10131          seen it yet (type unit per_cu's can share symtabs).  */
10132       if (per_cu->is_debug_types)
10133         {
10134           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10135           if (*slot == NULL)
10136             {
10137               *slot = cust;
10138               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10139               if (cust->user == NULL)
10140                 cust->user = immediate_parent;
10141             }
10142         }
10143       else
10144         {
10145           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10146           if (cust->user == NULL)
10147             cust->user = immediate_parent;
10148         }
10149     }
10150
10151   for (ix = 0;
10152        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10153        ++ix)
10154     {
10155       recursively_compute_inclusions (result, all_children,
10156                                       all_type_symtabs, iter, cust);
10157     }
10158 }
10159
10160 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10161    PER_CU.  */
10162
10163 static void
10164 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10165 {
10166   gdb_assert (! per_cu->is_debug_types);
10167
10168   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10169     {
10170       int ix, len;
10171       struct dwarf2_per_cu_data *per_cu_iter;
10172       struct compunit_symtab *compunit_symtab_iter;
10173       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10174       htab_t all_children, all_type_symtabs;
10175       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10176
10177       /* If we don't have a symtab, we can just skip this case.  */
10178       if (cust == NULL)
10179         return;
10180
10181       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10182                                         NULL, xcalloc, xfree);
10183       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10184                                             NULL, xcalloc, xfree);
10185
10186       for (ix = 0;
10187            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10188                         ix, per_cu_iter);
10189            ++ix)
10190         {
10191           recursively_compute_inclusions (&result_symtabs, all_children,
10192                                           all_type_symtabs, per_cu_iter,
10193                                           cust);
10194         }
10195
10196       /* Now we have a transitive closure of all the included symtabs.  */
10197       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10198       cust->includes
10199         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10200                      struct compunit_symtab *, len + 1);
10201       for (ix = 0;
10202            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10203                         compunit_symtab_iter);
10204            ++ix)
10205         cust->includes[ix] = compunit_symtab_iter;
10206       cust->includes[len] = NULL;
10207
10208       VEC_free (compunit_symtab_ptr, result_symtabs);
10209       htab_delete (all_children);
10210       htab_delete (all_type_symtabs);
10211     }
10212 }
10213
10214 /* Compute the 'includes' field for the symtabs of all the CUs we just
10215    read.  */
10216
10217 static void
10218 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10219 {
10220   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10221     {
10222       if (! iter->is_debug_types)
10223         compute_compunit_symtab_includes (iter);
10224     }
10225
10226   dwarf2_per_objfile->just_read_cus.clear ();
10227 }
10228
10229 /* Generate full symbol information for PER_CU, whose DIEs have
10230    already been loaded into memory.  */
10231
10232 static void
10233 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10234                         enum language pretend_language)
10235 {
10236   struct dwarf2_cu *cu = per_cu->cu;
10237   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10238   struct objfile *objfile = dwarf2_per_objfile->objfile;
10239   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10240   CORE_ADDR lowpc, highpc;
10241   struct compunit_symtab *cust;
10242   CORE_ADDR baseaddr;
10243   struct block *static_block;
10244   CORE_ADDR addr;
10245
10246   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10247
10248   buildsym_init ();
10249   scoped_free_pendings free_pending;
10250
10251   /* Clear the list here in case something was left over.  */
10252   cu->method_list.clear ();
10253
10254   cu->list_in_scope = &file_symbols;
10255
10256   cu->language = pretend_language;
10257   cu->language_defn = language_def (cu->language);
10258
10259   /* Do line number decoding in read_file_scope () */
10260   process_die (cu->dies, cu);
10261
10262   /* For now fudge the Go package.  */
10263   if (cu->language == language_go)
10264     fixup_go_packaging (cu);
10265
10266   /* Now that we have processed all the DIEs in the CU, all the types 
10267      should be complete, and it should now be safe to compute all of the
10268      physnames.  */
10269   compute_delayed_physnames (cu);
10270
10271   if (cu->language == language_rust)
10272     rust_union_quirks (cu);
10273
10274   /* Some compilers don't define a DW_AT_high_pc attribute for the
10275      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10276      it, by scanning the DIE's below the compilation unit.  */
10277   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10278
10279   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10280   static_block = end_symtab_get_static_block (addr, 0, 1);
10281
10282   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10283      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10284      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10285      addrmap to help ensure it has an accurate map of pc values belonging to
10286      this comp unit.  */
10287   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10288
10289   cust = end_symtab_from_static_block (static_block,
10290                                        SECT_OFF_TEXT (objfile), 0);
10291
10292   if (cust != NULL)
10293     {
10294       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10295
10296       /* Set symtab language to language from DW_AT_language.  If the
10297          compilation is from a C file generated by language preprocessors, do
10298          not set the language if it was already deduced by start_subfile.  */
10299       if (!(cu->language == language_c
10300             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10301         COMPUNIT_FILETABS (cust)->language = cu->language;
10302
10303       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10304          produce DW_AT_location with location lists but it can be possibly
10305          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10306          there were bugs in prologue debug info, fixed later in GCC-4.5
10307          by "unwind info for epilogues" patch (which is not directly related).
10308
10309          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10310          needed, it would be wrong due to missing DW_AT_producer there.
10311
10312          Still one can confuse GDB by using non-standard GCC compilation
10313          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10314          */ 
10315       if (cu->has_loclist && gcc_4_minor >= 5)
10316         cust->locations_valid = 1;
10317
10318       if (gcc_4_minor >= 5)
10319         cust->epilogue_unwind_valid = 1;
10320
10321       cust->call_site_htab = cu->call_site_htab;
10322     }
10323
10324   if (dwarf2_per_objfile->using_index)
10325     per_cu->v.quick->compunit_symtab = cust;
10326   else
10327     {
10328       struct partial_symtab *pst = per_cu->v.psymtab;
10329       pst->compunit_symtab = cust;
10330       pst->readin = 1;
10331     }
10332
10333   /* Push it for inclusion processing later.  */
10334   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10335 }
10336
10337 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10338    already been loaded into memory.  */
10339
10340 static void
10341 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10342                         enum language pretend_language)
10343 {
10344   struct dwarf2_cu *cu = per_cu->cu;
10345   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10346   struct objfile *objfile = dwarf2_per_objfile->objfile;
10347   struct compunit_symtab *cust;
10348   struct signatured_type *sig_type;
10349
10350   gdb_assert (per_cu->is_debug_types);
10351   sig_type = (struct signatured_type *) per_cu;
10352
10353   buildsym_init ();
10354   scoped_free_pendings free_pending;
10355
10356   /* Clear the list here in case something was left over.  */
10357   cu->method_list.clear ();
10358
10359   cu->list_in_scope = &file_symbols;
10360
10361   cu->language = pretend_language;
10362   cu->language_defn = language_def (cu->language);
10363
10364   /* The symbol tables are set up in read_type_unit_scope.  */
10365   process_die (cu->dies, cu);
10366
10367   /* For now fudge the Go package.  */
10368   if (cu->language == language_go)
10369     fixup_go_packaging (cu);
10370
10371   /* Now that we have processed all the DIEs in the CU, all the types 
10372      should be complete, and it should now be safe to compute all of the
10373      physnames.  */
10374   compute_delayed_physnames (cu);
10375
10376   if (cu->language == language_rust)
10377     rust_union_quirks (cu);
10378
10379   /* TUs share symbol tables.
10380      If this is the first TU to use this symtab, complete the construction
10381      of it with end_expandable_symtab.  Otherwise, complete the addition of
10382      this TU's symbols to the existing symtab.  */
10383   if (sig_type->type_unit_group->compunit_symtab == NULL)
10384     {
10385       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10386       sig_type->type_unit_group->compunit_symtab = cust;
10387
10388       if (cust != NULL)
10389         {
10390           /* Set symtab language to language from DW_AT_language.  If the
10391              compilation is from a C file generated by language preprocessors,
10392              do not set the language if it was already deduced by
10393              start_subfile.  */
10394           if (!(cu->language == language_c
10395                 && COMPUNIT_FILETABS (cust)->language != language_c))
10396             COMPUNIT_FILETABS (cust)->language = cu->language;
10397         }
10398     }
10399   else
10400     {
10401       augment_type_symtab ();
10402       cust = sig_type->type_unit_group->compunit_symtab;
10403     }
10404
10405   if (dwarf2_per_objfile->using_index)
10406     per_cu->v.quick->compunit_symtab = cust;
10407   else
10408     {
10409       struct partial_symtab *pst = per_cu->v.psymtab;
10410       pst->compunit_symtab = cust;
10411       pst->readin = 1;
10412     }
10413 }
10414
10415 /* Process an imported unit DIE.  */
10416
10417 static void
10418 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10419 {
10420   struct attribute *attr;
10421
10422   /* For now we don't handle imported units in type units.  */
10423   if (cu->per_cu->is_debug_types)
10424     {
10425       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10426                " supported in type units [in module %s]"),
10427              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10428     }
10429
10430   attr = dwarf2_attr (die, DW_AT_import, cu);
10431   if (attr != NULL)
10432     {
10433       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10434       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10435       dwarf2_per_cu_data *per_cu
10436         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10437                                             cu->per_cu->dwarf2_per_objfile);
10438
10439       /* If necessary, add it to the queue and load its DIEs.  */
10440       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10441         load_full_comp_unit (per_cu, false, cu->language);
10442
10443       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10444                      per_cu);
10445     }
10446 }
10447
10448 /* RAII object that represents a process_die scope: i.e.,
10449    starts/finishes processing a DIE.  */
10450 class process_die_scope
10451 {
10452 public:
10453   process_die_scope (die_info *die, dwarf2_cu *cu)
10454     : m_die (die), m_cu (cu)
10455   {
10456     /* We should only be processing DIEs not already in process.  */
10457     gdb_assert (!m_die->in_process);
10458     m_die->in_process = true;
10459   }
10460
10461   ~process_die_scope ()
10462   {
10463     m_die->in_process = false;
10464
10465     /* If we're done processing the DIE for the CU that owns the line
10466        header, we don't need the line header anymore.  */
10467     if (m_cu->line_header_die_owner == m_die)
10468       {
10469         delete m_cu->line_header;
10470         m_cu->line_header = NULL;
10471         m_cu->line_header_die_owner = NULL;
10472       }
10473   }
10474
10475 private:
10476   die_info *m_die;
10477   dwarf2_cu *m_cu;
10478 };
10479
10480 /* Process a die and its children.  */
10481
10482 static void
10483 process_die (struct die_info *die, struct dwarf2_cu *cu)
10484 {
10485   process_die_scope scope (die, cu);
10486
10487   switch (die->tag)
10488     {
10489     case DW_TAG_padding:
10490       break;
10491     case DW_TAG_compile_unit:
10492     case DW_TAG_partial_unit:
10493       read_file_scope (die, cu);
10494       break;
10495     case DW_TAG_type_unit:
10496       read_type_unit_scope (die, cu);
10497       break;
10498     case DW_TAG_subprogram:
10499     case DW_TAG_inlined_subroutine:
10500       read_func_scope (die, cu);
10501       break;
10502     case DW_TAG_lexical_block:
10503     case DW_TAG_try_block:
10504     case DW_TAG_catch_block:
10505       read_lexical_block_scope (die, cu);
10506       break;
10507     case DW_TAG_call_site:
10508     case DW_TAG_GNU_call_site:
10509       read_call_site_scope (die, cu);
10510       break;
10511     case DW_TAG_class_type:
10512     case DW_TAG_interface_type:
10513     case DW_TAG_structure_type:
10514     case DW_TAG_union_type:
10515       process_structure_scope (die, cu);
10516       break;
10517     case DW_TAG_enumeration_type:
10518       process_enumeration_scope (die, cu);
10519       break;
10520
10521     /* These dies have a type, but processing them does not create
10522        a symbol or recurse to process the children.  Therefore we can
10523        read them on-demand through read_type_die.  */
10524     case DW_TAG_subroutine_type:
10525     case DW_TAG_set_type:
10526     case DW_TAG_array_type:
10527     case DW_TAG_pointer_type:
10528     case DW_TAG_ptr_to_member_type:
10529     case DW_TAG_reference_type:
10530     case DW_TAG_rvalue_reference_type:
10531     case DW_TAG_string_type:
10532       break;
10533
10534     case DW_TAG_base_type:
10535     case DW_TAG_subrange_type:
10536     case DW_TAG_typedef:
10537       /* Add a typedef symbol for the type definition, if it has a
10538          DW_AT_name.  */
10539       new_symbol (die, read_type_die (die, cu), cu);
10540       break;
10541     case DW_TAG_common_block:
10542       read_common_block (die, cu);
10543       break;
10544     case DW_TAG_common_inclusion:
10545       break;
10546     case DW_TAG_namespace:
10547       cu->processing_has_namespace_info = 1;
10548       read_namespace (die, cu);
10549       break;
10550     case DW_TAG_module:
10551       cu->processing_has_namespace_info = 1;
10552       read_module (die, cu);
10553       break;
10554     case DW_TAG_imported_declaration:
10555       cu->processing_has_namespace_info = 1;
10556       if (read_namespace_alias (die, cu))
10557         break;
10558       /* The declaration is not a global namespace alias.  */
10559       /* Fall through.  */
10560     case DW_TAG_imported_module:
10561       cu->processing_has_namespace_info = 1;
10562       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10563                                  || cu->language != language_fortran))
10564         complaint (_("Tag '%s' has unexpected children"),
10565                    dwarf_tag_name (die->tag));
10566       read_import_statement (die, cu);
10567       break;
10568
10569     case DW_TAG_imported_unit:
10570       process_imported_unit_die (die, cu);
10571       break;
10572
10573     case DW_TAG_variable:
10574       read_variable (die, cu);
10575       break;
10576
10577     default:
10578       new_symbol (die, NULL, cu);
10579       break;
10580     }
10581 }
10582 \f
10583 /* DWARF name computation.  */
10584
10585 /* A helper function for dwarf2_compute_name which determines whether DIE
10586    needs to have the name of the scope prepended to the name listed in the
10587    die.  */
10588
10589 static int
10590 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10591 {
10592   struct attribute *attr;
10593
10594   switch (die->tag)
10595     {
10596     case DW_TAG_namespace:
10597     case DW_TAG_typedef:
10598     case DW_TAG_class_type:
10599     case DW_TAG_interface_type:
10600     case DW_TAG_structure_type:
10601     case DW_TAG_union_type:
10602     case DW_TAG_enumeration_type:
10603     case DW_TAG_enumerator:
10604     case DW_TAG_subprogram:
10605     case DW_TAG_inlined_subroutine:
10606     case DW_TAG_member:
10607     case DW_TAG_imported_declaration:
10608       return 1;
10609
10610     case DW_TAG_variable:
10611     case DW_TAG_constant:
10612       /* We only need to prefix "globally" visible variables.  These include
10613          any variable marked with DW_AT_external or any variable that
10614          lives in a namespace.  [Variables in anonymous namespaces
10615          require prefixing, but they are not DW_AT_external.]  */
10616
10617       if (dwarf2_attr (die, DW_AT_specification, cu))
10618         {
10619           struct dwarf2_cu *spec_cu = cu;
10620
10621           return die_needs_namespace (die_specification (die, &spec_cu),
10622                                       spec_cu);
10623         }
10624
10625       attr = dwarf2_attr (die, DW_AT_external, cu);
10626       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10627           && die->parent->tag != DW_TAG_module)
10628         return 0;
10629       /* A variable in a lexical block of some kind does not need a
10630          namespace, even though in C++ such variables may be external
10631          and have a mangled name.  */
10632       if (die->parent->tag ==  DW_TAG_lexical_block
10633           || die->parent->tag ==  DW_TAG_try_block
10634           || die->parent->tag ==  DW_TAG_catch_block
10635           || die->parent->tag == DW_TAG_subprogram)
10636         return 0;
10637       return 1;
10638
10639     default:
10640       return 0;
10641     }
10642 }
10643
10644 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10645    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10646    defined for the given DIE.  */
10647
10648 static struct attribute *
10649 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10650 {
10651   struct attribute *attr;
10652
10653   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10654   if (attr == NULL)
10655     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10656
10657   return attr;
10658 }
10659
10660 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10661    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10662    defined for the given DIE.  */
10663
10664 static const char *
10665 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10666 {
10667   const char *linkage_name;
10668
10669   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10670   if (linkage_name == NULL)
10671     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10672
10673   return linkage_name;
10674 }
10675
10676 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10677    compute the physname for the object, which include a method's:
10678    - formal parameters (C++),
10679    - receiver type (Go),
10680
10681    The term "physname" is a bit confusing.
10682    For C++, for example, it is the demangled name.
10683    For Go, for example, it's the mangled name.
10684
10685    For Ada, return the DIE's linkage name rather than the fully qualified
10686    name.  PHYSNAME is ignored..
10687
10688    The result is allocated on the objfile_obstack and canonicalized.  */
10689
10690 static const char *
10691 dwarf2_compute_name (const char *name,
10692                      struct die_info *die, struct dwarf2_cu *cu,
10693                      int physname)
10694 {
10695   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10696
10697   if (name == NULL)
10698     name = dwarf2_name (die, cu);
10699
10700   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10701      but otherwise compute it by typename_concat inside GDB.
10702      FIXME: Actually this is not really true, or at least not always true.
10703      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10704      Fortran names because there is no mangling standard.  So new_symbol
10705      will set the demangled name to the result of dwarf2_full_name, and it is
10706      the demangled name that GDB uses if it exists.  */
10707   if (cu->language == language_ada
10708       || (cu->language == language_fortran && physname))
10709     {
10710       /* For Ada unit, we prefer the linkage name over the name, as
10711          the former contains the exported name, which the user expects
10712          to be able to reference.  Ideally, we want the user to be able
10713          to reference this entity using either natural or linkage name,
10714          but we haven't started looking at this enhancement yet.  */
10715       const char *linkage_name = dw2_linkage_name (die, cu);
10716
10717       if (linkage_name != NULL)
10718         return linkage_name;
10719     }
10720
10721   /* These are the only languages we know how to qualify names in.  */
10722   if (name != NULL
10723       && (cu->language == language_cplus
10724           || cu->language == language_fortran || cu->language == language_d
10725           || cu->language == language_rust))
10726     {
10727       if (die_needs_namespace (die, cu))
10728         {
10729           const char *prefix;
10730           const char *canonical_name = NULL;
10731
10732           string_file buf;
10733
10734           prefix = determine_prefix (die, cu);
10735           if (*prefix != '\0')
10736             {
10737               char *prefixed_name = typename_concat (NULL, prefix, name,
10738                                                      physname, cu);
10739
10740               buf.puts (prefixed_name);
10741               xfree (prefixed_name);
10742             }
10743           else
10744             buf.puts (name);
10745
10746           /* Template parameters may be specified in the DIE's DW_AT_name, or
10747              as children with DW_TAG_template_type_param or
10748              DW_TAG_value_type_param.  If the latter, add them to the name
10749              here.  If the name already has template parameters, then
10750              skip this step; some versions of GCC emit both, and
10751              it is more efficient to use the pre-computed name.
10752
10753              Something to keep in mind about this process: it is very
10754              unlikely, or in some cases downright impossible, to produce
10755              something that will match the mangled name of a function.
10756              If the definition of the function has the same debug info,
10757              we should be able to match up with it anyway.  But fallbacks
10758              using the minimal symbol, for instance to find a method
10759              implemented in a stripped copy of libstdc++, will not work.
10760              If we do not have debug info for the definition, we will have to
10761              match them up some other way.
10762
10763              When we do name matching there is a related problem with function
10764              templates; two instantiated function templates are allowed to
10765              differ only by their return types, which we do not add here.  */
10766
10767           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10768             {
10769               struct attribute *attr;
10770               struct die_info *child;
10771               int first = 1;
10772
10773               die->building_fullname = 1;
10774
10775               for (child = die->child; child != NULL; child = child->sibling)
10776                 {
10777                   struct type *type;
10778                   LONGEST value;
10779                   const gdb_byte *bytes;
10780                   struct dwarf2_locexpr_baton *baton;
10781                   struct value *v;
10782
10783                   if (child->tag != DW_TAG_template_type_param
10784                       && child->tag != DW_TAG_template_value_param)
10785                     continue;
10786
10787                   if (first)
10788                     {
10789                       buf.puts ("<");
10790                       first = 0;
10791                     }
10792                   else
10793                     buf.puts (", ");
10794
10795                   attr = dwarf2_attr (child, DW_AT_type, cu);
10796                   if (attr == NULL)
10797                     {
10798                       complaint (_("template parameter missing DW_AT_type"));
10799                       buf.puts ("UNKNOWN_TYPE");
10800                       continue;
10801                     }
10802                   type = die_type (child, cu);
10803
10804                   if (child->tag == DW_TAG_template_type_param)
10805                     {
10806                       c_print_type (type, "", &buf, -1, 0, cu->language,
10807                                     &type_print_raw_options);
10808                       continue;
10809                     }
10810
10811                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10812                   if (attr == NULL)
10813                     {
10814                       complaint (_("template parameter missing "
10815                                    "DW_AT_const_value"));
10816                       buf.puts ("UNKNOWN_VALUE");
10817                       continue;
10818                     }
10819
10820                   dwarf2_const_value_attr (attr, type, name,
10821                                            &cu->comp_unit_obstack, cu,
10822                                            &value, &bytes, &baton);
10823
10824                   if (TYPE_NOSIGN (type))
10825                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10826                        changed, this can use value_print instead.  */
10827                     c_printchar (value, type, &buf);
10828                   else
10829                     {
10830                       struct value_print_options opts;
10831
10832                       if (baton != NULL)
10833                         v = dwarf2_evaluate_loc_desc (type, NULL,
10834                                                       baton->data,
10835                                                       baton->size,
10836                                                       baton->per_cu);
10837                       else if (bytes != NULL)
10838                         {
10839                           v = allocate_value (type);
10840                           memcpy (value_contents_writeable (v), bytes,
10841                                   TYPE_LENGTH (type));
10842                         }
10843                       else
10844                         v = value_from_longest (type, value);
10845
10846                       /* Specify decimal so that we do not depend on
10847                          the radix.  */
10848                       get_formatted_print_options (&opts, 'd');
10849                       opts.raw = 1;
10850                       value_print (v, &buf, &opts);
10851                       release_value (v);
10852                     }
10853                 }
10854
10855               die->building_fullname = 0;
10856
10857               if (!first)
10858                 {
10859                   /* Close the argument list, with a space if necessary
10860                      (nested templates).  */
10861                   if (!buf.empty () && buf.string ().back () == '>')
10862                     buf.puts (" >");
10863                   else
10864                     buf.puts (">");
10865                 }
10866             }
10867
10868           /* For C++ methods, append formal parameter type
10869              information, if PHYSNAME.  */
10870
10871           if (physname && die->tag == DW_TAG_subprogram
10872               && cu->language == language_cplus)
10873             {
10874               struct type *type = read_type_die (die, cu);
10875
10876               c_type_print_args (type, &buf, 1, cu->language,
10877                                  &type_print_raw_options);
10878
10879               if (cu->language == language_cplus)
10880                 {
10881                   /* Assume that an artificial first parameter is
10882                      "this", but do not crash if it is not.  RealView
10883                      marks unnamed (and thus unused) parameters as
10884                      artificial; there is no way to differentiate
10885                      the two cases.  */
10886                   if (TYPE_NFIELDS (type) > 0
10887                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10888                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10889                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10890                                                                         0))))
10891                     buf.puts (" const");
10892                 }
10893             }
10894
10895           const std::string &intermediate_name = buf.string ();
10896
10897           if (cu->language == language_cplus)
10898             canonical_name
10899               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10900                                           &objfile->per_bfd->storage_obstack);
10901
10902           /* If we only computed INTERMEDIATE_NAME, or if
10903              INTERMEDIATE_NAME is already canonical, then we need to
10904              copy it to the appropriate obstack.  */
10905           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10906             name = ((const char *)
10907                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10908                                    intermediate_name.c_str (),
10909                                    intermediate_name.length ()));
10910           else
10911             name = canonical_name;
10912         }
10913     }
10914
10915   return name;
10916 }
10917
10918 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10919    If scope qualifiers are appropriate they will be added.  The result
10920    will be allocated on the storage_obstack, or NULL if the DIE does
10921    not have a name.  NAME may either be from a previous call to
10922    dwarf2_name or NULL.
10923
10924    The output string will be canonicalized (if C++).  */
10925
10926 static const char *
10927 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10928 {
10929   return dwarf2_compute_name (name, die, cu, 0);
10930 }
10931
10932 /* Construct a physname for the given DIE in CU.  NAME may either be
10933    from a previous call to dwarf2_name or NULL.  The result will be
10934    allocated on the objfile_objstack or NULL if the DIE does not have a
10935    name.
10936
10937    The output string will be canonicalized (if C++).  */
10938
10939 static const char *
10940 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10941 {
10942   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10943   const char *retval, *mangled = NULL, *canon = NULL;
10944   int need_copy = 1;
10945
10946   /* In this case dwarf2_compute_name is just a shortcut not building anything
10947      on its own.  */
10948   if (!die_needs_namespace (die, cu))
10949     return dwarf2_compute_name (name, die, cu, 1);
10950
10951   mangled = dw2_linkage_name (die, cu);
10952
10953   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10954      See https://github.com/rust-lang/rust/issues/32925.  */
10955   if (cu->language == language_rust && mangled != NULL
10956       && strchr (mangled, '{') != NULL)
10957     mangled = NULL;
10958
10959   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10960      has computed.  */
10961   gdb::unique_xmalloc_ptr<char> demangled;
10962   if (mangled != NULL)
10963     {
10964
10965       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10966         {
10967           /* Do nothing (do not demangle the symbol name).  */
10968         }
10969       else if (cu->language == language_go)
10970         {
10971           /* This is a lie, but we already lie to the caller new_symbol.
10972              new_symbol assumes we return the mangled name.
10973              This just undoes that lie until things are cleaned up.  */
10974         }
10975       else
10976         {
10977           /* Use DMGL_RET_DROP for C++ template functions to suppress
10978              their return type.  It is easier for GDB users to search
10979              for such functions as `name(params)' than `long name(params)'.
10980              In such case the minimal symbol names do not match the full
10981              symbol names but for template functions there is never a need
10982              to look up their definition from their declaration so
10983              the only disadvantage remains the minimal symbol variant
10984              `long name(params)' does not have the proper inferior type.  */
10985           demangled.reset (gdb_demangle (mangled,
10986                                          (DMGL_PARAMS | DMGL_ANSI
10987                                           | DMGL_RET_DROP)));
10988         }
10989       if (demangled)
10990         canon = demangled.get ();
10991       else
10992         {
10993           canon = mangled;
10994           need_copy = 0;
10995         }
10996     }
10997
10998   if (canon == NULL || check_physname)
10999     {
11000       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11001
11002       if (canon != NULL && strcmp (physname, canon) != 0)
11003         {
11004           /* It may not mean a bug in GDB.  The compiler could also
11005              compute DW_AT_linkage_name incorrectly.  But in such case
11006              GDB would need to be bug-to-bug compatible.  */
11007
11008           complaint (_("Computed physname <%s> does not match demangled <%s> "
11009                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11010                      physname, canon, mangled, sect_offset_str (die->sect_off),
11011                      objfile_name (objfile));
11012
11013           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11014              is available here - over computed PHYSNAME.  It is safer
11015              against both buggy GDB and buggy compilers.  */
11016
11017           retval = canon;
11018         }
11019       else
11020         {
11021           retval = physname;
11022           need_copy = 0;
11023         }
11024     }
11025   else
11026     retval = canon;
11027
11028   if (need_copy)
11029     retval = ((const char *)
11030               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11031                              retval, strlen (retval)));
11032
11033   return retval;
11034 }
11035
11036 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11037    a new symbol for it.
11038
11039    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11040
11041 static int
11042 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11043 {
11044   struct attribute *attr;
11045
11046   /* If the die does not have a name, this is not a namespace
11047      alias.  */
11048   attr = dwarf2_attr (die, DW_AT_name, cu);
11049   if (attr != NULL)
11050     {
11051       int num;
11052       struct die_info *d = die;
11053       struct dwarf2_cu *imported_cu = cu;
11054
11055       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11056          keep inspecting DIEs until we hit the underlying import.  */
11057 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11058       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11059         {
11060           attr = dwarf2_attr (d, DW_AT_import, cu);
11061           if (attr == NULL)
11062             break;
11063
11064           d = follow_die_ref (d, attr, &imported_cu);
11065           if (d->tag != DW_TAG_imported_declaration)
11066             break;
11067         }
11068
11069       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11070         {
11071           complaint (_("DIE at %s has too many recursively imported "
11072                        "declarations"), sect_offset_str (d->sect_off));
11073           return 0;
11074         }
11075
11076       if (attr != NULL)
11077         {
11078           struct type *type;
11079           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11080
11081           type = get_die_type_at_offset (sect_off, cu->per_cu);
11082           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11083             {
11084               /* This declaration is a global namespace alias.  Add
11085                  a symbol for it whose type is the aliased namespace.  */
11086               new_symbol (die, type, cu);
11087               return 1;
11088             }
11089         }
11090     }
11091
11092   return 0;
11093 }
11094
11095 /* Return the using directives repository (global or local?) to use in the
11096    current context for LANGUAGE.
11097
11098    For Ada, imported declarations can materialize renamings, which *may* be
11099    global.  However it is impossible (for now?) in DWARF to distinguish
11100    "external" imported declarations and "static" ones.  As all imported
11101    declarations seem to be static in all other languages, make them all CU-wide
11102    global only in Ada.  */
11103
11104 static struct using_direct **
11105 using_directives (enum language language)
11106 {
11107   if (language == language_ada && context_stack_depth == 0)
11108     return &global_using_directives;
11109   else
11110     return &local_using_directives;
11111 }
11112
11113 /* Read the import statement specified by the given die and record it.  */
11114
11115 static void
11116 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11117 {
11118   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11119   struct attribute *import_attr;
11120   struct die_info *imported_die, *child_die;
11121   struct dwarf2_cu *imported_cu;
11122   const char *imported_name;
11123   const char *imported_name_prefix;
11124   const char *canonical_name;
11125   const char *import_alias;
11126   const char *imported_declaration = NULL;
11127   const char *import_prefix;
11128   std::vector<const char *> excludes;
11129
11130   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11131   if (import_attr == NULL)
11132     {
11133       complaint (_("Tag '%s' has no DW_AT_import"),
11134                  dwarf_tag_name (die->tag));
11135       return;
11136     }
11137
11138   imported_cu = cu;
11139   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11140   imported_name = dwarf2_name (imported_die, imported_cu);
11141   if (imported_name == NULL)
11142     {
11143       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11144
11145         The import in the following code:
11146         namespace A
11147           {
11148             typedef int B;
11149           }
11150
11151         int main ()
11152           {
11153             using A::B;
11154             B b;
11155             return b;
11156           }
11157
11158         ...
11159          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11160             <52>   DW_AT_decl_file   : 1
11161             <53>   DW_AT_decl_line   : 6
11162             <54>   DW_AT_import      : <0x75>
11163          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11164             <59>   DW_AT_name        : B
11165             <5b>   DW_AT_decl_file   : 1
11166             <5c>   DW_AT_decl_line   : 2
11167             <5d>   DW_AT_type        : <0x6e>
11168         ...
11169          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11170             <76>   DW_AT_byte_size   : 4
11171             <77>   DW_AT_encoding    : 5        (signed)
11172
11173         imports the wrong die ( 0x75 instead of 0x58 ).
11174         This case will be ignored until the gcc bug is fixed.  */
11175       return;
11176     }
11177
11178   /* Figure out the local name after import.  */
11179   import_alias = dwarf2_name (die, cu);
11180
11181   /* Figure out where the statement is being imported to.  */
11182   import_prefix = determine_prefix (die, cu);
11183
11184   /* Figure out what the scope of the imported die is and prepend it
11185      to the name of the imported die.  */
11186   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11187
11188   if (imported_die->tag != DW_TAG_namespace
11189       && imported_die->tag != DW_TAG_module)
11190     {
11191       imported_declaration = imported_name;
11192       canonical_name = imported_name_prefix;
11193     }
11194   else if (strlen (imported_name_prefix) > 0)
11195     canonical_name = obconcat (&objfile->objfile_obstack,
11196                                imported_name_prefix,
11197                                (cu->language == language_d ? "." : "::"),
11198                                imported_name, (char *) NULL);
11199   else
11200     canonical_name = imported_name;
11201
11202   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11203     for (child_die = die->child; child_die && child_die->tag;
11204          child_die = sibling_die (child_die))
11205       {
11206         /* DWARF-4: A Fortran use statement with a “rename list” may be
11207            represented by an imported module entry with an import attribute
11208            referring to the module and owned entries corresponding to those
11209            entities that are renamed as part of being imported.  */
11210
11211         if (child_die->tag != DW_TAG_imported_declaration)
11212           {
11213             complaint (_("child DW_TAG_imported_declaration expected "
11214                          "- DIE at %s [in module %s]"),
11215                        sect_offset_str (child_die->sect_off),
11216                        objfile_name (objfile));
11217             continue;
11218           }
11219
11220         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11221         if (import_attr == NULL)
11222           {
11223             complaint (_("Tag '%s' has no DW_AT_import"),
11224                        dwarf_tag_name (child_die->tag));
11225             continue;
11226           }
11227
11228         imported_cu = cu;
11229         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11230                                               &imported_cu);
11231         imported_name = dwarf2_name (imported_die, imported_cu);
11232         if (imported_name == NULL)
11233           {
11234             complaint (_("child DW_TAG_imported_declaration has unknown "
11235                          "imported name - DIE at %s [in module %s]"),
11236                        sect_offset_str (child_die->sect_off),
11237                        objfile_name (objfile));
11238             continue;
11239           }
11240
11241         excludes.push_back (imported_name);
11242
11243         process_die (child_die, cu);
11244       }
11245
11246   add_using_directive (using_directives (cu->language),
11247                        import_prefix,
11248                        canonical_name,
11249                        import_alias,
11250                        imported_declaration,
11251                        excludes,
11252                        0,
11253                        &objfile->objfile_obstack);
11254 }
11255
11256 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11257    types, but gives them a size of zero.  Starting with version 14,
11258    ICC is compatible with GCC.  */
11259
11260 static int
11261 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11262 {
11263   if (!cu->checked_producer)
11264     check_producer (cu);
11265
11266   return cu->producer_is_icc_lt_14;
11267 }
11268
11269 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11270    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11271    this, it was first present in GCC release 4.3.0.  */
11272
11273 static int
11274 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11275 {
11276   if (!cu->checked_producer)
11277     check_producer (cu);
11278
11279   return cu->producer_is_gcc_lt_4_3;
11280 }
11281
11282 static file_and_directory
11283 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11284 {
11285   file_and_directory res;
11286
11287   /* Find the filename.  Do not use dwarf2_name here, since the filename
11288      is not a source language identifier.  */
11289   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11290   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11291
11292   if (res.comp_dir == NULL
11293       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11294       && IS_ABSOLUTE_PATH (res.name))
11295     {
11296       res.comp_dir_storage = ldirname (res.name);
11297       if (!res.comp_dir_storage.empty ())
11298         res.comp_dir = res.comp_dir_storage.c_str ();
11299     }
11300   if (res.comp_dir != NULL)
11301     {
11302       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11303          directory, get rid of it.  */
11304       const char *cp = strchr (res.comp_dir, ':');
11305
11306       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11307         res.comp_dir = cp + 1;
11308     }
11309
11310   if (res.name == NULL)
11311     res.name = "<unknown>";
11312
11313   return res;
11314 }
11315
11316 /* Handle DW_AT_stmt_list for a compilation unit.
11317    DIE is the DW_TAG_compile_unit die for CU.
11318    COMP_DIR is the compilation directory.  LOWPC is passed to
11319    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11320
11321 static void
11322 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11323                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11324 {
11325   struct dwarf2_per_objfile *dwarf2_per_objfile
11326     = cu->per_cu->dwarf2_per_objfile;
11327   struct objfile *objfile = dwarf2_per_objfile->objfile;
11328   struct attribute *attr;
11329   struct line_header line_header_local;
11330   hashval_t line_header_local_hash;
11331   void **slot;
11332   int decode_mapping;
11333
11334   gdb_assert (! cu->per_cu->is_debug_types);
11335
11336   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11337   if (attr == NULL)
11338     return;
11339
11340   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11341
11342   /* The line header hash table is only created if needed (it exists to
11343      prevent redundant reading of the line table for partial_units).
11344      If we're given a partial_unit, we'll need it.  If we're given a
11345      compile_unit, then use the line header hash table if it's already
11346      created, but don't create one just yet.  */
11347
11348   if (dwarf2_per_objfile->line_header_hash == NULL
11349       && die->tag == DW_TAG_partial_unit)
11350     {
11351       dwarf2_per_objfile->line_header_hash
11352         = htab_create_alloc_ex (127, line_header_hash_voidp,
11353                                 line_header_eq_voidp,
11354                                 free_line_header_voidp,
11355                                 &objfile->objfile_obstack,
11356                                 hashtab_obstack_allocate,
11357                                 dummy_obstack_deallocate);
11358     }
11359
11360   line_header_local.sect_off = line_offset;
11361   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11362   line_header_local_hash = line_header_hash (&line_header_local);
11363   if (dwarf2_per_objfile->line_header_hash != NULL)
11364     {
11365       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11366                                        &line_header_local,
11367                                        line_header_local_hash, NO_INSERT);
11368
11369       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11370          is not present in *SLOT (since if there is something in *SLOT then
11371          it will be for a partial_unit).  */
11372       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11373         {
11374           gdb_assert (*slot != NULL);
11375           cu->line_header = (struct line_header *) *slot;
11376           return;
11377         }
11378     }
11379
11380   /* dwarf_decode_line_header does not yet provide sufficient information.
11381      We always have to call also dwarf_decode_lines for it.  */
11382   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11383   if (lh == NULL)
11384     return;
11385
11386   cu->line_header = lh.release ();
11387   cu->line_header_die_owner = die;
11388
11389   if (dwarf2_per_objfile->line_header_hash == NULL)
11390     slot = NULL;
11391   else
11392     {
11393       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11394                                        &line_header_local,
11395                                        line_header_local_hash, INSERT);
11396       gdb_assert (slot != NULL);
11397     }
11398   if (slot != NULL && *slot == NULL)
11399     {
11400       /* This newly decoded line number information unit will be owned
11401          by line_header_hash hash table.  */
11402       *slot = cu->line_header;
11403       cu->line_header_die_owner = NULL;
11404     }
11405   else
11406     {
11407       /* We cannot free any current entry in (*slot) as that struct line_header
11408          may be already used by multiple CUs.  Create only temporary decoded
11409          line_header for this CU - it may happen at most once for each line
11410          number information unit.  And if we're not using line_header_hash
11411          then this is what we want as well.  */
11412       gdb_assert (die->tag != DW_TAG_partial_unit);
11413     }
11414   decode_mapping = (die->tag != DW_TAG_partial_unit);
11415   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11416                       decode_mapping);
11417
11418 }
11419
11420 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11421
11422 static void
11423 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11424 {
11425   struct dwarf2_per_objfile *dwarf2_per_objfile
11426     = cu->per_cu->dwarf2_per_objfile;
11427   struct objfile *objfile = dwarf2_per_objfile->objfile;
11428   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11429   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11430   CORE_ADDR highpc = ((CORE_ADDR) 0);
11431   struct attribute *attr;
11432   struct die_info *child_die;
11433   CORE_ADDR baseaddr;
11434
11435   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11436
11437   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11438
11439   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11440      from finish_block.  */
11441   if (lowpc == ((CORE_ADDR) -1))
11442     lowpc = highpc;
11443   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11444
11445   file_and_directory fnd = find_file_and_directory (die, cu);
11446
11447   prepare_one_comp_unit (cu, die, cu->language);
11448
11449   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11450      standardised yet.  As a workaround for the language detection we fall
11451      back to the DW_AT_producer string.  */
11452   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11453     cu->language = language_opencl;
11454
11455   /* Similar hack for Go.  */
11456   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11457     set_cu_language (DW_LANG_Go, cu);
11458
11459   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11460
11461   /* Decode line number information if present.  We do this before
11462      processing child DIEs, so that the line header table is available
11463      for DW_AT_decl_file.  */
11464   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11465
11466   /* Process all dies in compilation unit.  */
11467   if (die->child != NULL)
11468     {
11469       child_die = die->child;
11470       while (child_die && child_die->tag)
11471         {
11472           process_die (child_die, cu);
11473           child_die = sibling_die (child_die);
11474         }
11475     }
11476
11477   /* Decode macro information, if present.  Dwarf 2 macro information
11478      refers to information in the line number info statement program
11479      header, so we can only read it if we've read the header
11480      successfully.  */
11481   attr = dwarf2_attr (die, DW_AT_macros, cu);
11482   if (attr == NULL)
11483     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11484   if (attr && cu->line_header)
11485     {
11486       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11487         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11488
11489       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11490     }
11491   else
11492     {
11493       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11494       if (attr && cu->line_header)
11495         {
11496           unsigned int macro_offset = DW_UNSND (attr);
11497
11498           dwarf_decode_macros (cu, macro_offset, 0);
11499         }
11500     }
11501 }
11502
11503 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11504    Create the set of symtabs used by this TU, or if this TU is sharing
11505    symtabs with another TU and the symtabs have already been created
11506    then restore those symtabs in the line header.
11507    We don't need the pc/line-number mapping for type units.  */
11508
11509 static void
11510 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11511 {
11512   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11513   struct type_unit_group *tu_group;
11514   int first_time;
11515   struct attribute *attr;
11516   unsigned int i;
11517   struct signatured_type *sig_type;
11518
11519   gdb_assert (per_cu->is_debug_types);
11520   sig_type = (struct signatured_type *) per_cu;
11521
11522   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11523
11524   /* If we're using .gdb_index (includes -readnow) then
11525      per_cu->type_unit_group may not have been set up yet.  */
11526   if (sig_type->type_unit_group == NULL)
11527     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11528   tu_group = sig_type->type_unit_group;
11529
11530   /* If we've already processed this stmt_list there's no real need to
11531      do it again, we could fake it and just recreate the part we need
11532      (file name,index -> symtab mapping).  If data shows this optimization
11533      is useful we can do it then.  */
11534   first_time = tu_group->compunit_symtab == NULL;
11535
11536   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11537      debug info.  */
11538   line_header_up lh;
11539   if (attr != NULL)
11540     {
11541       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11542       lh = dwarf_decode_line_header (line_offset, cu);
11543     }
11544   if (lh == NULL)
11545     {
11546       if (first_time)
11547         dwarf2_start_symtab (cu, "", NULL, 0);
11548       else
11549         {
11550           gdb_assert (tu_group->symtabs == NULL);
11551           restart_symtab (tu_group->compunit_symtab, "", 0);
11552         }
11553       return;
11554     }
11555
11556   cu->line_header = lh.release ();
11557   cu->line_header_die_owner = die;
11558
11559   if (first_time)
11560     {
11561       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11562
11563       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11564          still initializing it, and our caller (a few levels up)
11565          process_full_type_unit still needs to know if this is the first
11566          time.  */
11567
11568       tu_group->num_symtabs = cu->line_header->file_names.size ();
11569       tu_group->symtabs = XNEWVEC (struct symtab *,
11570                                    cu->line_header->file_names.size ());
11571
11572       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11573         {
11574           file_entry &fe = cu->line_header->file_names[i];
11575
11576           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11577
11578           if (current_subfile->symtab == NULL)
11579             {
11580               /* NOTE: start_subfile will recognize when it's been
11581                  passed a file it has already seen.  So we can't
11582                  assume there's a simple mapping from
11583                  cu->line_header->file_names to subfiles, plus
11584                  cu->line_header->file_names may contain dups.  */
11585               current_subfile->symtab
11586                 = allocate_symtab (cust, current_subfile->name);
11587             }
11588
11589           fe.symtab = current_subfile->symtab;
11590           tu_group->symtabs[i] = fe.symtab;
11591         }
11592     }
11593   else
11594     {
11595       restart_symtab (tu_group->compunit_symtab, "", 0);
11596
11597       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11598         {
11599           file_entry &fe = cu->line_header->file_names[i];
11600
11601           fe.symtab = tu_group->symtabs[i];
11602         }
11603     }
11604
11605   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11606      so they don't have a "real" (so to speak) symtab anyway.
11607      There is later code that will assign the main symtab to all symbols
11608      that don't have one.  We need to handle the case of a symbol with a
11609      missing symtab (DW_AT_decl_file) anyway.  */
11610 }
11611
11612 /* Process DW_TAG_type_unit.
11613    For TUs we want to skip the first top level sibling if it's not the
11614    actual type being defined by this TU.  In this case the first top
11615    level sibling is there to provide context only.  */
11616
11617 static void
11618 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11619 {
11620   struct die_info *child_die;
11621
11622   prepare_one_comp_unit (cu, die, language_minimal);
11623
11624   /* Initialize (or reinitialize) the machinery for building symtabs.
11625      We do this before processing child DIEs, so that the line header table
11626      is available for DW_AT_decl_file.  */
11627   setup_type_unit_groups (die, cu);
11628
11629   if (die->child != NULL)
11630     {
11631       child_die = die->child;
11632       while (child_die && child_die->tag)
11633         {
11634           process_die (child_die, cu);
11635           child_die = sibling_die (child_die);
11636         }
11637     }
11638 }
11639 \f
11640 /* DWO/DWP files.
11641
11642    http://gcc.gnu.org/wiki/DebugFission
11643    http://gcc.gnu.org/wiki/DebugFissionDWP
11644
11645    To simplify handling of both DWO files ("object" files with the DWARF info)
11646    and DWP files (a file with the DWOs packaged up into one file), we treat
11647    DWP files as having a collection of virtual DWO files.  */
11648
11649 static hashval_t
11650 hash_dwo_file (const void *item)
11651 {
11652   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11653   hashval_t hash;
11654
11655   hash = htab_hash_string (dwo_file->dwo_name);
11656   if (dwo_file->comp_dir != NULL)
11657     hash += htab_hash_string (dwo_file->comp_dir);
11658   return hash;
11659 }
11660
11661 static int
11662 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11663 {
11664   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11665   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11666
11667   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11668     return 0;
11669   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11670     return lhs->comp_dir == rhs->comp_dir;
11671   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11672 }
11673
11674 /* Allocate a hash table for DWO files.  */
11675
11676 static htab_t
11677 allocate_dwo_file_hash_table (struct objfile *objfile)
11678 {
11679   return htab_create_alloc_ex (41,
11680                                hash_dwo_file,
11681                                eq_dwo_file,
11682                                NULL,
11683                                &objfile->objfile_obstack,
11684                                hashtab_obstack_allocate,
11685                                dummy_obstack_deallocate);
11686 }
11687
11688 /* Lookup DWO file DWO_NAME.  */
11689
11690 static void **
11691 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11692                       const char *dwo_name,
11693                       const char *comp_dir)
11694 {
11695   struct dwo_file find_entry;
11696   void **slot;
11697
11698   if (dwarf2_per_objfile->dwo_files == NULL)
11699     dwarf2_per_objfile->dwo_files
11700       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11701
11702   memset (&find_entry, 0, sizeof (find_entry));
11703   find_entry.dwo_name = dwo_name;
11704   find_entry.comp_dir = comp_dir;
11705   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11706
11707   return slot;
11708 }
11709
11710 static hashval_t
11711 hash_dwo_unit (const void *item)
11712 {
11713   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11714
11715   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11716   return dwo_unit->signature;
11717 }
11718
11719 static int
11720 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11721 {
11722   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11723   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11724
11725   /* The signature is assumed to be unique within the DWO file.
11726      So while object file CU dwo_id's always have the value zero,
11727      that's OK, assuming each object file DWO file has only one CU,
11728      and that's the rule for now.  */
11729   return lhs->signature == rhs->signature;
11730 }
11731
11732 /* Allocate a hash table for DWO CUs,TUs.
11733    There is one of these tables for each of CUs,TUs for each DWO file.  */
11734
11735 static htab_t
11736 allocate_dwo_unit_table (struct objfile *objfile)
11737 {
11738   /* Start out with a pretty small number.
11739      Generally DWO files contain only one CU and maybe some TUs.  */
11740   return htab_create_alloc_ex (3,
11741                                hash_dwo_unit,
11742                                eq_dwo_unit,
11743                                NULL,
11744                                &objfile->objfile_obstack,
11745                                hashtab_obstack_allocate,
11746                                dummy_obstack_deallocate);
11747 }
11748
11749 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11750
11751 struct create_dwo_cu_data
11752 {
11753   struct dwo_file *dwo_file;
11754   struct dwo_unit dwo_unit;
11755 };
11756
11757 /* die_reader_func for create_dwo_cu.  */
11758
11759 static void
11760 create_dwo_cu_reader (const struct die_reader_specs *reader,
11761                       const gdb_byte *info_ptr,
11762                       struct die_info *comp_unit_die,
11763                       int has_children,
11764                       void *datap)
11765 {
11766   struct dwarf2_cu *cu = reader->cu;
11767   sect_offset sect_off = cu->per_cu->sect_off;
11768   struct dwarf2_section_info *section = cu->per_cu->section;
11769   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11770   struct dwo_file *dwo_file = data->dwo_file;
11771   struct dwo_unit *dwo_unit = &data->dwo_unit;
11772   struct attribute *attr;
11773
11774   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11775   if (attr == NULL)
11776     {
11777       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11778                    " its dwo_id [in module %s]"),
11779                  sect_offset_str (sect_off), dwo_file->dwo_name);
11780       return;
11781     }
11782
11783   dwo_unit->dwo_file = dwo_file;
11784   dwo_unit->signature = DW_UNSND (attr);
11785   dwo_unit->section = section;
11786   dwo_unit->sect_off = sect_off;
11787   dwo_unit->length = cu->per_cu->length;
11788
11789   if (dwarf_read_debug)
11790     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11791                         sect_offset_str (sect_off),
11792                         hex_string (dwo_unit->signature));
11793 }
11794
11795 /* Create the dwo_units for the CUs in a DWO_FILE.
11796    Note: This function processes DWO files only, not DWP files.  */
11797
11798 static void
11799 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11800                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11801                        htab_t &cus_htab)
11802 {
11803   struct objfile *objfile = dwarf2_per_objfile->objfile;
11804   const gdb_byte *info_ptr, *end_ptr;
11805
11806   dwarf2_read_section (objfile, &section);
11807   info_ptr = section.buffer;
11808
11809   if (info_ptr == NULL)
11810     return;
11811
11812   if (dwarf_read_debug)
11813     {
11814       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11815                           get_section_name (&section),
11816                           get_section_file_name (&section));
11817     }
11818
11819   end_ptr = info_ptr + section.size;
11820   while (info_ptr < end_ptr)
11821     {
11822       struct dwarf2_per_cu_data per_cu;
11823       struct create_dwo_cu_data create_dwo_cu_data;
11824       struct dwo_unit *dwo_unit;
11825       void **slot;
11826       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11827
11828       memset (&create_dwo_cu_data.dwo_unit, 0,
11829               sizeof (create_dwo_cu_data.dwo_unit));
11830       memset (&per_cu, 0, sizeof (per_cu));
11831       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11832       per_cu.is_debug_types = 0;
11833       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11834       per_cu.section = &section;
11835       create_dwo_cu_data.dwo_file = &dwo_file;
11836
11837       init_cutu_and_read_dies_no_follow (
11838           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11839       info_ptr += per_cu.length;
11840
11841       // If the unit could not be parsed, skip it.
11842       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11843         continue;
11844
11845       if (cus_htab == NULL)
11846         cus_htab = allocate_dwo_unit_table (objfile);
11847
11848       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11849       *dwo_unit = create_dwo_cu_data.dwo_unit;
11850       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11851       gdb_assert (slot != NULL);
11852       if (*slot != NULL)
11853         {
11854           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11855           sect_offset dup_sect_off = dup_cu->sect_off;
11856
11857           complaint (_("debug cu entry at offset %s is duplicate to"
11858                        " the entry at offset %s, signature %s"),
11859                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11860                      hex_string (dwo_unit->signature));
11861         }
11862       *slot = (void *)dwo_unit;
11863     }
11864 }
11865
11866 /* DWP file .debug_{cu,tu}_index section format:
11867    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11868
11869    DWP Version 1:
11870
11871    Both index sections have the same format, and serve to map a 64-bit
11872    signature to a set of section numbers.  Each section begins with a header,
11873    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11874    indexes, and a pool of 32-bit section numbers.  The index sections will be
11875    aligned at 8-byte boundaries in the file.
11876
11877    The index section header consists of:
11878
11879     V, 32 bit version number
11880     -, 32 bits unused
11881     N, 32 bit number of compilation units or type units in the index
11882     M, 32 bit number of slots in the hash table
11883
11884    Numbers are recorded using the byte order of the application binary.
11885
11886    The hash table begins at offset 16 in the section, and consists of an array
11887    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11888    order of the application binary).  Unused slots in the hash table are 0.
11889    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11890
11891    The parallel table begins immediately after the hash table
11892    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11893    array of 32-bit indexes (using the byte order of the application binary),
11894    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11895    table contains a 32-bit index into the pool of section numbers.  For unused
11896    hash table slots, the corresponding entry in the parallel table will be 0.
11897
11898    The pool of section numbers begins immediately following the hash table
11899    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11900    section numbers consists of an array of 32-bit words (using the byte order
11901    of the application binary).  Each item in the array is indexed starting
11902    from 0.  The hash table entry provides the index of the first section
11903    number in the set.  Additional section numbers in the set follow, and the
11904    set is terminated by a 0 entry (section number 0 is not used in ELF).
11905
11906    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11907    section must be the first entry in the set, and the .debug_abbrev.dwo must
11908    be the second entry. Other members of the set may follow in any order.
11909
11910    ---
11911
11912    DWP Version 2:
11913
11914    DWP Version 2 combines all the .debug_info, etc. sections into one,
11915    and the entries in the index tables are now offsets into these sections.
11916    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11917    section.
11918
11919    Index Section Contents:
11920     Header
11921     Hash Table of Signatures   dwp_hash_table.hash_table
11922     Parallel Table of Indices  dwp_hash_table.unit_table
11923     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11924     Table of Section Sizes     dwp_hash_table.v2.sizes
11925
11926    The index section header consists of:
11927
11928     V, 32 bit version number
11929     L, 32 bit number of columns in the table of section offsets
11930     N, 32 bit number of compilation units or type units in the index
11931     M, 32 bit number of slots in the hash table
11932
11933    Numbers are recorded using the byte order of the application binary.
11934
11935    The hash table has the same format as version 1.
11936    The parallel table of indices has the same format as version 1,
11937    except that the entries are origin-1 indices into the table of sections
11938    offsets and the table of section sizes.
11939
11940    The table of offsets begins immediately following the parallel table
11941    (at offset 16 + 12 * M from the beginning of the section).  The table is
11942    a two-dimensional array of 32-bit words (using the byte order of the
11943    application binary), with L columns and N+1 rows, in row-major order.
11944    Each row in the array is indexed starting from 0.  The first row provides
11945    a key to the remaining rows: each column in this row provides an identifier
11946    for a debug section, and the offsets in the same column of subsequent rows
11947    refer to that section.  The section identifiers are:
11948
11949     DW_SECT_INFO         1  .debug_info.dwo
11950     DW_SECT_TYPES        2  .debug_types.dwo
11951     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11952     DW_SECT_LINE         4  .debug_line.dwo
11953     DW_SECT_LOC          5  .debug_loc.dwo
11954     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11955     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11956     DW_SECT_MACRO        8  .debug_macro.dwo
11957
11958    The offsets provided by the CU and TU index sections are the base offsets
11959    for the contributions made by each CU or TU to the corresponding section
11960    in the package file.  Each CU and TU header contains an abbrev_offset
11961    field, used to find the abbreviations table for that CU or TU within the
11962    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11963    be interpreted as relative to the base offset given in the index section.
11964    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11965    should be interpreted as relative to the base offset for .debug_line.dwo,
11966    and offsets into other debug sections obtained from DWARF attributes should
11967    also be interpreted as relative to the corresponding base offset.
11968
11969    The table of sizes begins immediately following the table of offsets.
11970    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11971    with L columns and N rows, in row-major order.  Each row in the array is
11972    indexed starting from 1 (row 0 is shared by the two tables).
11973
11974    ---
11975
11976    Hash table lookup is handled the same in version 1 and 2:
11977
11978    We assume that N and M will not exceed 2^32 - 1.
11979    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11980
11981    Given a 64-bit compilation unit signature or a type signature S, an entry
11982    in the hash table is located as follows:
11983
11984    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11985       the low-order k bits all set to 1.
11986
11987    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11988
11989    3) If the hash table entry at index H matches the signature, use that
11990       entry.  If the hash table entry at index H is unused (all zeroes),
11991       terminate the search: the signature is not present in the table.
11992
11993    4) Let H = (H + H') modulo M. Repeat at Step 3.
11994
11995    Because M > N and H' and M are relatively prime, the search is guaranteed
11996    to stop at an unused slot or find the match.  */
11997
11998 /* Create a hash table to map DWO IDs to their CU/TU entry in
11999    .debug_{info,types}.dwo in DWP_FILE.
12000    Returns NULL if there isn't one.
12001    Note: This function processes DWP files only, not DWO files.  */
12002
12003 static struct dwp_hash_table *
12004 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12005                        struct dwp_file *dwp_file, int is_debug_types)
12006 {
12007   struct objfile *objfile = dwarf2_per_objfile->objfile;
12008   bfd *dbfd = dwp_file->dbfd.get ();
12009   const gdb_byte *index_ptr, *index_end;
12010   struct dwarf2_section_info *index;
12011   uint32_t version, nr_columns, nr_units, nr_slots;
12012   struct dwp_hash_table *htab;
12013
12014   if (is_debug_types)
12015     index = &dwp_file->sections.tu_index;
12016   else
12017     index = &dwp_file->sections.cu_index;
12018
12019   if (dwarf2_section_empty_p (index))
12020     return NULL;
12021   dwarf2_read_section (objfile, index);
12022
12023   index_ptr = index->buffer;
12024   index_end = index_ptr + index->size;
12025
12026   version = read_4_bytes (dbfd, index_ptr);
12027   index_ptr += 4;
12028   if (version == 2)
12029     nr_columns = read_4_bytes (dbfd, index_ptr);
12030   else
12031     nr_columns = 0;
12032   index_ptr += 4;
12033   nr_units = read_4_bytes (dbfd, index_ptr);
12034   index_ptr += 4;
12035   nr_slots = read_4_bytes (dbfd, index_ptr);
12036   index_ptr += 4;
12037
12038   if (version != 1 && version != 2)
12039     {
12040       error (_("Dwarf Error: unsupported DWP file version (%s)"
12041                " [in module %s]"),
12042              pulongest (version), dwp_file->name);
12043     }
12044   if (nr_slots != (nr_slots & -nr_slots))
12045     {
12046       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12047                " is not power of 2 [in module %s]"),
12048              pulongest (nr_slots), dwp_file->name);
12049     }
12050
12051   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12052   htab->version = version;
12053   htab->nr_columns = nr_columns;
12054   htab->nr_units = nr_units;
12055   htab->nr_slots = nr_slots;
12056   htab->hash_table = index_ptr;
12057   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12058
12059   /* Exit early if the table is empty.  */
12060   if (nr_slots == 0 || nr_units == 0
12061       || (version == 2 && nr_columns == 0))
12062     {
12063       /* All must be zero.  */
12064       if (nr_slots != 0 || nr_units != 0
12065           || (version == 2 && nr_columns != 0))
12066         {
12067           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12068                        " all zero [in modules %s]"),
12069                      dwp_file->name);
12070         }
12071       return htab;
12072     }
12073
12074   if (version == 1)
12075     {
12076       htab->section_pool.v1.indices =
12077         htab->unit_table + sizeof (uint32_t) * nr_slots;
12078       /* It's harder to decide whether the section is too small in v1.
12079          V1 is deprecated anyway so we punt.  */
12080     }
12081   else
12082     {
12083       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12084       int *ids = htab->section_pool.v2.section_ids;
12085       /* Reverse map for error checking.  */
12086       int ids_seen[DW_SECT_MAX + 1];
12087       int i;
12088
12089       if (nr_columns < 2)
12090         {
12091           error (_("Dwarf Error: bad DWP hash table, too few columns"
12092                    " in section table [in module %s]"),
12093                  dwp_file->name);
12094         }
12095       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12096         {
12097           error (_("Dwarf Error: bad DWP hash table, too many columns"
12098                    " in section table [in module %s]"),
12099                  dwp_file->name);
12100         }
12101       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12102       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12103       for (i = 0; i < nr_columns; ++i)
12104         {
12105           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12106
12107           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12108             {
12109               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12110                        " in section table [in module %s]"),
12111                      id, dwp_file->name);
12112             }
12113           if (ids_seen[id] != -1)
12114             {
12115               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12116                        " id %d in section table [in module %s]"),
12117                      id, dwp_file->name);
12118             }
12119           ids_seen[id] = i;
12120           ids[i] = id;
12121         }
12122       /* Must have exactly one info or types section.  */
12123       if (((ids_seen[DW_SECT_INFO] != -1)
12124            + (ids_seen[DW_SECT_TYPES] != -1))
12125           != 1)
12126         {
12127           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12128                    " DWO info/types section [in module %s]"),
12129                  dwp_file->name);
12130         }
12131       /* Must have an abbrev section.  */
12132       if (ids_seen[DW_SECT_ABBREV] == -1)
12133         {
12134           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12135                    " section [in module %s]"),
12136                  dwp_file->name);
12137         }
12138       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12139       htab->section_pool.v2.sizes =
12140         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12141                                          * nr_units * nr_columns);
12142       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12143                                           * nr_units * nr_columns))
12144           > index_end)
12145         {
12146           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12147                    " [in module %s]"),
12148                  dwp_file->name);
12149         }
12150     }
12151
12152   return htab;
12153 }
12154
12155 /* Update SECTIONS with the data from SECTP.
12156
12157    This function is like the other "locate" section routines that are
12158    passed to bfd_map_over_sections, but in this context the sections to
12159    read comes from the DWP V1 hash table, not the full ELF section table.
12160
12161    The result is non-zero for success, or zero if an error was found.  */
12162
12163 static int
12164 locate_v1_virtual_dwo_sections (asection *sectp,
12165                                 struct virtual_v1_dwo_sections *sections)
12166 {
12167   const struct dwop_section_names *names = &dwop_section_names;
12168
12169   if (section_is_p (sectp->name, &names->abbrev_dwo))
12170     {
12171       /* There can be only one.  */
12172       if (sections->abbrev.s.section != NULL)
12173         return 0;
12174       sections->abbrev.s.section = sectp;
12175       sections->abbrev.size = bfd_get_section_size (sectp);
12176     }
12177   else if (section_is_p (sectp->name, &names->info_dwo)
12178            || section_is_p (sectp->name, &names->types_dwo))
12179     {
12180       /* There can be only one.  */
12181       if (sections->info_or_types.s.section != NULL)
12182         return 0;
12183       sections->info_or_types.s.section = sectp;
12184       sections->info_or_types.size = bfd_get_section_size (sectp);
12185     }
12186   else if (section_is_p (sectp->name, &names->line_dwo))
12187     {
12188       /* There can be only one.  */
12189       if (sections->line.s.section != NULL)
12190         return 0;
12191       sections->line.s.section = sectp;
12192       sections->line.size = bfd_get_section_size (sectp);
12193     }
12194   else if (section_is_p (sectp->name, &names->loc_dwo))
12195     {
12196       /* There can be only one.  */
12197       if (sections->loc.s.section != NULL)
12198         return 0;
12199       sections->loc.s.section = sectp;
12200       sections->loc.size = bfd_get_section_size (sectp);
12201     }
12202   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12203     {
12204       /* There can be only one.  */
12205       if (sections->macinfo.s.section != NULL)
12206         return 0;
12207       sections->macinfo.s.section = sectp;
12208       sections->macinfo.size = bfd_get_section_size (sectp);
12209     }
12210   else if (section_is_p (sectp->name, &names->macro_dwo))
12211     {
12212       /* There can be only one.  */
12213       if (sections->macro.s.section != NULL)
12214         return 0;
12215       sections->macro.s.section = sectp;
12216       sections->macro.size = bfd_get_section_size (sectp);
12217     }
12218   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12219     {
12220       /* There can be only one.  */
12221       if (sections->str_offsets.s.section != NULL)
12222         return 0;
12223       sections->str_offsets.s.section = sectp;
12224       sections->str_offsets.size = bfd_get_section_size (sectp);
12225     }
12226   else
12227     {
12228       /* No other kind of section is valid.  */
12229       return 0;
12230     }
12231
12232   return 1;
12233 }
12234
12235 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12236    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12237    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12238    This is for DWP version 1 files.  */
12239
12240 static struct dwo_unit *
12241 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12242                            struct dwp_file *dwp_file,
12243                            uint32_t unit_index,
12244                            const char *comp_dir,
12245                            ULONGEST signature, int is_debug_types)
12246 {
12247   struct objfile *objfile = dwarf2_per_objfile->objfile;
12248   const struct dwp_hash_table *dwp_htab =
12249     is_debug_types ? dwp_file->tus : dwp_file->cus;
12250   bfd *dbfd = dwp_file->dbfd.get ();
12251   const char *kind = is_debug_types ? "TU" : "CU";
12252   struct dwo_file *dwo_file;
12253   struct dwo_unit *dwo_unit;
12254   struct virtual_v1_dwo_sections sections;
12255   void **dwo_file_slot;
12256   int i;
12257
12258   gdb_assert (dwp_file->version == 1);
12259
12260   if (dwarf_read_debug)
12261     {
12262       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12263                           kind,
12264                           pulongest (unit_index), hex_string (signature),
12265                           dwp_file->name);
12266     }
12267
12268   /* Fetch the sections of this DWO unit.
12269      Put a limit on the number of sections we look for so that bad data
12270      doesn't cause us to loop forever.  */
12271
12272 #define MAX_NR_V1_DWO_SECTIONS \
12273   (1 /* .debug_info or .debug_types */ \
12274    + 1 /* .debug_abbrev */ \
12275    + 1 /* .debug_line */ \
12276    + 1 /* .debug_loc */ \
12277    + 1 /* .debug_str_offsets */ \
12278    + 1 /* .debug_macro or .debug_macinfo */ \
12279    + 1 /* trailing zero */)
12280
12281   memset (&sections, 0, sizeof (sections));
12282
12283   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12284     {
12285       asection *sectp;
12286       uint32_t section_nr =
12287         read_4_bytes (dbfd,
12288                       dwp_htab->section_pool.v1.indices
12289                       + (unit_index + i) * sizeof (uint32_t));
12290
12291       if (section_nr == 0)
12292         break;
12293       if (section_nr >= dwp_file->num_sections)
12294         {
12295           error (_("Dwarf Error: bad DWP hash table, section number too large"
12296                    " [in module %s]"),
12297                  dwp_file->name);
12298         }
12299
12300       sectp = dwp_file->elf_sections[section_nr];
12301       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12302         {
12303           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12304                    " [in module %s]"),
12305                  dwp_file->name);
12306         }
12307     }
12308
12309   if (i < 2
12310       || dwarf2_section_empty_p (&sections.info_or_types)
12311       || dwarf2_section_empty_p (&sections.abbrev))
12312     {
12313       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12314                " [in module %s]"),
12315              dwp_file->name);
12316     }
12317   if (i == MAX_NR_V1_DWO_SECTIONS)
12318     {
12319       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12320                " [in module %s]"),
12321              dwp_file->name);
12322     }
12323
12324   /* It's easier for the rest of the code if we fake a struct dwo_file and
12325      have dwo_unit "live" in that.  At least for now.
12326
12327      The DWP file can be made up of a random collection of CUs and TUs.
12328      However, for each CU + set of TUs that came from the same original DWO
12329      file, we can combine them back into a virtual DWO file to save space
12330      (fewer struct dwo_file objects to allocate).  Remember that for really
12331      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12332
12333   std::string virtual_dwo_name =
12334     string_printf ("virtual-dwo/%d-%d-%d-%d",
12335                    get_section_id (&sections.abbrev),
12336                    get_section_id (&sections.line),
12337                    get_section_id (&sections.loc),
12338                    get_section_id (&sections.str_offsets));
12339   /* Can we use an existing virtual DWO file?  */
12340   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12341                                         virtual_dwo_name.c_str (),
12342                                         comp_dir);
12343   /* Create one if necessary.  */
12344   if (*dwo_file_slot == NULL)
12345     {
12346       if (dwarf_read_debug)
12347         {
12348           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12349                               virtual_dwo_name.c_str ());
12350         }
12351       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12352       dwo_file->dwo_name
12353         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12354                                         virtual_dwo_name.c_str (),
12355                                         virtual_dwo_name.size ());
12356       dwo_file->comp_dir = comp_dir;
12357       dwo_file->sections.abbrev = sections.abbrev;
12358       dwo_file->sections.line = sections.line;
12359       dwo_file->sections.loc = sections.loc;
12360       dwo_file->sections.macinfo = sections.macinfo;
12361       dwo_file->sections.macro = sections.macro;
12362       dwo_file->sections.str_offsets = sections.str_offsets;
12363       /* The "str" section is global to the entire DWP file.  */
12364       dwo_file->sections.str = dwp_file->sections.str;
12365       /* The info or types section is assigned below to dwo_unit,
12366          there's no need to record it in dwo_file.
12367          Also, we can't simply record type sections in dwo_file because
12368          we record a pointer into the vector in dwo_unit.  As we collect more
12369          types we'll grow the vector and eventually have to reallocate space
12370          for it, invalidating all copies of pointers into the previous
12371          contents.  */
12372       *dwo_file_slot = dwo_file;
12373     }
12374   else
12375     {
12376       if (dwarf_read_debug)
12377         {
12378           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12379                               virtual_dwo_name.c_str ());
12380         }
12381       dwo_file = (struct dwo_file *) *dwo_file_slot;
12382     }
12383
12384   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12385   dwo_unit->dwo_file = dwo_file;
12386   dwo_unit->signature = signature;
12387   dwo_unit->section =
12388     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12389   *dwo_unit->section = sections.info_or_types;
12390   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12391
12392   return dwo_unit;
12393 }
12394
12395 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12396    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12397    piece within that section used by a TU/CU, return a virtual section
12398    of just that piece.  */
12399
12400 static struct dwarf2_section_info
12401 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12402                        struct dwarf2_section_info *section,
12403                        bfd_size_type offset, bfd_size_type size)
12404 {
12405   struct dwarf2_section_info result;
12406   asection *sectp;
12407
12408   gdb_assert (section != NULL);
12409   gdb_assert (!section->is_virtual);
12410
12411   memset (&result, 0, sizeof (result));
12412   result.s.containing_section = section;
12413   result.is_virtual = 1;
12414
12415   if (size == 0)
12416     return result;
12417
12418   sectp = get_section_bfd_section (section);
12419
12420   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12421      bounds of the real section.  This is a pretty-rare event, so just
12422      flag an error (easier) instead of a warning and trying to cope.  */
12423   if (sectp == NULL
12424       || offset + size > bfd_get_section_size (sectp))
12425     {
12426       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12427                " in section %s [in module %s]"),
12428              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12429              objfile_name (dwarf2_per_objfile->objfile));
12430     }
12431
12432   result.virtual_offset = offset;
12433   result.size = size;
12434   return result;
12435 }
12436
12437 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12438    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12439    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12440    This is for DWP version 2 files.  */
12441
12442 static struct dwo_unit *
12443 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12444                            struct dwp_file *dwp_file,
12445                            uint32_t unit_index,
12446                            const char *comp_dir,
12447                            ULONGEST signature, int is_debug_types)
12448 {
12449   struct objfile *objfile = dwarf2_per_objfile->objfile;
12450   const struct dwp_hash_table *dwp_htab =
12451     is_debug_types ? dwp_file->tus : dwp_file->cus;
12452   bfd *dbfd = dwp_file->dbfd.get ();
12453   const char *kind = is_debug_types ? "TU" : "CU";
12454   struct dwo_file *dwo_file;
12455   struct dwo_unit *dwo_unit;
12456   struct virtual_v2_dwo_sections sections;
12457   void **dwo_file_slot;
12458   int i;
12459
12460   gdb_assert (dwp_file->version == 2);
12461
12462   if (dwarf_read_debug)
12463     {
12464       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12465                           kind,
12466                           pulongest (unit_index), hex_string (signature),
12467                           dwp_file->name);
12468     }
12469
12470   /* Fetch the section offsets of this DWO unit.  */
12471
12472   memset (&sections, 0, sizeof (sections));
12473
12474   for (i = 0; i < dwp_htab->nr_columns; ++i)
12475     {
12476       uint32_t offset = read_4_bytes (dbfd,
12477                                       dwp_htab->section_pool.v2.offsets
12478                                       + (((unit_index - 1) * dwp_htab->nr_columns
12479                                           + i)
12480                                          * sizeof (uint32_t)));
12481       uint32_t size = read_4_bytes (dbfd,
12482                                     dwp_htab->section_pool.v2.sizes
12483                                     + (((unit_index - 1) * dwp_htab->nr_columns
12484                                         + i)
12485                                        * sizeof (uint32_t)));
12486
12487       switch (dwp_htab->section_pool.v2.section_ids[i])
12488         {
12489         case DW_SECT_INFO:
12490         case DW_SECT_TYPES:
12491           sections.info_or_types_offset = offset;
12492           sections.info_or_types_size = size;
12493           break;
12494         case DW_SECT_ABBREV:
12495           sections.abbrev_offset = offset;
12496           sections.abbrev_size = size;
12497           break;
12498         case DW_SECT_LINE:
12499           sections.line_offset = offset;
12500           sections.line_size = size;
12501           break;
12502         case DW_SECT_LOC:
12503           sections.loc_offset = offset;
12504           sections.loc_size = size;
12505           break;
12506         case DW_SECT_STR_OFFSETS:
12507           sections.str_offsets_offset = offset;
12508           sections.str_offsets_size = size;
12509           break;
12510         case DW_SECT_MACINFO:
12511           sections.macinfo_offset = offset;
12512           sections.macinfo_size = size;
12513           break;
12514         case DW_SECT_MACRO:
12515           sections.macro_offset = offset;
12516           sections.macro_size = size;
12517           break;
12518         }
12519     }
12520
12521   /* It's easier for the rest of the code if we fake a struct dwo_file and
12522      have dwo_unit "live" in that.  At least for now.
12523
12524      The DWP file can be made up of a random collection of CUs and TUs.
12525      However, for each CU + set of TUs that came from the same original DWO
12526      file, we can combine them back into a virtual DWO file to save space
12527      (fewer struct dwo_file objects to allocate).  Remember that for really
12528      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12529
12530   std::string virtual_dwo_name =
12531     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12532                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12533                    (long) (sections.line_size ? sections.line_offset : 0),
12534                    (long) (sections.loc_size ? sections.loc_offset : 0),
12535                    (long) (sections.str_offsets_size
12536                            ? sections.str_offsets_offset : 0));
12537   /* Can we use an existing virtual DWO file?  */
12538   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12539                                         virtual_dwo_name.c_str (),
12540                                         comp_dir);
12541   /* Create one if necessary.  */
12542   if (*dwo_file_slot == NULL)
12543     {
12544       if (dwarf_read_debug)
12545         {
12546           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12547                               virtual_dwo_name.c_str ());
12548         }
12549       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12550       dwo_file->dwo_name
12551         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12552                                         virtual_dwo_name.c_str (),
12553                                         virtual_dwo_name.size ());
12554       dwo_file->comp_dir = comp_dir;
12555       dwo_file->sections.abbrev =
12556         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12557                                sections.abbrev_offset, sections.abbrev_size);
12558       dwo_file->sections.line =
12559         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12560                                sections.line_offset, sections.line_size);
12561       dwo_file->sections.loc =
12562         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12563                                sections.loc_offset, sections.loc_size);
12564       dwo_file->sections.macinfo =
12565         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12566                                sections.macinfo_offset, sections.macinfo_size);
12567       dwo_file->sections.macro =
12568         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12569                                sections.macro_offset, sections.macro_size);
12570       dwo_file->sections.str_offsets =
12571         create_dwp_v2_section (dwarf2_per_objfile,
12572                                &dwp_file->sections.str_offsets,
12573                                sections.str_offsets_offset,
12574                                sections.str_offsets_size);
12575       /* The "str" section is global to the entire DWP file.  */
12576       dwo_file->sections.str = dwp_file->sections.str;
12577       /* The info or types section is assigned below to dwo_unit,
12578          there's no need to record it in dwo_file.
12579          Also, we can't simply record type sections in dwo_file because
12580          we record a pointer into the vector in dwo_unit.  As we collect more
12581          types we'll grow the vector and eventually have to reallocate space
12582          for it, invalidating all copies of pointers into the previous
12583          contents.  */
12584       *dwo_file_slot = dwo_file;
12585     }
12586   else
12587     {
12588       if (dwarf_read_debug)
12589         {
12590           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12591                               virtual_dwo_name.c_str ());
12592         }
12593       dwo_file = (struct dwo_file *) *dwo_file_slot;
12594     }
12595
12596   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12597   dwo_unit->dwo_file = dwo_file;
12598   dwo_unit->signature = signature;
12599   dwo_unit->section =
12600     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12601   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12602                                               is_debug_types
12603                                               ? &dwp_file->sections.types
12604                                               : &dwp_file->sections.info,
12605                                               sections.info_or_types_offset,
12606                                               sections.info_or_types_size);
12607   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12608
12609   return dwo_unit;
12610 }
12611
12612 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12613    Returns NULL if the signature isn't found.  */
12614
12615 static struct dwo_unit *
12616 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12617                         struct dwp_file *dwp_file, const char *comp_dir,
12618                         ULONGEST signature, int is_debug_types)
12619 {
12620   const struct dwp_hash_table *dwp_htab =
12621     is_debug_types ? dwp_file->tus : dwp_file->cus;
12622   bfd *dbfd = dwp_file->dbfd.get ();
12623   uint32_t mask = dwp_htab->nr_slots - 1;
12624   uint32_t hash = signature & mask;
12625   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12626   unsigned int i;
12627   void **slot;
12628   struct dwo_unit find_dwo_cu;
12629
12630   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12631   find_dwo_cu.signature = signature;
12632   slot = htab_find_slot (is_debug_types
12633                          ? dwp_file->loaded_tus
12634                          : dwp_file->loaded_cus,
12635                          &find_dwo_cu, INSERT);
12636
12637   if (*slot != NULL)
12638     return (struct dwo_unit *) *slot;
12639
12640   /* Use a for loop so that we don't loop forever on bad debug info.  */
12641   for (i = 0; i < dwp_htab->nr_slots; ++i)
12642     {
12643       ULONGEST signature_in_table;
12644
12645       signature_in_table =
12646         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12647       if (signature_in_table == signature)
12648         {
12649           uint32_t unit_index =
12650             read_4_bytes (dbfd,
12651                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12652
12653           if (dwp_file->version == 1)
12654             {
12655               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12656                                                  dwp_file, unit_index,
12657                                                  comp_dir, signature,
12658                                                  is_debug_types);
12659             }
12660           else
12661             {
12662               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12663                                                  dwp_file, unit_index,
12664                                                  comp_dir, signature,
12665                                                  is_debug_types);
12666             }
12667           return (struct dwo_unit *) *slot;
12668         }
12669       if (signature_in_table == 0)
12670         return NULL;
12671       hash = (hash + hash2) & mask;
12672     }
12673
12674   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12675            " [in module %s]"),
12676          dwp_file->name);
12677 }
12678
12679 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12680    Open the file specified by FILE_NAME and hand it off to BFD for
12681    preliminary analysis.  Return a newly initialized bfd *, which
12682    includes a canonicalized copy of FILE_NAME.
12683    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12684    SEARCH_CWD is true if the current directory is to be searched.
12685    It will be searched before debug-file-directory.
12686    If successful, the file is added to the bfd include table of the
12687    objfile's bfd (see gdb_bfd_record_inclusion).
12688    If unable to find/open the file, return NULL.
12689    NOTE: This function is derived from symfile_bfd_open.  */
12690
12691 static gdb_bfd_ref_ptr
12692 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12693                     const char *file_name, int is_dwp, int search_cwd)
12694 {
12695   int desc;
12696   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12697      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12698      to debug_file_directory.  */
12699   const char *search_path;
12700   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12701
12702   gdb::unique_xmalloc_ptr<char> search_path_holder;
12703   if (search_cwd)
12704     {
12705       if (*debug_file_directory != '\0')
12706         {
12707           search_path_holder.reset (concat (".", dirname_separator_string,
12708                                             debug_file_directory,
12709                                             (char *) NULL));
12710           search_path = search_path_holder.get ();
12711         }
12712       else
12713         search_path = ".";
12714     }
12715   else
12716     search_path = debug_file_directory;
12717
12718   openp_flags flags = OPF_RETURN_REALPATH;
12719   if (is_dwp)
12720     flags |= OPF_SEARCH_IN_PATH;
12721
12722   gdb::unique_xmalloc_ptr<char> absolute_name;
12723   desc = openp (search_path, flags, file_name,
12724                 O_RDONLY | O_BINARY, &absolute_name);
12725   if (desc < 0)
12726     return NULL;
12727
12728   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12729                                          gnutarget, desc));
12730   if (sym_bfd == NULL)
12731     return NULL;
12732   bfd_set_cacheable (sym_bfd.get (), 1);
12733
12734   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12735     return NULL;
12736
12737   /* Success.  Record the bfd as having been included by the objfile's bfd.
12738      This is important because things like demangled_names_hash lives in the
12739      objfile's per_bfd space and may have references to things like symbol
12740      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12741   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12742
12743   return sym_bfd;
12744 }
12745
12746 /* Try to open DWO file FILE_NAME.
12747    COMP_DIR is the DW_AT_comp_dir attribute.
12748    The result is the bfd handle of the file.
12749    If there is a problem finding or opening the file, return NULL.
12750    Upon success, the canonicalized path of the file is stored in the bfd,
12751    same as symfile_bfd_open.  */
12752
12753 static gdb_bfd_ref_ptr
12754 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12755                const char *file_name, const char *comp_dir)
12756 {
12757   if (IS_ABSOLUTE_PATH (file_name))
12758     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12759                                0 /*is_dwp*/, 0 /*search_cwd*/);
12760
12761   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12762
12763   if (comp_dir != NULL)
12764     {
12765       char *path_to_try = concat (comp_dir, SLASH_STRING,
12766                                   file_name, (char *) NULL);
12767
12768       /* NOTE: If comp_dir is a relative path, this will also try the
12769          search path, which seems useful.  */
12770       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12771                                                 path_to_try,
12772                                                 0 /*is_dwp*/,
12773                                                 1 /*search_cwd*/));
12774       xfree (path_to_try);
12775       if (abfd != NULL)
12776         return abfd;
12777     }
12778
12779   /* That didn't work, try debug-file-directory, which, despite its name,
12780      is a list of paths.  */
12781
12782   if (*debug_file_directory == '\0')
12783     return NULL;
12784
12785   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12786                              0 /*is_dwp*/, 1 /*search_cwd*/);
12787 }
12788
12789 /* This function is mapped across the sections and remembers the offset and
12790    size of each of the DWO debugging sections we are interested in.  */
12791
12792 static void
12793 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12794 {
12795   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12796   const struct dwop_section_names *names = &dwop_section_names;
12797
12798   if (section_is_p (sectp->name, &names->abbrev_dwo))
12799     {
12800       dwo_sections->abbrev.s.section = sectp;
12801       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12802     }
12803   else if (section_is_p (sectp->name, &names->info_dwo))
12804     {
12805       dwo_sections->info.s.section = sectp;
12806       dwo_sections->info.size = bfd_get_section_size (sectp);
12807     }
12808   else if (section_is_p (sectp->name, &names->line_dwo))
12809     {
12810       dwo_sections->line.s.section = sectp;
12811       dwo_sections->line.size = bfd_get_section_size (sectp);
12812     }
12813   else if (section_is_p (sectp->name, &names->loc_dwo))
12814     {
12815       dwo_sections->loc.s.section = sectp;
12816       dwo_sections->loc.size = bfd_get_section_size (sectp);
12817     }
12818   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12819     {
12820       dwo_sections->macinfo.s.section = sectp;
12821       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12822     }
12823   else if (section_is_p (sectp->name, &names->macro_dwo))
12824     {
12825       dwo_sections->macro.s.section = sectp;
12826       dwo_sections->macro.size = bfd_get_section_size (sectp);
12827     }
12828   else if (section_is_p (sectp->name, &names->str_dwo))
12829     {
12830       dwo_sections->str.s.section = sectp;
12831       dwo_sections->str.size = bfd_get_section_size (sectp);
12832     }
12833   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12834     {
12835       dwo_sections->str_offsets.s.section = sectp;
12836       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12837     }
12838   else if (section_is_p (sectp->name, &names->types_dwo))
12839     {
12840       struct dwarf2_section_info type_section;
12841
12842       memset (&type_section, 0, sizeof (type_section));
12843       type_section.s.section = sectp;
12844       type_section.size = bfd_get_section_size (sectp);
12845       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12846                      &type_section);
12847     }
12848 }
12849
12850 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12851    by PER_CU.  This is for the non-DWP case.
12852    The result is NULL if DWO_NAME can't be found.  */
12853
12854 static struct dwo_file *
12855 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12856                         const char *dwo_name, const char *comp_dir)
12857 {
12858   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12859   struct objfile *objfile = dwarf2_per_objfile->objfile;
12860
12861   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12862   if (dbfd == NULL)
12863     {
12864       if (dwarf_read_debug)
12865         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12866       return NULL;
12867     }
12868
12869   /* We use a unique pointer here, despite the obstack allocation,
12870      because a dwo_file needs some cleanup if it is abandoned.  */
12871   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12872                                         struct dwo_file));
12873   dwo_file->dwo_name = dwo_name;
12874   dwo_file->comp_dir = comp_dir;
12875   dwo_file->dbfd = dbfd.release ();
12876
12877   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12878                          &dwo_file->sections);
12879
12880   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12881                          dwo_file->cus);
12882
12883   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12884                                  dwo_file->sections.types, dwo_file->tus);
12885
12886   if (dwarf_read_debug)
12887     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12888
12889   return dwo_file.release ();
12890 }
12891
12892 /* This function is mapped across the sections and remembers the offset and
12893    size of each of the DWP debugging sections common to version 1 and 2 that
12894    we are interested in.  */
12895
12896 static void
12897 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12898                                    void *dwp_file_ptr)
12899 {
12900   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12901   const struct dwop_section_names *names = &dwop_section_names;
12902   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12903
12904   /* Record the ELF section number for later lookup: this is what the
12905      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12906   gdb_assert (elf_section_nr < dwp_file->num_sections);
12907   dwp_file->elf_sections[elf_section_nr] = sectp;
12908
12909   /* Look for specific sections that we need.  */
12910   if (section_is_p (sectp->name, &names->str_dwo))
12911     {
12912       dwp_file->sections.str.s.section = sectp;
12913       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12914     }
12915   else if (section_is_p (sectp->name, &names->cu_index))
12916     {
12917       dwp_file->sections.cu_index.s.section = sectp;
12918       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12919     }
12920   else if (section_is_p (sectp->name, &names->tu_index))
12921     {
12922       dwp_file->sections.tu_index.s.section = sectp;
12923       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12924     }
12925 }
12926
12927 /* This function is mapped across the sections and remembers the offset and
12928    size of each of the DWP version 2 debugging sections that we are interested
12929    in.  This is split into a separate function because we don't know if we
12930    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12931
12932 static void
12933 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12934 {
12935   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12936   const struct dwop_section_names *names = &dwop_section_names;
12937   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12938
12939   /* Record the ELF section number for later lookup: this is what the
12940      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12941   gdb_assert (elf_section_nr < dwp_file->num_sections);
12942   dwp_file->elf_sections[elf_section_nr] = sectp;
12943
12944   /* Look for specific sections that we need.  */
12945   if (section_is_p (sectp->name, &names->abbrev_dwo))
12946     {
12947       dwp_file->sections.abbrev.s.section = sectp;
12948       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12949     }
12950   else if (section_is_p (sectp->name, &names->info_dwo))
12951     {
12952       dwp_file->sections.info.s.section = sectp;
12953       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12954     }
12955   else if (section_is_p (sectp->name, &names->line_dwo))
12956     {
12957       dwp_file->sections.line.s.section = sectp;
12958       dwp_file->sections.line.size = bfd_get_section_size (sectp);
12959     }
12960   else if (section_is_p (sectp->name, &names->loc_dwo))
12961     {
12962       dwp_file->sections.loc.s.section = sectp;
12963       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
12964     }
12965   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12966     {
12967       dwp_file->sections.macinfo.s.section = sectp;
12968       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
12969     }
12970   else if (section_is_p (sectp->name, &names->macro_dwo))
12971     {
12972       dwp_file->sections.macro.s.section = sectp;
12973       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
12974     }
12975   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12976     {
12977       dwp_file->sections.str_offsets.s.section = sectp;
12978       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
12979     }
12980   else if (section_is_p (sectp->name, &names->types_dwo))
12981     {
12982       dwp_file->sections.types.s.section = sectp;
12983       dwp_file->sections.types.size = bfd_get_section_size (sectp);
12984     }
12985 }
12986
12987 /* Hash function for dwp_file loaded CUs/TUs.  */
12988
12989 static hashval_t
12990 hash_dwp_loaded_cutus (const void *item)
12991 {
12992   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12993
12994   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12995   return dwo_unit->signature;
12996 }
12997
12998 /* Equality function for dwp_file loaded CUs/TUs.  */
12999
13000 static int
13001 eq_dwp_loaded_cutus (const void *a, const void *b)
13002 {
13003   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13004   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13005
13006   return dua->signature == dub->signature;
13007 }
13008
13009 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13010
13011 static htab_t
13012 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13013 {
13014   return htab_create_alloc_ex (3,
13015                                hash_dwp_loaded_cutus,
13016                                eq_dwp_loaded_cutus,
13017                                NULL,
13018                                &objfile->objfile_obstack,
13019                                hashtab_obstack_allocate,
13020                                dummy_obstack_deallocate);
13021 }
13022
13023 /* Try to open DWP file FILE_NAME.
13024    The result is the bfd handle of the file.
13025    If there is a problem finding or opening the file, return NULL.
13026    Upon success, the canonicalized path of the file is stored in the bfd,
13027    same as symfile_bfd_open.  */
13028
13029 static gdb_bfd_ref_ptr
13030 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13031                const char *file_name)
13032 {
13033   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13034                                             1 /*is_dwp*/,
13035                                             1 /*search_cwd*/));
13036   if (abfd != NULL)
13037     return abfd;
13038
13039   /* Work around upstream bug 15652.
13040      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13041      [Whether that's a "bug" is debatable, but it is getting in our way.]
13042      We have no real idea where the dwp file is, because gdb's realpath-ing
13043      of the executable's path may have discarded the needed info.
13044      [IWBN if the dwp file name was recorded in the executable, akin to
13045      .gnu_debuglink, but that doesn't exist yet.]
13046      Strip the directory from FILE_NAME and search again.  */
13047   if (*debug_file_directory != '\0')
13048     {
13049       /* Don't implicitly search the current directory here.
13050          If the user wants to search "." to handle this case,
13051          it must be added to debug-file-directory.  */
13052       return try_open_dwop_file (dwarf2_per_objfile,
13053                                  lbasename (file_name), 1 /*is_dwp*/,
13054                                  0 /*search_cwd*/);
13055     }
13056
13057   return NULL;
13058 }
13059
13060 /* Initialize the use of the DWP file for the current objfile.
13061    By convention the name of the DWP file is ${objfile}.dwp.
13062    The result is NULL if it can't be found.  */
13063
13064 static std::unique_ptr<struct dwp_file>
13065 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13066 {
13067   struct objfile *objfile = dwarf2_per_objfile->objfile;
13068
13069   /* Try to find first .dwp for the binary file before any symbolic links
13070      resolving.  */
13071
13072   /* If the objfile is a debug file, find the name of the real binary
13073      file and get the name of dwp file from there.  */
13074   std::string dwp_name;
13075   if (objfile->separate_debug_objfile_backlink != NULL)
13076     {
13077       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13078       const char *backlink_basename = lbasename (backlink->original_name);
13079
13080       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13081     }
13082   else
13083     dwp_name = objfile->original_name;
13084
13085   dwp_name += ".dwp";
13086
13087   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13088   if (dbfd == NULL
13089       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13090     {
13091       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13092       dwp_name = objfile_name (objfile);
13093       dwp_name += ".dwp";
13094       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13095     }
13096
13097   if (dbfd == NULL)
13098     {
13099       if (dwarf_read_debug)
13100         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13101       return std::unique_ptr<dwp_file> ();
13102     }
13103
13104   const char *name = bfd_get_filename (dbfd.get ());
13105   std::unique_ptr<struct dwp_file> dwp_file
13106     (new struct dwp_file (name, std::move (dbfd)));
13107
13108   /* +1: section 0 is unused */
13109   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13110   dwp_file->elf_sections =
13111     OBSTACK_CALLOC (&objfile->objfile_obstack,
13112                     dwp_file->num_sections, asection *);
13113
13114   bfd_map_over_sections (dwp_file->dbfd.get (),
13115                          dwarf2_locate_common_dwp_sections,
13116                          dwp_file.get ());
13117
13118   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13119                                          0);
13120
13121   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13122                                          1);
13123
13124   /* The DWP file version is stored in the hash table.  Oh well.  */
13125   if (dwp_file->cus && dwp_file->tus
13126       && dwp_file->cus->version != dwp_file->tus->version)
13127     {
13128       /* Technically speaking, we should try to limp along, but this is
13129          pretty bizarre.  We use pulongest here because that's the established
13130          portability solution (e.g, we cannot use %u for uint32_t).  */
13131       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13132                " TU version %s [in DWP file %s]"),
13133              pulongest (dwp_file->cus->version),
13134              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13135     }
13136
13137   if (dwp_file->cus)
13138     dwp_file->version = dwp_file->cus->version;
13139   else if (dwp_file->tus)
13140     dwp_file->version = dwp_file->tus->version;
13141   else
13142     dwp_file->version = 2;
13143
13144   if (dwp_file->version == 2)
13145     bfd_map_over_sections (dwp_file->dbfd.get (),
13146                            dwarf2_locate_v2_dwp_sections,
13147                            dwp_file.get ());
13148
13149   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13150   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13151
13152   if (dwarf_read_debug)
13153     {
13154       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13155       fprintf_unfiltered (gdb_stdlog,
13156                           "    %s CUs, %s TUs\n",
13157                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13158                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13159     }
13160
13161   return dwp_file;
13162 }
13163
13164 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13165
13166 static struct dwp_file *
13167 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13168 {
13169   if (! dwarf2_per_objfile->dwp_checked)
13170     {
13171       dwarf2_per_objfile->dwp_file
13172         = open_and_init_dwp_file (dwarf2_per_objfile);
13173       dwarf2_per_objfile->dwp_checked = 1;
13174     }
13175   return dwarf2_per_objfile->dwp_file.get ();
13176 }
13177
13178 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13179    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13180    or in the DWP file for the objfile, referenced by THIS_UNIT.
13181    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13182    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13183
13184    This is called, for example, when wanting to read a variable with a
13185    complex location.  Therefore we don't want to do file i/o for every call.
13186    Therefore we don't want to look for a DWO file on every call.
13187    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13188    then we check if we've already seen DWO_NAME, and only THEN do we check
13189    for a DWO file.
13190
13191    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13192    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13193
13194 static struct dwo_unit *
13195 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13196                  const char *dwo_name, const char *comp_dir,
13197                  ULONGEST signature, int is_debug_types)
13198 {
13199   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13200   struct objfile *objfile = dwarf2_per_objfile->objfile;
13201   const char *kind = is_debug_types ? "TU" : "CU";
13202   void **dwo_file_slot;
13203   struct dwo_file *dwo_file;
13204   struct dwp_file *dwp_file;
13205
13206   /* First see if there's a DWP file.
13207      If we have a DWP file but didn't find the DWO inside it, don't
13208      look for the original DWO file.  It makes gdb behave differently
13209      depending on whether one is debugging in the build tree.  */
13210
13211   dwp_file = get_dwp_file (dwarf2_per_objfile);
13212   if (dwp_file != NULL)
13213     {
13214       const struct dwp_hash_table *dwp_htab =
13215         is_debug_types ? dwp_file->tus : dwp_file->cus;
13216
13217       if (dwp_htab != NULL)
13218         {
13219           struct dwo_unit *dwo_cutu =
13220             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13221                                     signature, is_debug_types);
13222
13223           if (dwo_cutu != NULL)
13224             {
13225               if (dwarf_read_debug)
13226                 {
13227                   fprintf_unfiltered (gdb_stdlog,
13228                                       "Virtual DWO %s %s found: @%s\n",
13229                                       kind, hex_string (signature),
13230                                       host_address_to_string (dwo_cutu));
13231                 }
13232               return dwo_cutu;
13233             }
13234         }
13235     }
13236   else
13237     {
13238       /* No DWP file, look for the DWO file.  */
13239
13240       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13241                                             dwo_name, comp_dir);
13242       if (*dwo_file_slot == NULL)
13243         {
13244           /* Read in the file and build a table of the CUs/TUs it contains.  */
13245           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13246         }
13247       /* NOTE: This will be NULL if unable to open the file.  */
13248       dwo_file = (struct dwo_file *) *dwo_file_slot;
13249
13250       if (dwo_file != NULL)
13251         {
13252           struct dwo_unit *dwo_cutu = NULL;
13253
13254           if (is_debug_types && dwo_file->tus)
13255             {
13256               struct dwo_unit find_dwo_cutu;
13257
13258               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13259               find_dwo_cutu.signature = signature;
13260               dwo_cutu
13261                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13262             }
13263           else if (!is_debug_types && dwo_file->cus)
13264             {
13265               struct dwo_unit find_dwo_cutu;
13266
13267               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13268               find_dwo_cutu.signature = signature;
13269               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13270                                                        &find_dwo_cutu);
13271             }
13272
13273           if (dwo_cutu != NULL)
13274             {
13275               if (dwarf_read_debug)
13276                 {
13277                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13278                                       kind, dwo_name, hex_string (signature),
13279                                       host_address_to_string (dwo_cutu));
13280                 }
13281               return dwo_cutu;
13282             }
13283         }
13284     }
13285
13286   /* We didn't find it.  This could mean a dwo_id mismatch, or
13287      someone deleted the DWO/DWP file, or the search path isn't set up
13288      correctly to find the file.  */
13289
13290   if (dwarf_read_debug)
13291     {
13292       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13293                           kind, dwo_name, hex_string (signature));
13294     }
13295
13296   /* This is a warning and not a complaint because it can be caused by
13297      pilot error (e.g., user accidentally deleting the DWO).  */
13298   {
13299     /* Print the name of the DWP file if we looked there, helps the user
13300        better diagnose the problem.  */
13301     std::string dwp_text;
13302
13303     if (dwp_file != NULL)
13304       dwp_text = string_printf (" [in DWP file %s]",
13305                                 lbasename (dwp_file->name));
13306
13307     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13308                " [in module %s]"),
13309              kind, dwo_name, hex_string (signature),
13310              dwp_text.c_str (),
13311              this_unit->is_debug_types ? "TU" : "CU",
13312              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13313   }
13314   return NULL;
13315 }
13316
13317 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13318    See lookup_dwo_cutu_unit for details.  */
13319
13320 static struct dwo_unit *
13321 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13322                       const char *dwo_name, const char *comp_dir,
13323                       ULONGEST signature)
13324 {
13325   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13326 }
13327
13328 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13329    See lookup_dwo_cutu_unit for details.  */
13330
13331 static struct dwo_unit *
13332 lookup_dwo_type_unit (struct signatured_type *this_tu,
13333                       const char *dwo_name, const char *comp_dir)
13334 {
13335   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13336 }
13337
13338 /* Traversal function for queue_and_load_all_dwo_tus.  */
13339
13340 static int
13341 queue_and_load_dwo_tu (void **slot, void *info)
13342 {
13343   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13344   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13345   ULONGEST signature = dwo_unit->signature;
13346   struct signatured_type *sig_type =
13347     lookup_dwo_signatured_type (per_cu->cu, signature);
13348
13349   if (sig_type != NULL)
13350     {
13351       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13352
13353       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13354          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13355          while processing PER_CU.  */
13356       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13357         load_full_type_unit (sig_cu);
13358       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13359     }
13360
13361   return 1;
13362 }
13363
13364 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13365    The DWO may have the only definition of the type, though it may not be
13366    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13367    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13368
13369 static void
13370 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13371 {
13372   struct dwo_unit *dwo_unit;
13373   struct dwo_file *dwo_file;
13374
13375   gdb_assert (!per_cu->is_debug_types);
13376   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13377   gdb_assert (per_cu->cu != NULL);
13378
13379   dwo_unit = per_cu->cu->dwo_unit;
13380   gdb_assert (dwo_unit != NULL);
13381
13382   dwo_file = dwo_unit->dwo_file;
13383   if (dwo_file->tus != NULL)
13384     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13385 }
13386
13387 /* Free all resources associated with DWO_FILE.
13388    Close the DWO file and munmap the sections.  */
13389
13390 static void
13391 free_dwo_file (struct dwo_file *dwo_file)
13392 {
13393   /* Note: dbfd is NULL for virtual DWO files.  */
13394   gdb_bfd_unref (dwo_file->dbfd);
13395
13396   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13397 }
13398
13399 /* Traversal function for free_dwo_files.  */
13400
13401 static int
13402 free_dwo_file_from_slot (void **slot, void *info)
13403 {
13404   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13405
13406   free_dwo_file (dwo_file);
13407
13408   return 1;
13409 }
13410
13411 /* Free all resources associated with DWO_FILES.  */
13412
13413 static void
13414 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13415 {
13416   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13417 }
13418 \f
13419 /* Read in various DIEs.  */
13420
13421 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13422    Inherit only the children of the DW_AT_abstract_origin DIE not being
13423    already referenced by DW_AT_abstract_origin from the children of the
13424    current DIE.  */
13425
13426 static void
13427 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13428 {
13429   struct die_info *child_die;
13430   sect_offset *offsetp;
13431   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13432   struct die_info *origin_die;
13433   /* Iterator of the ORIGIN_DIE children.  */
13434   struct die_info *origin_child_die;
13435   struct attribute *attr;
13436   struct dwarf2_cu *origin_cu;
13437   struct pending **origin_previous_list_in_scope;
13438
13439   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13440   if (!attr)
13441     return;
13442
13443   /* Note that following die references may follow to a die in a
13444      different cu.  */
13445
13446   origin_cu = cu;
13447   origin_die = follow_die_ref (die, attr, &origin_cu);
13448
13449   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13450      symbols in.  */
13451   origin_previous_list_in_scope = origin_cu->list_in_scope;
13452   origin_cu->list_in_scope = cu->list_in_scope;
13453
13454   if (die->tag != origin_die->tag
13455       && !(die->tag == DW_TAG_inlined_subroutine
13456            && origin_die->tag == DW_TAG_subprogram))
13457     complaint (_("DIE %s and its abstract origin %s have different tags"),
13458                sect_offset_str (die->sect_off),
13459                sect_offset_str (origin_die->sect_off));
13460
13461   std::vector<sect_offset> offsets;
13462
13463   for (child_die = die->child;
13464        child_die && child_die->tag;
13465        child_die = sibling_die (child_die))
13466     {
13467       struct die_info *child_origin_die;
13468       struct dwarf2_cu *child_origin_cu;
13469
13470       /* We are trying to process concrete instance entries:
13471          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13472          it's not relevant to our analysis here. i.e. detecting DIEs that are
13473          present in the abstract instance but not referenced in the concrete
13474          one.  */
13475       if (child_die->tag == DW_TAG_call_site
13476           || child_die->tag == DW_TAG_GNU_call_site)
13477         continue;
13478
13479       /* For each CHILD_DIE, find the corresponding child of
13480          ORIGIN_DIE.  If there is more than one layer of
13481          DW_AT_abstract_origin, follow them all; there shouldn't be,
13482          but GCC versions at least through 4.4 generate this (GCC PR
13483          40573).  */
13484       child_origin_die = child_die;
13485       child_origin_cu = cu;
13486       while (1)
13487         {
13488           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13489                               child_origin_cu);
13490           if (attr == NULL)
13491             break;
13492           child_origin_die = follow_die_ref (child_origin_die, attr,
13493                                              &child_origin_cu);
13494         }
13495
13496       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13497          counterpart may exist.  */
13498       if (child_origin_die != child_die)
13499         {
13500           if (child_die->tag != child_origin_die->tag
13501               && !(child_die->tag == DW_TAG_inlined_subroutine
13502                    && child_origin_die->tag == DW_TAG_subprogram))
13503             complaint (_("Child DIE %s and its abstract origin %s have "
13504                          "different tags"),
13505                        sect_offset_str (child_die->sect_off),
13506                        sect_offset_str (child_origin_die->sect_off));
13507           if (child_origin_die->parent != origin_die)
13508             complaint (_("Child DIE %s and its abstract origin %s have "
13509                          "different parents"),
13510                        sect_offset_str (child_die->sect_off),
13511                        sect_offset_str (child_origin_die->sect_off));
13512           else
13513             offsets.push_back (child_origin_die->sect_off);
13514         }
13515     }
13516   std::sort (offsets.begin (), offsets.end ());
13517   sect_offset *offsets_end = offsets.data () + offsets.size ();
13518   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13519     if (offsetp[-1] == *offsetp)
13520       complaint (_("Multiple children of DIE %s refer "
13521                    "to DIE %s as their abstract origin"),
13522                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13523
13524   offsetp = offsets.data ();
13525   origin_child_die = origin_die->child;
13526   while (origin_child_die && origin_child_die->tag)
13527     {
13528       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13529       while (offsetp < offsets_end
13530              && *offsetp < origin_child_die->sect_off)
13531         offsetp++;
13532       if (offsetp >= offsets_end
13533           || *offsetp > origin_child_die->sect_off)
13534         {
13535           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13536              Check whether we're already processing ORIGIN_CHILD_DIE.
13537              This can happen with mutually referenced abstract_origins.
13538              PR 16581.  */
13539           if (!origin_child_die->in_process)
13540             process_die (origin_child_die, origin_cu);
13541         }
13542       origin_child_die = sibling_die (origin_child_die);
13543     }
13544   origin_cu->list_in_scope = origin_previous_list_in_scope;
13545 }
13546
13547 static void
13548 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13549 {
13550   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13551   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13552   struct context_stack *newobj;
13553   CORE_ADDR lowpc;
13554   CORE_ADDR highpc;
13555   struct die_info *child_die;
13556   struct attribute *attr, *call_line, *call_file;
13557   const char *name;
13558   CORE_ADDR baseaddr;
13559   struct block *block;
13560   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13561   std::vector<struct symbol *> template_args;
13562   struct template_symbol *templ_func = NULL;
13563
13564   if (inlined_func)
13565     {
13566       /* If we do not have call site information, we can't show the
13567          caller of this inlined function.  That's too confusing, so
13568          only use the scope for local variables.  */
13569       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13570       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13571       if (call_line == NULL || call_file == NULL)
13572         {
13573           read_lexical_block_scope (die, cu);
13574           return;
13575         }
13576     }
13577
13578   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13579
13580   name = dwarf2_name (die, cu);
13581
13582   /* Ignore functions with missing or empty names.  These are actually
13583      illegal according to the DWARF standard.  */
13584   if (name == NULL)
13585     {
13586       complaint (_("missing name for subprogram DIE at %s"),
13587                  sect_offset_str (die->sect_off));
13588       return;
13589     }
13590
13591   /* Ignore functions with missing or invalid low and high pc attributes.  */
13592   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13593       <= PC_BOUNDS_INVALID)
13594     {
13595       attr = dwarf2_attr (die, DW_AT_external, cu);
13596       if (!attr || !DW_UNSND (attr))
13597         complaint (_("cannot get low and high bounds "
13598                      "for subprogram DIE at %s"),
13599                    sect_offset_str (die->sect_off));
13600       return;
13601     }
13602
13603   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13604   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13605
13606   /* If we have any template arguments, then we must allocate a
13607      different sort of symbol.  */
13608   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13609     {
13610       if (child_die->tag == DW_TAG_template_type_param
13611           || child_die->tag == DW_TAG_template_value_param)
13612         {
13613           templ_func = allocate_template_symbol (objfile);
13614           templ_func->subclass = SYMBOL_TEMPLATE;
13615           break;
13616         }
13617     }
13618
13619   newobj = push_context (0, lowpc);
13620   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13621                              (struct symbol *) templ_func);
13622
13623   /* If there is a location expression for DW_AT_frame_base, record
13624      it.  */
13625   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13626   if (attr)
13627     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13628
13629   /* If there is a location for the static link, record it.  */
13630   newobj->static_link = NULL;
13631   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13632   if (attr)
13633     {
13634       newobj->static_link
13635         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13636       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13637     }
13638
13639   cu->list_in_scope = &local_symbols;
13640
13641   if (die->child != NULL)
13642     {
13643       child_die = die->child;
13644       while (child_die && child_die->tag)
13645         {
13646           if (child_die->tag == DW_TAG_template_type_param
13647               || child_die->tag == DW_TAG_template_value_param)
13648             {
13649               struct symbol *arg = new_symbol (child_die, NULL, cu);
13650
13651               if (arg != NULL)
13652                 template_args.push_back (arg);
13653             }
13654           else
13655             process_die (child_die, cu);
13656           child_die = sibling_die (child_die);
13657         }
13658     }
13659
13660   inherit_abstract_dies (die, cu);
13661
13662   /* If we have a DW_AT_specification, we might need to import using
13663      directives from the context of the specification DIE.  See the
13664      comment in determine_prefix.  */
13665   if (cu->language == language_cplus
13666       && dwarf2_attr (die, DW_AT_specification, cu))
13667     {
13668       struct dwarf2_cu *spec_cu = cu;
13669       struct die_info *spec_die = die_specification (die, &spec_cu);
13670
13671       while (spec_die)
13672         {
13673           child_die = spec_die->child;
13674           while (child_die && child_die->tag)
13675             {
13676               if (child_die->tag == DW_TAG_imported_module)
13677                 process_die (child_die, spec_cu);
13678               child_die = sibling_die (child_die);
13679             }
13680
13681           /* In some cases, GCC generates specification DIEs that
13682              themselves contain DW_AT_specification attributes.  */
13683           spec_die = die_specification (spec_die, &spec_cu);
13684         }
13685     }
13686
13687   newobj = pop_context ();
13688   /* Make a block for the local symbols within.  */
13689   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13690                         newobj->static_link, lowpc, highpc);
13691
13692   /* For C++, set the block's scope.  */
13693   if ((cu->language == language_cplus
13694        || cu->language == language_fortran
13695        || cu->language == language_d
13696        || cu->language == language_rust)
13697       && cu->processing_has_namespace_info)
13698     block_set_scope (block, determine_prefix (die, cu),
13699                      &objfile->objfile_obstack);
13700
13701   /* If we have address ranges, record them.  */
13702   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13703
13704   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13705
13706   /* Attach template arguments to function.  */
13707   if (!template_args.empty ())
13708     {
13709       gdb_assert (templ_func != NULL);
13710
13711       templ_func->n_template_arguments = template_args.size ();
13712       templ_func->template_arguments
13713         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13714                      templ_func->n_template_arguments);
13715       memcpy (templ_func->template_arguments,
13716               template_args.data (),
13717               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13718     }
13719
13720   /* In C++, we can have functions nested inside functions (e.g., when
13721      a function declares a class that has methods).  This means that
13722      when we finish processing a function scope, we may need to go
13723      back to building a containing block's symbol lists.  */
13724   local_symbols = newobj->locals;
13725   local_using_directives = newobj->local_using_directives;
13726
13727   /* If we've finished processing a top-level function, subsequent
13728      symbols go in the file symbol list.  */
13729   if (outermost_context_p ())
13730     cu->list_in_scope = &file_symbols;
13731 }
13732
13733 /* Process all the DIES contained within a lexical block scope.  Start
13734    a new scope, process the dies, and then close the scope.  */
13735
13736 static void
13737 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13738 {
13739   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13740   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13741   struct context_stack *newobj;
13742   CORE_ADDR lowpc, highpc;
13743   struct die_info *child_die;
13744   CORE_ADDR baseaddr;
13745
13746   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13747
13748   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13749   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13750      as multiple lexical blocks?  Handling children in a sane way would
13751      be nasty.  Might be easier to properly extend generic blocks to
13752      describe ranges.  */
13753   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13754     {
13755     case PC_BOUNDS_NOT_PRESENT:
13756       /* DW_TAG_lexical_block has no attributes, process its children as if
13757          there was no wrapping by that DW_TAG_lexical_block.
13758          GCC does no longer produces such DWARF since GCC r224161.  */
13759       for (child_die = die->child;
13760            child_die != NULL && child_die->tag;
13761            child_die = sibling_die (child_die))
13762         process_die (child_die, cu);
13763       return;
13764     case PC_BOUNDS_INVALID:
13765       return;
13766     }
13767   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13768   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13769
13770   push_context (0, lowpc);
13771   if (die->child != NULL)
13772     {
13773       child_die = die->child;
13774       while (child_die && child_die->tag)
13775         {
13776           process_die (child_die, cu);
13777           child_die = sibling_die (child_die);
13778         }
13779     }
13780   inherit_abstract_dies (die, cu);
13781   newobj = pop_context ();
13782
13783   if (local_symbols != NULL || local_using_directives != NULL)
13784     {
13785       struct block *block
13786         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13787                         newobj->start_addr, highpc);
13788
13789       /* Note that recording ranges after traversing children, as we
13790          do here, means that recording a parent's ranges entails
13791          walking across all its children's ranges as they appear in
13792          the address map, which is quadratic behavior.
13793
13794          It would be nicer to record the parent's ranges before
13795          traversing its children, simply overriding whatever you find
13796          there.  But since we don't even decide whether to create a
13797          block until after we've traversed its children, that's hard
13798          to do.  */
13799       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13800     }
13801   local_symbols = newobj->locals;
13802   local_using_directives = newobj->local_using_directives;
13803 }
13804
13805 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13806
13807 static void
13808 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13809 {
13810   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13811   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13812   CORE_ADDR pc, baseaddr;
13813   struct attribute *attr;
13814   struct call_site *call_site, call_site_local;
13815   void **slot;
13816   int nparams;
13817   struct die_info *child_die;
13818
13819   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13820
13821   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13822   if (attr == NULL)
13823     {
13824       /* This was a pre-DWARF-5 GNU extension alias
13825          for DW_AT_call_return_pc.  */
13826       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13827     }
13828   if (!attr)
13829     {
13830       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13831                    "DIE %s [in module %s]"),
13832                  sect_offset_str (die->sect_off), objfile_name (objfile));
13833       return;
13834     }
13835   pc = attr_value_as_address (attr) + baseaddr;
13836   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13837
13838   if (cu->call_site_htab == NULL)
13839     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13840                                                NULL, &objfile->objfile_obstack,
13841                                                hashtab_obstack_allocate, NULL);
13842   call_site_local.pc = pc;
13843   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13844   if (*slot != NULL)
13845     {
13846       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13847                    "DIE %s [in module %s]"),
13848                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13849                  objfile_name (objfile));
13850       return;
13851     }
13852
13853   /* Count parameters at the caller.  */
13854
13855   nparams = 0;
13856   for (child_die = die->child; child_die && child_die->tag;
13857        child_die = sibling_die (child_die))
13858     {
13859       if (child_die->tag != DW_TAG_call_site_parameter
13860           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13861         {
13862           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13863                        "DW_TAG_call_site child DIE %s [in module %s]"),
13864                      child_die->tag, sect_offset_str (child_die->sect_off),
13865                      objfile_name (objfile));
13866           continue;
13867         }
13868
13869       nparams++;
13870     }
13871
13872   call_site
13873     = ((struct call_site *)
13874        obstack_alloc (&objfile->objfile_obstack,
13875                       sizeof (*call_site)
13876                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13877   *slot = call_site;
13878   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13879   call_site->pc = pc;
13880
13881   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13882       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13883     {
13884       struct die_info *func_die;
13885
13886       /* Skip also over DW_TAG_inlined_subroutine.  */
13887       for (func_die = die->parent;
13888            func_die && func_die->tag != DW_TAG_subprogram
13889            && func_die->tag != DW_TAG_subroutine_type;
13890            func_die = func_die->parent);
13891
13892       /* DW_AT_call_all_calls is a superset
13893          of DW_AT_call_all_tail_calls.  */
13894       if (func_die
13895           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13896           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13897           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13898           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13899         {
13900           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13901              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13902              both the initial caller containing the real return address PC and
13903              the final callee containing the current PC of a chain of tail
13904              calls do not need to have the tail call list complete.  But any
13905              function candidate for a virtual tail call frame searched via
13906              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13907              determined unambiguously.  */
13908         }
13909       else
13910         {
13911           struct type *func_type = NULL;
13912
13913           if (func_die)
13914             func_type = get_die_type (func_die, cu);
13915           if (func_type != NULL)
13916             {
13917               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13918
13919               /* Enlist this call site to the function.  */
13920               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13921               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13922             }
13923           else
13924             complaint (_("Cannot find function owning DW_TAG_call_site "
13925                          "DIE %s [in module %s]"),
13926                        sect_offset_str (die->sect_off), objfile_name (objfile));
13927         }
13928     }
13929
13930   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13931   if (attr == NULL)
13932     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13933   if (attr == NULL)
13934     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13935   if (attr == NULL)
13936     {
13937       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13938       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13939     }
13940   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13941   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13942     /* Keep NULL DWARF_BLOCK.  */;
13943   else if (attr_form_is_block (attr))
13944     {
13945       struct dwarf2_locexpr_baton *dlbaton;
13946
13947       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13948       dlbaton->data = DW_BLOCK (attr)->data;
13949       dlbaton->size = DW_BLOCK (attr)->size;
13950       dlbaton->per_cu = cu->per_cu;
13951
13952       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13953     }
13954   else if (attr_form_is_ref (attr))
13955     {
13956       struct dwarf2_cu *target_cu = cu;
13957       struct die_info *target_die;
13958
13959       target_die = follow_die_ref (die, attr, &target_cu);
13960       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13961       if (die_is_declaration (target_die, target_cu))
13962         {
13963           const char *target_physname;
13964
13965           /* Prefer the mangled name; otherwise compute the demangled one.  */
13966           target_physname = dw2_linkage_name (target_die, target_cu);
13967           if (target_physname == NULL)
13968             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13969           if (target_physname == NULL)
13970             complaint (_("DW_AT_call_target target DIE has invalid "
13971                          "physname, for referencing DIE %s [in module %s]"),
13972                        sect_offset_str (die->sect_off), objfile_name (objfile));
13973           else
13974             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13975         }
13976       else
13977         {
13978           CORE_ADDR lowpc;
13979
13980           /* DW_AT_entry_pc should be preferred.  */
13981           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13982               <= PC_BOUNDS_INVALID)
13983             complaint (_("DW_AT_call_target target DIE has invalid "
13984                          "low pc, for referencing DIE %s [in module %s]"),
13985                        sect_offset_str (die->sect_off), objfile_name (objfile));
13986           else
13987             {
13988               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13989               SET_FIELD_PHYSADDR (call_site->target, lowpc);
13990             }
13991         }
13992     }
13993   else
13994     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13995                  "block nor reference, for DIE %s [in module %s]"),
13996                sect_offset_str (die->sect_off), objfile_name (objfile));
13997
13998   call_site->per_cu = cu->per_cu;
13999
14000   for (child_die = die->child;
14001        child_die && child_die->tag;
14002        child_die = sibling_die (child_die))
14003     {
14004       struct call_site_parameter *parameter;
14005       struct attribute *loc, *origin;
14006
14007       if (child_die->tag != DW_TAG_call_site_parameter
14008           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14009         {
14010           /* Already printed the complaint above.  */
14011           continue;
14012         }
14013
14014       gdb_assert (call_site->parameter_count < nparams);
14015       parameter = &call_site->parameter[call_site->parameter_count];
14016
14017       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14018          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14019          register is contained in DW_AT_call_value.  */
14020
14021       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14022       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14023       if (origin == NULL)
14024         {
14025           /* This was a pre-DWARF-5 GNU extension alias
14026              for DW_AT_call_parameter.  */
14027           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14028         }
14029       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14030         {
14031           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14032
14033           sect_offset sect_off
14034             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14035           if (!offset_in_cu_p (&cu->header, sect_off))
14036             {
14037               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14038                  binding can be done only inside one CU.  Such referenced DIE
14039                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14040               complaint (_("DW_AT_call_parameter offset is not in CU for "
14041                            "DW_TAG_call_site child DIE %s [in module %s]"),
14042                          sect_offset_str (child_die->sect_off),
14043                          objfile_name (objfile));
14044               continue;
14045             }
14046           parameter->u.param_cu_off
14047             = (cu_offset) (sect_off - cu->header.sect_off);
14048         }
14049       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14050         {
14051           complaint (_("No DW_FORM_block* DW_AT_location for "
14052                        "DW_TAG_call_site child DIE %s [in module %s]"),
14053                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14054           continue;
14055         }
14056       else
14057         {
14058           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14059             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14060           if (parameter->u.dwarf_reg != -1)
14061             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14062           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14063                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14064                                              &parameter->u.fb_offset))
14065             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14066           else
14067             {
14068               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14069                            "for DW_FORM_block* DW_AT_location is supported for "
14070                            "DW_TAG_call_site child DIE %s "
14071                            "[in module %s]"),
14072                          sect_offset_str (child_die->sect_off),
14073                          objfile_name (objfile));
14074               continue;
14075             }
14076         }
14077
14078       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14079       if (attr == NULL)
14080         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14081       if (!attr_form_is_block (attr))
14082         {
14083           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14084                        "DW_TAG_call_site child DIE %s [in module %s]"),
14085                      sect_offset_str (child_die->sect_off),
14086                      objfile_name (objfile));
14087           continue;
14088         }
14089       parameter->value = DW_BLOCK (attr)->data;
14090       parameter->value_size = DW_BLOCK (attr)->size;
14091
14092       /* Parameters are not pre-cleared by memset above.  */
14093       parameter->data_value = NULL;
14094       parameter->data_value_size = 0;
14095       call_site->parameter_count++;
14096
14097       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14098       if (attr == NULL)
14099         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14100       if (attr)
14101         {
14102           if (!attr_form_is_block (attr))
14103             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14104                          "DW_TAG_call_site child DIE %s [in module %s]"),
14105                        sect_offset_str (child_die->sect_off),
14106                        objfile_name (objfile));
14107           else
14108             {
14109               parameter->data_value = DW_BLOCK (attr)->data;
14110               parameter->data_value_size = DW_BLOCK (attr)->size;
14111             }
14112         }
14113     }
14114 }
14115
14116 /* Helper function for read_variable.  If DIE represents a virtual
14117    table, then return the type of the concrete object that is
14118    associated with the virtual table.  Otherwise, return NULL.  */
14119
14120 static struct type *
14121 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14122 {
14123   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14124   if (attr == NULL)
14125     return NULL;
14126
14127   /* Find the type DIE.  */
14128   struct die_info *type_die = NULL;
14129   struct dwarf2_cu *type_cu = cu;
14130
14131   if (attr_form_is_ref (attr))
14132     type_die = follow_die_ref (die, attr, &type_cu);
14133   if (type_die == NULL)
14134     return NULL;
14135
14136   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14137     return NULL;
14138   return die_containing_type (type_die, type_cu);
14139 }
14140
14141 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14142
14143 static void
14144 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14145 {
14146   struct rust_vtable_symbol *storage = NULL;
14147
14148   if (cu->language == language_rust)
14149     {
14150       struct type *containing_type = rust_containing_type (die, cu);
14151
14152       if (containing_type != NULL)
14153         {
14154           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14155
14156           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14157                                     struct rust_vtable_symbol);
14158           initialize_objfile_symbol (storage);
14159           storage->concrete_type = containing_type;
14160           storage->subclass = SYMBOL_RUST_VTABLE;
14161         }
14162     }
14163
14164   new_symbol (die, NULL, cu, storage);
14165 }
14166
14167 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14168    reading .debug_rnglists.
14169    Callback's type should be:
14170     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14171    Return true if the attributes are present and valid, otherwise,
14172    return false.  */
14173
14174 template <typename Callback>
14175 static bool
14176 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14177                          Callback &&callback)
14178 {
14179   struct dwarf2_per_objfile *dwarf2_per_objfile
14180     = cu->per_cu->dwarf2_per_objfile;
14181   struct objfile *objfile = dwarf2_per_objfile->objfile;
14182   bfd *obfd = objfile->obfd;
14183   /* Base address selection entry.  */
14184   CORE_ADDR base;
14185   int found_base;
14186   const gdb_byte *buffer;
14187   CORE_ADDR baseaddr;
14188   bool overflow = false;
14189
14190   found_base = cu->base_known;
14191   base = cu->base_address;
14192
14193   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14194   if (offset >= dwarf2_per_objfile->rnglists.size)
14195     {
14196       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14197                  offset);
14198       return false;
14199     }
14200   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14201
14202   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14203
14204   while (1)
14205     {
14206       /* Initialize it due to a false compiler warning.  */
14207       CORE_ADDR range_beginning = 0, range_end = 0;
14208       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14209                                  + dwarf2_per_objfile->rnglists.size);
14210       unsigned int bytes_read;
14211
14212       if (buffer == buf_end)
14213         {
14214           overflow = true;
14215           break;
14216         }
14217       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14218       switch (rlet)
14219         {
14220         case DW_RLE_end_of_list:
14221           break;
14222         case DW_RLE_base_address:
14223           if (buffer + cu->header.addr_size > buf_end)
14224             {
14225               overflow = true;
14226               break;
14227             }
14228           base = read_address (obfd, buffer, cu, &bytes_read);
14229           found_base = 1;
14230           buffer += bytes_read;
14231           break;
14232         case DW_RLE_start_length:
14233           if (buffer + cu->header.addr_size > buf_end)
14234             {
14235               overflow = true;
14236               break;
14237             }
14238           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14239           buffer += bytes_read;
14240           range_end = (range_beginning
14241                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14242           buffer += bytes_read;
14243           if (buffer > buf_end)
14244             {
14245               overflow = true;
14246               break;
14247             }
14248           break;
14249         case DW_RLE_offset_pair:
14250           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14251           buffer += bytes_read;
14252           if (buffer > buf_end)
14253             {
14254               overflow = true;
14255               break;
14256             }
14257           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14258           buffer += bytes_read;
14259           if (buffer > buf_end)
14260             {
14261               overflow = true;
14262               break;
14263             }
14264           break;
14265         case DW_RLE_start_end:
14266           if (buffer + 2 * cu->header.addr_size > buf_end)
14267             {
14268               overflow = true;
14269               break;
14270             }
14271           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14272           buffer += bytes_read;
14273           range_end = read_address (obfd, buffer, cu, &bytes_read);
14274           buffer += bytes_read;
14275           break;
14276         default:
14277           complaint (_("Invalid .debug_rnglists data (no base address)"));
14278           return false;
14279         }
14280       if (rlet == DW_RLE_end_of_list || overflow)
14281         break;
14282       if (rlet == DW_RLE_base_address)
14283         continue;
14284
14285       if (!found_base)
14286         {
14287           /* We have no valid base address for the ranges
14288              data.  */
14289           complaint (_("Invalid .debug_rnglists data (no base address)"));
14290           return false;
14291         }
14292
14293       if (range_beginning > range_end)
14294         {
14295           /* Inverted range entries are invalid.  */
14296           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14297           return false;
14298         }
14299
14300       /* Empty range entries have no effect.  */
14301       if (range_beginning == range_end)
14302         continue;
14303
14304       range_beginning += base;
14305       range_end += base;
14306
14307       /* A not-uncommon case of bad debug info.
14308          Don't pollute the addrmap with bad data.  */
14309       if (range_beginning + baseaddr == 0
14310           && !dwarf2_per_objfile->has_section_at_zero)
14311         {
14312           complaint (_(".debug_rnglists entry has start address of zero"
14313                        " [in module %s]"), objfile_name (objfile));
14314           continue;
14315         }
14316
14317       callback (range_beginning, range_end);
14318     }
14319
14320   if (overflow)
14321     {
14322       complaint (_("Offset %d is not terminated "
14323                    "for DW_AT_ranges attribute"),
14324                  offset);
14325       return false;
14326     }
14327
14328   return true;
14329 }
14330
14331 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14332    Callback's type should be:
14333     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14334    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14335
14336 template <typename Callback>
14337 static int
14338 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14339                        Callback &&callback)
14340 {
14341   struct dwarf2_per_objfile *dwarf2_per_objfile
14342       = cu->per_cu->dwarf2_per_objfile;
14343   struct objfile *objfile = dwarf2_per_objfile->objfile;
14344   struct comp_unit_head *cu_header = &cu->header;
14345   bfd *obfd = objfile->obfd;
14346   unsigned int addr_size = cu_header->addr_size;
14347   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14348   /* Base address selection entry.  */
14349   CORE_ADDR base;
14350   int found_base;
14351   unsigned int dummy;
14352   const gdb_byte *buffer;
14353   CORE_ADDR baseaddr;
14354
14355   if (cu_header->version >= 5)
14356     return dwarf2_rnglists_process (offset, cu, callback);
14357
14358   found_base = cu->base_known;
14359   base = cu->base_address;
14360
14361   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14362   if (offset >= dwarf2_per_objfile->ranges.size)
14363     {
14364       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14365                  offset);
14366       return 0;
14367     }
14368   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14369
14370   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14371
14372   while (1)
14373     {
14374       CORE_ADDR range_beginning, range_end;
14375
14376       range_beginning = read_address (obfd, buffer, cu, &dummy);
14377       buffer += addr_size;
14378       range_end = read_address (obfd, buffer, cu, &dummy);
14379       buffer += addr_size;
14380       offset += 2 * addr_size;
14381
14382       /* An end of list marker is a pair of zero addresses.  */
14383       if (range_beginning == 0 && range_end == 0)
14384         /* Found the end of list entry.  */
14385         break;
14386
14387       /* Each base address selection entry is a pair of 2 values.
14388          The first is the largest possible address, the second is
14389          the base address.  Check for a base address here.  */
14390       if ((range_beginning & mask) == mask)
14391         {
14392           /* If we found the largest possible address, then we already
14393              have the base address in range_end.  */
14394           base = range_end;
14395           found_base = 1;
14396           continue;
14397         }
14398
14399       if (!found_base)
14400         {
14401           /* We have no valid base address for the ranges
14402              data.  */
14403           complaint (_("Invalid .debug_ranges data (no base address)"));
14404           return 0;
14405         }
14406
14407       if (range_beginning > range_end)
14408         {
14409           /* Inverted range entries are invalid.  */
14410           complaint (_("Invalid .debug_ranges data (inverted range)"));
14411           return 0;
14412         }
14413
14414       /* Empty range entries have no effect.  */
14415       if (range_beginning == range_end)
14416         continue;
14417
14418       range_beginning += base;
14419       range_end += base;
14420
14421       /* A not-uncommon case of bad debug info.
14422          Don't pollute the addrmap with bad data.  */
14423       if (range_beginning + baseaddr == 0
14424           && !dwarf2_per_objfile->has_section_at_zero)
14425         {
14426           complaint (_(".debug_ranges entry has start address of zero"
14427                        " [in module %s]"), objfile_name (objfile));
14428           continue;
14429         }
14430
14431       callback (range_beginning, range_end);
14432     }
14433
14434   return 1;
14435 }
14436
14437 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14438    Return 1 if the attributes are present and valid, otherwise, return 0.
14439    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14440
14441 static int
14442 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14443                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14444                     struct partial_symtab *ranges_pst)
14445 {
14446   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14447   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14448   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14449                                        SECT_OFF_TEXT (objfile));
14450   int low_set = 0;
14451   CORE_ADDR low = 0;
14452   CORE_ADDR high = 0;
14453   int retval;
14454
14455   retval = dwarf2_ranges_process (offset, cu,
14456     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14457     {
14458       if (ranges_pst != NULL)
14459         {
14460           CORE_ADDR lowpc;
14461           CORE_ADDR highpc;
14462
14463           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14464                                               range_beginning + baseaddr);
14465           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14466                                                range_end + baseaddr);
14467           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14468                              ranges_pst);
14469         }
14470
14471       /* FIXME: This is recording everything as a low-high
14472          segment of consecutive addresses.  We should have a
14473          data structure for discontiguous block ranges
14474          instead.  */
14475       if (! low_set)
14476         {
14477           low = range_beginning;
14478           high = range_end;
14479           low_set = 1;
14480         }
14481       else
14482         {
14483           if (range_beginning < low)
14484             low = range_beginning;
14485           if (range_end > high)
14486             high = range_end;
14487         }
14488     });
14489   if (!retval)
14490     return 0;
14491
14492   if (! low_set)
14493     /* If the first entry is an end-of-list marker, the range
14494        describes an empty scope, i.e. no instructions.  */
14495     return 0;
14496
14497   if (low_return)
14498     *low_return = low;
14499   if (high_return)
14500     *high_return = high;
14501   return 1;
14502 }
14503
14504 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14505    definition for the return value.  *LOWPC and *HIGHPC are set iff
14506    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14507
14508 static enum pc_bounds_kind
14509 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14510                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14511                       struct partial_symtab *pst)
14512 {
14513   struct dwarf2_per_objfile *dwarf2_per_objfile
14514     = cu->per_cu->dwarf2_per_objfile;
14515   struct attribute *attr;
14516   struct attribute *attr_high;
14517   CORE_ADDR low = 0;
14518   CORE_ADDR high = 0;
14519   enum pc_bounds_kind ret;
14520
14521   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14522   if (attr_high)
14523     {
14524       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14525       if (attr)
14526         {
14527           low = attr_value_as_address (attr);
14528           high = attr_value_as_address (attr_high);
14529           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14530             high += low;
14531         }
14532       else
14533         /* Found high w/o low attribute.  */
14534         return PC_BOUNDS_INVALID;
14535
14536       /* Found consecutive range of addresses.  */
14537       ret = PC_BOUNDS_HIGH_LOW;
14538     }
14539   else
14540     {
14541       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14542       if (attr != NULL)
14543         {
14544           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14545              We take advantage of the fact that DW_AT_ranges does not appear
14546              in DW_TAG_compile_unit of DWO files.  */
14547           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14548           unsigned int ranges_offset = (DW_UNSND (attr)
14549                                         + (need_ranges_base
14550                                            ? cu->ranges_base
14551                                            : 0));
14552
14553           /* Value of the DW_AT_ranges attribute is the offset in the
14554              .debug_ranges section.  */
14555           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14556             return PC_BOUNDS_INVALID;
14557           /* Found discontinuous range of addresses.  */
14558           ret = PC_BOUNDS_RANGES;
14559         }
14560       else
14561         return PC_BOUNDS_NOT_PRESENT;
14562     }
14563
14564   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14565   if (high <= low)
14566     return PC_BOUNDS_INVALID;
14567
14568   /* When using the GNU linker, .gnu.linkonce. sections are used to
14569      eliminate duplicate copies of functions and vtables and such.
14570      The linker will arbitrarily choose one and discard the others.
14571      The AT_*_pc values for such functions refer to local labels in
14572      these sections.  If the section from that file was discarded, the
14573      labels are not in the output, so the relocs get a value of 0.
14574      If this is a discarded function, mark the pc bounds as invalid,
14575      so that GDB will ignore it.  */
14576   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14577     return PC_BOUNDS_INVALID;
14578
14579   *lowpc = low;
14580   if (highpc)
14581     *highpc = high;
14582   return ret;
14583 }
14584
14585 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14586    its low and high PC addresses.  Do nothing if these addresses could not
14587    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14588    and HIGHPC to the high address if greater than HIGHPC.  */
14589
14590 static void
14591 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14592                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14593                                  struct dwarf2_cu *cu)
14594 {
14595   CORE_ADDR low, high;
14596   struct die_info *child = die->child;
14597
14598   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14599     {
14600       *lowpc = std::min (*lowpc, low);
14601       *highpc = std::max (*highpc, high);
14602     }
14603
14604   /* If the language does not allow nested subprograms (either inside
14605      subprograms or lexical blocks), we're done.  */
14606   if (cu->language != language_ada)
14607     return;
14608
14609   /* Check all the children of the given DIE.  If it contains nested
14610      subprograms, then check their pc bounds.  Likewise, we need to
14611      check lexical blocks as well, as they may also contain subprogram
14612      definitions.  */
14613   while (child && child->tag)
14614     {
14615       if (child->tag == DW_TAG_subprogram
14616           || child->tag == DW_TAG_lexical_block)
14617         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14618       child = sibling_die (child);
14619     }
14620 }
14621
14622 /* Get the low and high pc's represented by the scope DIE, and store
14623    them in *LOWPC and *HIGHPC.  If the correct values can't be
14624    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14625
14626 static void
14627 get_scope_pc_bounds (struct die_info *die,
14628                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14629                      struct dwarf2_cu *cu)
14630 {
14631   CORE_ADDR best_low = (CORE_ADDR) -1;
14632   CORE_ADDR best_high = (CORE_ADDR) 0;
14633   CORE_ADDR current_low, current_high;
14634
14635   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14636       >= PC_BOUNDS_RANGES)
14637     {
14638       best_low = current_low;
14639       best_high = current_high;
14640     }
14641   else
14642     {
14643       struct die_info *child = die->child;
14644
14645       while (child && child->tag)
14646         {
14647           switch (child->tag) {
14648           case DW_TAG_subprogram:
14649             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14650             break;
14651           case DW_TAG_namespace:
14652           case DW_TAG_module:
14653             /* FIXME: carlton/2004-01-16: Should we do this for
14654                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14655                that current GCC's always emit the DIEs corresponding
14656                to definitions of methods of classes as children of a
14657                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14658                the DIEs giving the declarations, which could be
14659                anywhere).  But I don't see any reason why the
14660                standards says that they have to be there.  */
14661             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14662
14663             if (current_low != ((CORE_ADDR) -1))
14664               {
14665                 best_low = std::min (best_low, current_low);
14666                 best_high = std::max (best_high, current_high);
14667               }
14668             break;
14669           default:
14670             /* Ignore.  */
14671             break;
14672           }
14673
14674           child = sibling_die (child);
14675         }
14676     }
14677
14678   *lowpc = best_low;
14679   *highpc = best_high;
14680 }
14681
14682 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14683    in DIE.  */
14684
14685 static void
14686 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14687                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14688 {
14689   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14690   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14691   struct attribute *attr;
14692   struct attribute *attr_high;
14693
14694   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14695   if (attr_high)
14696     {
14697       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14698       if (attr)
14699         {
14700           CORE_ADDR low = attr_value_as_address (attr);
14701           CORE_ADDR high = attr_value_as_address (attr_high);
14702
14703           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14704             high += low;
14705
14706           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14707           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14708           record_block_range (block, low, high - 1);
14709         }
14710     }
14711
14712   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14713   if (attr)
14714     {
14715       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14716          We take advantage of the fact that DW_AT_ranges does not appear
14717          in DW_TAG_compile_unit of DWO files.  */
14718       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14719
14720       /* The value of the DW_AT_ranges attribute is the offset of the
14721          address range list in the .debug_ranges section.  */
14722       unsigned long offset = (DW_UNSND (attr)
14723                               + (need_ranges_base ? cu->ranges_base : 0));
14724
14725       dwarf2_ranges_process (offset, cu,
14726         [&] (CORE_ADDR start, CORE_ADDR end)
14727         {
14728           start += baseaddr;
14729           end += baseaddr;
14730           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14731           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14732           record_block_range (block, start, end - 1);
14733         });
14734     }
14735 }
14736
14737 /* Check whether the producer field indicates either of GCC < 4.6, or the
14738    Intel C/C++ compiler, and cache the result in CU.  */
14739
14740 static void
14741 check_producer (struct dwarf2_cu *cu)
14742 {
14743   int major, minor;
14744
14745   if (cu->producer == NULL)
14746     {
14747       /* For unknown compilers expect their behavior is DWARF version
14748          compliant.
14749
14750          GCC started to support .debug_types sections by -gdwarf-4 since
14751          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14752          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14753          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14754          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14755     }
14756   else if (producer_is_gcc (cu->producer, &major, &minor))
14757     {
14758       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14759       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14760     }
14761   else if (producer_is_icc (cu->producer, &major, &minor))
14762     cu->producer_is_icc_lt_14 = major < 14;
14763   else
14764     {
14765       /* For other non-GCC compilers, expect their behavior is DWARF version
14766          compliant.  */
14767     }
14768
14769   cu->checked_producer = 1;
14770 }
14771
14772 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14773    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14774    during 4.6.0 experimental.  */
14775
14776 static int
14777 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14778 {
14779   if (!cu->checked_producer)
14780     check_producer (cu);
14781
14782   return cu->producer_is_gxx_lt_4_6;
14783 }
14784
14785 /* Return the default accessibility type if it is not overriden by
14786    DW_AT_accessibility.  */
14787
14788 static enum dwarf_access_attribute
14789 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14790 {
14791   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14792     {
14793       /* The default DWARF 2 accessibility for members is public, the default
14794          accessibility for inheritance is private.  */
14795
14796       if (die->tag != DW_TAG_inheritance)
14797         return DW_ACCESS_public;
14798       else
14799         return DW_ACCESS_private;
14800     }
14801   else
14802     {
14803       /* DWARF 3+ defines the default accessibility a different way.  The same
14804          rules apply now for DW_TAG_inheritance as for the members and it only
14805          depends on the container kind.  */
14806
14807       if (die->parent->tag == DW_TAG_class_type)
14808         return DW_ACCESS_private;
14809       else
14810         return DW_ACCESS_public;
14811     }
14812 }
14813
14814 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14815    offset.  If the attribute was not found return 0, otherwise return
14816    1.  If it was found but could not properly be handled, set *OFFSET
14817    to 0.  */
14818
14819 static int
14820 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14821                              LONGEST *offset)
14822 {
14823   struct attribute *attr;
14824
14825   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14826   if (attr != NULL)
14827     {
14828       *offset = 0;
14829
14830       /* Note that we do not check for a section offset first here.
14831          This is because DW_AT_data_member_location is new in DWARF 4,
14832          so if we see it, we can assume that a constant form is really
14833          a constant and not a section offset.  */
14834       if (attr_form_is_constant (attr))
14835         *offset = dwarf2_get_attr_constant_value (attr, 0);
14836       else if (attr_form_is_section_offset (attr))
14837         dwarf2_complex_location_expr_complaint ();
14838       else if (attr_form_is_block (attr))
14839         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14840       else
14841         dwarf2_complex_location_expr_complaint ();
14842
14843       return 1;
14844     }
14845
14846   return 0;
14847 }
14848
14849 /* Add an aggregate field to the field list.  */
14850
14851 static void
14852 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14853                   struct dwarf2_cu *cu)
14854 {
14855   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14856   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14857   struct nextfield *new_field;
14858   struct attribute *attr;
14859   struct field *fp;
14860   const char *fieldname = "";
14861
14862   if (die->tag == DW_TAG_inheritance)
14863     {
14864       fip->baseclasses.emplace_back ();
14865       new_field = &fip->baseclasses.back ();
14866     }
14867   else
14868     {
14869       fip->fields.emplace_back ();
14870       new_field = &fip->fields.back ();
14871     }
14872
14873   fip->nfields++;
14874
14875   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14876   if (attr)
14877     new_field->accessibility = DW_UNSND (attr);
14878   else
14879     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14880   if (new_field->accessibility != DW_ACCESS_public)
14881     fip->non_public_fields = 1;
14882
14883   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14884   if (attr)
14885     new_field->virtuality = DW_UNSND (attr);
14886   else
14887     new_field->virtuality = DW_VIRTUALITY_none;
14888
14889   fp = &new_field->field;
14890
14891   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14892     {
14893       LONGEST offset;
14894
14895       /* Data member other than a C++ static data member.  */
14896
14897       /* Get type of field.  */
14898       fp->type = die_type (die, cu);
14899
14900       SET_FIELD_BITPOS (*fp, 0);
14901
14902       /* Get bit size of field (zero if none).  */
14903       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14904       if (attr)
14905         {
14906           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14907         }
14908       else
14909         {
14910           FIELD_BITSIZE (*fp) = 0;
14911         }
14912
14913       /* Get bit offset of field.  */
14914       if (handle_data_member_location (die, cu, &offset))
14915         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14916       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14917       if (attr)
14918         {
14919           if (gdbarch_bits_big_endian (gdbarch))
14920             {
14921               /* For big endian bits, the DW_AT_bit_offset gives the
14922                  additional bit offset from the MSB of the containing
14923                  anonymous object to the MSB of the field.  We don't
14924                  have to do anything special since we don't need to
14925                  know the size of the anonymous object.  */
14926               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14927             }
14928           else
14929             {
14930               /* For little endian bits, compute the bit offset to the
14931                  MSB of the anonymous object, subtract off the number of
14932                  bits from the MSB of the field to the MSB of the
14933                  object, and then subtract off the number of bits of
14934                  the field itself.  The result is the bit offset of
14935                  the LSB of the field.  */
14936               int anonymous_size;
14937               int bit_offset = DW_UNSND (attr);
14938
14939               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14940               if (attr)
14941                 {
14942                   /* The size of the anonymous object containing
14943                      the bit field is explicit, so use the
14944                      indicated size (in bytes).  */
14945                   anonymous_size = DW_UNSND (attr);
14946                 }
14947               else
14948                 {
14949                   /* The size of the anonymous object containing
14950                      the bit field must be inferred from the type
14951                      attribute of the data member containing the
14952                      bit field.  */
14953                   anonymous_size = TYPE_LENGTH (fp->type);
14954                 }
14955               SET_FIELD_BITPOS (*fp,
14956                                 (FIELD_BITPOS (*fp)
14957                                  + anonymous_size * bits_per_byte
14958                                  - bit_offset - FIELD_BITSIZE (*fp)));
14959             }
14960         }
14961       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14962       if (attr != NULL)
14963         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14964                                 + dwarf2_get_attr_constant_value (attr, 0)));
14965
14966       /* Get name of field.  */
14967       fieldname = dwarf2_name (die, cu);
14968       if (fieldname == NULL)
14969         fieldname = "";
14970
14971       /* The name is already allocated along with this objfile, so we don't
14972          need to duplicate it for the type.  */
14973       fp->name = fieldname;
14974
14975       /* Change accessibility for artificial fields (e.g. virtual table
14976          pointer or virtual base class pointer) to private.  */
14977       if (dwarf2_attr (die, DW_AT_artificial, cu))
14978         {
14979           FIELD_ARTIFICIAL (*fp) = 1;
14980           new_field->accessibility = DW_ACCESS_private;
14981           fip->non_public_fields = 1;
14982         }
14983     }
14984   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14985     {
14986       /* C++ static member.  */
14987
14988       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14989          is a declaration, but all versions of G++ as of this writing
14990          (so through at least 3.2.1) incorrectly generate
14991          DW_TAG_variable tags.  */
14992
14993       const char *physname;
14994
14995       /* Get name of field.  */
14996       fieldname = dwarf2_name (die, cu);
14997       if (fieldname == NULL)
14998         return;
14999
15000       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15001       if (attr
15002           /* Only create a symbol if this is an external value.
15003              new_symbol checks this and puts the value in the global symbol
15004              table, which we want.  If it is not external, new_symbol
15005              will try to put the value in cu->list_in_scope which is wrong.  */
15006           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15007         {
15008           /* A static const member, not much different than an enum as far as
15009              we're concerned, except that we can support more types.  */
15010           new_symbol (die, NULL, cu);
15011         }
15012
15013       /* Get physical name.  */
15014       physname = dwarf2_physname (fieldname, die, cu);
15015
15016       /* The name is already allocated along with this objfile, so we don't
15017          need to duplicate it for the type.  */
15018       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15019       FIELD_TYPE (*fp) = die_type (die, cu);
15020       FIELD_NAME (*fp) = fieldname;
15021     }
15022   else if (die->tag == DW_TAG_inheritance)
15023     {
15024       LONGEST offset;
15025
15026       /* C++ base class field.  */
15027       if (handle_data_member_location (die, cu, &offset))
15028         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15029       FIELD_BITSIZE (*fp) = 0;
15030       FIELD_TYPE (*fp) = die_type (die, cu);
15031       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15032     }
15033   else if (die->tag == DW_TAG_variant_part)
15034     {
15035       /* process_structure_scope will treat this DIE as a union.  */
15036       process_structure_scope (die, cu);
15037
15038       /* The variant part is relative to the start of the enclosing
15039          structure.  */
15040       SET_FIELD_BITPOS (*fp, 0);
15041       fp->type = get_die_type (die, cu);
15042       fp->artificial = 1;
15043       fp->name = "<<variant>>";
15044     }
15045   else
15046     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15047 }
15048
15049 /* Can the type given by DIE define another type?  */
15050
15051 static bool
15052 type_can_define_types (const struct die_info *die)
15053 {
15054   switch (die->tag)
15055     {
15056     case DW_TAG_typedef:
15057     case DW_TAG_class_type:
15058     case DW_TAG_structure_type:
15059     case DW_TAG_union_type:
15060     case DW_TAG_enumeration_type:
15061       return true;
15062
15063     default:
15064       return false;
15065     }
15066 }
15067
15068 /* Add a type definition defined in the scope of the FIP's class.  */
15069
15070 static void
15071 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15072                       struct dwarf2_cu *cu)
15073 {
15074   struct decl_field fp;
15075   memset (&fp, 0, sizeof (fp));
15076
15077   gdb_assert (type_can_define_types (die));
15078
15079   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15080   fp.name = dwarf2_name (die, cu);
15081   fp.type = read_type_die (die, cu);
15082
15083   /* Save accessibility.  */
15084   enum dwarf_access_attribute accessibility;
15085   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15086   if (attr != NULL)
15087     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15088   else
15089     accessibility = dwarf2_default_access_attribute (die, cu);
15090   switch (accessibility)
15091     {
15092     case DW_ACCESS_public:
15093       /* The assumed value if neither private nor protected.  */
15094       break;
15095     case DW_ACCESS_private:
15096       fp.is_private = 1;
15097       break;
15098     case DW_ACCESS_protected:
15099       fp.is_protected = 1;
15100       break;
15101     default:
15102       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15103     }
15104
15105   if (die->tag == DW_TAG_typedef)
15106     fip->typedef_field_list.push_back (fp);
15107   else
15108     fip->nested_types_list.push_back (fp);
15109 }
15110
15111 /* Create the vector of fields, and attach it to the type.  */
15112
15113 static void
15114 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15115                               struct dwarf2_cu *cu)
15116 {
15117   int nfields = fip->nfields;
15118
15119   /* Record the field count, allocate space for the array of fields,
15120      and create blank accessibility bitfields if necessary.  */
15121   TYPE_NFIELDS (type) = nfields;
15122   TYPE_FIELDS (type) = (struct field *)
15123     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15124
15125   if (fip->non_public_fields && cu->language != language_ada)
15126     {
15127       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15128
15129       TYPE_FIELD_PRIVATE_BITS (type) =
15130         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15131       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15132
15133       TYPE_FIELD_PROTECTED_BITS (type) =
15134         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15135       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15136
15137       TYPE_FIELD_IGNORE_BITS (type) =
15138         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15139       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15140     }
15141
15142   /* If the type has baseclasses, allocate and clear a bit vector for
15143      TYPE_FIELD_VIRTUAL_BITS.  */
15144   if (!fip->baseclasses.empty () && cu->language != language_ada)
15145     {
15146       int num_bytes = B_BYTES (fip->baseclasses.size ());
15147       unsigned char *pointer;
15148
15149       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15150       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15151       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15152       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15153       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15154     }
15155
15156   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15157     {
15158       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15159
15160       for (int index = 0; index < nfields; ++index)
15161         {
15162           struct nextfield &field = fip->fields[index];
15163
15164           if (field.variant.is_discriminant)
15165             di->discriminant_index = index;
15166           else if (field.variant.default_branch)
15167             di->default_index = index;
15168           else
15169             di->discriminants[index] = field.variant.discriminant_value;
15170         }
15171     }
15172
15173   /* Copy the saved-up fields into the field vector.  */
15174   for (int i = 0; i < nfields; ++i)
15175     {
15176       struct nextfield &field
15177         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15178            : fip->fields[i - fip->baseclasses.size ()]);
15179
15180       TYPE_FIELD (type, i) = field.field;
15181       switch (field.accessibility)
15182         {
15183         case DW_ACCESS_private:
15184           if (cu->language != language_ada)
15185             SET_TYPE_FIELD_PRIVATE (type, i);
15186           break;
15187
15188         case DW_ACCESS_protected:
15189           if (cu->language != language_ada)
15190             SET_TYPE_FIELD_PROTECTED (type, i);
15191           break;
15192
15193         case DW_ACCESS_public:
15194           break;
15195
15196         default:
15197           /* Unknown accessibility.  Complain and treat it as public.  */
15198           {
15199             complaint (_("unsupported accessibility %d"),
15200                        field.accessibility);
15201           }
15202           break;
15203         }
15204       if (i < fip->baseclasses.size ())
15205         {
15206           switch (field.virtuality)
15207             {
15208             case DW_VIRTUALITY_virtual:
15209             case DW_VIRTUALITY_pure_virtual:
15210               if (cu->language == language_ada)
15211                 error (_("unexpected virtuality in component of Ada type"));
15212               SET_TYPE_FIELD_VIRTUAL (type, i);
15213               break;
15214             }
15215         }
15216     }
15217 }
15218
15219 /* Return true if this member function is a constructor, false
15220    otherwise.  */
15221
15222 static int
15223 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15224 {
15225   const char *fieldname;
15226   const char *type_name;
15227   int len;
15228
15229   if (die->parent == NULL)
15230     return 0;
15231
15232   if (die->parent->tag != DW_TAG_structure_type
15233       && die->parent->tag != DW_TAG_union_type
15234       && die->parent->tag != DW_TAG_class_type)
15235     return 0;
15236
15237   fieldname = dwarf2_name (die, cu);
15238   type_name = dwarf2_name (die->parent, cu);
15239   if (fieldname == NULL || type_name == NULL)
15240     return 0;
15241
15242   len = strlen (fieldname);
15243   return (strncmp (fieldname, type_name, len) == 0
15244           && (type_name[len] == '\0' || type_name[len] == '<'));
15245 }
15246
15247 /* Add a member function to the proper fieldlist.  */
15248
15249 static void
15250 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15251                       struct type *type, struct dwarf2_cu *cu)
15252 {
15253   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15254   struct attribute *attr;
15255   int i;
15256   struct fnfieldlist *flp = nullptr;
15257   struct fn_field *fnp;
15258   const char *fieldname;
15259   struct type *this_type;
15260   enum dwarf_access_attribute accessibility;
15261
15262   if (cu->language == language_ada)
15263     error (_("unexpected member function in Ada type"));
15264
15265   /* Get name of member function.  */
15266   fieldname = dwarf2_name (die, cu);
15267   if (fieldname == NULL)
15268     return;
15269
15270   /* Look up member function name in fieldlist.  */
15271   for (i = 0; i < fip->fnfieldlists.size (); i++)
15272     {
15273       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15274         {
15275           flp = &fip->fnfieldlists[i];
15276           break;
15277         }
15278     }
15279
15280   /* Create a new fnfieldlist if necessary.  */
15281   if (flp == nullptr)
15282     {
15283       fip->fnfieldlists.emplace_back ();
15284       flp = &fip->fnfieldlists.back ();
15285       flp->name = fieldname;
15286       i = fip->fnfieldlists.size () - 1;
15287     }
15288
15289   /* Create a new member function field and add it to the vector of
15290      fnfieldlists.  */
15291   flp->fnfields.emplace_back ();
15292   fnp = &flp->fnfields.back ();
15293
15294   /* Delay processing of the physname until later.  */
15295   if (cu->language == language_cplus)
15296     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15297                         die, cu);
15298   else
15299     {
15300       const char *physname = dwarf2_physname (fieldname, die, cu);
15301       fnp->physname = physname ? physname : "";
15302     }
15303
15304   fnp->type = alloc_type (objfile);
15305   this_type = read_type_die (die, cu);
15306   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15307     {
15308       int nparams = TYPE_NFIELDS (this_type);
15309
15310       /* TYPE is the domain of this method, and THIS_TYPE is the type
15311            of the method itself (TYPE_CODE_METHOD).  */
15312       smash_to_method_type (fnp->type, type,
15313                             TYPE_TARGET_TYPE (this_type),
15314                             TYPE_FIELDS (this_type),
15315                             TYPE_NFIELDS (this_type),
15316                             TYPE_VARARGS (this_type));
15317
15318       /* Handle static member functions.
15319          Dwarf2 has no clean way to discern C++ static and non-static
15320          member functions.  G++ helps GDB by marking the first
15321          parameter for non-static member functions (which is the this
15322          pointer) as artificial.  We obtain this information from
15323          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15324       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15325         fnp->voffset = VOFFSET_STATIC;
15326     }
15327   else
15328     complaint (_("member function type missing for '%s'"),
15329                dwarf2_full_name (fieldname, die, cu));
15330
15331   /* Get fcontext from DW_AT_containing_type if present.  */
15332   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15333     fnp->fcontext = die_containing_type (die, cu);
15334
15335   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15336      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15337
15338   /* Get accessibility.  */
15339   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15340   if (attr)
15341     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15342   else
15343     accessibility = dwarf2_default_access_attribute (die, cu);
15344   switch (accessibility)
15345     {
15346     case DW_ACCESS_private:
15347       fnp->is_private = 1;
15348       break;
15349     case DW_ACCESS_protected:
15350       fnp->is_protected = 1;
15351       break;
15352     }
15353
15354   /* Check for artificial methods.  */
15355   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15356   if (attr && DW_UNSND (attr) != 0)
15357     fnp->is_artificial = 1;
15358
15359   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15360
15361   /* Get index in virtual function table if it is a virtual member
15362      function.  For older versions of GCC, this is an offset in the
15363      appropriate virtual table, as specified by DW_AT_containing_type.
15364      For everyone else, it is an expression to be evaluated relative
15365      to the object address.  */
15366
15367   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15368   if (attr)
15369     {
15370       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15371         {
15372           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15373             {
15374               /* Old-style GCC.  */
15375               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15376             }
15377           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15378                    || (DW_BLOCK (attr)->size > 1
15379                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15380                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15381             {
15382               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15383               if ((fnp->voffset % cu->header.addr_size) != 0)
15384                 dwarf2_complex_location_expr_complaint ();
15385               else
15386                 fnp->voffset /= cu->header.addr_size;
15387               fnp->voffset += 2;
15388             }
15389           else
15390             dwarf2_complex_location_expr_complaint ();
15391
15392           if (!fnp->fcontext)
15393             {
15394               /* If there is no `this' field and no DW_AT_containing_type,
15395                  we cannot actually find a base class context for the
15396                  vtable!  */
15397               if (TYPE_NFIELDS (this_type) == 0
15398                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15399                 {
15400                   complaint (_("cannot determine context for virtual member "
15401                                "function \"%s\" (offset %s)"),
15402                              fieldname, sect_offset_str (die->sect_off));
15403                 }
15404               else
15405                 {
15406                   fnp->fcontext
15407                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15408                 }
15409             }
15410         }
15411       else if (attr_form_is_section_offset (attr))
15412         {
15413           dwarf2_complex_location_expr_complaint ();
15414         }
15415       else
15416         {
15417           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15418                                                  fieldname);
15419         }
15420     }
15421   else
15422     {
15423       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15424       if (attr && DW_UNSND (attr))
15425         {
15426           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15427           complaint (_("Member function \"%s\" (offset %s) is virtual "
15428                        "but the vtable offset is not specified"),
15429                      fieldname, sect_offset_str (die->sect_off));
15430           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15431           TYPE_CPLUS_DYNAMIC (type) = 1;
15432         }
15433     }
15434 }
15435
15436 /* Create the vector of member function fields, and attach it to the type.  */
15437
15438 static void
15439 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15440                                  struct dwarf2_cu *cu)
15441 {
15442   if (cu->language == language_ada)
15443     error (_("unexpected member functions in Ada type"));
15444
15445   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15446   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15447     TYPE_ALLOC (type,
15448                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15449
15450   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15451     {
15452       struct fnfieldlist &nf = fip->fnfieldlists[i];
15453       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15454
15455       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15456       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15457       fn_flp->fn_fields = (struct fn_field *)
15458         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15459
15460       for (int k = 0; k < nf.fnfields.size (); ++k)
15461         fn_flp->fn_fields[k] = nf.fnfields[k];
15462     }
15463
15464   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15465 }
15466
15467 /* Returns non-zero if NAME is the name of a vtable member in CU's
15468    language, zero otherwise.  */
15469 static int
15470 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15471 {
15472   static const char vptr[] = "_vptr";
15473
15474   /* Look for the C++ form of the vtable.  */
15475   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15476     return 1;
15477
15478   return 0;
15479 }
15480
15481 /* GCC outputs unnamed structures that are really pointers to member
15482    functions, with the ABI-specified layout.  If TYPE describes
15483    such a structure, smash it into a member function type.
15484
15485    GCC shouldn't do this; it should just output pointer to member DIEs.
15486    This is GCC PR debug/28767.  */
15487
15488 static void
15489 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15490 {
15491   struct type *pfn_type, *self_type, *new_type;
15492
15493   /* Check for a structure with no name and two children.  */
15494   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15495     return;
15496
15497   /* Check for __pfn and __delta members.  */
15498   if (TYPE_FIELD_NAME (type, 0) == NULL
15499       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15500       || TYPE_FIELD_NAME (type, 1) == NULL
15501       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15502     return;
15503
15504   /* Find the type of the method.  */
15505   pfn_type = TYPE_FIELD_TYPE (type, 0);
15506   if (pfn_type == NULL
15507       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15508       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15509     return;
15510
15511   /* Look for the "this" argument.  */
15512   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15513   if (TYPE_NFIELDS (pfn_type) == 0
15514       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15515       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15516     return;
15517
15518   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15519   new_type = alloc_type (objfile);
15520   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15521                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15522                         TYPE_VARARGS (pfn_type));
15523   smash_to_methodptr_type (type, new_type);
15524 }
15525
15526 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15527    appropriate error checking and issuing complaints if there is a
15528    problem.  */
15529
15530 static ULONGEST
15531 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15532 {
15533   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15534
15535   if (attr == nullptr)
15536     return 0;
15537
15538   if (!attr_form_is_constant (attr))
15539     {
15540       complaint (_("DW_AT_alignment must have constant form"
15541                    " - DIE at %s [in module %s]"),
15542                  sect_offset_str (die->sect_off),
15543                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15544       return 0;
15545     }
15546
15547   ULONGEST align;
15548   if (attr->form == DW_FORM_sdata)
15549     {
15550       LONGEST val = DW_SND (attr);
15551       if (val < 0)
15552         {
15553           complaint (_("DW_AT_alignment value must not be negative"
15554                        " - DIE at %s [in module %s]"),
15555                      sect_offset_str (die->sect_off),
15556                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15557           return 0;
15558         }
15559       align = val;
15560     }
15561   else
15562     align = DW_UNSND (attr);
15563
15564   if (align == 0)
15565     {
15566       complaint (_("DW_AT_alignment value must not be zero"
15567                    " - DIE at %s [in module %s]"),
15568                  sect_offset_str (die->sect_off),
15569                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15570       return 0;
15571     }
15572   if ((align & (align - 1)) != 0)
15573     {
15574       complaint (_("DW_AT_alignment value must be a power of 2"
15575                    " - DIE at %s [in module %s]"),
15576                  sect_offset_str (die->sect_off),
15577                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15578       return 0;
15579     }
15580
15581   return align;
15582 }
15583
15584 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15585    the alignment for TYPE.  */
15586
15587 static void
15588 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15589                      struct type *type)
15590 {
15591   if (!set_type_align (type, get_alignment (cu, die)))
15592     complaint (_("DW_AT_alignment value too large"
15593                  " - DIE at %s [in module %s]"),
15594                sect_offset_str (die->sect_off),
15595                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15596 }
15597
15598 /* Called when we find the DIE that starts a structure or union scope
15599    (definition) to create a type for the structure or union.  Fill in
15600    the type's name and general properties; the members will not be
15601    processed until process_structure_scope.  A symbol table entry for
15602    the type will also not be done until process_structure_scope (assuming
15603    the type has a name).
15604
15605    NOTE: we need to call these functions regardless of whether or not the
15606    DIE has a DW_AT_name attribute, since it might be an anonymous
15607    structure or union.  This gets the type entered into our set of
15608    user defined types.  */
15609
15610 static struct type *
15611 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15612 {
15613   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15614   struct type *type;
15615   struct attribute *attr;
15616   const char *name;
15617
15618   /* If the definition of this type lives in .debug_types, read that type.
15619      Don't follow DW_AT_specification though, that will take us back up
15620      the chain and we want to go down.  */
15621   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15622   if (attr)
15623     {
15624       type = get_DW_AT_signature_type (die, attr, cu);
15625
15626       /* The type's CU may not be the same as CU.
15627          Ensure TYPE is recorded with CU in die_type_hash.  */
15628       return set_die_type (die, type, cu);
15629     }
15630
15631   type = alloc_type (objfile);
15632   INIT_CPLUS_SPECIFIC (type);
15633
15634   name = dwarf2_name (die, cu);
15635   if (name != NULL)
15636     {
15637       if (cu->language == language_cplus
15638           || cu->language == language_d
15639           || cu->language == language_rust)
15640         {
15641           const char *full_name = dwarf2_full_name (name, die, cu);
15642
15643           /* dwarf2_full_name might have already finished building the DIE's
15644              type.  If so, there is no need to continue.  */
15645           if (get_die_type (die, cu) != NULL)
15646             return get_die_type (die, cu);
15647
15648           TYPE_NAME (type) = full_name;
15649         }
15650       else
15651         {
15652           /* The name is already allocated along with this objfile, so
15653              we don't need to duplicate it for the type.  */
15654           TYPE_NAME (type) = name;
15655         }
15656     }
15657
15658   if (die->tag == DW_TAG_structure_type)
15659     {
15660       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15661     }
15662   else if (die->tag == DW_TAG_union_type)
15663     {
15664       TYPE_CODE (type) = TYPE_CODE_UNION;
15665     }
15666   else if (die->tag == DW_TAG_variant_part)
15667     {
15668       TYPE_CODE (type) = TYPE_CODE_UNION;
15669       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15670     }
15671   else
15672     {
15673       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15674     }
15675
15676   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15677     TYPE_DECLARED_CLASS (type) = 1;
15678
15679   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15680   if (attr)
15681     {
15682       if (attr_form_is_constant (attr))
15683         TYPE_LENGTH (type) = DW_UNSND (attr);
15684       else
15685         {
15686           /* For the moment, dynamic type sizes are not supported
15687              by GDB's struct type.  The actual size is determined
15688              on-demand when resolving the type of a given object,
15689              so set the type's length to zero for now.  Otherwise,
15690              we record an expression as the length, and that expression
15691              could lead to a very large value, which could eventually
15692              lead to us trying to allocate that much memory when creating
15693              a value of that type.  */
15694           TYPE_LENGTH (type) = 0;
15695         }
15696     }
15697   else
15698     {
15699       TYPE_LENGTH (type) = 0;
15700     }
15701
15702   maybe_set_alignment (cu, die, type);
15703
15704   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15705     {
15706       /* ICC<14 does not output the required DW_AT_declaration on
15707          incomplete types, but gives them a size of zero.  */
15708       TYPE_STUB (type) = 1;
15709     }
15710   else
15711     TYPE_STUB_SUPPORTED (type) = 1;
15712
15713   if (die_is_declaration (die, cu))
15714     TYPE_STUB (type) = 1;
15715   else if (attr == NULL && die->child == NULL
15716            && producer_is_realview (cu->producer))
15717     /* RealView does not output the required DW_AT_declaration
15718        on incomplete types.  */
15719     TYPE_STUB (type) = 1;
15720
15721   /* We need to add the type field to the die immediately so we don't
15722      infinitely recurse when dealing with pointers to the structure
15723      type within the structure itself.  */
15724   set_die_type (die, type, cu);
15725
15726   /* set_die_type should be already done.  */
15727   set_descriptive_type (type, die, cu);
15728
15729   return type;
15730 }
15731
15732 /* A helper for process_structure_scope that handles a single member
15733    DIE.  */
15734
15735 static void
15736 handle_struct_member_die (struct die_info *child_die, struct type *type,
15737                           struct field_info *fi,
15738                           std::vector<struct symbol *> *template_args,
15739                           struct dwarf2_cu *cu)
15740 {
15741   if (child_die->tag == DW_TAG_member
15742       || child_die->tag == DW_TAG_variable
15743       || child_die->tag == DW_TAG_variant_part)
15744     {
15745       /* NOTE: carlton/2002-11-05: A C++ static data member
15746          should be a DW_TAG_member that is a declaration, but
15747          all versions of G++ as of this writing (so through at
15748          least 3.2.1) incorrectly generate DW_TAG_variable
15749          tags for them instead.  */
15750       dwarf2_add_field (fi, child_die, cu);
15751     }
15752   else if (child_die->tag == DW_TAG_subprogram)
15753     {
15754       /* Rust doesn't have member functions in the C++ sense.
15755          However, it does emit ordinary functions as children
15756          of a struct DIE.  */
15757       if (cu->language == language_rust)
15758         read_func_scope (child_die, cu);
15759       else
15760         {
15761           /* C++ member function.  */
15762           dwarf2_add_member_fn (fi, child_die, type, cu);
15763         }
15764     }
15765   else if (child_die->tag == DW_TAG_inheritance)
15766     {
15767       /* C++ base class field.  */
15768       dwarf2_add_field (fi, child_die, cu);
15769     }
15770   else if (type_can_define_types (child_die))
15771     dwarf2_add_type_defn (fi, child_die, cu);
15772   else if (child_die->tag == DW_TAG_template_type_param
15773            || child_die->tag == DW_TAG_template_value_param)
15774     {
15775       struct symbol *arg = new_symbol (child_die, NULL, cu);
15776
15777       if (arg != NULL)
15778         template_args->push_back (arg);
15779     }
15780   else if (child_die->tag == DW_TAG_variant)
15781     {
15782       /* In a variant we want to get the discriminant and also add a
15783          field for our sole member child.  */
15784       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15785
15786       for (struct die_info *variant_child = child_die->child;
15787            variant_child != NULL;
15788            variant_child = sibling_die (variant_child))
15789         {
15790           if (variant_child->tag == DW_TAG_member)
15791             {
15792               handle_struct_member_die (variant_child, type, fi,
15793                                         template_args, cu);
15794               /* Only handle the one.  */
15795               break;
15796             }
15797         }
15798
15799       /* We don't handle this but we might as well report it if we see
15800          it.  */
15801       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15802           complaint (_("DW_AT_discr_list is not supported yet"
15803                        " - DIE at %s [in module %s]"),
15804                      sect_offset_str (child_die->sect_off),
15805                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15806
15807       /* The first field was just added, so we can stash the
15808          discriminant there.  */
15809       gdb_assert (!fi->fields.empty ());
15810       if (discr == NULL)
15811         fi->fields.back ().variant.default_branch = true;
15812       else
15813         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15814     }
15815 }
15816
15817 /* Finish creating a structure or union type, including filling in
15818    its members and creating a symbol for it.  */
15819
15820 static void
15821 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15822 {
15823   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15824   struct die_info *child_die;
15825   struct type *type;
15826
15827   type = get_die_type (die, cu);
15828   if (type == NULL)
15829     type = read_structure_type (die, cu);
15830
15831   /* When reading a DW_TAG_variant_part, we need to notice when we
15832      read the discriminant member, so we can record it later in the
15833      discriminant_info.  */
15834   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15835   sect_offset discr_offset;
15836
15837   if (is_variant_part)
15838     {
15839       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15840       if (discr == NULL)
15841         {
15842           /* Maybe it's a univariant form, an extension we support.
15843              In this case arrange not to check the offset.  */
15844           is_variant_part = false;
15845         }
15846       else if (attr_form_is_ref (discr))
15847         {
15848           struct dwarf2_cu *target_cu = cu;
15849           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15850
15851           discr_offset = target_die->sect_off;
15852         }
15853       else
15854         {
15855           complaint (_("DW_AT_discr does not have DIE reference form"
15856                        " - DIE at %s [in module %s]"),
15857                      sect_offset_str (die->sect_off),
15858                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15859           is_variant_part = false;
15860         }
15861     }
15862
15863   if (die->child != NULL && ! die_is_declaration (die, cu))
15864     {
15865       struct field_info fi;
15866       std::vector<struct symbol *> template_args;
15867
15868       child_die = die->child;
15869
15870       while (child_die && child_die->tag)
15871         {
15872           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15873
15874           if (is_variant_part && discr_offset == child_die->sect_off)
15875             fi.fields.back ().variant.is_discriminant = true;
15876
15877           child_die = sibling_die (child_die);
15878         }
15879
15880       /* Attach template arguments to type.  */
15881       if (!template_args.empty ())
15882         {
15883           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15884           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15885           TYPE_TEMPLATE_ARGUMENTS (type)
15886             = XOBNEWVEC (&objfile->objfile_obstack,
15887                          struct symbol *,
15888                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15889           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15890                   template_args.data (),
15891                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15892                    * sizeof (struct symbol *)));
15893         }
15894
15895       /* Attach fields and member functions to the type.  */
15896       if (fi.nfields)
15897         dwarf2_attach_fields_to_type (&fi, type, cu);
15898       if (!fi.fnfieldlists.empty ())
15899         {
15900           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15901
15902           /* Get the type which refers to the base class (possibly this
15903              class itself) which contains the vtable pointer for the current
15904              class from the DW_AT_containing_type attribute.  This use of
15905              DW_AT_containing_type is a GNU extension.  */
15906
15907           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15908             {
15909               struct type *t = die_containing_type (die, cu);
15910
15911               set_type_vptr_basetype (type, t);
15912               if (type == t)
15913                 {
15914                   int i;
15915
15916                   /* Our own class provides vtbl ptr.  */
15917                   for (i = TYPE_NFIELDS (t) - 1;
15918                        i >= TYPE_N_BASECLASSES (t);
15919                        --i)
15920                     {
15921                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15922
15923                       if (is_vtable_name (fieldname, cu))
15924                         {
15925                           set_type_vptr_fieldno (type, i);
15926                           break;
15927                         }
15928                     }
15929
15930                   /* Complain if virtual function table field not found.  */
15931                   if (i < TYPE_N_BASECLASSES (t))
15932                     complaint (_("virtual function table pointer "
15933                                  "not found when defining class '%s'"),
15934                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15935                 }
15936               else
15937                 {
15938                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15939                 }
15940             }
15941           else if (cu->producer
15942                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15943             {
15944               /* The IBM XLC compiler does not provide direct indication
15945                  of the containing type, but the vtable pointer is
15946                  always named __vfp.  */
15947
15948               int i;
15949
15950               for (i = TYPE_NFIELDS (type) - 1;
15951                    i >= TYPE_N_BASECLASSES (type);
15952                    --i)
15953                 {
15954                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15955                     {
15956                       set_type_vptr_fieldno (type, i);
15957                       set_type_vptr_basetype (type, type);
15958                       break;
15959                     }
15960                 }
15961             }
15962         }
15963
15964       /* Copy fi.typedef_field_list linked list elements content into the
15965          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15966       if (!fi.typedef_field_list.empty ())
15967         {
15968           int count = fi.typedef_field_list.size ();
15969
15970           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15971           TYPE_TYPEDEF_FIELD_ARRAY (type)
15972             = ((struct decl_field *)
15973                TYPE_ALLOC (type,
15974                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15975           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15976
15977           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15978             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15979         }
15980
15981       /* Copy fi.nested_types_list linked list elements content into the
15982          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15983       if (!fi.nested_types_list.empty () && cu->language != language_ada)
15984         {
15985           int count = fi.nested_types_list.size ();
15986
15987           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15988           TYPE_NESTED_TYPES_ARRAY (type)
15989             = ((struct decl_field *)
15990                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15991           TYPE_NESTED_TYPES_COUNT (type) = count;
15992
15993           for (int i = 0; i < fi.nested_types_list.size (); ++i)
15994             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15995         }
15996     }
15997
15998   quirk_gcc_member_function_pointer (type, objfile);
15999   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16000     cu->rust_unions.push_back (type);
16001
16002   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16003      snapshots) has been known to create a die giving a declaration
16004      for a class that has, as a child, a die giving a definition for a
16005      nested class.  So we have to process our children even if the
16006      current die is a declaration.  Normally, of course, a declaration
16007      won't have any children at all.  */
16008
16009   child_die = die->child;
16010
16011   while (child_die != NULL && child_die->tag)
16012     {
16013       if (child_die->tag == DW_TAG_member
16014           || child_die->tag == DW_TAG_variable
16015           || child_die->tag == DW_TAG_inheritance
16016           || child_die->tag == DW_TAG_template_value_param
16017           || child_die->tag == DW_TAG_template_type_param)
16018         {
16019           /* Do nothing.  */
16020         }
16021       else
16022         process_die (child_die, cu);
16023
16024       child_die = sibling_die (child_die);
16025     }
16026
16027   /* Do not consider external references.  According to the DWARF standard,
16028      these DIEs are identified by the fact that they have no byte_size
16029      attribute, and a declaration attribute.  */
16030   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16031       || !die_is_declaration (die, cu))
16032     new_symbol (die, type, cu);
16033 }
16034
16035 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16036    update TYPE using some information only available in DIE's children.  */
16037
16038 static void
16039 update_enumeration_type_from_children (struct die_info *die,
16040                                        struct type *type,
16041                                        struct dwarf2_cu *cu)
16042 {
16043   struct die_info *child_die;
16044   int unsigned_enum = 1;
16045   int flag_enum = 1;
16046   ULONGEST mask = 0;
16047
16048   auto_obstack obstack;
16049
16050   for (child_die = die->child;
16051        child_die != NULL && child_die->tag;
16052        child_die = sibling_die (child_die))
16053     {
16054       struct attribute *attr;
16055       LONGEST value;
16056       const gdb_byte *bytes;
16057       struct dwarf2_locexpr_baton *baton;
16058       const char *name;
16059
16060       if (child_die->tag != DW_TAG_enumerator)
16061         continue;
16062
16063       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16064       if (attr == NULL)
16065         continue;
16066
16067       name = dwarf2_name (child_die, cu);
16068       if (name == NULL)
16069         name = "<anonymous enumerator>";
16070
16071       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16072                                &value, &bytes, &baton);
16073       if (value < 0)
16074         {
16075           unsigned_enum = 0;
16076           flag_enum = 0;
16077         }
16078       else if ((mask & value) != 0)
16079         flag_enum = 0;
16080       else
16081         mask |= value;
16082
16083       /* If we already know that the enum type is neither unsigned, nor
16084          a flag type, no need to look at the rest of the enumerates.  */
16085       if (!unsigned_enum && !flag_enum)
16086         break;
16087     }
16088
16089   if (unsigned_enum)
16090     TYPE_UNSIGNED (type) = 1;
16091   if (flag_enum)
16092     TYPE_FLAG_ENUM (type) = 1;
16093 }
16094
16095 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16096    complete the type's fields yet, or create any symbols.  */
16097
16098 static struct type *
16099 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16100 {
16101   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16102   struct type *type;
16103   struct attribute *attr;
16104   const char *name;
16105
16106   /* If the definition of this type lives in .debug_types, read that type.
16107      Don't follow DW_AT_specification though, that will take us back up
16108      the chain and we want to go down.  */
16109   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16110   if (attr)
16111     {
16112       type = get_DW_AT_signature_type (die, attr, cu);
16113
16114       /* The type's CU may not be the same as CU.
16115          Ensure TYPE is recorded with CU in die_type_hash.  */
16116       return set_die_type (die, type, cu);
16117     }
16118
16119   type = alloc_type (objfile);
16120
16121   TYPE_CODE (type) = TYPE_CODE_ENUM;
16122   name = dwarf2_full_name (NULL, die, cu);
16123   if (name != NULL)
16124     TYPE_NAME (type) = name;
16125
16126   attr = dwarf2_attr (die, DW_AT_type, cu);
16127   if (attr != NULL)
16128     {
16129       struct type *underlying_type = die_type (die, cu);
16130
16131       TYPE_TARGET_TYPE (type) = underlying_type;
16132     }
16133
16134   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16135   if (attr)
16136     {
16137       TYPE_LENGTH (type) = DW_UNSND (attr);
16138     }
16139   else
16140     {
16141       TYPE_LENGTH (type) = 0;
16142     }
16143
16144   maybe_set_alignment (cu, die, type);
16145
16146   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16147      declared as private in the package spec, and then defined only
16148      inside the package body.  Such types are known as Taft Amendment
16149      Types.  When another package uses such a type, an incomplete DIE
16150      may be generated by the compiler.  */
16151   if (die_is_declaration (die, cu))
16152     TYPE_STUB (type) = 1;
16153
16154   /* Finish the creation of this type by using the enum's children.
16155      We must call this even when the underlying type has been provided
16156      so that we can determine if we're looking at a "flag" enum.  */
16157   update_enumeration_type_from_children (die, type, cu);
16158
16159   /* If this type has an underlying type that is not a stub, then we
16160      may use its attributes.  We always use the "unsigned" attribute
16161      in this situation, because ordinarily we guess whether the type
16162      is unsigned -- but the guess can be wrong and the underlying type
16163      can tell us the reality.  However, we defer to a local size
16164      attribute if one exists, because this lets the compiler override
16165      the underlying type if needed.  */
16166   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16167     {
16168       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16169       if (TYPE_LENGTH (type) == 0)
16170         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16171       if (TYPE_RAW_ALIGN (type) == 0
16172           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16173         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16174     }
16175
16176   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16177
16178   return set_die_type (die, type, cu);
16179 }
16180
16181 /* Given a pointer to a die which begins an enumeration, process all
16182    the dies that define the members of the enumeration, and create the
16183    symbol for the enumeration type.
16184
16185    NOTE: We reverse the order of the element list.  */
16186
16187 static void
16188 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16189 {
16190   struct type *this_type;
16191
16192   this_type = get_die_type (die, cu);
16193   if (this_type == NULL)
16194     this_type = read_enumeration_type (die, cu);
16195
16196   if (die->child != NULL)
16197     {
16198       struct die_info *child_die;
16199       struct symbol *sym;
16200       struct field *fields = NULL;
16201       int num_fields = 0;
16202       const char *name;
16203
16204       child_die = die->child;
16205       while (child_die && child_die->tag)
16206         {
16207           if (child_die->tag != DW_TAG_enumerator)
16208             {
16209               process_die (child_die, cu);
16210             }
16211           else
16212             {
16213               name = dwarf2_name (child_die, cu);
16214               if (name)
16215                 {
16216                   sym = new_symbol (child_die, this_type, cu);
16217
16218                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16219                     {
16220                       fields = (struct field *)
16221                         xrealloc (fields,
16222                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16223                                   * sizeof (struct field));
16224                     }
16225
16226                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16227                   FIELD_TYPE (fields[num_fields]) = NULL;
16228                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16229                   FIELD_BITSIZE (fields[num_fields]) = 0;
16230
16231                   num_fields++;
16232                 }
16233             }
16234
16235           child_die = sibling_die (child_die);
16236         }
16237
16238       if (num_fields)
16239         {
16240           TYPE_NFIELDS (this_type) = num_fields;
16241           TYPE_FIELDS (this_type) = (struct field *)
16242             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16243           memcpy (TYPE_FIELDS (this_type), fields,
16244                   sizeof (struct field) * num_fields);
16245           xfree (fields);
16246         }
16247     }
16248
16249   /* If we are reading an enum from a .debug_types unit, and the enum
16250      is a declaration, and the enum is not the signatured type in the
16251      unit, then we do not want to add a symbol for it.  Adding a
16252      symbol would in some cases obscure the true definition of the
16253      enum, giving users an incomplete type when the definition is
16254      actually available.  Note that we do not want to do this for all
16255      enums which are just declarations, because C++0x allows forward
16256      enum declarations.  */
16257   if (cu->per_cu->is_debug_types
16258       && die_is_declaration (die, cu))
16259     {
16260       struct signatured_type *sig_type;
16261
16262       sig_type = (struct signatured_type *) cu->per_cu;
16263       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16264       if (sig_type->type_offset_in_section != die->sect_off)
16265         return;
16266     }
16267
16268   new_symbol (die, this_type, cu);
16269 }
16270
16271 /* Extract all information from a DW_TAG_array_type DIE and put it in
16272    the DIE's type field.  For now, this only handles one dimensional
16273    arrays.  */
16274
16275 static struct type *
16276 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16277 {
16278   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16279   struct die_info *child_die;
16280   struct type *type;
16281   struct type *element_type, *range_type, *index_type;
16282   struct attribute *attr;
16283   const char *name;
16284   struct dynamic_prop *byte_stride_prop = NULL;
16285   unsigned int bit_stride = 0;
16286
16287   element_type = die_type (die, cu);
16288
16289   /* The die_type call above may have already set the type for this DIE.  */
16290   type = get_die_type (die, cu);
16291   if (type)
16292     return type;
16293
16294   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16295   if (attr != NULL)
16296     {
16297       int stride_ok;
16298
16299       byte_stride_prop
16300         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16301       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16302       if (!stride_ok)
16303         {
16304           complaint (_("unable to read array DW_AT_byte_stride "
16305                        " - DIE at %s [in module %s]"),
16306                      sect_offset_str (die->sect_off),
16307                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16308           /* Ignore this attribute.  We will likely not be able to print
16309              arrays of this type correctly, but there is little we can do
16310              to help if we cannot read the attribute's value.  */
16311           byte_stride_prop = NULL;
16312         }
16313     }
16314
16315   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16316   if (attr != NULL)
16317     bit_stride = DW_UNSND (attr);
16318
16319   /* Irix 6.2 native cc creates array types without children for
16320      arrays with unspecified length.  */
16321   if (die->child == NULL)
16322     {
16323       index_type = objfile_type (objfile)->builtin_int;
16324       range_type = create_static_range_type (NULL, index_type, 0, -1);
16325       type = create_array_type_with_stride (NULL, element_type, range_type,
16326                                             byte_stride_prop, bit_stride);
16327       return set_die_type (die, type, cu);
16328     }
16329
16330   std::vector<struct type *> range_types;
16331   child_die = die->child;
16332   while (child_die && child_die->tag)
16333     {
16334       if (child_die->tag == DW_TAG_subrange_type)
16335         {
16336           struct type *child_type = read_type_die (child_die, cu);
16337
16338           if (child_type != NULL)
16339             {
16340               /* The range type was succesfully read.  Save it for the
16341                  array type creation.  */
16342               range_types.push_back (child_type);
16343             }
16344         }
16345       child_die = sibling_die (child_die);
16346     }
16347
16348   /* Dwarf2 dimensions are output from left to right, create the
16349      necessary array types in backwards order.  */
16350
16351   type = element_type;
16352
16353   if (read_array_order (die, cu) == DW_ORD_col_major)
16354     {
16355       int i = 0;
16356
16357       while (i < range_types.size ())
16358         type = create_array_type_with_stride (NULL, type, range_types[i++],
16359                                               byte_stride_prop, bit_stride);
16360     }
16361   else
16362     {
16363       size_t ndim = range_types.size ();
16364       while (ndim-- > 0)
16365         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16366                                               byte_stride_prop, bit_stride);
16367     }
16368
16369   /* Understand Dwarf2 support for vector types (like they occur on
16370      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16371      array type.  This is not part of the Dwarf2/3 standard yet, but a
16372      custom vendor extension.  The main difference between a regular
16373      array and the vector variant is that vectors are passed by value
16374      to functions.  */
16375   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16376   if (attr)
16377     make_vector_type (type);
16378
16379   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16380      implementation may choose to implement triple vectors using this
16381      attribute.  */
16382   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16383   if (attr)
16384     {
16385       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16386         TYPE_LENGTH (type) = DW_UNSND (attr);
16387       else
16388         complaint (_("DW_AT_byte_size for array type smaller "
16389                      "than the total size of elements"));
16390     }
16391
16392   name = dwarf2_name (die, cu);
16393   if (name)
16394     TYPE_NAME (type) = name;
16395
16396   maybe_set_alignment (cu, die, type);
16397
16398   /* Install the type in the die.  */
16399   set_die_type (die, type, cu);
16400
16401   /* set_die_type should be already done.  */
16402   set_descriptive_type (type, die, cu);
16403
16404   return type;
16405 }
16406
16407 static enum dwarf_array_dim_ordering
16408 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16409 {
16410   struct attribute *attr;
16411
16412   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16413
16414   if (attr)
16415     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16416
16417   /* GNU F77 is a special case, as at 08/2004 array type info is the
16418      opposite order to the dwarf2 specification, but data is still
16419      laid out as per normal fortran.
16420
16421      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16422      version checking.  */
16423
16424   if (cu->language == language_fortran
16425       && cu->producer && strstr (cu->producer, "GNU F77"))
16426     {
16427       return DW_ORD_row_major;
16428     }
16429
16430   switch (cu->language_defn->la_array_ordering)
16431     {
16432     case array_column_major:
16433       return DW_ORD_col_major;
16434     case array_row_major:
16435     default:
16436       return DW_ORD_row_major;
16437     };
16438 }
16439
16440 /* Extract all information from a DW_TAG_set_type DIE and put it in
16441    the DIE's type field.  */
16442
16443 static struct type *
16444 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16445 {
16446   struct type *domain_type, *set_type;
16447   struct attribute *attr;
16448
16449   domain_type = die_type (die, cu);
16450
16451   /* The die_type call above may have already set the type for this DIE.  */
16452   set_type = get_die_type (die, cu);
16453   if (set_type)
16454     return set_type;
16455
16456   set_type = create_set_type (NULL, domain_type);
16457
16458   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16459   if (attr)
16460     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16461
16462   maybe_set_alignment (cu, die, set_type);
16463
16464   return set_die_type (die, set_type, cu);
16465 }
16466
16467 /* A helper for read_common_block that creates a locexpr baton.
16468    SYM is the symbol which we are marking as computed.
16469    COMMON_DIE is the DIE for the common block.
16470    COMMON_LOC is the location expression attribute for the common
16471    block itself.
16472    MEMBER_LOC is the location expression attribute for the particular
16473    member of the common block that we are processing.
16474    CU is the CU from which the above come.  */
16475
16476 static void
16477 mark_common_block_symbol_computed (struct symbol *sym,
16478                                    struct die_info *common_die,
16479                                    struct attribute *common_loc,
16480                                    struct attribute *member_loc,
16481                                    struct dwarf2_cu *cu)
16482 {
16483   struct dwarf2_per_objfile *dwarf2_per_objfile
16484     = cu->per_cu->dwarf2_per_objfile;
16485   struct objfile *objfile = dwarf2_per_objfile->objfile;
16486   struct dwarf2_locexpr_baton *baton;
16487   gdb_byte *ptr;
16488   unsigned int cu_off;
16489   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16490   LONGEST offset = 0;
16491
16492   gdb_assert (common_loc && member_loc);
16493   gdb_assert (attr_form_is_block (common_loc));
16494   gdb_assert (attr_form_is_block (member_loc)
16495               || attr_form_is_constant (member_loc));
16496
16497   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16498   baton->per_cu = cu->per_cu;
16499   gdb_assert (baton->per_cu);
16500
16501   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16502
16503   if (attr_form_is_constant (member_loc))
16504     {
16505       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16506       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16507     }
16508   else
16509     baton->size += DW_BLOCK (member_loc)->size;
16510
16511   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16512   baton->data = ptr;
16513
16514   *ptr++ = DW_OP_call4;
16515   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16516   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16517   ptr += 4;
16518
16519   if (attr_form_is_constant (member_loc))
16520     {
16521       *ptr++ = DW_OP_addr;
16522       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16523       ptr += cu->header.addr_size;
16524     }
16525   else
16526     {
16527       /* We have to copy the data here, because DW_OP_call4 will only
16528          use a DW_AT_location attribute.  */
16529       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16530       ptr += DW_BLOCK (member_loc)->size;
16531     }
16532
16533   *ptr++ = DW_OP_plus;
16534   gdb_assert (ptr - baton->data == baton->size);
16535
16536   SYMBOL_LOCATION_BATON (sym) = baton;
16537   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16538 }
16539
16540 /* Create appropriate locally-scoped variables for all the
16541    DW_TAG_common_block entries.  Also create a struct common_block
16542    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16543    is used to sepate the common blocks name namespace from regular
16544    variable names.  */
16545
16546 static void
16547 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16548 {
16549   struct attribute *attr;
16550
16551   attr = dwarf2_attr (die, DW_AT_location, cu);
16552   if (attr)
16553     {
16554       /* Support the .debug_loc offsets.  */
16555       if (attr_form_is_block (attr))
16556         {
16557           /* Ok.  */
16558         }
16559       else if (attr_form_is_section_offset (attr))
16560         {
16561           dwarf2_complex_location_expr_complaint ();
16562           attr = NULL;
16563         }
16564       else
16565         {
16566           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16567                                                  "common block member");
16568           attr = NULL;
16569         }
16570     }
16571
16572   if (die->child != NULL)
16573     {
16574       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16575       struct die_info *child_die;
16576       size_t n_entries = 0, size;
16577       struct common_block *common_block;
16578       struct symbol *sym;
16579
16580       for (child_die = die->child;
16581            child_die && child_die->tag;
16582            child_die = sibling_die (child_die))
16583         ++n_entries;
16584
16585       size = (sizeof (struct common_block)
16586               + (n_entries - 1) * sizeof (struct symbol *));
16587       common_block
16588         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16589                                                  size);
16590       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16591       common_block->n_entries = 0;
16592
16593       for (child_die = die->child;
16594            child_die && child_die->tag;
16595            child_die = sibling_die (child_die))
16596         {
16597           /* Create the symbol in the DW_TAG_common_block block in the current
16598              symbol scope.  */
16599           sym = new_symbol (child_die, NULL, cu);
16600           if (sym != NULL)
16601             {
16602               struct attribute *member_loc;
16603
16604               common_block->contents[common_block->n_entries++] = sym;
16605
16606               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16607                                         cu);
16608               if (member_loc)
16609                 {
16610                   /* GDB has handled this for a long time, but it is
16611                      not specified by DWARF.  It seems to have been
16612                      emitted by gfortran at least as recently as:
16613                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16614                   complaint (_("Variable in common block has "
16615                                "DW_AT_data_member_location "
16616                                "- DIE at %s [in module %s]"),
16617                                sect_offset_str (child_die->sect_off),
16618                              objfile_name (objfile));
16619
16620                   if (attr_form_is_section_offset (member_loc))
16621                     dwarf2_complex_location_expr_complaint ();
16622                   else if (attr_form_is_constant (member_loc)
16623                            || attr_form_is_block (member_loc))
16624                     {
16625                       if (attr)
16626                         mark_common_block_symbol_computed (sym, die, attr,
16627                                                            member_loc, cu);
16628                     }
16629                   else
16630                     dwarf2_complex_location_expr_complaint ();
16631                 }
16632             }
16633         }
16634
16635       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16636       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16637     }
16638 }
16639
16640 /* Create a type for a C++ namespace.  */
16641
16642 static struct type *
16643 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16644 {
16645   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16646   const char *previous_prefix, *name;
16647   int is_anonymous;
16648   struct type *type;
16649
16650   /* For extensions, reuse the type of the original namespace.  */
16651   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16652     {
16653       struct die_info *ext_die;
16654       struct dwarf2_cu *ext_cu = cu;
16655
16656       ext_die = dwarf2_extension (die, &ext_cu);
16657       type = read_type_die (ext_die, ext_cu);
16658
16659       /* EXT_CU may not be the same as CU.
16660          Ensure TYPE is recorded with CU in die_type_hash.  */
16661       return set_die_type (die, type, cu);
16662     }
16663
16664   name = namespace_name (die, &is_anonymous, cu);
16665
16666   /* Now build the name of the current namespace.  */
16667
16668   previous_prefix = determine_prefix (die, cu);
16669   if (previous_prefix[0] != '\0')
16670     name = typename_concat (&objfile->objfile_obstack,
16671                             previous_prefix, name, 0, cu);
16672
16673   /* Create the type.  */
16674   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16675
16676   return set_die_type (die, type, cu);
16677 }
16678
16679 /* Read a namespace scope.  */
16680
16681 static void
16682 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16683 {
16684   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16685   int is_anonymous;
16686
16687   /* Add a symbol associated to this if we haven't seen the namespace
16688      before.  Also, add a using directive if it's an anonymous
16689      namespace.  */
16690
16691   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16692     {
16693       struct type *type;
16694
16695       type = read_type_die (die, cu);
16696       new_symbol (die, type, cu);
16697
16698       namespace_name (die, &is_anonymous, cu);
16699       if (is_anonymous)
16700         {
16701           const char *previous_prefix = determine_prefix (die, cu);
16702
16703           std::vector<const char *> excludes;
16704           add_using_directive (using_directives (cu->language),
16705                                previous_prefix, TYPE_NAME (type), NULL,
16706                                NULL, excludes, 0, &objfile->objfile_obstack);
16707         }
16708     }
16709
16710   if (die->child != NULL)
16711     {
16712       struct die_info *child_die = die->child;
16713
16714       while (child_die && child_die->tag)
16715         {
16716           process_die (child_die, cu);
16717           child_die = sibling_die (child_die);
16718         }
16719     }
16720 }
16721
16722 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16723    imported module.  Still we need that type as local Fortran "use ... only"
16724    declaration imports depend on the created type in determine_prefix.  */
16725
16726 static struct type *
16727 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16728 {
16729   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16730   const char *module_name;
16731   struct type *type;
16732
16733   module_name = dwarf2_name (die, cu);
16734   if (!module_name)
16735     complaint (_("DW_TAG_module has no name, offset %s"),
16736                sect_offset_str (die->sect_off));
16737   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16738
16739   return set_die_type (die, type, cu);
16740 }
16741
16742 /* Read a Fortran module.  */
16743
16744 static void
16745 read_module (struct die_info *die, struct dwarf2_cu *cu)
16746 {
16747   struct die_info *child_die = die->child;
16748   struct type *type;
16749
16750   type = read_type_die (die, cu);
16751   new_symbol (die, type, cu);
16752
16753   while (child_die && child_die->tag)
16754     {
16755       process_die (child_die, cu);
16756       child_die = sibling_die (child_die);
16757     }
16758 }
16759
16760 /* Return the name of the namespace represented by DIE.  Set
16761    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16762    namespace.  */
16763
16764 static const char *
16765 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16766 {
16767   struct die_info *current_die;
16768   const char *name = NULL;
16769
16770   /* Loop through the extensions until we find a name.  */
16771
16772   for (current_die = die;
16773        current_die != NULL;
16774        current_die = dwarf2_extension (die, &cu))
16775     {
16776       /* We don't use dwarf2_name here so that we can detect the absence
16777          of a name -> anonymous namespace.  */
16778       name = dwarf2_string_attr (die, DW_AT_name, cu);
16779
16780       if (name != NULL)
16781         break;
16782     }
16783
16784   /* Is it an anonymous namespace?  */
16785
16786   *is_anonymous = (name == NULL);
16787   if (*is_anonymous)
16788     name = CP_ANONYMOUS_NAMESPACE_STR;
16789
16790   return name;
16791 }
16792
16793 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16794    the user defined type vector.  */
16795
16796 static struct type *
16797 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16798 {
16799   struct gdbarch *gdbarch
16800     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16801   struct comp_unit_head *cu_header = &cu->header;
16802   struct type *type;
16803   struct attribute *attr_byte_size;
16804   struct attribute *attr_address_class;
16805   int byte_size, addr_class;
16806   struct type *target_type;
16807
16808   target_type = die_type (die, cu);
16809
16810   /* The die_type call above may have already set the type for this DIE.  */
16811   type = get_die_type (die, cu);
16812   if (type)
16813     return type;
16814
16815   type = lookup_pointer_type (target_type);
16816
16817   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16818   if (attr_byte_size)
16819     byte_size = DW_UNSND (attr_byte_size);
16820   else
16821     byte_size = cu_header->addr_size;
16822
16823   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16824   if (attr_address_class)
16825     addr_class = DW_UNSND (attr_address_class);
16826   else
16827     addr_class = DW_ADDR_none;
16828
16829   ULONGEST alignment = get_alignment (cu, die);
16830
16831   /* If the pointer size, alignment, or address class is different
16832      than the default, create a type variant marked as such and set
16833      the length accordingly.  */
16834   if (TYPE_LENGTH (type) != byte_size
16835       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16836           && alignment != TYPE_RAW_ALIGN (type))
16837       || addr_class != DW_ADDR_none)
16838     {
16839       if (gdbarch_address_class_type_flags_p (gdbarch))
16840         {
16841           int type_flags;
16842
16843           type_flags = gdbarch_address_class_type_flags
16844                          (gdbarch, byte_size, addr_class);
16845           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16846                       == 0);
16847           type = make_type_with_address_space (type, type_flags);
16848         }
16849       else if (TYPE_LENGTH (type) != byte_size)
16850         {
16851           complaint (_("invalid pointer size %d"), byte_size);
16852         }
16853       else if (TYPE_RAW_ALIGN (type) != alignment)
16854         {
16855           complaint (_("Invalid DW_AT_alignment"
16856                        " - DIE at %s [in module %s]"),
16857                      sect_offset_str (die->sect_off),
16858                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16859         }
16860       else
16861         {
16862           /* Should we also complain about unhandled address classes?  */
16863         }
16864     }
16865
16866   TYPE_LENGTH (type) = byte_size;
16867   set_type_align (type, alignment);
16868   return set_die_type (die, type, cu);
16869 }
16870
16871 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16872    the user defined type vector.  */
16873
16874 static struct type *
16875 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16876 {
16877   struct type *type;
16878   struct type *to_type;
16879   struct type *domain;
16880
16881   to_type = die_type (die, cu);
16882   domain = die_containing_type (die, cu);
16883
16884   /* The calls above may have already set the type for this DIE.  */
16885   type = get_die_type (die, cu);
16886   if (type)
16887     return type;
16888
16889   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16890     type = lookup_methodptr_type (to_type);
16891   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16892     {
16893       struct type *new_type
16894         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16895
16896       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16897                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16898                             TYPE_VARARGS (to_type));
16899       type = lookup_methodptr_type (new_type);
16900     }
16901   else
16902     type = lookup_memberptr_type (to_type, domain);
16903
16904   return set_die_type (die, type, cu);
16905 }
16906
16907 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16908    the user defined type vector.  */
16909
16910 static struct type *
16911 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16912                           enum type_code refcode)
16913 {
16914   struct comp_unit_head *cu_header = &cu->header;
16915   struct type *type, *target_type;
16916   struct attribute *attr;
16917
16918   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16919
16920   target_type = die_type (die, cu);
16921
16922   /* The die_type call above may have already set the type for this DIE.  */
16923   type = get_die_type (die, cu);
16924   if (type)
16925     return type;
16926
16927   type = lookup_reference_type (target_type, refcode);
16928   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16929   if (attr)
16930     {
16931       TYPE_LENGTH (type) = DW_UNSND (attr);
16932     }
16933   else
16934     {
16935       TYPE_LENGTH (type) = cu_header->addr_size;
16936     }
16937   maybe_set_alignment (cu, die, type);
16938   return set_die_type (die, type, cu);
16939 }
16940
16941 /* Add the given cv-qualifiers to the element type of the array.  GCC
16942    outputs DWARF type qualifiers that apply to an array, not the
16943    element type.  But GDB relies on the array element type to carry
16944    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16945    specification.  */
16946
16947 static struct type *
16948 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16949                    struct type *base_type, int cnst, int voltl)
16950 {
16951   struct type *el_type, *inner_array;
16952
16953   base_type = copy_type (base_type);
16954   inner_array = base_type;
16955
16956   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16957     {
16958       TYPE_TARGET_TYPE (inner_array) =
16959         copy_type (TYPE_TARGET_TYPE (inner_array));
16960       inner_array = TYPE_TARGET_TYPE (inner_array);
16961     }
16962
16963   el_type = TYPE_TARGET_TYPE (inner_array);
16964   cnst |= TYPE_CONST (el_type);
16965   voltl |= TYPE_VOLATILE (el_type);
16966   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16967
16968   return set_die_type (die, base_type, cu);
16969 }
16970
16971 static struct type *
16972 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16973 {
16974   struct type *base_type, *cv_type;
16975
16976   base_type = die_type (die, cu);
16977
16978   /* The die_type call above may have already set the type for this DIE.  */
16979   cv_type = get_die_type (die, cu);
16980   if (cv_type)
16981     return cv_type;
16982
16983   /* In case the const qualifier is applied to an array type, the element type
16984      is so qualified, not the array type (section 6.7.3 of C99).  */
16985   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16986     return add_array_cv_type (die, cu, base_type, 1, 0);
16987
16988   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16989   return set_die_type (die, cv_type, cu);
16990 }
16991
16992 static struct type *
16993 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16994 {
16995   struct type *base_type, *cv_type;
16996
16997   base_type = die_type (die, cu);
16998
16999   /* The die_type call above may have already set the type for this DIE.  */
17000   cv_type = get_die_type (die, cu);
17001   if (cv_type)
17002     return cv_type;
17003
17004   /* In case the volatile qualifier is applied to an array type, the
17005      element type is so qualified, not the array type (section 6.7.3
17006      of C99).  */
17007   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17008     return add_array_cv_type (die, cu, base_type, 0, 1);
17009
17010   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17011   return set_die_type (die, cv_type, cu);
17012 }
17013
17014 /* Handle DW_TAG_restrict_type.  */
17015
17016 static struct type *
17017 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17018 {
17019   struct type *base_type, *cv_type;
17020
17021   base_type = die_type (die, cu);
17022
17023   /* The die_type call above may have already set the type for this DIE.  */
17024   cv_type = get_die_type (die, cu);
17025   if (cv_type)
17026     return cv_type;
17027
17028   cv_type = make_restrict_type (base_type);
17029   return set_die_type (die, cv_type, cu);
17030 }
17031
17032 /* Handle DW_TAG_atomic_type.  */
17033
17034 static struct type *
17035 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17036 {
17037   struct type *base_type, *cv_type;
17038
17039   base_type = die_type (die, cu);
17040
17041   /* The die_type call above may have already set the type for this DIE.  */
17042   cv_type = get_die_type (die, cu);
17043   if (cv_type)
17044     return cv_type;
17045
17046   cv_type = make_atomic_type (base_type);
17047   return set_die_type (die, cv_type, cu);
17048 }
17049
17050 /* Extract all information from a DW_TAG_string_type DIE and add to
17051    the user defined type vector.  It isn't really a user defined type,
17052    but it behaves like one, with other DIE's using an AT_user_def_type
17053    attribute to reference it.  */
17054
17055 static struct type *
17056 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17057 {
17058   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17059   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17060   struct type *type, *range_type, *index_type, *char_type;
17061   struct attribute *attr;
17062   unsigned int length;
17063
17064   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17065   if (attr)
17066     {
17067       length = DW_UNSND (attr);
17068     }
17069   else
17070     {
17071       /* Check for the DW_AT_byte_size attribute.  */
17072       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17073       if (attr)
17074         {
17075           length = DW_UNSND (attr);
17076         }
17077       else
17078         {
17079           length = 1;
17080         }
17081     }
17082
17083   index_type = objfile_type (objfile)->builtin_int;
17084   range_type = create_static_range_type (NULL, index_type, 1, length);
17085   char_type = language_string_char_type (cu->language_defn, gdbarch);
17086   type = create_string_type (NULL, char_type, range_type);
17087
17088   return set_die_type (die, type, cu);
17089 }
17090
17091 /* Assuming that DIE corresponds to a function, returns nonzero
17092    if the function is prototyped.  */
17093
17094 static int
17095 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17096 {
17097   struct attribute *attr;
17098
17099   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17100   if (attr && (DW_UNSND (attr) != 0))
17101     return 1;
17102
17103   /* The DWARF standard implies that the DW_AT_prototyped attribute
17104      is only meaninful for C, but the concept also extends to other
17105      languages that allow unprototyped functions (Eg: Objective C).
17106      For all other languages, assume that functions are always
17107      prototyped.  */
17108   if (cu->language != language_c
17109       && cu->language != language_objc
17110       && cu->language != language_opencl)
17111     return 1;
17112
17113   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17114      prototyped and unprototyped functions; default to prototyped,
17115      since that is more common in modern code (and RealView warns
17116      about unprototyped functions).  */
17117   if (producer_is_realview (cu->producer))
17118     return 1;
17119
17120   return 0;
17121 }
17122
17123 /* Handle DIES due to C code like:
17124
17125    struct foo
17126    {
17127    int (*funcp)(int a, long l);
17128    int b;
17129    };
17130
17131    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17132
17133 static struct type *
17134 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17135 {
17136   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17137   struct type *type;            /* Type that this function returns.  */
17138   struct type *ftype;           /* Function that returns above type.  */
17139   struct attribute *attr;
17140
17141   type = die_type (die, cu);
17142
17143   /* The die_type call above may have already set the type for this DIE.  */
17144   ftype = get_die_type (die, cu);
17145   if (ftype)
17146     return ftype;
17147
17148   ftype = lookup_function_type (type);
17149
17150   if (prototyped_function_p (die, cu))
17151     TYPE_PROTOTYPED (ftype) = 1;
17152
17153   /* Store the calling convention in the type if it's available in
17154      the subroutine die.  Otherwise set the calling convention to
17155      the default value DW_CC_normal.  */
17156   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17157   if (attr)
17158     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17159   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17160     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17161   else
17162     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17163
17164   /* Record whether the function returns normally to its caller or not
17165      if the DWARF producer set that information.  */
17166   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17167   if (attr && (DW_UNSND (attr) != 0))
17168     TYPE_NO_RETURN (ftype) = 1;
17169
17170   /* We need to add the subroutine type to the die immediately so
17171      we don't infinitely recurse when dealing with parameters
17172      declared as the same subroutine type.  */
17173   set_die_type (die, ftype, cu);
17174
17175   if (die->child != NULL)
17176     {
17177       struct type *void_type = objfile_type (objfile)->builtin_void;
17178       struct die_info *child_die;
17179       int nparams, iparams;
17180
17181       /* Count the number of parameters.
17182          FIXME: GDB currently ignores vararg functions, but knows about
17183          vararg member functions.  */
17184       nparams = 0;
17185       child_die = die->child;
17186       while (child_die && child_die->tag)
17187         {
17188           if (child_die->tag == DW_TAG_formal_parameter)
17189             nparams++;
17190           else if (child_die->tag == DW_TAG_unspecified_parameters)
17191             TYPE_VARARGS (ftype) = 1;
17192           child_die = sibling_die (child_die);
17193         }
17194
17195       /* Allocate storage for parameters and fill them in.  */
17196       TYPE_NFIELDS (ftype) = nparams;
17197       TYPE_FIELDS (ftype) = (struct field *)
17198         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17199
17200       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17201          even if we error out during the parameters reading below.  */
17202       for (iparams = 0; iparams < nparams; iparams++)
17203         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17204
17205       iparams = 0;
17206       child_die = die->child;
17207       while (child_die && child_die->tag)
17208         {
17209           if (child_die->tag == DW_TAG_formal_parameter)
17210             {
17211               struct type *arg_type;
17212
17213               /* DWARF version 2 has no clean way to discern C++
17214                  static and non-static member functions.  G++ helps
17215                  GDB by marking the first parameter for non-static
17216                  member functions (which is the this pointer) as
17217                  artificial.  We pass this information to
17218                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17219
17220                  DWARF version 3 added DW_AT_object_pointer, which GCC
17221                  4.5 does not yet generate.  */
17222               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17223               if (attr)
17224                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17225               else
17226                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17227               arg_type = die_type (child_die, cu);
17228
17229               /* RealView does not mark THIS as const, which the testsuite
17230                  expects.  GCC marks THIS as const in method definitions,
17231                  but not in the class specifications (GCC PR 43053).  */
17232               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17233                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17234                 {
17235                   int is_this = 0;
17236                   struct dwarf2_cu *arg_cu = cu;
17237                   const char *name = dwarf2_name (child_die, cu);
17238
17239                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17240                   if (attr)
17241                     {
17242                       /* If the compiler emits this, use it.  */
17243                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17244                         is_this = 1;
17245                     }
17246                   else if (name && strcmp (name, "this") == 0)
17247                     /* Function definitions will have the argument names.  */
17248                     is_this = 1;
17249                   else if (name == NULL && iparams == 0)
17250                     /* Declarations may not have the names, so like
17251                        elsewhere in GDB, assume an artificial first
17252                        argument is "this".  */
17253                     is_this = 1;
17254
17255                   if (is_this)
17256                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17257                                              arg_type, 0);
17258                 }
17259
17260               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17261               iparams++;
17262             }
17263           child_die = sibling_die (child_die);
17264         }
17265     }
17266
17267   return ftype;
17268 }
17269
17270 static struct type *
17271 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17272 {
17273   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17274   const char *name = NULL;
17275   struct type *this_type, *target_type;
17276
17277   name = dwarf2_full_name (NULL, die, cu);
17278   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17279   TYPE_TARGET_STUB (this_type) = 1;
17280   set_die_type (die, this_type, cu);
17281   target_type = die_type (die, cu);
17282   if (target_type != this_type)
17283     TYPE_TARGET_TYPE (this_type) = target_type;
17284   else
17285     {
17286       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17287          spec and cause infinite loops in GDB.  */
17288       complaint (_("Self-referential DW_TAG_typedef "
17289                    "- DIE at %s [in module %s]"),
17290                  sect_offset_str (die->sect_off), objfile_name (objfile));
17291       TYPE_TARGET_TYPE (this_type) = NULL;
17292     }
17293   return this_type;
17294 }
17295
17296 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17297    (which may be different from NAME) to the architecture back-end to allow
17298    it to guess the correct format if necessary.  */
17299
17300 static struct type *
17301 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17302                         const char *name_hint)
17303 {
17304   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17305   const struct floatformat **format;
17306   struct type *type;
17307
17308   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17309   if (format)
17310     type = init_float_type (objfile, bits, name, format);
17311   else
17312     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17313
17314   return type;
17315 }
17316
17317 /* Find a representation of a given base type and install
17318    it in the TYPE field of the die.  */
17319
17320 static struct type *
17321 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17322 {
17323   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17324   struct type *type;
17325   struct attribute *attr;
17326   int encoding = 0, bits = 0;
17327   const char *name;
17328
17329   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17330   if (attr)
17331     {
17332       encoding = DW_UNSND (attr);
17333     }
17334   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17335   if (attr)
17336     {
17337       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17338     }
17339   name = dwarf2_name (die, cu);
17340   if (!name)
17341     {
17342       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17343     }
17344
17345   switch (encoding)
17346     {
17347       case DW_ATE_address:
17348         /* Turn DW_ATE_address into a void * pointer.  */
17349         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17350         type = init_pointer_type (objfile, bits, name, type);
17351         break;
17352       case DW_ATE_boolean:
17353         type = init_boolean_type (objfile, bits, 1, name);
17354         break;
17355       case DW_ATE_complex_float:
17356         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17357         type = init_complex_type (objfile, name, type);
17358         break;
17359       case DW_ATE_decimal_float:
17360         type = init_decfloat_type (objfile, bits, name);
17361         break;
17362       case DW_ATE_float:
17363         type = dwarf2_init_float_type (objfile, bits, name, name);
17364         break;
17365       case DW_ATE_signed:
17366         type = init_integer_type (objfile, bits, 0, name);
17367         break;
17368       case DW_ATE_unsigned:
17369         if (cu->language == language_fortran
17370             && name
17371             && startswith (name, "character("))
17372           type = init_character_type (objfile, bits, 1, name);
17373         else
17374           type = init_integer_type (objfile, bits, 1, name);
17375         break;
17376       case DW_ATE_signed_char:
17377         if (cu->language == language_ada || cu->language == language_m2
17378             || cu->language == language_pascal
17379             || cu->language == language_fortran)
17380           type = init_character_type (objfile, bits, 0, name);
17381         else
17382           type = init_integer_type (objfile, bits, 0, name);
17383         break;
17384       case DW_ATE_unsigned_char:
17385         if (cu->language == language_ada || cu->language == language_m2
17386             || cu->language == language_pascal
17387             || cu->language == language_fortran
17388             || cu->language == language_rust)
17389           type = init_character_type (objfile, bits, 1, name);
17390         else
17391           type = init_integer_type (objfile, bits, 1, name);
17392         break;
17393       case DW_ATE_UTF:
17394         {
17395           gdbarch *arch = get_objfile_arch (objfile);
17396
17397           if (bits == 16)
17398             type = builtin_type (arch)->builtin_char16;
17399           else if (bits == 32)
17400             type = builtin_type (arch)->builtin_char32;
17401           else
17402             {
17403               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17404                          bits);
17405               type = init_integer_type (objfile, bits, 1, name);
17406             }
17407           return set_die_type (die, type, cu);
17408         }
17409         break;
17410
17411       default:
17412         complaint (_("unsupported DW_AT_encoding: '%s'"),
17413                    dwarf_type_encoding_name (encoding));
17414         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17415         break;
17416     }
17417
17418   if (name && strcmp (name, "char") == 0)
17419     TYPE_NOSIGN (type) = 1;
17420
17421   maybe_set_alignment (cu, die, type);
17422
17423   return set_die_type (die, type, cu);
17424 }
17425
17426 /* Parse dwarf attribute if it's a block, reference or constant and put the
17427    resulting value of the attribute into struct bound_prop.
17428    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17429
17430 static int
17431 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17432                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17433 {
17434   struct dwarf2_property_baton *baton;
17435   struct obstack *obstack
17436     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17437
17438   if (attr == NULL || prop == NULL)
17439     return 0;
17440
17441   if (attr_form_is_block (attr))
17442     {
17443       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17444       baton->referenced_type = NULL;
17445       baton->locexpr.per_cu = cu->per_cu;
17446       baton->locexpr.size = DW_BLOCK (attr)->size;
17447       baton->locexpr.data = DW_BLOCK (attr)->data;
17448       prop->data.baton = baton;
17449       prop->kind = PROP_LOCEXPR;
17450       gdb_assert (prop->data.baton != NULL);
17451     }
17452   else if (attr_form_is_ref (attr))
17453     {
17454       struct dwarf2_cu *target_cu = cu;
17455       struct die_info *target_die;
17456       struct attribute *target_attr;
17457
17458       target_die = follow_die_ref (die, attr, &target_cu);
17459       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17460       if (target_attr == NULL)
17461         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17462                                    target_cu);
17463       if (target_attr == NULL)
17464         return 0;
17465
17466       switch (target_attr->name)
17467         {
17468           case DW_AT_location:
17469             if (attr_form_is_section_offset (target_attr))
17470               {
17471                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17472                 baton->referenced_type = die_type (target_die, target_cu);
17473                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17474                 prop->data.baton = baton;
17475                 prop->kind = PROP_LOCLIST;
17476                 gdb_assert (prop->data.baton != NULL);
17477               }
17478             else if (attr_form_is_block (target_attr))
17479               {
17480                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17481                 baton->referenced_type = die_type (target_die, target_cu);
17482                 baton->locexpr.per_cu = cu->per_cu;
17483                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17484                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17485                 prop->data.baton = baton;
17486                 prop->kind = PROP_LOCEXPR;
17487                 gdb_assert (prop->data.baton != NULL);
17488               }
17489             else
17490               {
17491                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17492                                                        "dynamic property");
17493                 return 0;
17494               }
17495             break;
17496           case DW_AT_data_member_location:
17497             {
17498               LONGEST offset;
17499
17500               if (!handle_data_member_location (target_die, target_cu,
17501                                                 &offset))
17502                 return 0;
17503
17504               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17505               baton->referenced_type = read_type_die (target_die->parent,
17506                                                       target_cu);
17507               baton->offset_info.offset = offset;
17508               baton->offset_info.type = die_type (target_die, target_cu);
17509               prop->data.baton = baton;
17510               prop->kind = PROP_ADDR_OFFSET;
17511               break;
17512             }
17513         }
17514     }
17515   else if (attr_form_is_constant (attr))
17516     {
17517       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17518       prop->kind = PROP_CONST;
17519     }
17520   else
17521     {
17522       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17523                                              dwarf2_name (die, cu));
17524       return 0;
17525     }
17526
17527   return 1;
17528 }
17529
17530 /* Read the given DW_AT_subrange DIE.  */
17531
17532 static struct type *
17533 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17534 {
17535   struct type *base_type, *orig_base_type;
17536   struct type *range_type;
17537   struct attribute *attr;
17538   struct dynamic_prop low, high;
17539   int low_default_is_valid;
17540   int high_bound_is_count = 0;
17541   const char *name;
17542   LONGEST negative_mask;
17543
17544   orig_base_type = die_type (die, cu);
17545   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17546      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17547      creating the range type, but we use the result of check_typedef
17548      when examining properties of the type.  */
17549   base_type = check_typedef (orig_base_type);
17550
17551   /* The die_type call above may have already set the type for this DIE.  */
17552   range_type = get_die_type (die, cu);
17553   if (range_type)
17554     return range_type;
17555
17556   low.kind = PROP_CONST;
17557   high.kind = PROP_CONST;
17558   high.data.const_val = 0;
17559
17560   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17561      omitting DW_AT_lower_bound.  */
17562   switch (cu->language)
17563     {
17564     case language_c:
17565     case language_cplus:
17566       low.data.const_val = 0;
17567       low_default_is_valid = 1;
17568       break;
17569     case language_fortran:
17570       low.data.const_val = 1;
17571       low_default_is_valid = 1;
17572       break;
17573     case language_d:
17574     case language_objc:
17575     case language_rust:
17576       low.data.const_val = 0;
17577       low_default_is_valid = (cu->header.version >= 4);
17578       break;
17579     case language_ada:
17580     case language_m2:
17581     case language_pascal:
17582       low.data.const_val = 1;
17583       low_default_is_valid = (cu->header.version >= 4);
17584       break;
17585     default:
17586       low.data.const_val = 0;
17587       low_default_is_valid = 0;
17588       break;
17589     }
17590
17591   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17592   if (attr)
17593     attr_to_dynamic_prop (attr, die, cu, &low);
17594   else if (!low_default_is_valid)
17595     complaint (_("Missing DW_AT_lower_bound "
17596                                       "- DIE at %s [in module %s]"),
17597                sect_offset_str (die->sect_off),
17598                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17599
17600   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17601   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17602     {
17603       attr = dwarf2_attr (die, DW_AT_count, cu);
17604       if (attr_to_dynamic_prop (attr, die, cu, &high))
17605         {
17606           /* If bounds are constant do the final calculation here.  */
17607           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17608             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17609           else
17610             high_bound_is_count = 1;
17611         }
17612     }
17613
17614   /* Dwarf-2 specifications explicitly allows to create subrange types
17615      without specifying a base type.
17616      In that case, the base type must be set to the type of
17617      the lower bound, upper bound or count, in that order, if any of these
17618      three attributes references an object that has a type.
17619      If no base type is found, the Dwarf-2 specifications say that
17620      a signed integer type of size equal to the size of an address should
17621      be used.
17622      For the following C code: `extern char gdb_int [];'
17623      GCC produces an empty range DIE.
17624      FIXME: muller/2010-05-28: Possible references to object for low bound,
17625      high bound or count are not yet handled by this code.  */
17626   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17627     {
17628       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17629       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17630       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17631       struct type *int_type = objfile_type (objfile)->builtin_int;
17632
17633       /* Test "int", "long int", and "long long int" objfile types,
17634          and select the first one having a size above or equal to the
17635          architecture address size.  */
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;
17641           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17642             base_type = int_type;
17643           else
17644             {
17645               int_type = objfile_type (objfile)->builtin_long_long;
17646               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17647                 base_type = int_type;
17648             }
17649         }
17650     }
17651
17652   /* Normally, the DWARF producers are expected to use a signed
17653      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17654      But this is unfortunately not always the case, as witnessed
17655      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17656      is used instead.  To work around that ambiguity, we treat
17657      the bounds as signed, and thus sign-extend their values, when
17658      the base type is signed.  */
17659   negative_mask =
17660     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17661   if (low.kind == PROP_CONST
17662       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17663     low.data.const_val |= negative_mask;
17664   if (high.kind == PROP_CONST
17665       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17666     high.data.const_val |= negative_mask;
17667
17668   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17669
17670   if (high_bound_is_count)
17671     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17672
17673   /* Ada expects an empty array on no boundary attributes.  */
17674   if (attr == NULL && cu->language != language_ada)
17675     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17676
17677   name = dwarf2_name (die, cu);
17678   if (name)
17679     TYPE_NAME (range_type) = name;
17680
17681   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17682   if (attr)
17683     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17684
17685   maybe_set_alignment (cu, die, range_type);
17686
17687   set_die_type (die, range_type, cu);
17688
17689   /* set_die_type should be already done.  */
17690   set_descriptive_type (range_type, die, cu);
17691
17692   return range_type;
17693 }
17694
17695 static struct type *
17696 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17697 {
17698   struct type *type;
17699
17700   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17701                     NULL);
17702   TYPE_NAME (type) = dwarf2_name (die, cu);
17703
17704   /* In Ada, an unspecified type is typically used when the description
17705      of the type is defered to a different unit.  When encountering
17706      such a type, we treat it as a stub, and try to resolve it later on,
17707      when needed.  */
17708   if (cu->language == language_ada)
17709     TYPE_STUB (type) = 1;
17710
17711   return set_die_type (die, type, cu);
17712 }
17713
17714 /* Read a single die and all its descendents.  Set the die's sibling
17715    field to NULL; set other fields in the die correctly, and set all
17716    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17717    location of the info_ptr after reading all of those dies.  PARENT
17718    is the parent of the die in question.  */
17719
17720 static struct die_info *
17721 read_die_and_children (const struct die_reader_specs *reader,
17722                        const gdb_byte *info_ptr,
17723                        const gdb_byte **new_info_ptr,
17724                        struct die_info *parent)
17725 {
17726   struct die_info *die;
17727   const gdb_byte *cur_ptr;
17728   int has_children;
17729
17730   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17731   if (die == NULL)
17732     {
17733       *new_info_ptr = cur_ptr;
17734       return NULL;
17735     }
17736   store_in_ref_table (die, reader->cu);
17737
17738   if (has_children)
17739     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17740   else
17741     {
17742       die->child = NULL;
17743       *new_info_ptr = cur_ptr;
17744     }
17745
17746   die->sibling = NULL;
17747   die->parent = parent;
17748   return die;
17749 }
17750
17751 /* Read a die, all of its descendents, and all of its siblings; set
17752    all of the fields of all of the dies correctly.  Arguments are as
17753    in read_die_and_children.  */
17754
17755 static struct die_info *
17756 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17757                          const gdb_byte *info_ptr,
17758                          const gdb_byte **new_info_ptr,
17759                          struct die_info *parent)
17760 {
17761   struct die_info *first_die, *last_sibling;
17762   const gdb_byte *cur_ptr;
17763
17764   cur_ptr = info_ptr;
17765   first_die = last_sibling = NULL;
17766
17767   while (1)
17768     {
17769       struct die_info *die
17770         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17771
17772       if (die == NULL)
17773         {
17774           *new_info_ptr = cur_ptr;
17775           return first_die;
17776         }
17777
17778       if (!first_die)
17779         first_die = die;
17780       else
17781         last_sibling->sibling = die;
17782
17783       last_sibling = die;
17784     }
17785 }
17786
17787 /* Read a die, all of its descendents, and all of its siblings; set
17788    all of the fields of all of the dies correctly.  Arguments are as
17789    in read_die_and_children.
17790    This the main entry point for reading a DIE and all its children.  */
17791
17792 static struct die_info *
17793 read_die_and_siblings (const struct die_reader_specs *reader,
17794                        const gdb_byte *info_ptr,
17795                        const gdb_byte **new_info_ptr,
17796                        struct die_info *parent)
17797 {
17798   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17799                                                   new_info_ptr, parent);
17800
17801   if (dwarf_die_debug)
17802     {
17803       fprintf_unfiltered (gdb_stdlog,
17804                           "Read die from %s@0x%x of %s:\n",
17805                           get_section_name (reader->die_section),
17806                           (unsigned) (info_ptr - reader->die_section->buffer),
17807                           bfd_get_filename (reader->abfd));
17808       dump_die (die, dwarf_die_debug);
17809     }
17810
17811   return die;
17812 }
17813
17814 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17815    attributes.
17816    The caller is responsible for filling in the extra attributes
17817    and updating (*DIEP)->num_attrs.
17818    Set DIEP to point to a newly allocated die with its information,
17819    except for its child, sibling, and parent fields.
17820    Set HAS_CHILDREN to tell whether the die has children or not.  */
17821
17822 static const gdb_byte *
17823 read_full_die_1 (const struct die_reader_specs *reader,
17824                  struct die_info **diep, const gdb_byte *info_ptr,
17825                  int *has_children, int num_extra_attrs)
17826 {
17827   unsigned int abbrev_number, bytes_read, i;
17828   struct abbrev_info *abbrev;
17829   struct die_info *die;
17830   struct dwarf2_cu *cu = reader->cu;
17831   bfd *abfd = reader->abfd;
17832
17833   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17834   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17835   info_ptr += bytes_read;
17836   if (!abbrev_number)
17837     {
17838       *diep = NULL;
17839       *has_children = 0;
17840       return info_ptr;
17841     }
17842
17843   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17844   if (!abbrev)
17845     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17846            abbrev_number,
17847            bfd_get_filename (abfd));
17848
17849   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17850   die->sect_off = sect_off;
17851   die->tag = abbrev->tag;
17852   die->abbrev = abbrev_number;
17853
17854   /* Make the result usable.
17855      The caller needs to update num_attrs after adding the extra
17856      attributes.  */
17857   die->num_attrs = abbrev->num_attrs;
17858
17859   for (i = 0; i < abbrev->num_attrs; ++i)
17860     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17861                                info_ptr);
17862
17863   *diep = die;
17864   *has_children = abbrev->has_children;
17865   return info_ptr;
17866 }
17867
17868 /* Read a die and all its attributes.
17869    Set DIEP to point to a newly allocated die with its information,
17870    except for its child, sibling, and parent fields.
17871    Set HAS_CHILDREN to tell whether the die has children or not.  */
17872
17873 static const gdb_byte *
17874 read_full_die (const struct die_reader_specs *reader,
17875                struct die_info **diep, const gdb_byte *info_ptr,
17876                int *has_children)
17877 {
17878   const gdb_byte *result;
17879
17880   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17881
17882   if (dwarf_die_debug)
17883     {
17884       fprintf_unfiltered (gdb_stdlog,
17885                           "Read die from %s@0x%x of %s:\n",
17886                           get_section_name (reader->die_section),
17887                           (unsigned) (info_ptr - reader->die_section->buffer),
17888                           bfd_get_filename (reader->abfd));
17889       dump_die (*diep, dwarf_die_debug);
17890     }
17891
17892   return result;
17893 }
17894 \f
17895 /* Abbreviation tables.
17896
17897    In DWARF version 2, the description of the debugging information is
17898    stored in a separate .debug_abbrev section.  Before we read any
17899    dies from a section we read in all abbreviations and install them
17900    in a hash table.  */
17901
17902 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17903
17904 struct abbrev_info *
17905 abbrev_table::alloc_abbrev ()
17906 {
17907   struct abbrev_info *abbrev;
17908
17909   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
17910   memset (abbrev, 0, sizeof (struct abbrev_info));
17911
17912   return abbrev;
17913 }
17914
17915 /* Add an abbreviation to the table.  */
17916
17917 void
17918 abbrev_table::add_abbrev (unsigned int abbrev_number,
17919                           struct abbrev_info *abbrev)
17920 {
17921   unsigned int hash_number;
17922
17923   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17924   abbrev->next = m_abbrevs[hash_number];
17925   m_abbrevs[hash_number] = abbrev;
17926 }
17927
17928 /* Look up an abbrev in the table.
17929    Returns NULL if the abbrev is not found.  */
17930
17931 struct abbrev_info *
17932 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
17933 {
17934   unsigned int hash_number;
17935   struct abbrev_info *abbrev;
17936
17937   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17938   abbrev = m_abbrevs[hash_number];
17939
17940   while (abbrev)
17941     {
17942       if (abbrev->number == abbrev_number)
17943         return abbrev;
17944       abbrev = abbrev->next;
17945     }
17946   return NULL;
17947 }
17948
17949 /* Read in an abbrev table.  */
17950
17951 static abbrev_table_up
17952 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
17953                          struct dwarf2_section_info *section,
17954                          sect_offset sect_off)
17955 {
17956   struct objfile *objfile = dwarf2_per_objfile->objfile;
17957   bfd *abfd = get_section_bfd_owner (section);
17958   const gdb_byte *abbrev_ptr;
17959   struct abbrev_info *cur_abbrev;
17960   unsigned int abbrev_number, bytes_read, abbrev_name;
17961   unsigned int abbrev_form;
17962   struct attr_abbrev *cur_attrs;
17963   unsigned int allocated_attrs;
17964
17965   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
17966
17967   dwarf2_read_section (objfile, section);
17968   abbrev_ptr = section->buffer + to_underlying (sect_off);
17969   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17970   abbrev_ptr += bytes_read;
17971
17972   allocated_attrs = ATTR_ALLOC_CHUNK;
17973   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
17974
17975   /* Loop until we reach an abbrev number of 0.  */
17976   while (abbrev_number)
17977     {
17978       cur_abbrev = abbrev_table->alloc_abbrev ();
17979
17980       /* read in abbrev header */
17981       cur_abbrev->number = abbrev_number;
17982       cur_abbrev->tag
17983         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17984       abbrev_ptr += bytes_read;
17985       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
17986       abbrev_ptr += 1;
17987
17988       /* now read in declarations */
17989       for (;;)
17990         {
17991           LONGEST implicit_const;
17992
17993           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17994           abbrev_ptr += bytes_read;
17995           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17996           abbrev_ptr += bytes_read;
17997           if (abbrev_form == DW_FORM_implicit_const)
17998             {
17999               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18000                                                    &bytes_read);
18001               abbrev_ptr += bytes_read;
18002             }
18003           else
18004             {
18005               /* Initialize it due to a false compiler warning.  */
18006               implicit_const = -1;
18007             }
18008
18009           if (abbrev_name == 0)
18010             break;
18011
18012           if (cur_abbrev->num_attrs == allocated_attrs)
18013             {
18014               allocated_attrs += ATTR_ALLOC_CHUNK;
18015               cur_attrs
18016                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18017             }
18018
18019           cur_attrs[cur_abbrev->num_attrs].name
18020             = (enum dwarf_attribute) abbrev_name;
18021           cur_attrs[cur_abbrev->num_attrs].form
18022             = (enum dwarf_form) abbrev_form;
18023           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18024           ++cur_abbrev->num_attrs;
18025         }
18026
18027       cur_abbrev->attrs =
18028         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18029                    cur_abbrev->num_attrs);
18030       memcpy (cur_abbrev->attrs, cur_attrs,
18031               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18032
18033       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18034
18035       /* Get next abbreviation.
18036          Under Irix6 the abbreviations for a compilation unit are not
18037          always properly terminated with an abbrev number of 0.
18038          Exit loop if we encounter an abbreviation which we have
18039          already read (which means we are about to read the abbreviations
18040          for the next compile unit) or if the end of the abbreviation
18041          table is reached.  */
18042       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18043         break;
18044       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18045       abbrev_ptr += bytes_read;
18046       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18047         break;
18048     }
18049
18050   xfree (cur_attrs);
18051   return abbrev_table;
18052 }
18053
18054 /* Returns nonzero if TAG represents a type that we might generate a partial
18055    symbol for.  */
18056
18057 static int
18058 is_type_tag_for_partial (int tag)
18059 {
18060   switch (tag)
18061     {
18062 #if 0
18063     /* Some types that would be reasonable to generate partial symbols for,
18064        that we don't at present.  */
18065     case DW_TAG_array_type:
18066     case DW_TAG_file_type:
18067     case DW_TAG_ptr_to_member_type:
18068     case DW_TAG_set_type:
18069     case DW_TAG_string_type:
18070     case DW_TAG_subroutine_type:
18071 #endif
18072     case DW_TAG_base_type:
18073     case DW_TAG_class_type:
18074     case DW_TAG_interface_type:
18075     case DW_TAG_enumeration_type:
18076     case DW_TAG_structure_type:
18077     case DW_TAG_subrange_type:
18078     case DW_TAG_typedef:
18079     case DW_TAG_union_type:
18080       return 1;
18081     default:
18082       return 0;
18083     }
18084 }
18085
18086 /* Load all DIEs that are interesting for partial symbols into memory.  */
18087
18088 static struct partial_die_info *
18089 load_partial_dies (const struct die_reader_specs *reader,
18090                    const gdb_byte *info_ptr, int building_psymtab)
18091 {
18092   struct dwarf2_cu *cu = reader->cu;
18093   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18094   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18095   unsigned int bytes_read;
18096   unsigned int load_all = 0;
18097   int nesting_level = 1;
18098
18099   parent_die = NULL;
18100   last_die = NULL;
18101
18102   gdb_assert (cu->per_cu != NULL);
18103   if (cu->per_cu->load_all_dies)
18104     load_all = 1;
18105
18106   cu->partial_dies
18107     = htab_create_alloc_ex (cu->header.length / 12,
18108                             partial_die_hash,
18109                             partial_die_eq,
18110                             NULL,
18111                             &cu->comp_unit_obstack,
18112                             hashtab_obstack_allocate,
18113                             dummy_obstack_deallocate);
18114
18115   while (1)
18116     {
18117       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18118
18119       /* A NULL abbrev means the end of a series of children.  */
18120       if (abbrev == NULL)
18121         {
18122           if (--nesting_level == 0)
18123             return first_die;
18124
18125           info_ptr += bytes_read;
18126           last_die = parent_die;
18127           parent_die = parent_die->die_parent;
18128           continue;
18129         }
18130
18131       /* Check for template arguments.  We never save these; if
18132          they're seen, we just mark the parent, and go on our way.  */
18133       if (parent_die != NULL
18134           && cu->language == language_cplus
18135           && (abbrev->tag == DW_TAG_template_type_param
18136               || abbrev->tag == DW_TAG_template_value_param))
18137         {
18138           parent_die->has_template_arguments = 1;
18139
18140           if (!load_all)
18141             {
18142               /* We don't need a partial DIE for the template argument.  */
18143               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18144               continue;
18145             }
18146         }
18147
18148       /* We only recurse into c++ subprograms looking for template arguments.
18149          Skip their other children.  */
18150       if (!load_all
18151           && cu->language == language_cplus
18152           && parent_die != NULL
18153           && parent_die->tag == DW_TAG_subprogram)
18154         {
18155           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18156           continue;
18157         }
18158
18159       /* Check whether this DIE is interesting enough to save.  Normally
18160          we would not be interested in members here, but there may be
18161          later variables referencing them via DW_AT_specification (for
18162          static members).  */
18163       if (!load_all
18164           && !is_type_tag_for_partial (abbrev->tag)
18165           && abbrev->tag != DW_TAG_constant
18166           && abbrev->tag != DW_TAG_enumerator
18167           && abbrev->tag != DW_TAG_subprogram
18168           && abbrev->tag != DW_TAG_inlined_subroutine
18169           && abbrev->tag != DW_TAG_lexical_block
18170           && abbrev->tag != DW_TAG_variable
18171           && abbrev->tag != DW_TAG_namespace
18172           && abbrev->tag != DW_TAG_module
18173           && abbrev->tag != DW_TAG_member
18174           && abbrev->tag != DW_TAG_imported_unit
18175           && abbrev->tag != DW_TAG_imported_declaration)
18176         {
18177           /* Otherwise we skip to the next sibling, if any.  */
18178           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18179           continue;
18180         }
18181
18182       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18183                                    abbrev);
18184
18185       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18186
18187       /* This two-pass algorithm for processing partial symbols has a
18188          high cost in cache pressure.  Thus, handle some simple cases
18189          here which cover the majority of C partial symbols.  DIEs
18190          which neither have specification tags in them, nor could have
18191          specification tags elsewhere pointing at them, can simply be
18192          processed and discarded.
18193
18194          This segment is also optional; scan_partial_symbols and
18195          add_partial_symbol will handle these DIEs if we chain
18196          them in normally.  When compilers which do not emit large
18197          quantities of duplicate debug information are more common,
18198          this code can probably be removed.  */
18199
18200       /* Any complete simple types at the top level (pretty much all
18201          of them, for a language without namespaces), can be processed
18202          directly.  */
18203       if (parent_die == NULL
18204           && pdi.has_specification == 0
18205           && pdi.is_declaration == 0
18206           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18207               || pdi.tag == DW_TAG_base_type
18208               || pdi.tag == DW_TAG_subrange_type))
18209         {
18210           if (building_psymtab && pdi.name != NULL)
18211             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18212                                  VAR_DOMAIN, LOC_TYPEDEF,
18213                                  &objfile->static_psymbols,
18214                                  0, cu->language, objfile);
18215           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18216           continue;
18217         }
18218
18219       /* The exception for DW_TAG_typedef with has_children above is
18220          a workaround of GCC PR debug/47510.  In the case of this complaint
18221          type_name_or_error will error on such types later.
18222
18223          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18224          it could not find the child DIEs referenced later, this is checked
18225          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18226
18227       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18228         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18229                      "- DIE at %s [in module %s]"),
18230                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18231
18232       /* If we're at the second level, and we're an enumerator, and
18233          our parent has no specification (meaning possibly lives in a
18234          namespace elsewhere), then we can add the partial symbol now
18235          instead of queueing it.  */
18236       if (pdi.tag == DW_TAG_enumerator
18237           && parent_die != NULL
18238           && parent_die->die_parent == NULL
18239           && parent_die->tag == DW_TAG_enumeration_type
18240           && parent_die->has_specification == 0)
18241         {
18242           if (pdi.name == NULL)
18243             complaint (_("malformed enumerator DIE ignored"));
18244           else if (building_psymtab)
18245             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18246                                  VAR_DOMAIN, LOC_CONST,
18247                                  cu->language == language_cplus
18248                                  ? &objfile->global_psymbols
18249                                  : &objfile->static_psymbols,
18250                                  0, cu->language, objfile);
18251
18252           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18253           continue;
18254         }
18255
18256       struct partial_die_info *part_die
18257         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18258
18259       /* We'll save this DIE so link it in.  */
18260       part_die->die_parent = parent_die;
18261       part_die->die_sibling = NULL;
18262       part_die->die_child = NULL;
18263
18264       if (last_die && last_die == parent_die)
18265         last_die->die_child = part_die;
18266       else if (last_die)
18267         last_die->die_sibling = part_die;
18268
18269       last_die = part_die;
18270
18271       if (first_die == NULL)
18272         first_die = part_die;
18273
18274       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18275          find interesting need to be in the hash table, because we
18276          also have the parent/sibling/child chains; only those that we
18277          might refer to by offset later during partial symbol reading.
18278
18279          For now this means things that might have be the target of a
18280          DW_AT_specification, DW_AT_abstract_origin, or
18281          DW_AT_extension.  DW_AT_extension will refer only to
18282          namespaces; DW_AT_abstract_origin refers to functions (and
18283          many things under the function DIE, but we do not recurse
18284          into function DIEs during partial symbol reading) and
18285          possibly variables as well; DW_AT_specification refers to
18286          declarations.  Declarations ought to have the DW_AT_declaration
18287          flag.  It happens that GCC forgets to put it in sometimes, but
18288          only for functions, not for types.
18289
18290          Adding more things than necessary to the hash table is harmless
18291          except for the performance cost.  Adding too few will result in
18292          wasted time in find_partial_die, when we reread the compilation
18293          unit with load_all_dies set.  */
18294
18295       if (load_all
18296           || abbrev->tag == DW_TAG_constant
18297           || abbrev->tag == DW_TAG_subprogram
18298           || abbrev->tag == DW_TAG_variable
18299           || abbrev->tag == DW_TAG_namespace
18300           || part_die->is_declaration)
18301         {
18302           void **slot;
18303
18304           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18305                                            to_underlying (part_die->sect_off),
18306                                            INSERT);
18307           *slot = part_die;
18308         }
18309
18310       /* For some DIEs we want to follow their children (if any).  For C
18311          we have no reason to follow the children of structures; for other
18312          languages we have to, so that we can get at method physnames
18313          to infer fully qualified class names, for DW_AT_specification,
18314          and for C++ template arguments.  For C++, we also look one level
18315          inside functions to find template arguments (if the name of the
18316          function does not already contain the template arguments).
18317
18318          For Ada, we need to scan the children of subprograms and lexical
18319          blocks as well because Ada allows the definition of nested
18320          entities that could be interesting for the debugger, such as
18321          nested subprograms for instance.  */
18322       if (last_die->has_children
18323           && (load_all
18324               || last_die->tag == DW_TAG_namespace
18325               || last_die->tag == DW_TAG_module
18326               || last_die->tag == DW_TAG_enumeration_type
18327               || (cu->language == language_cplus
18328                   && last_die->tag == DW_TAG_subprogram
18329                   && (last_die->name == NULL
18330                       || strchr (last_die->name, '<') == NULL))
18331               || (cu->language != language_c
18332                   && (last_die->tag == DW_TAG_class_type
18333                       || last_die->tag == DW_TAG_interface_type
18334                       || last_die->tag == DW_TAG_structure_type
18335                       || last_die->tag == DW_TAG_union_type))
18336               || (cu->language == language_ada
18337                   && (last_die->tag == DW_TAG_subprogram
18338                       || last_die->tag == DW_TAG_lexical_block))))
18339         {
18340           nesting_level++;
18341           parent_die = last_die;
18342           continue;
18343         }
18344
18345       /* Otherwise we skip to the next sibling, if any.  */
18346       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18347
18348       /* Back to the top, do it again.  */
18349     }
18350 }
18351
18352 partial_die_info::partial_die_info (sect_offset sect_off_,
18353                                     struct abbrev_info *abbrev)
18354   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18355 {
18356 }
18357
18358 /* Read a minimal amount of information into the minimal die structure.
18359    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18360
18361 const gdb_byte *
18362 partial_die_info::read (const struct die_reader_specs *reader,
18363                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18364 {
18365   struct dwarf2_cu *cu = reader->cu;
18366   struct dwarf2_per_objfile *dwarf2_per_objfile
18367     = cu->per_cu->dwarf2_per_objfile;
18368   unsigned int i;
18369   int has_low_pc_attr = 0;
18370   int has_high_pc_attr = 0;
18371   int high_pc_relative = 0;
18372
18373   for (i = 0; i < abbrev.num_attrs; ++i)
18374     {
18375       struct attribute attr;
18376
18377       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18378
18379       /* Store the data if it is of an attribute we want to keep in a
18380          partial symbol table.  */
18381       switch (attr.name)
18382         {
18383         case DW_AT_name:
18384           switch (tag)
18385             {
18386             case DW_TAG_compile_unit:
18387             case DW_TAG_partial_unit:
18388             case DW_TAG_type_unit:
18389               /* Compilation units have a DW_AT_name that is a filename, not
18390                  a source language identifier.  */
18391             case DW_TAG_enumeration_type:
18392             case DW_TAG_enumerator:
18393               /* These tags always have simple identifiers already; no need
18394                  to canonicalize them.  */
18395               name = DW_STRING (&attr);
18396               break;
18397             default:
18398               {
18399                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18400
18401                 name
18402                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18403                                               &objfile->per_bfd->storage_obstack);
18404               }
18405               break;
18406             }
18407           break;
18408         case DW_AT_linkage_name:
18409         case DW_AT_MIPS_linkage_name:
18410           /* Note that both forms of linkage name might appear.  We
18411              assume they will be the same, and we only store the last
18412              one we see.  */
18413           if (cu->language == language_ada)
18414             name = DW_STRING (&attr);
18415           linkage_name = DW_STRING (&attr);
18416           break;
18417         case DW_AT_low_pc:
18418           has_low_pc_attr = 1;
18419           lowpc = attr_value_as_address (&attr);
18420           break;
18421         case DW_AT_high_pc:
18422           has_high_pc_attr = 1;
18423           highpc = attr_value_as_address (&attr);
18424           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18425                 high_pc_relative = 1;
18426           break;
18427         case DW_AT_location:
18428           /* Support the .debug_loc offsets.  */
18429           if (attr_form_is_block (&attr))
18430             {
18431                d.locdesc = DW_BLOCK (&attr);
18432             }
18433           else if (attr_form_is_section_offset (&attr))
18434             {
18435               dwarf2_complex_location_expr_complaint ();
18436             }
18437           else
18438             {
18439               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18440                                                      "partial symbol information");
18441             }
18442           break;
18443         case DW_AT_external:
18444           is_external = DW_UNSND (&attr);
18445           break;
18446         case DW_AT_declaration:
18447           is_declaration = DW_UNSND (&attr);
18448           break;
18449         case DW_AT_type:
18450           has_type = 1;
18451           break;
18452         case DW_AT_abstract_origin:
18453         case DW_AT_specification:
18454         case DW_AT_extension:
18455           has_specification = 1;
18456           spec_offset = dwarf2_get_ref_die_offset (&attr);
18457           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18458                                    || cu->per_cu->is_dwz);
18459           break;
18460         case DW_AT_sibling:
18461           /* Ignore absolute siblings, they might point outside of
18462              the current compile unit.  */
18463           if (attr.form == DW_FORM_ref_addr)
18464             complaint (_("ignoring absolute DW_AT_sibling"));
18465           else
18466             {
18467               const gdb_byte *buffer = reader->buffer;
18468               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18469               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18470
18471               if (sibling_ptr < info_ptr)
18472                 complaint (_("DW_AT_sibling points backwards"));
18473               else if (sibling_ptr > reader->buffer_end)
18474                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18475               else
18476                 sibling = sibling_ptr;
18477             }
18478           break;
18479         case DW_AT_byte_size:
18480           has_byte_size = 1;
18481           break;
18482         case DW_AT_const_value:
18483           has_const_value = 1;
18484           break;
18485         case DW_AT_calling_convention:
18486           /* DWARF doesn't provide a way to identify a program's source-level
18487              entry point.  DW_AT_calling_convention attributes are only meant
18488              to describe functions' calling conventions.
18489
18490              However, because it's a necessary piece of information in
18491              Fortran, and before DWARF 4 DW_CC_program was the only
18492              piece of debugging information whose definition refers to
18493              a 'main program' at all, several compilers marked Fortran
18494              main programs with DW_CC_program --- even when those
18495              functions use the standard calling conventions.
18496
18497              Although DWARF now specifies a way to provide this
18498              information, we support this practice for backward
18499              compatibility.  */
18500           if (DW_UNSND (&attr) == DW_CC_program
18501               && cu->language == language_fortran)
18502             main_subprogram = 1;
18503           break;
18504         case DW_AT_inline:
18505           if (DW_UNSND (&attr) == DW_INL_inlined
18506               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18507             may_be_inlined = 1;
18508           break;
18509
18510         case DW_AT_import:
18511           if (tag == DW_TAG_imported_unit)
18512             {
18513               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18514               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18515                                   || cu->per_cu->is_dwz);
18516             }
18517           break;
18518
18519         case DW_AT_main_subprogram:
18520           main_subprogram = DW_UNSND (&attr);
18521           break;
18522
18523         default:
18524           break;
18525         }
18526     }
18527
18528   if (high_pc_relative)
18529     highpc += lowpc;
18530
18531   if (has_low_pc_attr && has_high_pc_attr)
18532     {
18533       /* When using the GNU linker, .gnu.linkonce. sections are used to
18534          eliminate duplicate copies of functions and vtables and such.
18535          The linker will arbitrarily choose one and discard the others.
18536          The AT_*_pc values for such functions refer to local labels in
18537          these sections.  If the section from that file was discarded, the
18538          labels are not in the output, so the relocs get a value of 0.
18539          If this is a discarded function, mark the pc bounds as invalid,
18540          so that GDB will ignore it.  */
18541       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18542         {
18543           struct objfile *objfile = dwarf2_per_objfile->objfile;
18544           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18545
18546           complaint (_("DW_AT_low_pc %s is zero "
18547                        "for DIE at %s [in module %s]"),
18548                      paddress (gdbarch, lowpc),
18549                      sect_offset_str (sect_off),
18550                      objfile_name (objfile));
18551         }
18552       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18553       else if (lowpc >= highpc)
18554         {
18555           struct objfile *objfile = dwarf2_per_objfile->objfile;
18556           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18557
18558           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18559                        "for DIE at %s [in module %s]"),
18560                      paddress (gdbarch, lowpc),
18561                      paddress (gdbarch, highpc),
18562                      sect_offset_str (sect_off),
18563                      objfile_name (objfile));
18564         }
18565       else
18566         has_pc_info = 1;
18567     }
18568
18569   return info_ptr;
18570 }
18571
18572 /* Find a cached partial DIE at OFFSET in CU.  */
18573
18574 struct partial_die_info *
18575 dwarf2_cu::find_partial_die (sect_offset sect_off)
18576 {
18577   struct partial_die_info *lookup_die = NULL;
18578   struct partial_die_info part_die (sect_off);
18579
18580   lookup_die = ((struct partial_die_info *)
18581                 htab_find_with_hash (partial_dies, &part_die,
18582                                      to_underlying (sect_off)));
18583
18584   return lookup_die;
18585 }
18586
18587 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18588    except in the case of .debug_types DIEs which do not reference
18589    outside their CU (they do however referencing other types via
18590    DW_FORM_ref_sig8).  */
18591
18592 static struct partial_die_info *
18593 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18594 {
18595   struct dwarf2_per_objfile *dwarf2_per_objfile
18596     = cu->per_cu->dwarf2_per_objfile;
18597   struct objfile *objfile = dwarf2_per_objfile->objfile;
18598   struct dwarf2_per_cu_data *per_cu = NULL;
18599   struct partial_die_info *pd = NULL;
18600
18601   if (offset_in_dwz == cu->per_cu->is_dwz
18602       && offset_in_cu_p (&cu->header, sect_off))
18603     {
18604       pd = cu->find_partial_die (sect_off);
18605       if (pd != NULL)
18606         return pd;
18607       /* We missed recording what we needed.
18608          Load all dies and try again.  */
18609       per_cu = cu->per_cu;
18610     }
18611   else
18612     {
18613       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18614       if (cu->per_cu->is_debug_types)
18615         {
18616           error (_("Dwarf Error: Type Unit at offset %s contains"
18617                    " external reference to offset %s [in module %s].\n"),
18618                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18619                  bfd_get_filename (objfile->obfd));
18620         }
18621       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18622                                                  dwarf2_per_objfile);
18623
18624       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18625         load_partial_comp_unit (per_cu);
18626
18627       per_cu->cu->last_used = 0;
18628       pd = per_cu->cu->find_partial_die (sect_off);
18629     }
18630
18631   /* If we didn't find it, and not all dies have been loaded,
18632      load them all and try again.  */
18633
18634   if (pd == NULL && per_cu->load_all_dies == 0)
18635     {
18636       per_cu->load_all_dies = 1;
18637
18638       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18639          THIS_CU->cu may already be in use.  So we can't just free it and
18640          replace its DIEs with the ones we read in.  Instead, we leave those
18641          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18642          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18643          set.  */
18644       load_partial_comp_unit (per_cu);
18645
18646       pd = per_cu->cu->find_partial_die (sect_off);
18647     }
18648
18649   if (pd == NULL)
18650     internal_error (__FILE__, __LINE__,
18651                     _("could not find partial DIE %s "
18652                       "in cache [from module %s]\n"),
18653                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18654   return pd;
18655 }
18656
18657 /* See if we can figure out if the class lives in a namespace.  We do
18658    this by looking for a member function; its demangled name will
18659    contain namespace info, if there is any.  */
18660
18661 static void
18662 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18663                                   struct dwarf2_cu *cu)
18664 {
18665   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18666      what template types look like, because the demangler
18667      frequently doesn't give the same name as the debug info.  We
18668      could fix this by only using the demangled name to get the
18669      prefix (but see comment in read_structure_type).  */
18670
18671   struct partial_die_info *real_pdi;
18672   struct partial_die_info *child_pdi;
18673
18674   /* If this DIE (this DIE's specification, if any) has a parent, then
18675      we should not do this.  We'll prepend the parent's fully qualified
18676      name when we create the partial symbol.  */
18677
18678   real_pdi = struct_pdi;
18679   while (real_pdi->has_specification)
18680     real_pdi = find_partial_die (real_pdi->spec_offset,
18681                                  real_pdi->spec_is_dwz, cu);
18682
18683   if (real_pdi->die_parent != NULL)
18684     return;
18685
18686   for (child_pdi = struct_pdi->die_child;
18687        child_pdi != NULL;
18688        child_pdi = child_pdi->die_sibling)
18689     {
18690       if (child_pdi->tag == DW_TAG_subprogram
18691           && child_pdi->linkage_name != NULL)
18692         {
18693           char *actual_class_name
18694             = language_class_name_from_physname (cu->language_defn,
18695                                                  child_pdi->linkage_name);
18696           if (actual_class_name != NULL)
18697             {
18698               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18699               struct_pdi->name
18700                 = ((const char *)
18701                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18702                                   actual_class_name,
18703                                   strlen (actual_class_name)));
18704               xfree (actual_class_name);
18705             }
18706           break;
18707         }
18708     }
18709 }
18710
18711 void
18712 partial_die_info::fixup (struct dwarf2_cu *cu)
18713 {
18714   /* Once we've fixed up a die, there's no point in doing so again.
18715      This also avoids a memory leak if we were to call
18716      guess_partial_die_structure_name multiple times.  */
18717   if (fixup_called)
18718     return;
18719
18720   /* If we found a reference attribute and the DIE has no name, try
18721      to find a name in the referred to DIE.  */
18722
18723   if (name == NULL && has_specification)
18724     {
18725       struct partial_die_info *spec_die;
18726
18727       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18728
18729       spec_die->fixup (cu);
18730
18731       if (spec_die->name)
18732         {
18733           name = spec_die->name;
18734
18735           /* Copy DW_AT_external attribute if it is set.  */
18736           if (spec_die->is_external)
18737             is_external = spec_die->is_external;
18738         }
18739     }
18740
18741   /* Set default names for some unnamed DIEs.  */
18742
18743   if (name == NULL && tag == DW_TAG_namespace)
18744     name = CP_ANONYMOUS_NAMESPACE_STR;
18745
18746   /* If there is no parent die to provide a namespace, and there are
18747      children, see if we can determine the namespace from their linkage
18748      name.  */
18749   if (cu->language == language_cplus
18750       && !VEC_empty (dwarf2_section_info_def,
18751                      cu->per_cu->dwarf2_per_objfile->types)
18752       && die_parent == NULL
18753       && has_children
18754       && (tag == DW_TAG_class_type
18755           || tag == DW_TAG_structure_type
18756           || tag == DW_TAG_union_type))
18757     guess_partial_die_structure_name (this, cu);
18758
18759   /* GCC might emit a nameless struct or union that has a linkage
18760      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18761   if (name == NULL
18762       && (tag == DW_TAG_class_type
18763           || tag == DW_TAG_interface_type
18764           || tag == DW_TAG_structure_type
18765           || tag == DW_TAG_union_type)
18766       && linkage_name != NULL)
18767     {
18768       char *demangled;
18769
18770       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18771       if (demangled)
18772         {
18773           const char *base;
18774
18775           /* Strip any leading namespaces/classes, keep only the base name.
18776              DW_AT_name for named DIEs does not contain the prefixes.  */
18777           base = strrchr (demangled, ':');
18778           if (base && base > demangled && base[-1] == ':')
18779             base++;
18780           else
18781             base = demangled;
18782
18783           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18784           name
18785             = ((const char *)
18786                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18787                               base, strlen (base)));
18788           xfree (demangled);
18789         }
18790     }
18791
18792   fixup_called = 1;
18793 }
18794
18795 /* Read an attribute value described by an attribute form.  */
18796
18797 static const gdb_byte *
18798 read_attribute_value (const struct die_reader_specs *reader,
18799                       struct attribute *attr, unsigned form,
18800                       LONGEST implicit_const, const gdb_byte *info_ptr)
18801 {
18802   struct dwarf2_cu *cu = reader->cu;
18803   struct dwarf2_per_objfile *dwarf2_per_objfile
18804     = cu->per_cu->dwarf2_per_objfile;
18805   struct objfile *objfile = dwarf2_per_objfile->objfile;
18806   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18807   bfd *abfd = reader->abfd;
18808   struct comp_unit_head *cu_header = &cu->header;
18809   unsigned int bytes_read;
18810   struct dwarf_block *blk;
18811
18812   attr->form = (enum dwarf_form) form;
18813   switch (form)
18814     {
18815     case DW_FORM_ref_addr:
18816       if (cu->header.version == 2)
18817         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18818       else
18819         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18820                                        &cu->header, &bytes_read);
18821       info_ptr += bytes_read;
18822       break;
18823     case DW_FORM_GNU_ref_alt:
18824       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18825       info_ptr += bytes_read;
18826       break;
18827     case DW_FORM_addr:
18828       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18829       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18830       info_ptr += bytes_read;
18831       break;
18832     case DW_FORM_block2:
18833       blk = dwarf_alloc_block (cu);
18834       blk->size = read_2_bytes (abfd, info_ptr);
18835       info_ptr += 2;
18836       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18837       info_ptr += blk->size;
18838       DW_BLOCK (attr) = blk;
18839       break;
18840     case DW_FORM_block4:
18841       blk = dwarf_alloc_block (cu);
18842       blk->size = read_4_bytes (abfd, info_ptr);
18843       info_ptr += 4;
18844       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18845       info_ptr += blk->size;
18846       DW_BLOCK (attr) = blk;
18847       break;
18848     case DW_FORM_data2:
18849       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18850       info_ptr += 2;
18851       break;
18852     case DW_FORM_data4:
18853       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18854       info_ptr += 4;
18855       break;
18856     case DW_FORM_data8:
18857       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18858       info_ptr += 8;
18859       break;
18860     case DW_FORM_data16:
18861       blk = dwarf_alloc_block (cu);
18862       blk->size = 16;
18863       blk->data = read_n_bytes (abfd, info_ptr, 16);
18864       info_ptr += 16;
18865       DW_BLOCK (attr) = blk;
18866       break;
18867     case DW_FORM_sec_offset:
18868       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18869       info_ptr += bytes_read;
18870       break;
18871     case DW_FORM_string:
18872       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18873       DW_STRING_IS_CANONICAL (attr) = 0;
18874       info_ptr += bytes_read;
18875       break;
18876     case DW_FORM_strp:
18877       if (!cu->per_cu->is_dwz)
18878         {
18879           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18880                                                    abfd, info_ptr, cu_header,
18881                                                    &bytes_read);
18882           DW_STRING_IS_CANONICAL (attr) = 0;
18883           info_ptr += bytes_read;
18884           break;
18885         }
18886       /* FALLTHROUGH */
18887     case DW_FORM_line_strp:
18888       if (!cu->per_cu->is_dwz)
18889         {
18890           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18891                                                         abfd, info_ptr,
18892                                                         cu_header, &bytes_read);
18893           DW_STRING_IS_CANONICAL (attr) = 0;
18894           info_ptr += bytes_read;
18895           break;
18896         }
18897       /* FALLTHROUGH */
18898     case DW_FORM_GNU_strp_alt:
18899       {
18900         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18901         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18902                                           &bytes_read);
18903
18904         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18905                                                           dwz, str_offset);
18906         DW_STRING_IS_CANONICAL (attr) = 0;
18907         info_ptr += bytes_read;
18908       }
18909       break;
18910     case DW_FORM_exprloc:
18911     case DW_FORM_block:
18912       blk = dwarf_alloc_block (cu);
18913       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18914       info_ptr += bytes_read;
18915       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18916       info_ptr += blk->size;
18917       DW_BLOCK (attr) = blk;
18918       break;
18919     case DW_FORM_block1:
18920       blk = dwarf_alloc_block (cu);
18921       blk->size = read_1_byte (abfd, info_ptr);
18922       info_ptr += 1;
18923       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18924       info_ptr += blk->size;
18925       DW_BLOCK (attr) = blk;
18926       break;
18927     case DW_FORM_data1:
18928       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18929       info_ptr += 1;
18930       break;
18931     case DW_FORM_flag:
18932       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18933       info_ptr += 1;
18934       break;
18935     case DW_FORM_flag_present:
18936       DW_UNSND (attr) = 1;
18937       break;
18938     case DW_FORM_sdata:
18939       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18940       info_ptr += bytes_read;
18941       break;
18942     case DW_FORM_udata:
18943       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18944       info_ptr += bytes_read;
18945       break;
18946     case DW_FORM_ref1:
18947       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18948                          + read_1_byte (abfd, info_ptr));
18949       info_ptr += 1;
18950       break;
18951     case DW_FORM_ref2:
18952       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18953                          + read_2_bytes (abfd, info_ptr));
18954       info_ptr += 2;
18955       break;
18956     case DW_FORM_ref4:
18957       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18958                          + read_4_bytes (abfd, info_ptr));
18959       info_ptr += 4;
18960       break;
18961     case DW_FORM_ref8:
18962       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18963                          + read_8_bytes (abfd, info_ptr));
18964       info_ptr += 8;
18965       break;
18966     case DW_FORM_ref_sig8:
18967       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18968       info_ptr += 8;
18969       break;
18970     case DW_FORM_ref_udata:
18971       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18972                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
18973       info_ptr += bytes_read;
18974       break;
18975     case DW_FORM_indirect:
18976       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18977       info_ptr += bytes_read;
18978       if (form == DW_FORM_implicit_const)
18979         {
18980           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18981           info_ptr += bytes_read;
18982         }
18983       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
18984                                        info_ptr);
18985       break;
18986     case DW_FORM_implicit_const:
18987       DW_SND (attr) = implicit_const;
18988       break;
18989     case DW_FORM_GNU_addr_index:
18990       if (reader->dwo_file == NULL)
18991         {
18992           /* For now flag a hard error.
18993              Later we can turn this into a complaint.  */
18994           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
18995                  dwarf_form_name (form),
18996                  bfd_get_filename (abfd));
18997         }
18998       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
18999       info_ptr += bytes_read;
19000       break;
19001     case DW_FORM_GNU_str_index:
19002       if (reader->dwo_file == NULL)
19003         {
19004           /* For now flag a hard error.
19005              Later we can turn this into a complaint if warranted.  */
19006           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19007                  dwarf_form_name (form),
19008                  bfd_get_filename (abfd));
19009         }
19010       {
19011         ULONGEST str_index =
19012           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19013
19014         DW_STRING (attr) = read_str_index (reader, str_index);
19015         DW_STRING_IS_CANONICAL (attr) = 0;
19016         info_ptr += bytes_read;
19017       }
19018       break;
19019     default:
19020       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19021              dwarf_form_name (form),
19022              bfd_get_filename (abfd));
19023     }
19024
19025   /* Super hack.  */
19026   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19027     attr->form = DW_FORM_GNU_ref_alt;
19028
19029   /* We have seen instances where the compiler tried to emit a byte
19030      size attribute of -1 which ended up being encoded as an unsigned
19031      0xffffffff.  Although 0xffffffff is technically a valid size value,
19032      an object of this size seems pretty unlikely so we can relatively
19033      safely treat these cases as if the size attribute was invalid and
19034      treat them as zero by default.  */
19035   if (attr->name == DW_AT_byte_size
19036       && form == DW_FORM_data4
19037       && DW_UNSND (attr) >= 0xffffffff)
19038     {
19039       complaint
19040         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19041          hex_string (DW_UNSND (attr)));
19042       DW_UNSND (attr) = 0;
19043     }
19044
19045   return info_ptr;
19046 }
19047
19048 /* Read an attribute described by an abbreviated attribute.  */
19049
19050 static const gdb_byte *
19051 read_attribute (const struct die_reader_specs *reader,
19052                 struct attribute *attr, struct attr_abbrev *abbrev,
19053                 const gdb_byte *info_ptr)
19054 {
19055   attr->name = abbrev->name;
19056   return read_attribute_value (reader, attr, abbrev->form,
19057                                abbrev->implicit_const, info_ptr);
19058 }
19059
19060 /* Read dwarf information from a buffer.  */
19061
19062 static unsigned int
19063 read_1_byte (bfd *abfd, const gdb_byte *buf)
19064 {
19065   return bfd_get_8 (abfd, buf);
19066 }
19067
19068 static int
19069 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19070 {
19071   return bfd_get_signed_8 (abfd, buf);
19072 }
19073
19074 static unsigned int
19075 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19076 {
19077   return bfd_get_16 (abfd, buf);
19078 }
19079
19080 static int
19081 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19082 {
19083   return bfd_get_signed_16 (abfd, buf);
19084 }
19085
19086 static unsigned int
19087 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19088 {
19089   return bfd_get_32 (abfd, buf);
19090 }
19091
19092 static int
19093 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19094 {
19095   return bfd_get_signed_32 (abfd, buf);
19096 }
19097
19098 static ULONGEST
19099 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19100 {
19101   return bfd_get_64 (abfd, buf);
19102 }
19103
19104 static CORE_ADDR
19105 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19106               unsigned int *bytes_read)
19107 {
19108   struct comp_unit_head *cu_header = &cu->header;
19109   CORE_ADDR retval = 0;
19110
19111   if (cu_header->signed_addr_p)
19112     {
19113       switch (cu_header->addr_size)
19114         {
19115         case 2:
19116           retval = bfd_get_signed_16 (abfd, buf);
19117           break;
19118         case 4:
19119           retval = bfd_get_signed_32 (abfd, buf);
19120           break;
19121         case 8:
19122           retval = bfd_get_signed_64 (abfd, buf);
19123           break;
19124         default:
19125           internal_error (__FILE__, __LINE__,
19126                           _("read_address: bad switch, signed [in module %s]"),
19127                           bfd_get_filename (abfd));
19128         }
19129     }
19130   else
19131     {
19132       switch (cu_header->addr_size)
19133         {
19134         case 2:
19135           retval = bfd_get_16 (abfd, buf);
19136           break;
19137         case 4:
19138           retval = bfd_get_32 (abfd, buf);
19139           break;
19140         case 8:
19141           retval = bfd_get_64 (abfd, buf);
19142           break;
19143         default:
19144           internal_error (__FILE__, __LINE__,
19145                           _("read_address: bad switch, "
19146                             "unsigned [in module %s]"),
19147                           bfd_get_filename (abfd));
19148         }
19149     }
19150
19151   *bytes_read = cu_header->addr_size;
19152   return retval;
19153 }
19154
19155 /* Read the initial length from a section.  The (draft) DWARF 3
19156    specification allows the initial length to take up either 4 bytes
19157    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19158    bytes describe the length and all offsets will be 8 bytes in length
19159    instead of 4.
19160
19161    An older, non-standard 64-bit format is also handled by this
19162    function.  The older format in question stores the initial length
19163    as an 8-byte quantity without an escape value.  Lengths greater
19164    than 2^32 aren't very common which means that the initial 4 bytes
19165    is almost always zero.  Since a length value of zero doesn't make
19166    sense for the 32-bit format, this initial zero can be considered to
19167    be an escape value which indicates the presence of the older 64-bit
19168    format.  As written, the code can't detect (old format) lengths
19169    greater than 4GB.  If it becomes necessary to handle lengths
19170    somewhat larger than 4GB, we could allow other small values (such
19171    as the non-sensical values of 1, 2, and 3) to also be used as
19172    escape values indicating the presence of the old format.
19173
19174    The value returned via bytes_read should be used to increment the
19175    relevant pointer after calling read_initial_length().
19176
19177    [ Note:  read_initial_length() and read_offset() are based on the
19178      document entitled "DWARF Debugging Information Format", revision
19179      3, draft 8, dated November 19, 2001.  This document was obtained
19180      from:
19181
19182         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19183
19184      This document is only a draft and is subject to change.  (So beware.)
19185
19186      Details regarding the older, non-standard 64-bit format were
19187      determined empirically by examining 64-bit ELF files produced by
19188      the SGI toolchain on an IRIX 6.5 machine.
19189
19190      - Kevin, July 16, 2002
19191    ] */
19192
19193 static LONGEST
19194 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19195 {
19196   LONGEST length = bfd_get_32 (abfd, buf);
19197
19198   if (length == 0xffffffff)
19199     {
19200       length = bfd_get_64 (abfd, buf + 4);
19201       *bytes_read = 12;
19202     }
19203   else if (length == 0)
19204     {
19205       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19206       length = bfd_get_64 (abfd, buf);
19207       *bytes_read = 8;
19208     }
19209   else
19210     {
19211       *bytes_read = 4;
19212     }
19213
19214   return length;
19215 }
19216
19217 /* Cover function for read_initial_length.
19218    Returns the length of the object at BUF, and stores the size of the
19219    initial length in *BYTES_READ and stores the size that offsets will be in
19220    *OFFSET_SIZE.
19221    If the initial length size is not equivalent to that specified in
19222    CU_HEADER then issue a complaint.
19223    This is useful when reading non-comp-unit headers.  */
19224
19225 static LONGEST
19226 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19227                                         const struct comp_unit_head *cu_header,
19228                                         unsigned int *bytes_read,
19229                                         unsigned int *offset_size)
19230 {
19231   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19232
19233   gdb_assert (cu_header->initial_length_size == 4
19234               || cu_header->initial_length_size == 8
19235               || cu_header->initial_length_size == 12);
19236
19237   if (cu_header->initial_length_size != *bytes_read)
19238     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19239
19240   *offset_size = (*bytes_read == 4) ? 4 : 8;
19241   return length;
19242 }
19243
19244 /* Read an offset from the data stream.  The size of the offset is
19245    given by cu_header->offset_size.  */
19246
19247 static LONGEST
19248 read_offset (bfd *abfd, const gdb_byte *buf,
19249              const struct comp_unit_head *cu_header,
19250              unsigned int *bytes_read)
19251 {
19252   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19253
19254   *bytes_read = cu_header->offset_size;
19255   return offset;
19256 }
19257
19258 /* Read an offset from the data stream.  */
19259
19260 static LONGEST
19261 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19262 {
19263   LONGEST retval = 0;
19264
19265   switch (offset_size)
19266     {
19267     case 4:
19268       retval = bfd_get_32 (abfd, buf);
19269       break;
19270     case 8:
19271       retval = bfd_get_64 (abfd, buf);
19272       break;
19273     default:
19274       internal_error (__FILE__, __LINE__,
19275                       _("read_offset_1: bad switch [in module %s]"),
19276                       bfd_get_filename (abfd));
19277     }
19278
19279   return retval;
19280 }
19281
19282 static const gdb_byte *
19283 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19284 {
19285   /* If the size of a host char is 8 bits, we can return a pointer
19286      to the buffer, otherwise we have to copy the data to a buffer
19287      allocated on the temporary obstack.  */
19288   gdb_assert (HOST_CHAR_BIT == 8);
19289   return buf;
19290 }
19291
19292 static const char *
19293 read_direct_string (bfd *abfd, const gdb_byte *buf,
19294                     unsigned int *bytes_read_ptr)
19295 {
19296   /* If the size of a host char is 8 bits, we can return a pointer
19297      to the string, otherwise we have to copy the string to a buffer
19298      allocated on the temporary obstack.  */
19299   gdb_assert (HOST_CHAR_BIT == 8);
19300   if (*buf == '\0')
19301     {
19302       *bytes_read_ptr = 1;
19303       return NULL;
19304     }
19305   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19306   return (const char *) buf;
19307 }
19308
19309 /* Return pointer to string at section SECT offset STR_OFFSET with error
19310    reporting strings FORM_NAME and SECT_NAME.  */
19311
19312 static const char *
19313 read_indirect_string_at_offset_from (struct objfile *objfile,
19314                                      bfd *abfd, LONGEST str_offset,
19315                                      struct dwarf2_section_info *sect,
19316                                      const char *form_name,
19317                                      const char *sect_name)
19318 {
19319   dwarf2_read_section (objfile, sect);
19320   if (sect->buffer == NULL)
19321     error (_("%s used without %s section [in module %s]"),
19322            form_name, sect_name, bfd_get_filename (abfd));
19323   if (str_offset >= sect->size)
19324     error (_("%s pointing outside of %s section [in module %s]"),
19325            form_name, sect_name, bfd_get_filename (abfd));
19326   gdb_assert (HOST_CHAR_BIT == 8);
19327   if (sect->buffer[str_offset] == '\0')
19328     return NULL;
19329   return (const char *) (sect->buffer + str_offset);
19330 }
19331
19332 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19333
19334 static const char *
19335 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19336                                 bfd *abfd, LONGEST str_offset)
19337 {
19338   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19339                                               abfd, str_offset,
19340                                               &dwarf2_per_objfile->str,
19341                                               "DW_FORM_strp", ".debug_str");
19342 }
19343
19344 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19345
19346 static const char *
19347 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19348                                      bfd *abfd, LONGEST str_offset)
19349 {
19350   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19351                                               abfd, str_offset,
19352                                               &dwarf2_per_objfile->line_str,
19353                                               "DW_FORM_line_strp",
19354                                               ".debug_line_str");
19355 }
19356
19357 /* Read a string at offset STR_OFFSET in the .debug_str section from
19358    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19359    the string consists of a single NUL byte, return NULL; otherwise
19360    return a pointer to the string.  */
19361
19362 static const char *
19363 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19364                                LONGEST str_offset)
19365 {
19366   dwarf2_read_section (objfile, &dwz->str);
19367
19368   if (dwz->str.buffer == NULL)
19369     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19370              "section [in module %s]"),
19371            bfd_get_filename (dwz->dwz_bfd));
19372   if (str_offset >= dwz->str.size)
19373     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19374              ".debug_str section [in module %s]"),
19375            bfd_get_filename (dwz->dwz_bfd));
19376   gdb_assert (HOST_CHAR_BIT == 8);
19377   if (dwz->str.buffer[str_offset] == '\0')
19378     return NULL;
19379   return (const char *) (dwz->str.buffer + str_offset);
19380 }
19381
19382 /* Return pointer to string at .debug_str offset as read from BUF.
19383    BUF is assumed to be in a compilation unit described by CU_HEADER.
19384    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19385
19386 static const char *
19387 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19388                       const gdb_byte *buf,
19389                       const struct comp_unit_head *cu_header,
19390                       unsigned int *bytes_read_ptr)
19391 {
19392   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19393
19394   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19395 }
19396
19397 /* Return pointer to string at .debug_line_str offset as read from BUF.
19398    BUF is assumed to be in a compilation unit described by CU_HEADER.
19399    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19400
19401 static const char *
19402 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19403                            bfd *abfd, const gdb_byte *buf,
19404                            const struct comp_unit_head *cu_header,
19405                            unsigned int *bytes_read_ptr)
19406 {
19407   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19408
19409   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19410                                               str_offset);
19411 }
19412
19413 ULONGEST
19414 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19415                           unsigned int *bytes_read_ptr)
19416 {
19417   ULONGEST result;
19418   unsigned int num_read;
19419   int shift;
19420   unsigned char byte;
19421
19422   result = 0;
19423   shift = 0;
19424   num_read = 0;
19425   while (1)
19426     {
19427       byte = bfd_get_8 (abfd, buf);
19428       buf++;
19429       num_read++;
19430       result |= ((ULONGEST) (byte & 127) << shift);
19431       if ((byte & 128) == 0)
19432         {
19433           break;
19434         }
19435       shift += 7;
19436     }
19437   *bytes_read_ptr = num_read;
19438   return result;
19439 }
19440
19441 static LONGEST
19442 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19443                     unsigned int *bytes_read_ptr)
19444 {
19445   LONGEST result;
19446   int shift, num_read;
19447   unsigned char byte;
19448
19449   result = 0;
19450   shift = 0;
19451   num_read = 0;
19452   while (1)
19453     {
19454       byte = bfd_get_8 (abfd, buf);
19455       buf++;
19456       num_read++;
19457       result |= ((LONGEST) (byte & 127) << shift);
19458       shift += 7;
19459       if ((byte & 128) == 0)
19460         {
19461           break;
19462         }
19463     }
19464   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19465     result |= -(((LONGEST) 1) << shift);
19466   *bytes_read_ptr = num_read;
19467   return result;
19468 }
19469
19470 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19471    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19472    ADDR_SIZE is the size of addresses from the CU header.  */
19473
19474 static CORE_ADDR
19475 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19476                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19477 {
19478   struct objfile *objfile = dwarf2_per_objfile->objfile;
19479   bfd *abfd = objfile->obfd;
19480   const gdb_byte *info_ptr;
19481
19482   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19483   if (dwarf2_per_objfile->addr.buffer == NULL)
19484     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19485            objfile_name (objfile));
19486   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19487     error (_("DW_FORM_addr_index pointing outside of "
19488              ".debug_addr section [in module %s]"),
19489            objfile_name (objfile));
19490   info_ptr = (dwarf2_per_objfile->addr.buffer
19491               + addr_base + addr_index * addr_size);
19492   if (addr_size == 4)
19493     return bfd_get_32 (abfd, info_ptr);
19494   else
19495     return bfd_get_64 (abfd, info_ptr);
19496 }
19497
19498 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19499
19500 static CORE_ADDR
19501 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19502 {
19503   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19504                             cu->addr_base, cu->header.addr_size);
19505 }
19506
19507 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19508
19509 static CORE_ADDR
19510 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19511                              unsigned int *bytes_read)
19512 {
19513   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19514   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19515
19516   return read_addr_index (cu, addr_index);
19517 }
19518
19519 /* Data structure to pass results from dwarf2_read_addr_index_reader
19520    back to dwarf2_read_addr_index.  */
19521
19522 struct dwarf2_read_addr_index_data
19523 {
19524   ULONGEST addr_base;
19525   int addr_size;
19526 };
19527
19528 /* die_reader_func for dwarf2_read_addr_index.  */
19529
19530 static void
19531 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19532                                const gdb_byte *info_ptr,
19533                                struct die_info *comp_unit_die,
19534                                int has_children,
19535                                void *data)
19536 {
19537   struct dwarf2_cu *cu = reader->cu;
19538   struct dwarf2_read_addr_index_data *aidata =
19539     (struct dwarf2_read_addr_index_data *) data;
19540
19541   aidata->addr_base = cu->addr_base;
19542   aidata->addr_size = cu->header.addr_size;
19543 }
19544
19545 /* Given an index in .debug_addr, fetch the value.
19546    NOTE: This can be called during dwarf expression evaluation,
19547    long after the debug information has been read, and thus per_cu->cu
19548    may no longer exist.  */
19549
19550 CORE_ADDR
19551 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19552                         unsigned int addr_index)
19553 {
19554   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19555   struct dwarf2_cu *cu = per_cu->cu;
19556   ULONGEST addr_base;
19557   int addr_size;
19558
19559   /* We need addr_base and addr_size.
19560      If we don't have PER_CU->cu, we have to get it.
19561      Nasty, but the alternative is storing the needed info in PER_CU,
19562      which at this point doesn't seem justified: it's not clear how frequently
19563      it would get used and it would increase the size of every PER_CU.
19564      Entry points like dwarf2_per_cu_addr_size do a similar thing
19565      so we're not in uncharted territory here.
19566      Alas we need to be a bit more complicated as addr_base is contained
19567      in the DIE.
19568
19569      We don't need to read the entire CU(/TU).
19570      We just need the header and top level die.
19571
19572      IWBN to use the aging mechanism to let us lazily later discard the CU.
19573      For now we skip this optimization.  */
19574
19575   if (cu != NULL)
19576     {
19577       addr_base = cu->addr_base;
19578       addr_size = cu->header.addr_size;
19579     }
19580   else
19581     {
19582       struct dwarf2_read_addr_index_data aidata;
19583
19584       /* Note: We can't use init_cutu_and_read_dies_simple here,
19585          we need addr_base.  */
19586       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19587                                dwarf2_read_addr_index_reader, &aidata);
19588       addr_base = aidata.addr_base;
19589       addr_size = aidata.addr_size;
19590     }
19591
19592   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19593                             addr_size);
19594 }
19595
19596 /* Given a DW_FORM_GNU_str_index, fetch the string.
19597    This is only used by the Fission support.  */
19598
19599 static const char *
19600 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19601 {
19602   struct dwarf2_cu *cu = reader->cu;
19603   struct dwarf2_per_objfile *dwarf2_per_objfile
19604     = cu->per_cu->dwarf2_per_objfile;
19605   struct objfile *objfile = dwarf2_per_objfile->objfile;
19606   const char *objf_name = objfile_name (objfile);
19607   bfd *abfd = objfile->obfd;
19608   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19609   struct dwarf2_section_info *str_offsets_section =
19610     &reader->dwo_file->sections.str_offsets;
19611   const gdb_byte *info_ptr;
19612   ULONGEST str_offset;
19613   static const char form_name[] = "DW_FORM_GNU_str_index";
19614
19615   dwarf2_read_section (objfile, str_section);
19616   dwarf2_read_section (objfile, str_offsets_section);
19617   if (str_section->buffer == NULL)
19618     error (_("%s used without .debug_str.dwo section"
19619              " in CU at offset %s [in module %s]"),
19620            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19621   if (str_offsets_section->buffer == NULL)
19622     error (_("%s used without .debug_str_offsets.dwo section"
19623              " in CU at offset %s [in module %s]"),
19624            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19625   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19626     error (_("%s pointing outside of .debug_str_offsets.dwo"
19627              " section in CU at offset %s [in module %s]"),
19628            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19629   info_ptr = (str_offsets_section->buffer
19630               + str_index * cu->header.offset_size);
19631   if (cu->header.offset_size == 4)
19632     str_offset = bfd_get_32 (abfd, info_ptr);
19633   else
19634     str_offset = bfd_get_64 (abfd, info_ptr);
19635   if (str_offset >= str_section->size)
19636     error (_("Offset from %s pointing outside of"
19637              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19638            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19639   return (const char *) (str_section->buffer + str_offset);
19640 }
19641
19642 /* Return the length of an LEB128 number in BUF.  */
19643
19644 static int
19645 leb128_size (const gdb_byte *buf)
19646 {
19647   const gdb_byte *begin = buf;
19648   gdb_byte byte;
19649
19650   while (1)
19651     {
19652       byte = *buf++;
19653       if ((byte & 128) == 0)
19654         return buf - begin;
19655     }
19656 }
19657
19658 static void
19659 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19660 {
19661   switch (lang)
19662     {
19663     case DW_LANG_C89:
19664     case DW_LANG_C99:
19665     case DW_LANG_C11:
19666     case DW_LANG_C:
19667     case DW_LANG_UPC:
19668       cu->language = language_c;
19669       break;
19670     case DW_LANG_Java:
19671     case DW_LANG_C_plus_plus:
19672     case DW_LANG_C_plus_plus_11:
19673     case DW_LANG_C_plus_plus_14:
19674       cu->language = language_cplus;
19675       break;
19676     case DW_LANG_D:
19677       cu->language = language_d;
19678       break;
19679     case DW_LANG_Fortran77:
19680     case DW_LANG_Fortran90:
19681     case DW_LANG_Fortran95:
19682     case DW_LANG_Fortran03:
19683     case DW_LANG_Fortran08:
19684       cu->language = language_fortran;
19685       break;
19686     case DW_LANG_Go:
19687       cu->language = language_go;
19688       break;
19689     case DW_LANG_Mips_Assembler:
19690       cu->language = language_asm;
19691       break;
19692     case DW_LANG_Ada83:
19693     case DW_LANG_Ada95:
19694       cu->language = language_ada;
19695       break;
19696     case DW_LANG_Modula2:
19697       cu->language = language_m2;
19698       break;
19699     case DW_LANG_Pascal83:
19700       cu->language = language_pascal;
19701       break;
19702     case DW_LANG_ObjC:
19703       cu->language = language_objc;
19704       break;
19705     case DW_LANG_Rust:
19706     case DW_LANG_Rust_old:
19707       cu->language = language_rust;
19708       break;
19709     case DW_LANG_Cobol74:
19710     case DW_LANG_Cobol85:
19711     default:
19712       cu->language = language_minimal;
19713       break;
19714     }
19715   cu->language_defn = language_def (cu->language);
19716 }
19717
19718 /* Return the named attribute or NULL if not there.  */
19719
19720 static struct attribute *
19721 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19722 {
19723   for (;;)
19724     {
19725       unsigned int i;
19726       struct attribute *spec = NULL;
19727
19728       for (i = 0; i < die->num_attrs; ++i)
19729         {
19730           if (die->attrs[i].name == name)
19731             return &die->attrs[i];
19732           if (die->attrs[i].name == DW_AT_specification
19733               || die->attrs[i].name == DW_AT_abstract_origin)
19734             spec = &die->attrs[i];
19735         }
19736
19737       if (!spec)
19738         break;
19739
19740       die = follow_die_ref (die, spec, &cu);
19741     }
19742
19743   return NULL;
19744 }
19745
19746 /* Return the named attribute or NULL if not there,
19747    but do not follow DW_AT_specification, etc.
19748    This is for use in contexts where we're reading .debug_types dies.
19749    Following DW_AT_specification, DW_AT_abstract_origin will take us
19750    back up the chain, and we want to go down.  */
19751
19752 static struct attribute *
19753 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19754 {
19755   unsigned int i;
19756
19757   for (i = 0; i < die->num_attrs; ++i)
19758     if (die->attrs[i].name == name)
19759       return &die->attrs[i];
19760
19761   return NULL;
19762 }
19763
19764 /* Return the string associated with a string-typed attribute, or NULL if it
19765    is either not found or is of an incorrect type.  */
19766
19767 static const char *
19768 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19769 {
19770   struct attribute *attr;
19771   const char *str = NULL;
19772
19773   attr = dwarf2_attr (die, name, cu);
19774
19775   if (attr != NULL)
19776     {
19777       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19778           || attr->form == DW_FORM_string
19779           || attr->form == DW_FORM_GNU_str_index
19780           || attr->form == DW_FORM_GNU_strp_alt)
19781         str = DW_STRING (attr);
19782       else
19783         complaint (_("string type expected for attribute %s for "
19784                      "DIE at %s in module %s"),
19785                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19786                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19787     }
19788
19789   return str;
19790 }
19791
19792 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19793    and holds a non-zero value.  This function should only be used for
19794    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19795
19796 static int
19797 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19798 {
19799   struct attribute *attr = dwarf2_attr (die, name, cu);
19800
19801   return (attr && DW_UNSND (attr));
19802 }
19803
19804 static int
19805 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19806 {
19807   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19808      which value is non-zero.  However, we have to be careful with
19809      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19810      (via dwarf2_flag_true_p) follows this attribute.  So we may
19811      end up accidently finding a declaration attribute that belongs
19812      to a different DIE referenced by the specification attribute,
19813      even though the given DIE does not have a declaration attribute.  */
19814   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19815           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19816 }
19817
19818 /* Return the die giving the specification for DIE, if there is
19819    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19820    containing the return value on output.  If there is no
19821    specification, but there is an abstract origin, that is
19822    returned.  */
19823
19824 static struct die_info *
19825 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19826 {
19827   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19828                                              *spec_cu);
19829
19830   if (spec_attr == NULL)
19831     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19832
19833   if (spec_attr == NULL)
19834     return NULL;
19835   else
19836     return follow_die_ref (die, spec_attr, spec_cu);
19837 }
19838
19839 /* Stub for free_line_header to match void * callback types.  */
19840
19841 static void
19842 free_line_header_voidp (void *arg)
19843 {
19844   struct line_header *lh = (struct line_header *) arg;
19845
19846   delete lh;
19847 }
19848
19849 void
19850 line_header::add_include_dir (const char *include_dir)
19851 {
19852   if (dwarf_line_debug >= 2)
19853     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19854                         include_dirs.size () + 1, include_dir);
19855
19856   include_dirs.push_back (include_dir);
19857 }
19858
19859 void
19860 line_header::add_file_name (const char *name,
19861                             dir_index d_index,
19862                             unsigned int mod_time,
19863                             unsigned int length)
19864 {
19865   if (dwarf_line_debug >= 2)
19866     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19867                         (unsigned) file_names.size () + 1, name);
19868
19869   file_names.emplace_back (name, d_index, mod_time, length);
19870 }
19871
19872 /* A convenience function to find the proper .debug_line section for a CU.  */
19873
19874 static struct dwarf2_section_info *
19875 get_debug_line_section (struct dwarf2_cu *cu)
19876 {
19877   struct dwarf2_section_info *section;
19878   struct dwarf2_per_objfile *dwarf2_per_objfile
19879     = cu->per_cu->dwarf2_per_objfile;
19880
19881   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19882      DWO file.  */
19883   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19884     section = &cu->dwo_unit->dwo_file->sections.line;
19885   else if (cu->per_cu->is_dwz)
19886     {
19887       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19888
19889       section = &dwz->line;
19890     }
19891   else
19892     section = &dwarf2_per_objfile->line;
19893
19894   return section;
19895 }
19896
19897 /* Read directory or file name entry format, starting with byte of
19898    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19899    entries count and the entries themselves in the described entry
19900    format.  */
19901
19902 static void
19903 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19904                         bfd *abfd, const gdb_byte **bufp,
19905                         struct line_header *lh,
19906                         const struct comp_unit_head *cu_header,
19907                         void (*callback) (struct line_header *lh,
19908                                           const char *name,
19909                                           dir_index d_index,
19910                                           unsigned int mod_time,
19911                                           unsigned int length))
19912 {
19913   gdb_byte format_count, formati;
19914   ULONGEST data_count, datai;
19915   const gdb_byte *buf = *bufp;
19916   const gdb_byte *format_header_data;
19917   unsigned int bytes_read;
19918
19919   format_count = read_1_byte (abfd, buf);
19920   buf += 1;
19921   format_header_data = buf;
19922   for (formati = 0; formati < format_count; formati++)
19923     {
19924       read_unsigned_leb128 (abfd, buf, &bytes_read);
19925       buf += bytes_read;
19926       read_unsigned_leb128 (abfd, buf, &bytes_read);
19927       buf += bytes_read;
19928     }
19929
19930   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19931   buf += bytes_read;
19932   for (datai = 0; datai < data_count; datai++)
19933     {
19934       const gdb_byte *format = format_header_data;
19935       struct file_entry fe;
19936
19937       for (formati = 0; formati < format_count; formati++)
19938         {
19939           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19940           format += bytes_read;
19941
19942           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19943           format += bytes_read;
19944
19945           gdb::optional<const char *> string;
19946           gdb::optional<unsigned int> uint;
19947
19948           switch (form)
19949             {
19950             case DW_FORM_string:
19951               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19952               buf += bytes_read;
19953               break;
19954
19955             case DW_FORM_line_strp:
19956               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19957                                                          abfd, buf,
19958                                                          cu_header,
19959                                                          &bytes_read));
19960               buf += bytes_read;
19961               break;
19962
19963             case DW_FORM_data1:
19964               uint.emplace (read_1_byte (abfd, buf));
19965               buf += 1;
19966               break;
19967
19968             case DW_FORM_data2:
19969               uint.emplace (read_2_bytes (abfd, buf));
19970               buf += 2;
19971               break;
19972
19973             case DW_FORM_data4:
19974               uint.emplace (read_4_bytes (abfd, buf));
19975               buf += 4;
19976               break;
19977
19978             case DW_FORM_data8:
19979               uint.emplace (read_8_bytes (abfd, buf));
19980               buf += 8;
19981               break;
19982
19983             case DW_FORM_udata:
19984               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
19985               buf += bytes_read;
19986               break;
19987
19988             case DW_FORM_block:
19989               /* It is valid only for DW_LNCT_timestamp which is ignored by
19990                  current GDB.  */
19991               break;
19992             }
19993
19994           switch (content_type)
19995             {
19996             case DW_LNCT_path:
19997               if (string.has_value ())
19998                 fe.name = *string;
19999               break;
20000             case DW_LNCT_directory_index:
20001               if (uint.has_value ())
20002                 fe.d_index = (dir_index) *uint;
20003               break;
20004             case DW_LNCT_timestamp:
20005               if (uint.has_value ())
20006                 fe.mod_time = *uint;
20007               break;
20008             case DW_LNCT_size:
20009               if (uint.has_value ())
20010                 fe.length = *uint;
20011               break;
20012             case DW_LNCT_MD5:
20013               break;
20014             default:
20015               complaint (_("Unknown format content type %s"),
20016                          pulongest (content_type));
20017             }
20018         }
20019
20020       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20021     }
20022
20023   *bufp = buf;
20024 }
20025
20026 /* Read the statement program header starting at OFFSET in
20027    .debug_line, or .debug_line.dwo.  Return a pointer
20028    to a struct line_header, allocated using xmalloc.
20029    Returns NULL if there is a problem reading the header, e.g., if it
20030    has a version we don't understand.
20031
20032    NOTE: the strings in the include directory and file name tables of
20033    the returned object point into the dwarf line section buffer,
20034    and must not be freed.  */
20035
20036 static line_header_up
20037 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20038 {
20039   const gdb_byte *line_ptr;
20040   unsigned int bytes_read, offset_size;
20041   int i;
20042   const char *cur_dir, *cur_file;
20043   struct dwarf2_section_info *section;
20044   bfd *abfd;
20045   struct dwarf2_per_objfile *dwarf2_per_objfile
20046     = cu->per_cu->dwarf2_per_objfile;
20047
20048   section = get_debug_line_section (cu);
20049   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20050   if (section->buffer == NULL)
20051     {
20052       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20053         complaint (_("missing .debug_line.dwo section"));
20054       else
20055         complaint (_("missing .debug_line section"));
20056       return 0;
20057     }
20058
20059   /* We can't do this until we know the section is non-empty.
20060      Only then do we know we have such a section.  */
20061   abfd = get_section_bfd_owner (section);
20062
20063   /* Make sure that at least there's room for the total_length field.
20064      That could be 12 bytes long, but we're just going to fudge that.  */
20065   if (to_underlying (sect_off) + 4 >= section->size)
20066     {
20067       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20068       return 0;
20069     }
20070
20071   line_header_up lh (new line_header ());
20072
20073   lh->sect_off = sect_off;
20074   lh->offset_in_dwz = cu->per_cu->is_dwz;
20075
20076   line_ptr = section->buffer + to_underlying (sect_off);
20077
20078   /* Read in the header.  */
20079   lh->total_length =
20080     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20081                                             &bytes_read, &offset_size);
20082   line_ptr += bytes_read;
20083   if (line_ptr + lh->total_length > (section->buffer + section->size))
20084     {
20085       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20086       return 0;
20087     }
20088   lh->statement_program_end = line_ptr + lh->total_length;
20089   lh->version = read_2_bytes (abfd, line_ptr);
20090   line_ptr += 2;
20091   if (lh->version > 5)
20092     {
20093       /* This is a version we don't understand.  The format could have
20094          changed in ways we don't handle properly so just punt.  */
20095       complaint (_("unsupported version in .debug_line section"));
20096       return NULL;
20097     }
20098   if (lh->version >= 5)
20099     {
20100       gdb_byte segment_selector_size;
20101
20102       /* Skip address size.  */
20103       read_1_byte (abfd, line_ptr);
20104       line_ptr += 1;
20105
20106       segment_selector_size = read_1_byte (abfd, line_ptr);
20107       line_ptr += 1;
20108       if (segment_selector_size != 0)
20109         {
20110           complaint (_("unsupported segment selector size %u "
20111                        "in .debug_line section"),
20112                      segment_selector_size);
20113           return NULL;
20114         }
20115     }
20116   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20117   line_ptr += offset_size;
20118   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20119   line_ptr += 1;
20120   if (lh->version >= 4)
20121     {
20122       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20123       line_ptr += 1;
20124     }
20125   else
20126     lh->maximum_ops_per_instruction = 1;
20127
20128   if (lh->maximum_ops_per_instruction == 0)
20129     {
20130       lh->maximum_ops_per_instruction = 1;
20131       complaint (_("invalid maximum_ops_per_instruction "
20132                    "in `.debug_line' section"));
20133     }
20134
20135   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20136   line_ptr += 1;
20137   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20138   line_ptr += 1;
20139   lh->line_range = read_1_byte (abfd, line_ptr);
20140   line_ptr += 1;
20141   lh->opcode_base = read_1_byte (abfd, line_ptr);
20142   line_ptr += 1;
20143   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20144
20145   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20146   for (i = 1; i < lh->opcode_base; ++i)
20147     {
20148       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20149       line_ptr += 1;
20150     }
20151
20152   if (lh->version >= 5)
20153     {
20154       /* Read directory table.  */
20155       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20156                               &cu->header,
20157                               [] (struct line_header *lh, const char *name,
20158                                   dir_index d_index, unsigned int mod_time,
20159                                   unsigned int length)
20160         {
20161           lh->add_include_dir (name);
20162         });
20163
20164       /* Read file name table.  */
20165       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20166                               &cu->header,
20167                               [] (struct line_header *lh, const char *name,
20168                                   dir_index d_index, unsigned int mod_time,
20169                                   unsigned int length)
20170         {
20171           lh->add_file_name (name, d_index, mod_time, length);
20172         });
20173     }
20174   else
20175     {
20176       /* Read directory table.  */
20177       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20178         {
20179           line_ptr += bytes_read;
20180           lh->add_include_dir (cur_dir);
20181         }
20182       line_ptr += bytes_read;
20183
20184       /* Read file name table.  */
20185       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20186         {
20187           unsigned int mod_time, length;
20188           dir_index d_index;
20189
20190           line_ptr += bytes_read;
20191           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20192           line_ptr += bytes_read;
20193           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20194           line_ptr += bytes_read;
20195           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20196           line_ptr += bytes_read;
20197
20198           lh->add_file_name (cur_file, d_index, mod_time, length);
20199         }
20200       line_ptr += bytes_read;
20201     }
20202   lh->statement_program_start = line_ptr;
20203
20204   if (line_ptr > (section->buffer + section->size))
20205     complaint (_("line number info header doesn't "
20206                  "fit in `.debug_line' section"));
20207
20208   return lh;
20209 }
20210
20211 /* Subroutine of dwarf_decode_lines to simplify it.
20212    Return the file name of the psymtab for included file FILE_INDEX
20213    in line header LH of PST.
20214    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20215    If space for the result is malloc'd, *NAME_HOLDER will be set.
20216    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20217
20218 static const char *
20219 psymtab_include_file_name (const struct line_header *lh, int file_index,
20220                            const struct partial_symtab *pst,
20221                            const char *comp_dir,
20222                            gdb::unique_xmalloc_ptr<char> *name_holder)
20223 {
20224   const file_entry &fe = lh->file_names[file_index];
20225   const char *include_name = fe.name;
20226   const char *include_name_to_compare = include_name;
20227   const char *pst_filename;
20228   int file_is_pst;
20229
20230   const char *dir_name = fe.include_dir (lh);
20231
20232   gdb::unique_xmalloc_ptr<char> hold_compare;
20233   if (!IS_ABSOLUTE_PATH (include_name)
20234       && (dir_name != NULL || comp_dir != NULL))
20235     {
20236       /* Avoid creating a duplicate psymtab for PST.
20237          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20238          Before we do the comparison, however, we need to account
20239          for DIR_NAME and COMP_DIR.
20240          First prepend dir_name (if non-NULL).  If we still don't
20241          have an absolute path prepend comp_dir (if non-NULL).
20242          However, the directory we record in the include-file's
20243          psymtab does not contain COMP_DIR (to match the
20244          corresponding symtab(s)).
20245
20246          Example:
20247
20248          bash$ cd /tmp
20249          bash$ gcc -g ./hello.c
20250          include_name = "hello.c"
20251          dir_name = "."
20252          DW_AT_comp_dir = comp_dir = "/tmp"
20253          DW_AT_name = "./hello.c"
20254
20255       */
20256
20257       if (dir_name != NULL)
20258         {
20259           name_holder->reset (concat (dir_name, SLASH_STRING,
20260                                       include_name, (char *) NULL));
20261           include_name = name_holder->get ();
20262           include_name_to_compare = include_name;
20263         }
20264       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20265         {
20266           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20267                                       include_name, (char *) NULL));
20268           include_name_to_compare = hold_compare.get ();
20269         }
20270     }
20271
20272   pst_filename = pst->filename;
20273   gdb::unique_xmalloc_ptr<char> copied_name;
20274   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20275     {
20276       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20277                                  pst_filename, (char *) NULL));
20278       pst_filename = copied_name.get ();
20279     }
20280
20281   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20282
20283   if (file_is_pst)
20284     return NULL;
20285   return include_name;
20286 }
20287
20288 /* State machine to track the state of the line number program.  */
20289
20290 class lnp_state_machine
20291 {
20292 public:
20293   /* Initialize a machine state for the start of a line number
20294      program.  */
20295   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20296
20297   file_entry *current_file ()
20298   {
20299     /* lh->file_names is 0-based, but the file name numbers in the
20300        statement program are 1-based.  */
20301     return m_line_header->file_name_at (m_file);
20302   }
20303
20304   /* Record the line in the state machine.  END_SEQUENCE is true if
20305      we're processing the end of a sequence.  */
20306   void record_line (bool end_sequence);
20307
20308   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20309      nop-out rest of the lines in this sequence.  */
20310   void check_line_address (struct dwarf2_cu *cu,
20311                            const gdb_byte *line_ptr,
20312                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20313
20314   void handle_set_discriminator (unsigned int discriminator)
20315   {
20316     m_discriminator = discriminator;
20317     m_line_has_non_zero_discriminator |= discriminator != 0;
20318   }
20319
20320   /* Handle DW_LNE_set_address.  */
20321   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20322   {
20323     m_op_index = 0;
20324     address += baseaddr;
20325     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20326   }
20327
20328   /* Handle DW_LNS_advance_pc.  */
20329   void handle_advance_pc (CORE_ADDR adjust);
20330
20331   /* Handle a special opcode.  */
20332   void handle_special_opcode (unsigned char op_code);
20333
20334   /* Handle DW_LNS_advance_line.  */
20335   void handle_advance_line (int line_delta)
20336   {
20337     advance_line (line_delta);
20338   }
20339
20340   /* Handle DW_LNS_set_file.  */
20341   void handle_set_file (file_name_index file);
20342
20343   /* Handle DW_LNS_negate_stmt.  */
20344   void handle_negate_stmt ()
20345   {
20346     m_is_stmt = !m_is_stmt;
20347   }
20348
20349   /* Handle DW_LNS_const_add_pc.  */
20350   void handle_const_add_pc ();
20351
20352   /* Handle DW_LNS_fixed_advance_pc.  */
20353   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20354   {
20355     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20356     m_op_index = 0;
20357   }
20358
20359   /* Handle DW_LNS_copy.  */
20360   void handle_copy ()
20361   {
20362     record_line (false);
20363     m_discriminator = 0;
20364   }
20365
20366   /* Handle DW_LNE_end_sequence.  */
20367   void handle_end_sequence ()
20368   {
20369     m_record_line_callback = ::record_line;
20370   }
20371
20372 private:
20373   /* Advance the line by LINE_DELTA.  */
20374   void advance_line (int line_delta)
20375   {
20376     m_line += line_delta;
20377
20378     if (line_delta != 0)
20379       m_line_has_non_zero_discriminator = m_discriminator != 0;
20380   }
20381
20382   gdbarch *m_gdbarch;
20383
20384   /* True if we're recording lines.
20385      Otherwise we're building partial symtabs and are just interested in
20386      finding include files mentioned by the line number program.  */
20387   bool m_record_lines_p;
20388
20389   /* The line number header.  */
20390   line_header *m_line_header;
20391
20392   /* These are part of the standard DWARF line number state machine,
20393      and initialized according to the DWARF spec.  */
20394
20395   unsigned char m_op_index = 0;
20396   /* The line table index (1-based) of the current file.  */
20397   file_name_index m_file = (file_name_index) 1;
20398   unsigned int m_line = 1;
20399
20400   /* These are initialized in the constructor.  */
20401
20402   CORE_ADDR m_address;
20403   bool m_is_stmt;
20404   unsigned int m_discriminator;
20405
20406   /* Additional bits of state we need to track.  */
20407
20408   /* The last file that we called dwarf2_start_subfile for.
20409      This is only used for TLLs.  */
20410   unsigned int m_last_file = 0;
20411   /* The last file a line number was recorded for.  */
20412   struct subfile *m_last_subfile = NULL;
20413
20414   /* The function to call to record a line.  */
20415   record_line_ftype *m_record_line_callback = NULL;
20416
20417   /* The last line number that was recorded, used to coalesce
20418      consecutive entries for the same line.  This can happen, for
20419      example, when discriminators are present.  PR 17276.  */
20420   unsigned int m_last_line = 0;
20421   bool m_line_has_non_zero_discriminator = false;
20422 };
20423
20424 void
20425 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20426 {
20427   CORE_ADDR addr_adj = (((m_op_index + adjust)
20428                          / m_line_header->maximum_ops_per_instruction)
20429                         * m_line_header->minimum_instruction_length);
20430   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20431   m_op_index = ((m_op_index + adjust)
20432                 % m_line_header->maximum_ops_per_instruction);
20433 }
20434
20435 void
20436 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20437 {
20438   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20439   CORE_ADDR addr_adj = (((m_op_index
20440                           + (adj_opcode / m_line_header->line_range))
20441                          / m_line_header->maximum_ops_per_instruction)
20442                         * m_line_header->minimum_instruction_length);
20443   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20444   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20445                 % m_line_header->maximum_ops_per_instruction);
20446
20447   int line_delta = (m_line_header->line_base
20448                     + (adj_opcode % m_line_header->line_range));
20449   advance_line (line_delta);
20450   record_line (false);
20451   m_discriminator = 0;
20452 }
20453
20454 void
20455 lnp_state_machine::handle_set_file (file_name_index file)
20456 {
20457   m_file = file;
20458
20459   const file_entry *fe = current_file ();
20460   if (fe == NULL)
20461     dwarf2_debug_line_missing_file_complaint ();
20462   else if (m_record_lines_p)
20463     {
20464       const char *dir = fe->include_dir (m_line_header);
20465
20466       m_last_subfile = current_subfile;
20467       m_line_has_non_zero_discriminator = m_discriminator != 0;
20468       dwarf2_start_subfile (fe->name, dir);
20469     }
20470 }
20471
20472 void
20473 lnp_state_machine::handle_const_add_pc ()
20474 {
20475   CORE_ADDR adjust
20476     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20477
20478   CORE_ADDR addr_adj
20479     = (((m_op_index + adjust)
20480         / m_line_header->maximum_ops_per_instruction)
20481        * m_line_header->minimum_instruction_length);
20482
20483   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20484   m_op_index = ((m_op_index + adjust)
20485                 % m_line_header->maximum_ops_per_instruction);
20486 }
20487
20488 /* Ignore this record_line request.  */
20489
20490 static void
20491 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20492 {
20493   return;
20494 }
20495
20496 /* Return non-zero if we should add LINE to the line number table.
20497    LINE is the line to add, LAST_LINE is the last line that was added,
20498    LAST_SUBFILE is the subfile for LAST_LINE.
20499    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20500    had a non-zero discriminator.
20501
20502    We have to be careful in the presence of discriminators.
20503    E.g., for this line:
20504
20505      for (i = 0; i < 100000; i++);
20506
20507    clang can emit four line number entries for that one line,
20508    each with a different discriminator.
20509    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20510
20511    However, we want gdb to coalesce all four entries into one.
20512    Otherwise the user could stepi into the middle of the line and
20513    gdb would get confused about whether the pc really was in the
20514    middle of the line.
20515
20516    Things are further complicated by the fact that two consecutive
20517    line number entries for the same line is a heuristic used by gcc
20518    to denote the end of the prologue.  So we can't just discard duplicate
20519    entries, we have to be selective about it.  The heuristic we use is
20520    that we only collapse consecutive entries for the same line if at least
20521    one of those entries has a non-zero discriminator.  PR 17276.
20522
20523    Note: Addresses in the line number state machine can never go backwards
20524    within one sequence, thus this coalescing is ok.  */
20525
20526 static int
20527 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20528                      int line_has_non_zero_discriminator,
20529                      struct subfile *last_subfile)
20530 {
20531   if (current_subfile != last_subfile)
20532     return 1;
20533   if (line != last_line)
20534     return 1;
20535   /* Same line for the same file that we've seen already.
20536      As a last check, for pr 17276, only record the line if the line
20537      has never had a non-zero discriminator.  */
20538   if (!line_has_non_zero_discriminator)
20539     return 1;
20540   return 0;
20541 }
20542
20543 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20544    in the line table of subfile SUBFILE.  */
20545
20546 static void
20547 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20548                      unsigned int line, CORE_ADDR address,
20549                      record_line_ftype p_record_line)
20550 {
20551   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20552
20553   if (dwarf_line_debug)
20554     {
20555       fprintf_unfiltered (gdb_stdlog,
20556                           "Recording line %u, file %s, address %s\n",
20557                           line, lbasename (subfile->name),
20558                           paddress (gdbarch, address));
20559     }
20560
20561   (*p_record_line) (subfile, line, addr);
20562 }
20563
20564 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20565    Mark the end of a set of line number records.
20566    The arguments are the same as for dwarf_record_line_1.
20567    If SUBFILE is NULL the request is ignored.  */
20568
20569 static void
20570 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20571                    CORE_ADDR address, record_line_ftype p_record_line)
20572 {
20573   if (subfile == NULL)
20574     return;
20575
20576   if (dwarf_line_debug)
20577     {
20578       fprintf_unfiltered (gdb_stdlog,
20579                           "Finishing current line, file %s, address %s\n",
20580                           lbasename (subfile->name),
20581                           paddress (gdbarch, address));
20582     }
20583
20584   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20585 }
20586
20587 void
20588 lnp_state_machine::record_line (bool end_sequence)
20589 {
20590   if (dwarf_line_debug)
20591     {
20592       fprintf_unfiltered (gdb_stdlog,
20593                           "Processing actual line %u: file %u,"
20594                           " address %s, is_stmt %u, discrim %u\n",
20595                           m_line, to_underlying (m_file),
20596                           paddress (m_gdbarch, m_address),
20597                           m_is_stmt, m_discriminator);
20598     }
20599
20600   file_entry *fe = current_file ();
20601
20602   if (fe == NULL)
20603     dwarf2_debug_line_missing_file_complaint ();
20604   /* For now we ignore lines not starting on an instruction boundary.
20605      But not when processing end_sequence for compatibility with the
20606      previous version of the code.  */
20607   else if (m_op_index == 0 || end_sequence)
20608     {
20609       fe->included_p = 1;
20610       if (m_record_lines_p && m_is_stmt)
20611         {
20612           if (m_last_subfile != current_subfile || end_sequence)
20613             {
20614               dwarf_finish_line (m_gdbarch, m_last_subfile,
20615                                  m_address, m_record_line_callback);
20616             }
20617
20618           if (!end_sequence)
20619             {
20620               if (dwarf_record_line_p (m_line, m_last_line,
20621                                        m_line_has_non_zero_discriminator,
20622                                        m_last_subfile))
20623                 {
20624                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20625                                        m_line, m_address,
20626                                        m_record_line_callback);
20627                 }
20628               m_last_subfile = current_subfile;
20629               m_last_line = m_line;
20630             }
20631         }
20632     }
20633 }
20634
20635 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20636                                       bool record_lines_p)
20637 {
20638   m_gdbarch = arch;
20639   m_record_lines_p = record_lines_p;
20640   m_line_header = lh;
20641
20642   m_record_line_callback = ::record_line;
20643
20644   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20645      was a line entry for it so that the backend has a chance to adjust it
20646      and also record it in case it needs it.  This is currently used by MIPS
20647      code, cf. `mips_adjust_dwarf2_line'.  */
20648   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20649   m_is_stmt = lh->default_is_stmt;
20650   m_discriminator = 0;
20651 }
20652
20653 void
20654 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20655                                        const gdb_byte *line_ptr,
20656                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20657 {
20658   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20659      the pc range of the CU.  However, we restrict the test to only ADDRESS
20660      values of zero to preserve GDB's previous behaviour which is to handle
20661      the specific case of a function being GC'd by the linker.  */
20662
20663   if (address == 0 && address < unrelocated_lowpc)
20664     {
20665       /* This line table is for a function which has been
20666          GCd by the linker.  Ignore it.  PR gdb/12528 */
20667
20668       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20669       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20670
20671       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20672                  line_offset, objfile_name (objfile));
20673       m_record_line_callback = noop_record_line;
20674       /* Note: record_line_callback is left as noop_record_line until
20675          we see DW_LNE_end_sequence.  */
20676     }
20677 }
20678
20679 /* Subroutine of dwarf_decode_lines to simplify it.
20680    Process the line number information in LH.
20681    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20682    program in order to set included_p for every referenced header.  */
20683
20684 static void
20685 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20686                       const int decode_for_pst_p, CORE_ADDR lowpc)
20687 {
20688   const gdb_byte *line_ptr, *extended_end;
20689   const gdb_byte *line_end;
20690   unsigned int bytes_read, extended_len;
20691   unsigned char op_code, extended_op;
20692   CORE_ADDR baseaddr;
20693   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20694   bfd *abfd = objfile->obfd;
20695   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20696   /* True if we're recording line info (as opposed to building partial
20697      symtabs and just interested in finding include files mentioned by
20698      the line number program).  */
20699   bool record_lines_p = !decode_for_pst_p;
20700
20701   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20702
20703   line_ptr = lh->statement_program_start;
20704   line_end = lh->statement_program_end;
20705
20706   /* Read the statement sequences until there's nothing left.  */
20707   while (line_ptr < line_end)
20708     {
20709       /* The DWARF line number program state machine.  Reset the state
20710          machine at the start of each sequence.  */
20711       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20712       bool end_sequence = false;
20713
20714       if (record_lines_p)
20715         {
20716           /* Start a subfile for the current file of the state
20717              machine.  */
20718           const file_entry *fe = state_machine.current_file ();
20719
20720           if (fe != NULL)
20721             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20722         }
20723
20724       /* Decode the table.  */
20725       while (line_ptr < line_end && !end_sequence)
20726         {
20727           op_code = read_1_byte (abfd, line_ptr);
20728           line_ptr += 1;
20729
20730           if (op_code >= lh->opcode_base)
20731             {
20732               /* Special opcode.  */
20733               state_machine.handle_special_opcode (op_code);
20734             }
20735           else switch (op_code)
20736             {
20737             case DW_LNS_extended_op:
20738               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20739                                                    &bytes_read);
20740               line_ptr += bytes_read;
20741               extended_end = line_ptr + extended_len;
20742               extended_op = read_1_byte (abfd, line_ptr);
20743               line_ptr += 1;
20744               switch (extended_op)
20745                 {
20746                 case DW_LNE_end_sequence:
20747                   state_machine.handle_end_sequence ();
20748                   end_sequence = true;
20749                   break;
20750                 case DW_LNE_set_address:
20751                   {
20752                     CORE_ADDR address
20753                       = read_address (abfd, line_ptr, cu, &bytes_read);
20754                     line_ptr += bytes_read;
20755
20756                     state_machine.check_line_address (cu, line_ptr,
20757                                                       lowpc - baseaddr, address);
20758                     state_machine.handle_set_address (baseaddr, address);
20759                   }
20760                   break;
20761                 case DW_LNE_define_file:
20762                   {
20763                     const char *cur_file;
20764                     unsigned int mod_time, length;
20765                     dir_index dindex;
20766
20767                     cur_file = read_direct_string (abfd, line_ptr,
20768                                                    &bytes_read);
20769                     line_ptr += bytes_read;
20770                     dindex = (dir_index)
20771                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20772                     line_ptr += bytes_read;
20773                     mod_time =
20774                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20775                     line_ptr += bytes_read;
20776                     length =
20777                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20778                     line_ptr += bytes_read;
20779                     lh->add_file_name (cur_file, dindex, mod_time, length);
20780                   }
20781                   break;
20782                 case DW_LNE_set_discriminator:
20783                   {
20784                     /* The discriminator is not interesting to the
20785                        debugger; just ignore it.  We still need to
20786                        check its value though:
20787                        if there are consecutive entries for the same
20788                        (non-prologue) line we want to coalesce them.
20789                        PR 17276.  */
20790                     unsigned int discr
20791                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20792                     line_ptr += bytes_read;
20793
20794                     state_machine.handle_set_discriminator (discr);
20795                   }
20796                   break;
20797                 default:
20798                   complaint (_("mangled .debug_line section"));
20799                   return;
20800                 }
20801               /* Make sure that we parsed the extended op correctly.  If e.g.
20802                  we expected a different address size than the producer used,
20803                  we may have read the wrong number of bytes.  */
20804               if (line_ptr != extended_end)
20805                 {
20806                   complaint (_("mangled .debug_line section"));
20807                   return;
20808                 }
20809               break;
20810             case DW_LNS_copy:
20811               state_machine.handle_copy ();
20812               break;
20813             case DW_LNS_advance_pc:
20814               {
20815                 CORE_ADDR adjust
20816                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20817                 line_ptr += bytes_read;
20818
20819                 state_machine.handle_advance_pc (adjust);
20820               }
20821               break;
20822             case DW_LNS_advance_line:
20823               {
20824                 int line_delta
20825                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20826                 line_ptr += bytes_read;
20827
20828                 state_machine.handle_advance_line (line_delta);
20829               }
20830               break;
20831             case DW_LNS_set_file:
20832               {
20833                 file_name_index file
20834                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20835                                                             &bytes_read);
20836                 line_ptr += bytes_read;
20837
20838                 state_machine.handle_set_file (file);
20839               }
20840               break;
20841             case DW_LNS_set_column:
20842               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20843               line_ptr += bytes_read;
20844               break;
20845             case DW_LNS_negate_stmt:
20846               state_machine.handle_negate_stmt ();
20847               break;
20848             case DW_LNS_set_basic_block:
20849               break;
20850             /* Add to the address register of the state machine the
20851                address increment value corresponding to special opcode
20852                255.  I.e., this value is scaled by the minimum
20853                instruction length since special opcode 255 would have
20854                scaled the increment.  */
20855             case DW_LNS_const_add_pc:
20856               state_machine.handle_const_add_pc ();
20857               break;
20858             case DW_LNS_fixed_advance_pc:
20859               {
20860                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20861                 line_ptr += 2;
20862
20863                 state_machine.handle_fixed_advance_pc (addr_adj);
20864               }
20865               break;
20866             default:
20867               {
20868                 /* Unknown standard opcode, ignore it.  */
20869                 int i;
20870
20871                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20872                   {
20873                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20874                     line_ptr += bytes_read;
20875                   }
20876               }
20877             }
20878         }
20879
20880       if (!end_sequence)
20881         dwarf2_debug_line_missing_end_sequence_complaint ();
20882
20883       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20884          in which case we still finish recording the last line).  */
20885       state_machine.record_line (true);
20886     }
20887 }
20888
20889 /* Decode the Line Number Program (LNP) for the given line_header
20890    structure and CU.  The actual information extracted and the type
20891    of structures created from the LNP depends on the value of PST.
20892
20893    1. If PST is NULL, then this procedure uses the data from the program
20894       to create all necessary symbol tables, and their linetables.
20895
20896    2. If PST is not NULL, this procedure reads the program to determine
20897       the list of files included by the unit represented by PST, and
20898       builds all the associated partial symbol tables.
20899
20900    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20901    It is used for relative paths in the line table.
20902    NOTE: When processing partial symtabs (pst != NULL),
20903    comp_dir == pst->dirname.
20904
20905    NOTE: It is important that psymtabs have the same file name (via strcmp)
20906    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20907    symtab we don't use it in the name of the psymtabs we create.
20908    E.g. expand_line_sal requires this when finding psymtabs to expand.
20909    A good testcase for this is mb-inline.exp.
20910
20911    LOWPC is the lowest address in CU (or 0 if not known).
20912
20913    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20914    for its PC<->lines mapping information.  Otherwise only the filename
20915    table is read in.  */
20916
20917 static void
20918 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20919                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20920                     CORE_ADDR lowpc, int decode_mapping)
20921 {
20922   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20923   const int decode_for_pst_p = (pst != NULL);
20924
20925   if (decode_mapping)
20926     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20927
20928   if (decode_for_pst_p)
20929     {
20930       int file_index;
20931
20932       /* Now that we're done scanning the Line Header Program, we can
20933          create the psymtab of each included file.  */
20934       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20935         if (lh->file_names[file_index].included_p == 1)
20936           {
20937             gdb::unique_xmalloc_ptr<char> name_holder;
20938             const char *include_name =
20939               psymtab_include_file_name (lh, file_index, pst, comp_dir,
20940                                          &name_holder);
20941             if (include_name != NULL)
20942               dwarf2_create_include_psymtab (include_name, pst, objfile);
20943           }
20944     }
20945   else
20946     {
20947       /* Make sure a symtab is created for every file, even files
20948          which contain only variables (i.e. no code with associated
20949          line numbers).  */
20950       struct compunit_symtab *cust = buildsym_compunit_symtab ();
20951       int i;
20952
20953       for (i = 0; i < lh->file_names.size (); i++)
20954         {
20955           file_entry &fe = lh->file_names[i];
20956
20957           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
20958
20959           if (current_subfile->symtab == NULL)
20960             {
20961               current_subfile->symtab
20962                 = allocate_symtab (cust, current_subfile->name);
20963             }
20964           fe.symtab = current_subfile->symtab;
20965         }
20966     }
20967 }
20968
20969 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20970    DIRNAME the name of the source directory which contains FILENAME
20971    or NULL if not known.
20972    This routine tries to keep line numbers from identical absolute and
20973    relative file names in a common subfile.
20974
20975    Using the `list' example from the GDB testsuite, which resides in
20976    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20977    of /srcdir/list0.c yields the following debugging information for list0.c:
20978
20979    DW_AT_name:          /srcdir/list0.c
20980    DW_AT_comp_dir:      /compdir
20981    files.files[0].name: list0.h
20982    files.files[0].dir:  /srcdir
20983    files.files[1].name: list0.c
20984    files.files[1].dir:  /srcdir
20985
20986    The line number information for list0.c has to end up in a single
20987    subfile, so that `break /srcdir/list0.c:1' works as expected.
20988    start_subfile will ensure that this happens provided that we pass the
20989    concatenation of files.files[1].dir and files.files[1].name as the
20990    subfile's name.  */
20991
20992 static void
20993 dwarf2_start_subfile (const char *filename, const char *dirname)
20994 {
20995   char *copy = NULL;
20996
20997   /* In order not to lose the line information directory,
20998      we concatenate it to the filename when it makes sense.
20999      Note that the Dwarf3 standard says (speaking of filenames in line
21000      information): ``The directory index is ignored for file names
21001      that represent full path names''.  Thus ignoring dirname in the
21002      `else' branch below isn't an issue.  */
21003
21004   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21005     {
21006       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21007       filename = copy;
21008     }
21009
21010   start_subfile (filename);
21011
21012   if (copy != NULL)
21013     xfree (copy);
21014 }
21015
21016 /* Start a symtab for DWARF.
21017    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21018
21019 static struct compunit_symtab *
21020 dwarf2_start_symtab (struct dwarf2_cu *cu,
21021                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21022 {
21023   struct compunit_symtab *cust
21024     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21025                     low_pc, cu->language);
21026
21027   record_debugformat ("DWARF 2");
21028   record_producer (cu->producer);
21029
21030   /* We assume that we're processing GCC output.  */
21031   processing_gcc_compilation = 2;
21032
21033   cu->processing_has_namespace_info = 0;
21034
21035   return cust;
21036 }
21037
21038 static void
21039 var_decode_location (struct attribute *attr, struct symbol *sym,
21040                      struct dwarf2_cu *cu)
21041 {
21042   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21043   struct comp_unit_head *cu_header = &cu->header;
21044
21045   /* NOTE drow/2003-01-30: There used to be a comment and some special
21046      code here to turn a symbol with DW_AT_external and a
21047      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21048      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21049      with some versions of binutils) where shared libraries could have
21050      relocations against symbols in their debug information - the
21051      minimal symbol would have the right address, but the debug info
21052      would not.  It's no longer necessary, because we will explicitly
21053      apply relocations when we read in the debug information now.  */
21054
21055   /* A DW_AT_location attribute with no contents indicates that a
21056      variable has been optimized away.  */
21057   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21058     {
21059       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21060       return;
21061     }
21062
21063   /* Handle one degenerate form of location expression specially, to
21064      preserve GDB's previous behavior when section offsets are
21065      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21066      then mark this symbol as LOC_STATIC.  */
21067
21068   if (attr_form_is_block (attr)
21069       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21070            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21071           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21072               && (DW_BLOCK (attr)->size
21073                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21074     {
21075       unsigned int dummy;
21076
21077       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21078         SYMBOL_VALUE_ADDRESS (sym) =
21079           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21080       else
21081         SYMBOL_VALUE_ADDRESS (sym) =
21082           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21083       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21084       fixup_symbol_section (sym, objfile);
21085       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21086                                               SYMBOL_SECTION (sym));
21087       return;
21088     }
21089
21090   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21091      expression evaluator, and use LOC_COMPUTED only when necessary
21092      (i.e. when the value of a register or memory location is
21093      referenced, or a thread-local block, etc.).  Then again, it might
21094      not be worthwhile.  I'm assuming that it isn't unless performance
21095      or memory numbers show me otherwise.  */
21096
21097   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21098
21099   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21100     cu->has_loclist = 1;
21101 }
21102
21103 /* Given a pointer to a DWARF information entry, figure out if we need
21104    to make a symbol table entry for it, and if so, create a new entry
21105    and return a pointer to it.
21106    If TYPE is NULL, determine symbol type from the die, otherwise
21107    used the passed type.
21108    If SPACE is not NULL, use it to hold the new symbol.  If it is
21109    NULL, allocate a new symbol on the objfile's obstack.  */
21110
21111 static struct symbol *
21112 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21113             struct symbol *space)
21114 {
21115   struct dwarf2_per_objfile *dwarf2_per_objfile
21116     = cu->per_cu->dwarf2_per_objfile;
21117   struct objfile *objfile = dwarf2_per_objfile->objfile;
21118   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21119   struct symbol *sym = NULL;
21120   const char *name;
21121   struct attribute *attr = NULL;
21122   struct attribute *attr2 = NULL;
21123   CORE_ADDR baseaddr;
21124   struct pending **list_to_add = NULL;
21125
21126   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21127
21128   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21129
21130   name = dwarf2_name (die, cu);
21131   if (name)
21132     {
21133       const char *linkagename;
21134       int suppress_add = 0;
21135
21136       if (space)
21137         sym = space;
21138       else
21139         sym = allocate_symbol (objfile);
21140       OBJSTAT (objfile, n_syms++);
21141
21142       /* Cache this symbol's name and the name's demangled form (if any).  */
21143       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21144       linkagename = dwarf2_physname (name, die, cu);
21145       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21146
21147       /* Fortran does not have mangling standard and the mangling does differ
21148          between gfortran, iFort etc.  */
21149       if (cu->language == language_fortran
21150           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21151         symbol_set_demangled_name (&(sym->ginfo),
21152                                    dwarf2_full_name (name, die, cu),
21153                                    NULL);
21154
21155       /* Default assumptions.
21156          Use the passed type or decode it from the die.  */
21157       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21158       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21159       if (type != NULL)
21160         SYMBOL_TYPE (sym) = type;
21161       else
21162         SYMBOL_TYPE (sym) = die_type (die, cu);
21163       attr = dwarf2_attr (die,
21164                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21165                           cu);
21166       if (attr)
21167         {
21168           SYMBOL_LINE (sym) = DW_UNSND (attr);
21169         }
21170
21171       attr = dwarf2_attr (die,
21172                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21173                           cu);
21174       if (attr)
21175         {
21176           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21177           struct file_entry *fe;
21178
21179           if (cu->line_header != NULL)
21180             fe = cu->line_header->file_name_at (file_index);
21181           else
21182             fe = NULL;
21183
21184           if (fe == NULL)
21185             complaint (_("file index out of range"));
21186           else
21187             symbol_set_symtab (sym, fe->symtab);
21188         }
21189
21190       switch (die->tag)
21191         {
21192         case DW_TAG_label:
21193           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21194           if (attr)
21195             {
21196               CORE_ADDR addr;
21197
21198               addr = attr_value_as_address (attr);
21199               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21200               SYMBOL_VALUE_ADDRESS (sym) = addr;
21201             }
21202           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21203           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21204           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21205           add_symbol_to_list (sym, cu->list_in_scope);
21206           break;
21207         case DW_TAG_subprogram:
21208           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21209              finish_block.  */
21210           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21211           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21212           if ((attr2 && (DW_UNSND (attr2) != 0))
21213               || cu->language == language_ada)
21214             {
21215               /* Subprograms marked external are stored as a global symbol.
21216                  Ada subprograms, whether marked external or not, are always
21217                  stored as a global symbol, because we want to be able to
21218                  access them globally.  For instance, we want to be able
21219                  to break on a nested subprogram without having to
21220                  specify the context.  */
21221               list_to_add = &global_symbols;
21222             }
21223           else
21224             {
21225               list_to_add = cu->list_in_scope;
21226             }
21227           break;
21228         case DW_TAG_inlined_subroutine:
21229           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21230              finish_block.  */
21231           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21232           SYMBOL_INLINED (sym) = 1;
21233           list_to_add = cu->list_in_scope;
21234           break;
21235         case DW_TAG_template_value_param:
21236           suppress_add = 1;
21237           /* Fall through.  */
21238         case DW_TAG_constant:
21239         case DW_TAG_variable:
21240         case DW_TAG_member:
21241           /* Compilation with minimal debug info may result in
21242              variables with missing type entries.  Change the
21243              misleading `void' type to something sensible.  */
21244           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21245             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21246
21247           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21248           /* In the case of DW_TAG_member, we should only be called for
21249              static const members.  */
21250           if (die->tag == DW_TAG_member)
21251             {
21252               /* dwarf2_add_field uses die_is_declaration,
21253                  so we do the same.  */
21254               gdb_assert (die_is_declaration (die, cu));
21255               gdb_assert (attr);
21256             }
21257           if (attr)
21258             {
21259               dwarf2_const_value (attr, sym, cu);
21260               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21261               if (!suppress_add)
21262                 {
21263                   if (attr2 && (DW_UNSND (attr2) != 0))
21264                     list_to_add = &global_symbols;
21265                   else
21266                     list_to_add = cu->list_in_scope;
21267                 }
21268               break;
21269             }
21270           attr = dwarf2_attr (die, DW_AT_location, cu);
21271           if (attr)
21272             {
21273               var_decode_location (attr, sym, cu);
21274               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21275
21276               /* Fortran explicitly imports any global symbols to the local
21277                  scope by DW_TAG_common_block.  */
21278               if (cu->language == language_fortran && die->parent
21279                   && die->parent->tag == DW_TAG_common_block)
21280                 attr2 = NULL;
21281
21282               if (SYMBOL_CLASS (sym) == LOC_STATIC
21283                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21284                   && !dwarf2_per_objfile->has_section_at_zero)
21285                 {
21286                   /* When a static variable is eliminated by the linker,
21287                      the corresponding debug information is not stripped
21288                      out, but the variable address is set to null;
21289                      do not add such variables into symbol table.  */
21290                 }
21291               else if (attr2 && (DW_UNSND (attr2) != 0))
21292                 {
21293                   /* Workaround gfortran PR debug/40040 - it uses
21294                      DW_AT_location for variables in -fPIC libraries which may
21295                      get overriden by other libraries/executable and get
21296                      a different address.  Resolve it by the minimal symbol
21297                      which may come from inferior's executable using copy
21298                      relocation.  Make this workaround only for gfortran as for
21299                      other compilers GDB cannot guess the minimal symbol
21300                      Fortran mangling kind.  */
21301                   if (cu->language == language_fortran && die->parent
21302                       && die->parent->tag == DW_TAG_module
21303                       && cu->producer
21304                       && startswith (cu->producer, "GNU Fortran"))
21305                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21306
21307                   /* A variable with DW_AT_external is never static,
21308                      but it may be block-scoped.  */
21309                   list_to_add = (cu->list_in_scope == &file_symbols
21310                                  ? &global_symbols : cu->list_in_scope);
21311                 }
21312               else
21313                 list_to_add = cu->list_in_scope;
21314             }
21315           else
21316             {
21317               /* We do not know the address of this symbol.
21318                  If it is an external symbol and we have type information
21319                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21320                  The address of the variable will then be determined from
21321                  the minimal symbol table whenever the variable is
21322                  referenced.  */
21323               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21324
21325               /* Fortran explicitly imports any global symbols to the local
21326                  scope by DW_TAG_common_block.  */
21327               if (cu->language == language_fortran && die->parent
21328                   && die->parent->tag == DW_TAG_common_block)
21329                 {
21330                   /* SYMBOL_CLASS doesn't matter here because
21331                      read_common_block is going to reset it.  */
21332                   if (!suppress_add)
21333                     list_to_add = cu->list_in_scope;
21334                 }
21335               else if (attr2 && (DW_UNSND (attr2) != 0)
21336                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21337                 {
21338                   /* A variable with DW_AT_external is never static, but it
21339                      may be block-scoped.  */
21340                   list_to_add = (cu->list_in_scope == &file_symbols
21341                                  ? &global_symbols : cu->list_in_scope);
21342
21343                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21344                 }
21345               else if (!die_is_declaration (die, cu))
21346                 {
21347                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21348                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21349                   if (!suppress_add)
21350                     list_to_add = cu->list_in_scope;
21351                 }
21352             }
21353           break;
21354         case DW_TAG_formal_parameter:
21355           /* If we are inside a function, mark this as an argument.  If
21356              not, we might be looking at an argument to an inlined function
21357              when we do not have enough information to show inlined frames;
21358              pretend it's a local variable in that case so that the user can
21359              still see it.  */
21360           if (context_stack_depth > 0
21361               && context_stack[context_stack_depth - 1].name != NULL)
21362             SYMBOL_IS_ARGUMENT (sym) = 1;
21363           attr = dwarf2_attr (die, DW_AT_location, cu);
21364           if (attr)
21365             {
21366               var_decode_location (attr, sym, cu);
21367             }
21368           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21369           if (attr)
21370             {
21371               dwarf2_const_value (attr, sym, cu);
21372             }
21373
21374           list_to_add = cu->list_in_scope;
21375           break;
21376         case DW_TAG_unspecified_parameters:
21377           /* From varargs functions; gdb doesn't seem to have any
21378              interest in this information, so just ignore it for now.
21379              (FIXME?) */
21380           break;
21381         case DW_TAG_template_type_param:
21382           suppress_add = 1;
21383           /* Fall through.  */
21384         case DW_TAG_class_type:
21385         case DW_TAG_interface_type:
21386         case DW_TAG_structure_type:
21387         case DW_TAG_union_type:
21388         case DW_TAG_set_type:
21389         case DW_TAG_enumeration_type:
21390           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21391           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21392
21393           {
21394             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21395                really ever be static objects: otherwise, if you try
21396                to, say, break of a class's method and you're in a file
21397                which doesn't mention that class, it won't work unless
21398                the check for all static symbols in lookup_symbol_aux
21399                saves you.  See the OtherFileClass tests in
21400                gdb.c++/namespace.exp.  */
21401
21402             if (!suppress_add)
21403               {
21404                 list_to_add = (cu->list_in_scope == &file_symbols
21405                                && cu->language == language_cplus
21406                                ? &global_symbols : cu->list_in_scope);
21407
21408                 /* The semantics of C++ state that "struct foo {
21409                    ... }" also defines a typedef for "foo".  */
21410                 if (cu->language == language_cplus
21411                     || cu->language == language_ada
21412                     || cu->language == language_d
21413                     || cu->language == language_rust)
21414                   {
21415                     /* The symbol's name is already allocated along
21416                        with this objfile, so we don't need to
21417                        duplicate it for the type.  */
21418                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21419                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21420                   }
21421               }
21422           }
21423           break;
21424         case DW_TAG_typedef:
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_base_type:
21430         case DW_TAG_subrange_type:
21431           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21432           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21433           list_to_add = cu->list_in_scope;
21434           break;
21435         case DW_TAG_enumerator:
21436           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21437           if (attr)
21438             {
21439               dwarf2_const_value (attr, sym, cu);
21440             }
21441           {
21442             /* NOTE: carlton/2003-11-10: See comment above in the
21443                DW_TAG_class_type, etc. block.  */
21444
21445             list_to_add = (cu->list_in_scope == &file_symbols
21446                            && cu->language == language_cplus
21447                            ? &global_symbols : cu->list_in_scope);
21448           }
21449           break;
21450         case DW_TAG_imported_declaration:
21451         case DW_TAG_namespace:
21452           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21453           list_to_add = &global_symbols;
21454           break;
21455         case DW_TAG_module:
21456           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21457           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21458           list_to_add = &global_symbols;
21459           break;
21460         case DW_TAG_common_block:
21461           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21462           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21463           add_symbol_to_list (sym, cu->list_in_scope);
21464           break;
21465         default:
21466           /* Not a tag we recognize.  Hopefully we aren't processing
21467              trash data, but since we must specifically ignore things
21468              we don't recognize, there is nothing else we should do at
21469              this point.  */
21470           complaint (_("unsupported tag: '%s'"),
21471                      dwarf_tag_name (die->tag));
21472           break;
21473         }
21474
21475       if (suppress_add)
21476         {
21477           sym->hash_next = objfile->template_symbols;
21478           objfile->template_symbols = sym;
21479           list_to_add = NULL;
21480         }
21481
21482       if (list_to_add != NULL)
21483         add_symbol_to_list (sym, list_to_add);
21484
21485       /* For the benefit of old versions of GCC, check for anonymous
21486          namespaces based on the demangled name.  */
21487       if (!cu->processing_has_namespace_info
21488           && cu->language == language_cplus)
21489         cp_scan_for_anonymous_namespaces (sym, objfile);
21490     }
21491   return (sym);
21492 }
21493
21494 /* Given an attr with a DW_FORM_dataN value in host byte order,
21495    zero-extend it as appropriate for the symbol's type.  The DWARF
21496    standard (v4) is not entirely clear about the meaning of using
21497    DW_FORM_dataN for a constant with a signed type, where the type is
21498    wider than the data.  The conclusion of a discussion on the DWARF
21499    list was that this is unspecified.  We choose to always zero-extend
21500    because that is the interpretation long in use by GCC.  */
21501
21502 static gdb_byte *
21503 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21504                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21505 {
21506   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21507   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21508                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21509   LONGEST l = DW_UNSND (attr);
21510
21511   if (bits < sizeof (*value) * 8)
21512     {
21513       l &= ((LONGEST) 1 << bits) - 1;
21514       *value = l;
21515     }
21516   else if (bits == sizeof (*value) * 8)
21517     *value = l;
21518   else
21519     {
21520       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21521       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21522       return bytes;
21523     }
21524
21525   return NULL;
21526 }
21527
21528 /* Read a constant value from an attribute.  Either set *VALUE, or if
21529    the value does not fit in *VALUE, set *BYTES - either already
21530    allocated on the objfile obstack, or newly allocated on OBSTACK,
21531    or, set *BATON, if we translated the constant to a location
21532    expression.  */
21533
21534 static void
21535 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21536                          const char *name, struct obstack *obstack,
21537                          struct dwarf2_cu *cu,
21538                          LONGEST *value, const gdb_byte **bytes,
21539                          struct dwarf2_locexpr_baton **baton)
21540 {
21541   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21542   struct comp_unit_head *cu_header = &cu->header;
21543   struct dwarf_block *blk;
21544   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21545                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21546
21547   *value = 0;
21548   *bytes = NULL;
21549   *baton = NULL;
21550
21551   switch (attr->form)
21552     {
21553     case DW_FORM_addr:
21554     case DW_FORM_GNU_addr_index:
21555       {
21556         gdb_byte *data;
21557
21558         if (TYPE_LENGTH (type) != cu_header->addr_size)
21559           dwarf2_const_value_length_mismatch_complaint (name,
21560                                                         cu_header->addr_size,
21561                                                         TYPE_LENGTH (type));
21562         /* Symbols of this form are reasonably rare, so we just
21563            piggyback on the existing location code rather than writing
21564            a new implementation of symbol_computed_ops.  */
21565         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21566         (*baton)->per_cu = cu->per_cu;
21567         gdb_assert ((*baton)->per_cu);
21568
21569         (*baton)->size = 2 + cu_header->addr_size;
21570         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21571         (*baton)->data = data;
21572
21573         data[0] = DW_OP_addr;
21574         store_unsigned_integer (&data[1], cu_header->addr_size,
21575                                 byte_order, DW_ADDR (attr));
21576         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21577       }
21578       break;
21579     case DW_FORM_string:
21580     case DW_FORM_strp:
21581     case DW_FORM_GNU_str_index:
21582     case DW_FORM_GNU_strp_alt:
21583       /* DW_STRING is already allocated on the objfile obstack, point
21584          directly to it.  */
21585       *bytes = (const gdb_byte *) DW_STRING (attr);
21586       break;
21587     case DW_FORM_block1:
21588     case DW_FORM_block2:
21589     case DW_FORM_block4:
21590     case DW_FORM_block:
21591     case DW_FORM_exprloc:
21592     case DW_FORM_data16:
21593       blk = DW_BLOCK (attr);
21594       if (TYPE_LENGTH (type) != blk->size)
21595         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21596                                                       TYPE_LENGTH (type));
21597       *bytes = blk->data;
21598       break;
21599
21600       /* The DW_AT_const_value attributes are supposed to carry the
21601          symbol's value "represented as it would be on the target
21602          architecture."  By the time we get here, it's already been
21603          converted to host endianness, so we just need to sign- or
21604          zero-extend it as appropriate.  */
21605     case DW_FORM_data1:
21606       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21607       break;
21608     case DW_FORM_data2:
21609       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21610       break;
21611     case DW_FORM_data4:
21612       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21613       break;
21614     case DW_FORM_data8:
21615       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21616       break;
21617
21618     case DW_FORM_sdata:
21619     case DW_FORM_implicit_const:
21620       *value = DW_SND (attr);
21621       break;
21622
21623     case DW_FORM_udata:
21624       *value = DW_UNSND (attr);
21625       break;
21626
21627     default:
21628       complaint (_("unsupported const value attribute form: '%s'"),
21629                  dwarf_form_name (attr->form));
21630       *value = 0;
21631       break;
21632     }
21633 }
21634
21635
21636 /* Copy constant value from an attribute to a symbol.  */
21637
21638 static void
21639 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21640                     struct dwarf2_cu *cu)
21641 {
21642   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21643   LONGEST value;
21644   const gdb_byte *bytes;
21645   struct dwarf2_locexpr_baton *baton;
21646
21647   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21648                            SYMBOL_PRINT_NAME (sym),
21649                            &objfile->objfile_obstack, cu,
21650                            &value, &bytes, &baton);
21651
21652   if (baton != NULL)
21653     {
21654       SYMBOL_LOCATION_BATON (sym) = baton;
21655       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21656     }
21657   else if (bytes != NULL)
21658      {
21659       SYMBOL_VALUE_BYTES (sym) = bytes;
21660       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21661     }
21662   else
21663     {
21664       SYMBOL_VALUE (sym) = value;
21665       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21666     }
21667 }
21668
21669 /* Return the type of the die in question using its DW_AT_type attribute.  */
21670
21671 static struct type *
21672 die_type (struct die_info *die, struct dwarf2_cu *cu)
21673 {
21674   struct attribute *type_attr;
21675
21676   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21677   if (!type_attr)
21678     {
21679       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21680       /* A missing DW_AT_type represents a void type.  */
21681       return objfile_type (objfile)->builtin_void;
21682     }
21683
21684   return lookup_die_type (die, type_attr, cu);
21685 }
21686
21687 /* True iff CU's producer generates GNAT Ada auxiliary information
21688    that allows to find parallel types through that information instead
21689    of having to do expensive parallel lookups by type name.  */
21690
21691 static int
21692 need_gnat_info (struct dwarf2_cu *cu)
21693 {
21694   /* Assume that the Ada compiler was GNAT, which always produces
21695      the auxiliary information.  */
21696   return (cu->language == language_ada);
21697 }
21698
21699 /* Return the auxiliary type of the die in question using its
21700    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21701    attribute is not present.  */
21702
21703 static struct type *
21704 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21705 {
21706   struct attribute *type_attr;
21707
21708   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21709   if (!type_attr)
21710     return NULL;
21711
21712   return lookup_die_type (die, type_attr, cu);
21713 }
21714
21715 /* If DIE has a descriptive_type attribute, then set the TYPE's
21716    descriptive type accordingly.  */
21717
21718 static void
21719 set_descriptive_type (struct type *type, struct die_info *die,
21720                       struct dwarf2_cu *cu)
21721 {
21722   struct type *descriptive_type = die_descriptive_type (die, cu);
21723
21724   if (descriptive_type)
21725     {
21726       ALLOCATE_GNAT_AUX_TYPE (type);
21727       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21728     }
21729 }
21730
21731 /* Return the containing type of the die in question using its
21732    DW_AT_containing_type attribute.  */
21733
21734 static struct type *
21735 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21736 {
21737   struct attribute *type_attr;
21738   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21739
21740   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21741   if (!type_attr)
21742     error (_("Dwarf Error: Problem turning containing type into gdb type "
21743              "[in module %s]"), objfile_name (objfile));
21744
21745   return lookup_die_type (die, type_attr, cu);
21746 }
21747
21748 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21749
21750 static struct type *
21751 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21752 {
21753   struct dwarf2_per_objfile *dwarf2_per_objfile
21754     = cu->per_cu->dwarf2_per_objfile;
21755   struct objfile *objfile = dwarf2_per_objfile->objfile;
21756   char *message, *saved;
21757
21758   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21759                         objfile_name (objfile),
21760                         sect_offset_str (cu->header.sect_off),
21761                         sect_offset_str (die->sect_off));
21762   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21763                                   message, strlen (message));
21764   xfree (message);
21765
21766   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21767 }
21768
21769 /* Look up the type of DIE in CU using its type attribute ATTR.
21770    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21771    DW_AT_containing_type.
21772    If there is no type substitute an error marker.  */
21773
21774 static struct type *
21775 lookup_die_type (struct die_info *die, const struct attribute *attr,
21776                  struct dwarf2_cu *cu)
21777 {
21778   struct dwarf2_per_objfile *dwarf2_per_objfile
21779     = cu->per_cu->dwarf2_per_objfile;
21780   struct objfile *objfile = dwarf2_per_objfile->objfile;
21781   struct type *this_type;
21782
21783   gdb_assert (attr->name == DW_AT_type
21784               || attr->name == DW_AT_GNAT_descriptive_type
21785               || attr->name == DW_AT_containing_type);
21786
21787   /* First see if we have it cached.  */
21788
21789   if (attr->form == DW_FORM_GNU_ref_alt)
21790     {
21791       struct dwarf2_per_cu_data *per_cu;
21792       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21793
21794       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21795                                                  dwarf2_per_objfile);
21796       this_type = get_die_type_at_offset (sect_off, per_cu);
21797     }
21798   else if (attr_form_is_ref (attr))
21799     {
21800       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21801
21802       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21803     }
21804   else if (attr->form == DW_FORM_ref_sig8)
21805     {
21806       ULONGEST signature = DW_SIGNATURE (attr);
21807
21808       return get_signatured_type (die, signature, cu);
21809     }
21810   else
21811     {
21812       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21813                    " at %s [in module %s]"),
21814                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21815                  objfile_name (objfile));
21816       return build_error_marker_type (cu, die);
21817     }
21818
21819   /* If not cached we need to read it in.  */
21820
21821   if (this_type == NULL)
21822     {
21823       struct die_info *type_die = NULL;
21824       struct dwarf2_cu *type_cu = cu;
21825
21826       if (attr_form_is_ref (attr))
21827         type_die = follow_die_ref (die, attr, &type_cu);
21828       if (type_die == NULL)
21829         return build_error_marker_type (cu, die);
21830       /* If we find the type now, it's probably because the type came
21831          from an inter-CU reference and the type's CU got expanded before
21832          ours.  */
21833       this_type = read_type_die (type_die, type_cu);
21834     }
21835
21836   /* If we still don't have a type use an error marker.  */
21837
21838   if (this_type == NULL)
21839     return build_error_marker_type (cu, die);
21840
21841   return this_type;
21842 }
21843
21844 /* Return the type in DIE, CU.
21845    Returns NULL for invalid types.
21846
21847    This first does a lookup in die_type_hash,
21848    and only reads the die in if necessary.
21849
21850    NOTE: This can be called when reading in partial or full symbols.  */
21851
21852 static struct type *
21853 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21854 {
21855   struct type *this_type;
21856
21857   this_type = get_die_type (die, cu);
21858   if (this_type)
21859     return this_type;
21860
21861   return read_type_die_1 (die, cu);
21862 }
21863
21864 /* Read the type in DIE, CU.
21865    Returns NULL for invalid types.  */
21866
21867 static struct type *
21868 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21869 {
21870   struct type *this_type = NULL;
21871
21872   switch (die->tag)
21873     {
21874     case DW_TAG_class_type:
21875     case DW_TAG_interface_type:
21876     case DW_TAG_structure_type:
21877     case DW_TAG_union_type:
21878       this_type = read_structure_type (die, cu);
21879       break;
21880     case DW_TAG_enumeration_type:
21881       this_type = read_enumeration_type (die, cu);
21882       break;
21883     case DW_TAG_subprogram:
21884     case DW_TAG_subroutine_type:
21885     case DW_TAG_inlined_subroutine:
21886       this_type = read_subroutine_type (die, cu);
21887       break;
21888     case DW_TAG_array_type:
21889       this_type = read_array_type (die, cu);
21890       break;
21891     case DW_TAG_set_type:
21892       this_type = read_set_type (die, cu);
21893       break;
21894     case DW_TAG_pointer_type:
21895       this_type = read_tag_pointer_type (die, cu);
21896       break;
21897     case DW_TAG_ptr_to_member_type:
21898       this_type = read_tag_ptr_to_member_type (die, cu);
21899       break;
21900     case DW_TAG_reference_type:
21901       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21902       break;
21903     case DW_TAG_rvalue_reference_type:
21904       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21905       break;
21906     case DW_TAG_const_type:
21907       this_type = read_tag_const_type (die, cu);
21908       break;
21909     case DW_TAG_volatile_type:
21910       this_type = read_tag_volatile_type (die, cu);
21911       break;
21912     case DW_TAG_restrict_type:
21913       this_type = read_tag_restrict_type (die, cu);
21914       break;
21915     case DW_TAG_string_type:
21916       this_type = read_tag_string_type (die, cu);
21917       break;
21918     case DW_TAG_typedef:
21919       this_type = read_typedef (die, cu);
21920       break;
21921     case DW_TAG_subrange_type:
21922       this_type = read_subrange_type (die, cu);
21923       break;
21924     case DW_TAG_base_type:
21925       this_type = read_base_type (die, cu);
21926       break;
21927     case DW_TAG_unspecified_type:
21928       this_type = read_unspecified_type (die, cu);
21929       break;
21930     case DW_TAG_namespace:
21931       this_type = read_namespace_type (die, cu);
21932       break;
21933     case DW_TAG_module:
21934       this_type = read_module_type (die, cu);
21935       break;
21936     case DW_TAG_atomic_type:
21937       this_type = read_tag_atomic_type (die, cu);
21938       break;
21939     default:
21940       complaint (_("unexpected tag in read_type_die: '%s'"),
21941                  dwarf_tag_name (die->tag));
21942       break;
21943     }
21944
21945   return this_type;
21946 }
21947
21948 /* See if we can figure out if the class lives in a namespace.  We do
21949    this by looking for a member function; its demangled name will
21950    contain namespace info, if there is any.
21951    Return the computed name or NULL.
21952    Space for the result is allocated on the objfile's obstack.
21953    This is the full-die version of guess_partial_die_structure_name.
21954    In this case we know DIE has no useful parent.  */
21955
21956 static char *
21957 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21958 {
21959   struct die_info *spec_die;
21960   struct dwarf2_cu *spec_cu;
21961   struct die_info *child;
21962   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21963
21964   spec_cu = cu;
21965   spec_die = die_specification (die, &spec_cu);
21966   if (spec_die != NULL)
21967     {
21968       die = spec_die;
21969       cu = spec_cu;
21970     }
21971
21972   for (child = die->child;
21973        child != NULL;
21974        child = child->sibling)
21975     {
21976       if (child->tag == DW_TAG_subprogram)
21977         {
21978           const char *linkage_name = dw2_linkage_name (child, cu);
21979
21980           if (linkage_name != NULL)
21981             {
21982               char *actual_name
21983                 = language_class_name_from_physname (cu->language_defn,
21984                                                      linkage_name);
21985               char *name = NULL;
21986
21987               if (actual_name != NULL)
21988                 {
21989                   const char *die_name = dwarf2_name (die, cu);
21990
21991                   if (die_name != NULL
21992                       && strcmp (die_name, actual_name) != 0)
21993                     {
21994                       /* Strip off the class name from the full name.
21995                          We want the prefix.  */
21996                       int die_name_len = strlen (die_name);
21997                       int actual_name_len = strlen (actual_name);
21998
21999                       /* Test for '::' as a sanity check.  */
22000                       if (actual_name_len > die_name_len + 2
22001                           && actual_name[actual_name_len
22002                                          - die_name_len - 1] == ':')
22003                         name = (char *) obstack_copy0 (
22004                           &objfile->per_bfd->storage_obstack,
22005                           actual_name, actual_name_len - die_name_len - 2);
22006                     }
22007                 }
22008               xfree (actual_name);
22009               return name;
22010             }
22011         }
22012     }
22013
22014   return NULL;
22015 }
22016
22017 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22018    prefix part in such case.  See
22019    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22020
22021 static const char *
22022 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22023 {
22024   struct attribute *attr;
22025   const char *base;
22026
22027   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22028       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22029     return NULL;
22030
22031   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22032     return NULL;
22033
22034   attr = dw2_linkage_name_attr (die, cu);
22035   if (attr == NULL || DW_STRING (attr) == NULL)
22036     return NULL;
22037
22038   /* dwarf2_name had to be already called.  */
22039   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22040
22041   /* Strip the base name, keep any leading namespaces/classes.  */
22042   base = strrchr (DW_STRING (attr), ':');
22043   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22044     return "";
22045
22046   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22047   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22048                                  DW_STRING (attr),
22049                                  &base[-1] - DW_STRING (attr));
22050 }
22051
22052 /* Return the name of the namespace/class that DIE is defined within,
22053    or "" if we can't tell.  The caller should not xfree the result.
22054
22055    For example, if we're within the method foo() in the following
22056    code:
22057
22058    namespace N {
22059      class C {
22060        void foo () {
22061        }
22062      };
22063    }
22064
22065    then determine_prefix on foo's die will return "N::C".  */
22066
22067 static const char *
22068 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22069 {
22070   struct dwarf2_per_objfile *dwarf2_per_objfile
22071     = cu->per_cu->dwarf2_per_objfile;
22072   struct die_info *parent, *spec_die;
22073   struct dwarf2_cu *spec_cu;
22074   struct type *parent_type;
22075   const char *retval;
22076
22077   if (cu->language != language_cplus
22078       && cu->language != language_fortran && cu->language != language_d
22079       && cu->language != language_rust)
22080     return "";
22081
22082   retval = anonymous_struct_prefix (die, cu);
22083   if (retval)
22084     return retval;
22085
22086   /* We have to be careful in the presence of DW_AT_specification.
22087      For example, with GCC 3.4, given the code
22088
22089      namespace N {
22090        void foo() {
22091          // Definition of N::foo.
22092        }
22093      }
22094
22095      then we'll have a tree of DIEs like this:
22096
22097      1: DW_TAG_compile_unit
22098        2: DW_TAG_namespace        // N
22099          3: DW_TAG_subprogram     // declaration of N::foo
22100        4: DW_TAG_subprogram       // definition of N::foo
22101             DW_AT_specification   // refers to die #3
22102
22103      Thus, when processing die #4, we have to pretend that we're in
22104      the context of its DW_AT_specification, namely the contex of die
22105      #3.  */
22106   spec_cu = cu;
22107   spec_die = die_specification (die, &spec_cu);
22108   if (spec_die == NULL)
22109     parent = die->parent;
22110   else
22111     {
22112       parent = spec_die->parent;
22113       cu = spec_cu;
22114     }
22115
22116   if (parent == NULL)
22117     return "";
22118   else if (parent->building_fullname)
22119     {
22120       const char *name;
22121       const char *parent_name;
22122
22123       /* It has been seen on RealView 2.2 built binaries,
22124          DW_TAG_template_type_param types actually _defined_ as
22125          children of the parent class:
22126
22127          enum E {};
22128          template class <class Enum> Class{};
22129          Class<enum E> class_e;
22130
22131          1: DW_TAG_class_type (Class)
22132            2: DW_TAG_enumeration_type (E)
22133              3: DW_TAG_enumerator (enum1:0)
22134              3: DW_TAG_enumerator (enum2:1)
22135              ...
22136            2: DW_TAG_template_type_param
22137               DW_AT_type  DW_FORM_ref_udata (E)
22138
22139          Besides being broken debug info, it can put GDB into an
22140          infinite loop.  Consider:
22141
22142          When we're building the full name for Class<E>, we'll start
22143          at Class, and go look over its template type parameters,
22144          finding E.  We'll then try to build the full name of E, and
22145          reach here.  We're now trying to build the full name of E,
22146          and look over the parent DIE for containing scope.  In the
22147          broken case, if we followed the parent DIE of E, we'd again
22148          find Class, and once again go look at its template type
22149          arguments, etc., etc.  Simply don't consider such parent die
22150          as source-level parent of this die (it can't be, the language
22151          doesn't allow it), and break the loop here.  */
22152       name = dwarf2_name (die, cu);
22153       parent_name = dwarf2_name (parent, cu);
22154       complaint (_("template param type '%s' defined within parent '%s'"),
22155                  name ? name : "<unknown>",
22156                  parent_name ? parent_name : "<unknown>");
22157       return "";
22158     }
22159   else
22160     switch (parent->tag)
22161       {
22162       case DW_TAG_namespace:
22163         parent_type = read_type_die (parent, cu);
22164         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22165            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22166            Work around this problem here.  */
22167         if (cu->language == language_cplus
22168             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22169           return "";
22170         /* We give a name to even anonymous namespaces.  */
22171         return TYPE_NAME (parent_type);
22172       case DW_TAG_class_type:
22173       case DW_TAG_interface_type:
22174       case DW_TAG_structure_type:
22175       case DW_TAG_union_type:
22176       case DW_TAG_module:
22177         parent_type = read_type_die (parent, cu);
22178         if (TYPE_NAME (parent_type) != NULL)
22179           return TYPE_NAME (parent_type);
22180         else
22181           /* An anonymous structure is only allowed non-static data
22182              members; no typedefs, no member functions, et cetera.
22183              So it does not need a prefix.  */
22184           return "";
22185       case DW_TAG_compile_unit:
22186       case DW_TAG_partial_unit:
22187         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22188         if (cu->language == language_cplus
22189             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22190             && die->child != NULL
22191             && (die->tag == DW_TAG_class_type
22192                 || die->tag == DW_TAG_structure_type
22193                 || die->tag == DW_TAG_union_type))
22194           {
22195             char *name = guess_full_die_structure_name (die, cu);
22196             if (name != NULL)
22197               return name;
22198           }
22199         return "";
22200       case DW_TAG_enumeration_type:
22201         parent_type = read_type_die (parent, cu);
22202         if (TYPE_DECLARED_CLASS (parent_type))
22203           {
22204             if (TYPE_NAME (parent_type) != NULL)
22205               return TYPE_NAME (parent_type);
22206             return "";
22207           }
22208         /* Fall through.  */
22209       default:
22210         return determine_prefix (parent, cu);
22211       }
22212 }
22213
22214 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22215    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22216    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22217    an obconcat, otherwise allocate storage for the result.  The CU argument is
22218    used to determine the language and hence, the appropriate separator.  */
22219
22220 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22221
22222 static char *
22223 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22224                  int physname, struct dwarf2_cu *cu)
22225 {
22226   const char *lead = "";
22227   const char *sep;
22228
22229   if (suffix == NULL || suffix[0] == '\0'
22230       || prefix == NULL || prefix[0] == '\0')
22231     sep = "";
22232   else if (cu->language == language_d)
22233     {
22234       /* For D, the 'main' function could be defined in any module, but it
22235          should never be prefixed.  */
22236       if (strcmp (suffix, "D main") == 0)
22237         {
22238           prefix = "";
22239           sep = "";
22240         }
22241       else
22242         sep = ".";
22243     }
22244   else if (cu->language == language_fortran && physname)
22245     {
22246       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22247          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22248
22249       lead = "__";
22250       sep = "_MOD_";
22251     }
22252   else
22253     sep = "::";
22254
22255   if (prefix == NULL)
22256     prefix = "";
22257   if (suffix == NULL)
22258     suffix = "";
22259
22260   if (obs == NULL)
22261     {
22262       char *retval
22263         = ((char *)
22264            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22265
22266       strcpy (retval, lead);
22267       strcat (retval, prefix);
22268       strcat (retval, sep);
22269       strcat (retval, suffix);
22270       return retval;
22271     }
22272   else
22273     {
22274       /* We have an obstack.  */
22275       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22276     }
22277 }
22278
22279 /* Return sibling of die, NULL if no sibling.  */
22280
22281 static struct die_info *
22282 sibling_die (struct die_info *die)
22283 {
22284   return die->sibling;
22285 }
22286
22287 /* Get name of a die, return NULL if not found.  */
22288
22289 static const char *
22290 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22291                           struct obstack *obstack)
22292 {
22293   if (name && cu->language == language_cplus)
22294     {
22295       std::string canon_name = cp_canonicalize_string (name);
22296
22297       if (!canon_name.empty ())
22298         {
22299           if (canon_name != name)
22300             name = (const char *) obstack_copy0 (obstack,
22301                                                  canon_name.c_str (),
22302                                                  canon_name.length ());
22303         }
22304     }
22305
22306   return name;
22307 }
22308
22309 /* Get name of a die, return NULL if not found.
22310    Anonymous namespaces are converted to their magic string.  */
22311
22312 static const char *
22313 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22314 {
22315   struct attribute *attr;
22316   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22317
22318   attr = dwarf2_attr (die, DW_AT_name, cu);
22319   if ((!attr || !DW_STRING (attr))
22320       && die->tag != DW_TAG_namespace
22321       && die->tag != DW_TAG_class_type
22322       && die->tag != DW_TAG_interface_type
22323       && die->tag != DW_TAG_structure_type
22324       && die->tag != DW_TAG_union_type)
22325     return NULL;
22326
22327   switch (die->tag)
22328     {
22329     case DW_TAG_compile_unit:
22330     case DW_TAG_partial_unit:
22331       /* Compilation units have a DW_AT_name that is a filename, not
22332          a source language identifier.  */
22333     case DW_TAG_enumeration_type:
22334     case DW_TAG_enumerator:
22335       /* These tags always have simple identifiers already; no need
22336          to canonicalize them.  */
22337       return DW_STRING (attr);
22338
22339     case DW_TAG_namespace:
22340       if (attr != NULL && DW_STRING (attr) != NULL)
22341         return DW_STRING (attr);
22342       return CP_ANONYMOUS_NAMESPACE_STR;
22343
22344     case DW_TAG_class_type:
22345     case DW_TAG_interface_type:
22346     case DW_TAG_structure_type:
22347     case DW_TAG_union_type:
22348       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22349          structures or unions.  These were of the form "._%d" in GCC 4.1,
22350          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22351          and GCC 4.4.  We work around this problem by ignoring these.  */
22352       if (attr && DW_STRING (attr)
22353           && (startswith (DW_STRING (attr), "._")
22354               || startswith (DW_STRING (attr), "<anonymous")))
22355         return NULL;
22356
22357       /* GCC might emit a nameless typedef that has a linkage name.  See
22358          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22359       if (!attr || DW_STRING (attr) == NULL)
22360         {
22361           char *demangled = NULL;
22362
22363           attr = dw2_linkage_name_attr (die, cu);
22364           if (attr == NULL || DW_STRING (attr) == NULL)
22365             return NULL;
22366
22367           /* Avoid demangling DW_STRING (attr) the second time on a second
22368              call for the same DIE.  */
22369           if (!DW_STRING_IS_CANONICAL (attr))
22370             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22371
22372           if (demangled)
22373             {
22374               const char *base;
22375
22376               /* FIXME: we already did this for the partial symbol... */
22377               DW_STRING (attr)
22378                 = ((const char *)
22379                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22380                                   demangled, strlen (demangled)));
22381               DW_STRING_IS_CANONICAL (attr) = 1;
22382               xfree (demangled);
22383
22384               /* Strip any leading namespaces/classes, keep only the base name.
22385                  DW_AT_name for named DIEs does not contain the prefixes.  */
22386               base = strrchr (DW_STRING (attr), ':');
22387               if (base && base > DW_STRING (attr) && base[-1] == ':')
22388                 return &base[1];
22389               else
22390                 return DW_STRING (attr);
22391             }
22392         }
22393       break;
22394
22395     default:
22396       break;
22397     }
22398
22399   if (!DW_STRING_IS_CANONICAL (attr))
22400     {
22401       DW_STRING (attr)
22402         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22403                                     &objfile->per_bfd->storage_obstack);
22404       DW_STRING_IS_CANONICAL (attr) = 1;
22405     }
22406   return DW_STRING (attr);
22407 }
22408
22409 /* Return the die that this die in an extension of, or NULL if there
22410    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22411    containing the return value on output.  */
22412
22413 static struct die_info *
22414 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22415 {
22416   struct attribute *attr;
22417
22418   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22419   if (attr == NULL)
22420     return NULL;
22421
22422   return follow_die_ref (die, attr, ext_cu);
22423 }
22424
22425 /* Convert a DIE tag into its string name.  */
22426
22427 static const char *
22428 dwarf_tag_name (unsigned tag)
22429 {
22430   const char *name = get_DW_TAG_name (tag);
22431
22432   if (name == NULL)
22433     return "DW_TAG_<unknown>";
22434
22435   return name;
22436 }
22437
22438 /* Convert a DWARF attribute code into its string name.  */
22439
22440 static const char *
22441 dwarf_attr_name (unsigned attr)
22442 {
22443   const char *name;
22444
22445 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22446   if (attr == DW_AT_MIPS_fde)
22447     return "DW_AT_MIPS_fde";
22448 #else
22449   if (attr == DW_AT_HP_block_index)
22450     return "DW_AT_HP_block_index";
22451 #endif
22452
22453   name = get_DW_AT_name (attr);
22454
22455   if (name == NULL)
22456     return "DW_AT_<unknown>";
22457
22458   return name;
22459 }
22460
22461 /* Convert a DWARF value form code into its string name.  */
22462
22463 static const char *
22464 dwarf_form_name (unsigned form)
22465 {
22466   const char *name = get_DW_FORM_name (form);
22467
22468   if (name == NULL)
22469     return "DW_FORM_<unknown>";
22470
22471   return name;
22472 }
22473
22474 static const char *
22475 dwarf_bool_name (unsigned mybool)
22476 {
22477   if (mybool)
22478     return "TRUE";
22479   else
22480     return "FALSE";
22481 }
22482
22483 /* Convert a DWARF type code into its string name.  */
22484
22485 static const char *
22486 dwarf_type_encoding_name (unsigned enc)
22487 {
22488   const char *name = get_DW_ATE_name (enc);
22489
22490   if (name == NULL)
22491     return "DW_ATE_<unknown>";
22492
22493   return name;
22494 }
22495
22496 static void
22497 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22498 {
22499   unsigned int i;
22500
22501   print_spaces (indent, f);
22502   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22503                       dwarf_tag_name (die->tag), die->abbrev,
22504                       sect_offset_str (die->sect_off));
22505
22506   if (die->parent != NULL)
22507     {
22508       print_spaces (indent, f);
22509       fprintf_unfiltered (f, "  parent at offset: %s\n",
22510                           sect_offset_str (die->parent->sect_off));
22511     }
22512
22513   print_spaces (indent, f);
22514   fprintf_unfiltered (f, "  has children: %s\n",
22515            dwarf_bool_name (die->child != NULL));
22516
22517   print_spaces (indent, f);
22518   fprintf_unfiltered (f, "  attributes:\n");
22519
22520   for (i = 0; i < die->num_attrs; ++i)
22521     {
22522       print_spaces (indent, f);
22523       fprintf_unfiltered (f, "    %s (%s) ",
22524                dwarf_attr_name (die->attrs[i].name),
22525                dwarf_form_name (die->attrs[i].form));
22526
22527       switch (die->attrs[i].form)
22528         {
22529         case DW_FORM_addr:
22530         case DW_FORM_GNU_addr_index:
22531           fprintf_unfiltered (f, "address: ");
22532           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22533           break;
22534         case DW_FORM_block2:
22535         case DW_FORM_block4:
22536         case DW_FORM_block:
22537         case DW_FORM_block1:
22538           fprintf_unfiltered (f, "block: size %s",
22539                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22540           break;
22541         case DW_FORM_exprloc:
22542           fprintf_unfiltered (f, "expression: size %s",
22543                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22544           break;
22545         case DW_FORM_data16:
22546           fprintf_unfiltered (f, "constant of 16 bytes");
22547           break;
22548         case DW_FORM_ref_addr:
22549           fprintf_unfiltered (f, "ref address: ");
22550           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22551           break;
22552         case DW_FORM_GNU_ref_alt:
22553           fprintf_unfiltered (f, "alt ref address: ");
22554           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22555           break;
22556         case DW_FORM_ref1:
22557         case DW_FORM_ref2:
22558         case DW_FORM_ref4:
22559         case DW_FORM_ref8:
22560         case DW_FORM_ref_udata:
22561           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22562                               (long) (DW_UNSND (&die->attrs[i])));
22563           break;
22564         case DW_FORM_data1:
22565         case DW_FORM_data2:
22566         case DW_FORM_data4:
22567         case DW_FORM_data8:
22568         case DW_FORM_udata:
22569         case DW_FORM_sdata:
22570           fprintf_unfiltered (f, "constant: %s",
22571                               pulongest (DW_UNSND (&die->attrs[i])));
22572           break;
22573         case DW_FORM_sec_offset:
22574           fprintf_unfiltered (f, "section offset: %s",
22575                               pulongest (DW_UNSND (&die->attrs[i])));
22576           break;
22577         case DW_FORM_ref_sig8:
22578           fprintf_unfiltered (f, "signature: %s",
22579                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22580           break;
22581         case DW_FORM_string:
22582         case DW_FORM_strp:
22583         case DW_FORM_line_strp:
22584         case DW_FORM_GNU_str_index:
22585         case DW_FORM_GNU_strp_alt:
22586           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22587                    DW_STRING (&die->attrs[i])
22588                    ? DW_STRING (&die->attrs[i]) : "",
22589                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22590           break;
22591         case DW_FORM_flag:
22592           if (DW_UNSND (&die->attrs[i]))
22593             fprintf_unfiltered (f, "flag: TRUE");
22594           else
22595             fprintf_unfiltered (f, "flag: FALSE");
22596           break;
22597         case DW_FORM_flag_present:
22598           fprintf_unfiltered (f, "flag: TRUE");
22599           break;
22600         case DW_FORM_indirect:
22601           /* The reader will have reduced the indirect form to
22602              the "base form" so this form should not occur.  */
22603           fprintf_unfiltered (f, 
22604                               "unexpected attribute form: DW_FORM_indirect");
22605           break;
22606         case DW_FORM_implicit_const:
22607           fprintf_unfiltered (f, "constant: %s",
22608                               plongest (DW_SND (&die->attrs[i])));
22609           break;
22610         default:
22611           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22612                    die->attrs[i].form);
22613           break;
22614         }
22615       fprintf_unfiltered (f, "\n");
22616     }
22617 }
22618
22619 static void
22620 dump_die_for_error (struct die_info *die)
22621 {
22622   dump_die_shallow (gdb_stderr, 0, die);
22623 }
22624
22625 static void
22626 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22627 {
22628   int indent = level * 4;
22629
22630   gdb_assert (die != NULL);
22631
22632   if (level >= max_level)
22633     return;
22634
22635   dump_die_shallow (f, indent, die);
22636
22637   if (die->child != NULL)
22638     {
22639       print_spaces (indent, f);
22640       fprintf_unfiltered (f, "  Children:");
22641       if (level + 1 < max_level)
22642         {
22643           fprintf_unfiltered (f, "\n");
22644           dump_die_1 (f, level + 1, max_level, die->child);
22645         }
22646       else
22647         {
22648           fprintf_unfiltered (f,
22649                               " [not printed, max nesting level reached]\n");
22650         }
22651     }
22652
22653   if (die->sibling != NULL && level > 0)
22654     {
22655       dump_die_1 (f, level, max_level, die->sibling);
22656     }
22657 }
22658
22659 /* This is called from the pdie macro in gdbinit.in.
22660    It's not static so gcc will keep a copy callable from gdb.  */
22661
22662 void
22663 dump_die (struct die_info *die, int max_level)
22664 {
22665   dump_die_1 (gdb_stdlog, 0, max_level, die);
22666 }
22667
22668 static void
22669 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22670 {
22671   void **slot;
22672
22673   slot = htab_find_slot_with_hash (cu->die_hash, die,
22674                                    to_underlying (die->sect_off),
22675                                    INSERT);
22676
22677   *slot = die;
22678 }
22679
22680 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22681    required kind.  */
22682
22683 static sect_offset
22684 dwarf2_get_ref_die_offset (const struct attribute *attr)
22685 {
22686   if (attr_form_is_ref (attr))
22687     return (sect_offset) DW_UNSND (attr);
22688
22689   complaint (_("unsupported die ref attribute form: '%s'"),
22690              dwarf_form_name (attr->form));
22691   return {};
22692 }
22693
22694 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22695  * the value held by the attribute is not constant.  */
22696
22697 static LONGEST
22698 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22699 {
22700   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22701     return DW_SND (attr);
22702   else if (attr->form == DW_FORM_udata
22703            || attr->form == DW_FORM_data1
22704            || attr->form == DW_FORM_data2
22705            || attr->form == DW_FORM_data4
22706            || attr->form == DW_FORM_data8)
22707     return DW_UNSND (attr);
22708   else
22709     {
22710       /* For DW_FORM_data16 see attr_form_is_constant.  */
22711       complaint (_("Attribute value is not a constant (%s)"),
22712                  dwarf_form_name (attr->form));
22713       return default_value;
22714     }
22715 }
22716
22717 /* Follow reference or signature attribute ATTR of SRC_DIE.
22718    On entry *REF_CU is the CU of SRC_DIE.
22719    On exit *REF_CU is the CU of the result.  */
22720
22721 static struct die_info *
22722 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22723                        struct dwarf2_cu **ref_cu)
22724 {
22725   struct die_info *die;
22726
22727   if (attr_form_is_ref (attr))
22728     die = follow_die_ref (src_die, attr, ref_cu);
22729   else if (attr->form == DW_FORM_ref_sig8)
22730     die = follow_die_sig (src_die, attr, ref_cu);
22731   else
22732     {
22733       dump_die_for_error (src_die);
22734       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22735              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22736     }
22737
22738   return die;
22739 }
22740
22741 /* Follow reference OFFSET.
22742    On entry *REF_CU is the CU of the source die referencing OFFSET.
22743    On exit *REF_CU is the CU of the result.
22744    Returns NULL if OFFSET is invalid.  */
22745
22746 static struct die_info *
22747 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22748                    struct dwarf2_cu **ref_cu)
22749 {
22750   struct die_info temp_die;
22751   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22752   struct dwarf2_per_objfile *dwarf2_per_objfile
22753     = cu->per_cu->dwarf2_per_objfile;
22754
22755   gdb_assert (cu->per_cu != NULL);
22756
22757   target_cu = cu;
22758
22759   if (cu->per_cu->is_debug_types)
22760     {
22761       /* .debug_types CUs cannot reference anything outside their CU.
22762          If they need to, they have to reference a signatured type via
22763          DW_FORM_ref_sig8.  */
22764       if (!offset_in_cu_p (&cu->header, sect_off))
22765         return NULL;
22766     }
22767   else if (offset_in_dwz != cu->per_cu->is_dwz
22768            || !offset_in_cu_p (&cu->header, sect_off))
22769     {
22770       struct dwarf2_per_cu_data *per_cu;
22771
22772       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22773                                                  dwarf2_per_objfile);
22774
22775       /* If necessary, add it to the queue and load its DIEs.  */
22776       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22777         load_full_comp_unit (per_cu, false, cu->language);
22778
22779       target_cu = per_cu->cu;
22780     }
22781   else if (cu->dies == NULL)
22782     {
22783       /* We're loading full DIEs during partial symbol reading.  */
22784       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22785       load_full_comp_unit (cu->per_cu, false, language_minimal);
22786     }
22787
22788   *ref_cu = target_cu;
22789   temp_die.sect_off = sect_off;
22790   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22791                                                   &temp_die,
22792                                                   to_underlying (sect_off));
22793 }
22794
22795 /* Follow reference attribute ATTR of SRC_DIE.
22796    On entry *REF_CU is the CU of SRC_DIE.
22797    On exit *REF_CU is the CU of the result.  */
22798
22799 static struct die_info *
22800 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22801                 struct dwarf2_cu **ref_cu)
22802 {
22803   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22804   struct dwarf2_cu *cu = *ref_cu;
22805   struct die_info *die;
22806
22807   die = follow_die_offset (sect_off,
22808                            (attr->form == DW_FORM_GNU_ref_alt
22809                             || cu->per_cu->is_dwz),
22810                            ref_cu);
22811   if (!die)
22812     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22813            "at %s [in module %s]"),
22814            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22815            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22816
22817   return die;
22818 }
22819
22820 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22821    Returned value is intended for DW_OP_call*.  Returned
22822    dwarf2_locexpr_baton->data has lifetime of
22823    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22824
22825 struct dwarf2_locexpr_baton
22826 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22827                                struct dwarf2_per_cu_data *per_cu,
22828                                CORE_ADDR (*get_frame_pc) (void *baton),
22829                                void *baton)
22830 {
22831   struct dwarf2_cu *cu;
22832   struct die_info *die;
22833   struct attribute *attr;
22834   struct dwarf2_locexpr_baton retval;
22835   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22836   struct objfile *objfile = dwarf2_per_objfile->objfile;
22837
22838   if (per_cu->cu == NULL)
22839     load_cu (per_cu, false);
22840   cu = per_cu->cu;
22841   if (cu == NULL)
22842     {
22843       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22844          Instead just throw an error, not much else we can do.  */
22845       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22846              sect_offset_str (sect_off), objfile_name (objfile));
22847     }
22848
22849   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22850   if (!die)
22851     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22852            sect_offset_str (sect_off), objfile_name (objfile));
22853
22854   attr = dwarf2_attr (die, DW_AT_location, cu);
22855   if (!attr)
22856     {
22857       /* DWARF: "If there is no such attribute, then there is no effect.".
22858          DATA is ignored if SIZE is 0.  */
22859
22860       retval.data = NULL;
22861       retval.size = 0;
22862     }
22863   else if (attr_form_is_section_offset (attr))
22864     {
22865       struct dwarf2_loclist_baton loclist_baton;
22866       CORE_ADDR pc = (*get_frame_pc) (baton);
22867       size_t size;
22868
22869       fill_in_loclist_baton (cu, &loclist_baton, attr);
22870
22871       retval.data = dwarf2_find_location_expression (&loclist_baton,
22872                                                      &size, pc);
22873       retval.size = size;
22874     }
22875   else
22876     {
22877       if (!attr_form_is_block (attr))
22878         error (_("Dwarf Error: DIE at %s referenced in module %s "
22879                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22880                sect_offset_str (sect_off), objfile_name (objfile));
22881
22882       retval.data = DW_BLOCK (attr)->data;
22883       retval.size = DW_BLOCK (attr)->size;
22884     }
22885   retval.per_cu = cu->per_cu;
22886
22887   age_cached_comp_units (dwarf2_per_objfile);
22888
22889   return retval;
22890 }
22891
22892 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22893    offset.  */
22894
22895 struct dwarf2_locexpr_baton
22896 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22897                              struct dwarf2_per_cu_data *per_cu,
22898                              CORE_ADDR (*get_frame_pc) (void *baton),
22899                              void *baton)
22900 {
22901   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22902
22903   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22904 }
22905
22906 /* Write a constant of a given type as target-ordered bytes into
22907    OBSTACK.  */
22908
22909 static const gdb_byte *
22910 write_constant_as_bytes (struct obstack *obstack,
22911                          enum bfd_endian byte_order,
22912                          struct type *type,
22913                          ULONGEST value,
22914                          LONGEST *len)
22915 {
22916   gdb_byte *result;
22917
22918   *len = TYPE_LENGTH (type);
22919   result = (gdb_byte *) obstack_alloc (obstack, *len);
22920   store_unsigned_integer (result, *len, byte_order, value);
22921
22922   return result;
22923 }
22924
22925 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22926    pointer to the constant bytes and set LEN to the length of the
22927    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22928    does not have a DW_AT_const_value, return NULL.  */
22929
22930 const gdb_byte *
22931 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22932                              struct dwarf2_per_cu_data *per_cu,
22933                              struct obstack *obstack,
22934                              LONGEST *len)
22935 {
22936   struct dwarf2_cu *cu;
22937   struct die_info *die;
22938   struct attribute *attr;
22939   const gdb_byte *result = NULL;
22940   struct type *type;
22941   LONGEST value;
22942   enum bfd_endian byte_order;
22943   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22944
22945   if (per_cu->cu == NULL)
22946     load_cu (per_cu, false);
22947   cu = per_cu->cu;
22948   if (cu == NULL)
22949     {
22950       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22951          Instead just throw an error, not much else we can do.  */
22952       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22953              sect_offset_str (sect_off), objfile_name (objfile));
22954     }
22955
22956   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22957   if (!die)
22958     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22959            sect_offset_str (sect_off), objfile_name (objfile));
22960
22961   attr = dwarf2_attr (die, DW_AT_const_value, cu);
22962   if (attr == NULL)
22963     return NULL;
22964
22965   byte_order = (bfd_big_endian (objfile->obfd)
22966                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22967
22968   switch (attr->form)
22969     {
22970     case DW_FORM_addr:
22971     case DW_FORM_GNU_addr_index:
22972       {
22973         gdb_byte *tem;
22974
22975         *len = cu->header.addr_size;
22976         tem = (gdb_byte *) obstack_alloc (obstack, *len);
22977         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
22978         result = tem;
22979       }
22980       break;
22981     case DW_FORM_string:
22982     case DW_FORM_strp:
22983     case DW_FORM_GNU_str_index:
22984     case DW_FORM_GNU_strp_alt:
22985       /* DW_STRING is already allocated on the objfile obstack, point
22986          directly to it.  */
22987       result = (const gdb_byte *) DW_STRING (attr);
22988       *len = strlen (DW_STRING (attr));
22989       break;
22990     case DW_FORM_block1:
22991     case DW_FORM_block2:
22992     case DW_FORM_block4:
22993     case DW_FORM_block:
22994     case DW_FORM_exprloc:
22995     case DW_FORM_data16:
22996       result = DW_BLOCK (attr)->data;
22997       *len = DW_BLOCK (attr)->size;
22998       break;
22999
23000       /* The DW_AT_const_value attributes are supposed to carry the
23001          symbol's value "represented as it would be on the target
23002          architecture."  By the time we get here, it's already been
23003          converted to host endianness, so we just need to sign- or
23004          zero-extend it as appropriate.  */
23005     case DW_FORM_data1:
23006       type = die_type (die, cu);
23007       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23008       if (result == NULL)
23009         result = write_constant_as_bytes (obstack, byte_order,
23010                                           type, value, len);
23011       break;
23012     case DW_FORM_data2:
23013       type = die_type (die, cu);
23014       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23015       if (result == NULL)
23016         result = write_constant_as_bytes (obstack, byte_order,
23017                                           type, value, len);
23018       break;
23019     case DW_FORM_data4:
23020       type = die_type (die, cu);
23021       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23022       if (result == NULL)
23023         result = write_constant_as_bytes (obstack, byte_order,
23024                                           type, value, len);
23025       break;
23026     case DW_FORM_data8:
23027       type = die_type (die, cu);
23028       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23029       if (result == NULL)
23030         result = write_constant_as_bytes (obstack, byte_order,
23031                                           type, value, len);
23032       break;
23033
23034     case DW_FORM_sdata:
23035     case DW_FORM_implicit_const:
23036       type = die_type (die, cu);
23037       result = write_constant_as_bytes (obstack, byte_order,
23038                                         type, DW_SND (attr), len);
23039       break;
23040
23041     case DW_FORM_udata:
23042       type = die_type (die, cu);
23043       result = write_constant_as_bytes (obstack, byte_order,
23044                                         type, DW_UNSND (attr), len);
23045       break;
23046
23047     default:
23048       complaint (_("unsupported const value attribute form: '%s'"),
23049                  dwarf_form_name (attr->form));
23050       break;
23051     }
23052
23053   return result;
23054 }
23055
23056 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23057    valid type for this die is found.  */
23058
23059 struct type *
23060 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23061                                 struct dwarf2_per_cu_data *per_cu)
23062 {
23063   struct dwarf2_cu *cu;
23064   struct die_info *die;
23065
23066   if (per_cu->cu == NULL)
23067     load_cu (per_cu, false);
23068   cu = per_cu->cu;
23069   if (!cu)
23070     return NULL;
23071
23072   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23073   if (!die)
23074     return NULL;
23075
23076   return die_type (die, cu);
23077 }
23078
23079 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23080    PER_CU.  */
23081
23082 struct type *
23083 dwarf2_get_die_type (cu_offset die_offset,
23084                      struct dwarf2_per_cu_data *per_cu)
23085 {
23086   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23087   return get_die_type_at_offset (die_offset_sect, per_cu);
23088 }
23089
23090 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23091    On entry *REF_CU is the CU of SRC_DIE.
23092    On exit *REF_CU is the CU of the result.
23093    Returns NULL if the referenced DIE isn't found.  */
23094
23095 static struct die_info *
23096 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23097                   struct dwarf2_cu **ref_cu)
23098 {
23099   struct die_info temp_die;
23100   struct dwarf2_cu *sig_cu;
23101   struct die_info *die;
23102
23103   /* While it might be nice to assert sig_type->type == NULL here,
23104      we can get here for DW_AT_imported_declaration where we need
23105      the DIE not the type.  */
23106
23107   /* If necessary, add it to the queue and load its DIEs.  */
23108
23109   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23110     read_signatured_type (sig_type);
23111
23112   sig_cu = sig_type->per_cu.cu;
23113   gdb_assert (sig_cu != NULL);
23114   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23115   temp_die.sect_off = sig_type->type_offset_in_section;
23116   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23117                                                  to_underlying (temp_die.sect_off));
23118   if (die)
23119     {
23120       struct dwarf2_per_objfile *dwarf2_per_objfile
23121         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23122
23123       /* For .gdb_index version 7 keep track of included TUs.
23124          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23125       if (dwarf2_per_objfile->index_table != NULL
23126           && dwarf2_per_objfile->index_table->version <= 7)
23127         {
23128           VEC_safe_push (dwarf2_per_cu_ptr,
23129                          (*ref_cu)->per_cu->imported_symtabs,
23130                          sig_cu->per_cu);
23131         }
23132
23133       *ref_cu = sig_cu;
23134       return die;
23135     }
23136
23137   return NULL;
23138 }
23139
23140 /* Follow signatured type referenced by ATTR in SRC_DIE.
23141    On entry *REF_CU is the CU of SRC_DIE.
23142    On exit *REF_CU is the CU of the result.
23143    The result is the DIE of the type.
23144    If the referenced type cannot be found an error is thrown.  */
23145
23146 static struct die_info *
23147 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23148                 struct dwarf2_cu **ref_cu)
23149 {
23150   ULONGEST signature = DW_SIGNATURE (attr);
23151   struct signatured_type *sig_type;
23152   struct die_info *die;
23153
23154   gdb_assert (attr->form == DW_FORM_ref_sig8);
23155
23156   sig_type = lookup_signatured_type (*ref_cu, signature);
23157   /* sig_type will be NULL if the signatured type is missing from
23158      the debug info.  */
23159   if (sig_type == NULL)
23160     {
23161       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23162                " from DIE at %s [in module %s]"),
23163              hex_string (signature), sect_offset_str (src_die->sect_off),
23164              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23165     }
23166
23167   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23168   if (die == NULL)
23169     {
23170       dump_die_for_error (src_die);
23171       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23172                " from DIE at %s [in module %s]"),
23173              hex_string (signature), sect_offset_str (src_die->sect_off),
23174              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23175     }
23176
23177   return die;
23178 }
23179
23180 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23181    reading in and processing the type unit if necessary.  */
23182
23183 static struct type *
23184 get_signatured_type (struct die_info *die, ULONGEST signature,
23185                      struct dwarf2_cu *cu)
23186 {
23187   struct dwarf2_per_objfile *dwarf2_per_objfile
23188     = cu->per_cu->dwarf2_per_objfile;
23189   struct signatured_type *sig_type;
23190   struct dwarf2_cu *type_cu;
23191   struct die_info *type_die;
23192   struct type *type;
23193
23194   sig_type = lookup_signatured_type (cu, signature);
23195   /* sig_type will be NULL if the signatured type is missing from
23196      the debug info.  */
23197   if (sig_type == NULL)
23198     {
23199       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23200                    " from DIE at %s [in module %s]"),
23201                  hex_string (signature), sect_offset_str (die->sect_off),
23202                  objfile_name (dwarf2_per_objfile->objfile));
23203       return build_error_marker_type (cu, die);
23204     }
23205
23206   /* If we already know the type we're done.  */
23207   if (sig_type->type != NULL)
23208     return sig_type->type;
23209
23210   type_cu = cu;
23211   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23212   if (type_die != NULL)
23213     {
23214       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23215          is created.  This is important, for example, because for c++ classes
23216          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23217       type = read_type_die (type_die, type_cu);
23218       if (type == NULL)
23219         {
23220           complaint (_("Dwarf Error: Cannot build signatured type %s"
23221                        " referenced from DIE at %s [in module %s]"),
23222                      hex_string (signature), sect_offset_str (die->sect_off),
23223                      objfile_name (dwarf2_per_objfile->objfile));
23224           type = build_error_marker_type (cu, die);
23225         }
23226     }
23227   else
23228     {
23229       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23230                    " from DIE at %s [in module %s]"),
23231                  hex_string (signature), sect_offset_str (die->sect_off),
23232                  objfile_name (dwarf2_per_objfile->objfile));
23233       type = build_error_marker_type (cu, die);
23234     }
23235   sig_type->type = type;
23236
23237   return type;
23238 }
23239
23240 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23241    reading in and processing the type unit if necessary.  */
23242
23243 static struct type *
23244 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23245                           struct dwarf2_cu *cu) /* ARI: editCase function */
23246 {
23247   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23248   if (attr_form_is_ref (attr))
23249     {
23250       struct dwarf2_cu *type_cu = cu;
23251       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23252
23253       return read_type_die (type_die, type_cu);
23254     }
23255   else if (attr->form == DW_FORM_ref_sig8)
23256     {
23257       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23258     }
23259   else
23260     {
23261       struct dwarf2_per_objfile *dwarf2_per_objfile
23262         = cu->per_cu->dwarf2_per_objfile;
23263
23264       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23265                    " at %s [in module %s]"),
23266                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23267                  objfile_name (dwarf2_per_objfile->objfile));
23268       return build_error_marker_type (cu, die);
23269     }
23270 }
23271
23272 /* Load the DIEs associated with type unit PER_CU into memory.  */
23273
23274 static void
23275 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23276 {
23277   struct signatured_type *sig_type;
23278
23279   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23280   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23281
23282   /* We have the per_cu, but we need the signatured_type.
23283      Fortunately this is an easy translation.  */
23284   gdb_assert (per_cu->is_debug_types);
23285   sig_type = (struct signatured_type *) per_cu;
23286
23287   gdb_assert (per_cu->cu == NULL);
23288
23289   read_signatured_type (sig_type);
23290
23291   gdb_assert (per_cu->cu != NULL);
23292 }
23293
23294 /* die_reader_func for read_signatured_type.
23295    This is identical to load_full_comp_unit_reader,
23296    but is kept separate for now.  */
23297
23298 static void
23299 read_signatured_type_reader (const struct die_reader_specs *reader,
23300                              const gdb_byte *info_ptr,
23301                              struct die_info *comp_unit_die,
23302                              int has_children,
23303                              void *data)
23304 {
23305   struct dwarf2_cu *cu = reader->cu;
23306
23307   gdb_assert (cu->die_hash == NULL);
23308   cu->die_hash =
23309     htab_create_alloc_ex (cu->header.length / 12,
23310                           die_hash,
23311                           die_eq,
23312                           NULL,
23313                           &cu->comp_unit_obstack,
23314                           hashtab_obstack_allocate,
23315                           dummy_obstack_deallocate);
23316
23317   if (has_children)
23318     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23319                                                   &info_ptr, comp_unit_die);
23320   cu->dies = comp_unit_die;
23321   /* comp_unit_die is not stored in die_hash, no need.  */
23322
23323   /* We try not to read any attributes in this function, because not
23324      all CUs needed for references have been loaded yet, and symbol
23325      table processing isn't initialized.  But we have to set the CU language,
23326      or we won't be able to build types correctly.
23327      Similarly, if we do not read the producer, we can not apply
23328      producer-specific interpretation.  */
23329   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23330 }
23331
23332 /* Read in a signatured type and build its CU and DIEs.
23333    If the type is a stub for the real type in a DWO file,
23334    read in the real type from the DWO file as well.  */
23335
23336 static void
23337 read_signatured_type (struct signatured_type *sig_type)
23338 {
23339   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23340
23341   gdb_assert (per_cu->is_debug_types);
23342   gdb_assert (per_cu->cu == NULL);
23343
23344   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23345                            read_signatured_type_reader, NULL);
23346   sig_type->per_cu.tu_read = 1;
23347 }
23348
23349 /* Decode simple location descriptions.
23350    Given a pointer to a dwarf block that defines a location, compute
23351    the location and return the value.
23352
23353    NOTE drow/2003-11-18: This function is called in two situations
23354    now: for the address of static or global variables (partial symbols
23355    only) and for offsets into structures which are expected to be
23356    (more or less) constant.  The partial symbol case should go away,
23357    and only the constant case should remain.  That will let this
23358    function complain more accurately.  A few special modes are allowed
23359    without complaint for global variables (for instance, global
23360    register values and thread-local values).
23361
23362    A location description containing no operations indicates that the
23363    object is optimized out.  The return value is 0 for that case.
23364    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23365    callers will only want a very basic result and this can become a
23366    complaint.
23367
23368    Note that stack[0] is unused except as a default error return.  */
23369
23370 static CORE_ADDR
23371 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23372 {
23373   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23374   size_t i;
23375   size_t size = blk->size;
23376   const gdb_byte *data = blk->data;
23377   CORE_ADDR stack[64];
23378   int stacki;
23379   unsigned int bytes_read, unsnd;
23380   gdb_byte op;
23381
23382   i = 0;
23383   stacki = 0;
23384   stack[stacki] = 0;
23385   stack[++stacki] = 0;
23386
23387   while (i < size)
23388     {
23389       op = data[i++];
23390       switch (op)
23391         {
23392         case DW_OP_lit0:
23393         case DW_OP_lit1:
23394         case DW_OP_lit2:
23395         case DW_OP_lit3:
23396         case DW_OP_lit4:
23397         case DW_OP_lit5:
23398         case DW_OP_lit6:
23399         case DW_OP_lit7:
23400         case DW_OP_lit8:
23401         case DW_OP_lit9:
23402         case DW_OP_lit10:
23403         case DW_OP_lit11:
23404         case DW_OP_lit12:
23405         case DW_OP_lit13:
23406         case DW_OP_lit14:
23407         case DW_OP_lit15:
23408         case DW_OP_lit16:
23409         case DW_OP_lit17:
23410         case DW_OP_lit18:
23411         case DW_OP_lit19:
23412         case DW_OP_lit20:
23413         case DW_OP_lit21:
23414         case DW_OP_lit22:
23415         case DW_OP_lit23:
23416         case DW_OP_lit24:
23417         case DW_OP_lit25:
23418         case DW_OP_lit26:
23419         case DW_OP_lit27:
23420         case DW_OP_lit28:
23421         case DW_OP_lit29:
23422         case DW_OP_lit30:
23423         case DW_OP_lit31:
23424           stack[++stacki] = op - DW_OP_lit0;
23425           break;
23426
23427         case DW_OP_reg0:
23428         case DW_OP_reg1:
23429         case DW_OP_reg2:
23430         case DW_OP_reg3:
23431         case DW_OP_reg4:
23432         case DW_OP_reg5:
23433         case DW_OP_reg6:
23434         case DW_OP_reg7:
23435         case DW_OP_reg8:
23436         case DW_OP_reg9:
23437         case DW_OP_reg10:
23438         case DW_OP_reg11:
23439         case DW_OP_reg12:
23440         case DW_OP_reg13:
23441         case DW_OP_reg14:
23442         case DW_OP_reg15:
23443         case DW_OP_reg16:
23444         case DW_OP_reg17:
23445         case DW_OP_reg18:
23446         case DW_OP_reg19:
23447         case DW_OP_reg20:
23448         case DW_OP_reg21:
23449         case DW_OP_reg22:
23450         case DW_OP_reg23:
23451         case DW_OP_reg24:
23452         case DW_OP_reg25:
23453         case DW_OP_reg26:
23454         case DW_OP_reg27:
23455         case DW_OP_reg28:
23456         case DW_OP_reg29:
23457         case DW_OP_reg30:
23458         case DW_OP_reg31:
23459           stack[++stacki] = op - DW_OP_reg0;
23460           if (i < size)
23461             dwarf2_complex_location_expr_complaint ();
23462           break;
23463
23464         case DW_OP_regx:
23465           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23466           i += bytes_read;
23467           stack[++stacki] = unsnd;
23468           if (i < size)
23469             dwarf2_complex_location_expr_complaint ();
23470           break;
23471
23472         case DW_OP_addr:
23473           stack[++stacki] = read_address (objfile->obfd, &data[i],
23474                                           cu, &bytes_read);
23475           i += bytes_read;
23476           break;
23477
23478         case DW_OP_const1u:
23479           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23480           i += 1;
23481           break;
23482
23483         case DW_OP_const1s:
23484           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23485           i += 1;
23486           break;
23487
23488         case DW_OP_const2u:
23489           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23490           i += 2;
23491           break;
23492
23493         case DW_OP_const2s:
23494           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23495           i += 2;
23496           break;
23497
23498         case DW_OP_const4u:
23499           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23500           i += 4;
23501           break;
23502
23503         case DW_OP_const4s:
23504           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23505           i += 4;
23506           break;
23507
23508         case DW_OP_const8u:
23509           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23510           i += 8;
23511           break;
23512
23513         case DW_OP_constu:
23514           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23515                                                   &bytes_read);
23516           i += bytes_read;
23517           break;
23518
23519         case DW_OP_consts:
23520           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23521           i += bytes_read;
23522           break;
23523
23524         case DW_OP_dup:
23525           stack[stacki + 1] = stack[stacki];
23526           stacki++;
23527           break;
23528
23529         case DW_OP_plus:
23530           stack[stacki - 1] += stack[stacki];
23531           stacki--;
23532           break;
23533
23534         case DW_OP_plus_uconst:
23535           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23536                                                  &bytes_read);
23537           i += bytes_read;
23538           break;
23539
23540         case DW_OP_minus:
23541           stack[stacki - 1] -= stack[stacki];
23542           stacki--;
23543           break;
23544
23545         case DW_OP_deref:
23546           /* If we're not the last op, then we definitely can't encode
23547              this using GDB's address_class enum.  This is valid for partial
23548              global symbols, although the variable's address will be bogus
23549              in the psymtab.  */
23550           if (i < size)
23551             dwarf2_complex_location_expr_complaint ();
23552           break;
23553
23554         case DW_OP_GNU_push_tls_address:
23555         case DW_OP_form_tls_address:
23556           /* The top of the stack has the offset from the beginning
23557              of the thread control block at which the variable is located.  */
23558           /* Nothing should follow this operator, so the top of stack would
23559              be returned.  */
23560           /* This is valid for partial global symbols, but the variable's
23561              address will be bogus in the psymtab.  Make it always at least
23562              non-zero to not look as a variable garbage collected by linker
23563              which have DW_OP_addr 0.  */
23564           if (i < size)
23565             dwarf2_complex_location_expr_complaint ();
23566           stack[stacki]++;
23567           break;
23568
23569         case DW_OP_GNU_uninit:
23570           break;
23571
23572         case DW_OP_GNU_addr_index:
23573         case DW_OP_GNU_const_index:
23574           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23575                                                          &bytes_read);
23576           i += bytes_read;
23577           break;
23578
23579         default:
23580           {
23581             const char *name = get_DW_OP_name (op);
23582
23583             if (name)
23584               complaint (_("unsupported stack op: '%s'"),
23585                          name);
23586             else
23587               complaint (_("unsupported stack op: '%02x'"),
23588                          op);
23589           }
23590
23591           return (stack[stacki]);
23592         }
23593
23594       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23595          outside of the allocated space.  Also enforce minimum>0.  */
23596       if (stacki >= ARRAY_SIZE (stack) - 1)
23597         {
23598           complaint (_("location description stack overflow"));
23599           return 0;
23600         }
23601
23602       if (stacki <= 0)
23603         {
23604           complaint (_("location description stack underflow"));
23605           return 0;
23606         }
23607     }
23608   return (stack[stacki]);
23609 }
23610
23611 /* memory allocation interface */
23612
23613 static struct dwarf_block *
23614 dwarf_alloc_block (struct dwarf2_cu *cu)
23615 {
23616   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23617 }
23618
23619 static struct die_info *
23620 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23621 {
23622   struct die_info *die;
23623   size_t size = sizeof (struct die_info);
23624
23625   if (num_attrs > 1)
23626     size += (num_attrs - 1) * sizeof (struct attribute);
23627
23628   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23629   memset (die, 0, sizeof (struct die_info));
23630   return (die);
23631 }
23632
23633 \f
23634 /* Macro support.  */
23635
23636 /* Return file name relative to the compilation directory of file number I in
23637    *LH's file name table.  The result is allocated using xmalloc; the caller is
23638    responsible for freeing it.  */
23639
23640 static char *
23641 file_file_name (int file, struct line_header *lh)
23642 {
23643   /* Is the file number a valid index into the line header's file name
23644      table?  Remember that file numbers start with one, not zero.  */
23645   if (1 <= file && file <= lh->file_names.size ())
23646     {
23647       const file_entry &fe = lh->file_names[file - 1];
23648
23649       if (!IS_ABSOLUTE_PATH (fe.name))
23650         {
23651           const char *dir = fe.include_dir (lh);
23652           if (dir != NULL)
23653             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23654         }
23655       return xstrdup (fe.name);
23656     }
23657   else
23658     {
23659       /* The compiler produced a bogus file number.  We can at least
23660          record the macro definitions made in the file, even if we
23661          won't be able to find the file by name.  */
23662       char fake_name[80];
23663
23664       xsnprintf (fake_name, sizeof (fake_name),
23665                  "<bad macro file number %d>", file);
23666
23667       complaint (_("bad file number in macro information (%d)"),
23668                  file);
23669
23670       return xstrdup (fake_name);
23671     }
23672 }
23673
23674 /* Return the full name of file number I in *LH's file name table.
23675    Use COMP_DIR as the name of the current directory of the
23676    compilation.  The result is allocated using xmalloc; the caller is
23677    responsible for freeing it.  */
23678 static char *
23679 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23680 {
23681   /* Is the file number a valid index into the line header's file name
23682      table?  Remember that file numbers start with one, not zero.  */
23683   if (1 <= file && file <= lh->file_names.size ())
23684     {
23685       char *relative = file_file_name (file, lh);
23686
23687       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23688         return relative;
23689       return reconcat (relative, comp_dir, SLASH_STRING,
23690                        relative, (char *) NULL);
23691     }
23692   else
23693     return file_file_name (file, lh);
23694 }
23695
23696
23697 static struct macro_source_file *
23698 macro_start_file (int file, int line,
23699                   struct macro_source_file *current_file,
23700                   struct line_header *lh)
23701 {
23702   /* File name relative to the compilation directory of this source file.  */
23703   char *file_name = file_file_name (file, lh);
23704
23705   if (! current_file)
23706     {
23707       /* Note: We don't create a macro table for this compilation unit
23708          at all until we actually get a filename.  */
23709       struct macro_table *macro_table = get_macro_table ();
23710
23711       /* If we have no current file, then this must be the start_file
23712          directive for the compilation unit's main source file.  */
23713       current_file = macro_set_main (macro_table, file_name);
23714       macro_define_special (macro_table);
23715     }
23716   else
23717     current_file = macro_include (current_file, line, file_name);
23718
23719   xfree (file_name);
23720
23721   return current_file;
23722 }
23723
23724 static const char *
23725 consume_improper_spaces (const char *p, const char *body)
23726 {
23727   if (*p == ' ')
23728     {
23729       complaint (_("macro definition contains spaces "
23730                    "in formal argument list:\n`%s'"),
23731                  body);
23732
23733       while (*p == ' ')
23734         p++;
23735     }
23736
23737   return p;
23738 }
23739
23740
23741 static void
23742 parse_macro_definition (struct macro_source_file *file, int line,
23743                         const char *body)
23744 {
23745   const char *p;
23746
23747   /* The body string takes one of two forms.  For object-like macro
23748      definitions, it should be:
23749
23750         <macro name> " " <definition>
23751
23752      For function-like macro definitions, it should be:
23753
23754         <macro name> "() " <definition>
23755      or
23756         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23757
23758      Spaces may appear only where explicitly indicated, and in the
23759      <definition>.
23760
23761      The Dwarf 2 spec says that an object-like macro's name is always
23762      followed by a space, but versions of GCC around March 2002 omit
23763      the space when the macro's definition is the empty string.
23764
23765      The Dwarf 2 spec says that there should be no spaces between the
23766      formal arguments in a function-like macro's formal argument list,
23767      but versions of GCC around March 2002 include spaces after the
23768      commas.  */
23769
23770
23771   /* Find the extent of the macro name.  The macro name is terminated
23772      by either a space or null character (for an object-like macro) or
23773      an opening paren (for a function-like macro).  */
23774   for (p = body; *p; p++)
23775     if (*p == ' ' || *p == '(')
23776       break;
23777
23778   if (*p == ' ' || *p == '\0')
23779     {
23780       /* It's an object-like macro.  */
23781       int name_len = p - body;
23782       char *name = savestring (body, name_len);
23783       const char *replacement;
23784
23785       if (*p == ' ')
23786         replacement = body + name_len + 1;
23787       else
23788         {
23789           dwarf2_macro_malformed_definition_complaint (body);
23790           replacement = body + name_len;
23791         }
23792
23793       macro_define_object (file, line, name, replacement);
23794
23795       xfree (name);
23796     }
23797   else if (*p == '(')
23798     {
23799       /* It's a function-like macro.  */
23800       char *name = savestring (body, p - body);
23801       int argc = 0;
23802       int argv_size = 1;
23803       char **argv = XNEWVEC (char *, argv_size);
23804
23805       p++;
23806
23807       p = consume_improper_spaces (p, body);
23808
23809       /* Parse the formal argument list.  */
23810       while (*p && *p != ')')
23811         {
23812           /* Find the extent of the current argument name.  */
23813           const char *arg_start = p;
23814
23815           while (*p && *p != ',' && *p != ')' && *p != ' ')
23816             p++;
23817
23818           if (! *p || p == arg_start)
23819             dwarf2_macro_malformed_definition_complaint (body);
23820           else
23821             {
23822               /* Make sure argv has room for the new argument.  */
23823               if (argc >= argv_size)
23824                 {
23825                   argv_size *= 2;
23826                   argv = XRESIZEVEC (char *, argv, argv_size);
23827                 }
23828
23829               argv[argc++] = savestring (arg_start, p - arg_start);
23830             }
23831
23832           p = consume_improper_spaces (p, body);
23833
23834           /* Consume the comma, if present.  */
23835           if (*p == ',')
23836             {
23837               p++;
23838
23839               p = consume_improper_spaces (p, body);
23840             }
23841         }
23842
23843       if (*p == ')')
23844         {
23845           p++;
23846
23847           if (*p == ' ')
23848             /* Perfectly formed definition, no complaints.  */
23849             macro_define_function (file, line, name,
23850                                    argc, (const char **) argv,
23851                                    p + 1);
23852           else if (*p == '\0')
23853             {
23854               /* Complain, but do define it.  */
23855               dwarf2_macro_malformed_definition_complaint (body);
23856               macro_define_function (file, line, name,
23857                                      argc, (const char **) argv,
23858                                      p);
23859             }
23860           else
23861             /* Just complain.  */
23862             dwarf2_macro_malformed_definition_complaint (body);
23863         }
23864       else
23865         /* Just complain.  */
23866         dwarf2_macro_malformed_definition_complaint (body);
23867
23868       xfree (name);
23869       {
23870         int i;
23871
23872         for (i = 0; i < argc; i++)
23873           xfree (argv[i]);
23874       }
23875       xfree (argv);
23876     }
23877   else
23878     dwarf2_macro_malformed_definition_complaint (body);
23879 }
23880
23881 /* Skip some bytes from BYTES according to the form given in FORM.
23882    Returns the new pointer.  */
23883
23884 static const gdb_byte *
23885 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23886                  enum dwarf_form form,
23887                  unsigned int offset_size,
23888                  struct dwarf2_section_info *section)
23889 {
23890   unsigned int bytes_read;
23891
23892   switch (form)
23893     {
23894     case DW_FORM_data1:
23895     case DW_FORM_flag:
23896       ++bytes;
23897       break;
23898
23899     case DW_FORM_data2:
23900       bytes += 2;
23901       break;
23902
23903     case DW_FORM_data4:
23904       bytes += 4;
23905       break;
23906
23907     case DW_FORM_data8:
23908       bytes += 8;
23909       break;
23910
23911     case DW_FORM_data16:
23912       bytes += 16;
23913       break;
23914
23915     case DW_FORM_string:
23916       read_direct_string (abfd, bytes, &bytes_read);
23917       bytes += bytes_read;
23918       break;
23919
23920     case DW_FORM_sec_offset:
23921     case DW_FORM_strp:
23922     case DW_FORM_GNU_strp_alt:
23923       bytes += offset_size;
23924       break;
23925
23926     case DW_FORM_block:
23927       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23928       bytes += bytes_read;
23929       break;
23930
23931     case DW_FORM_block1:
23932       bytes += 1 + read_1_byte (abfd, bytes);
23933       break;
23934     case DW_FORM_block2:
23935       bytes += 2 + read_2_bytes (abfd, bytes);
23936       break;
23937     case DW_FORM_block4:
23938       bytes += 4 + read_4_bytes (abfd, bytes);
23939       break;
23940
23941     case DW_FORM_sdata:
23942     case DW_FORM_udata:
23943     case DW_FORM_GNU_addr_index:
23944     case DW_FORM_GNU_str_index:
23945       bytes = gdb_skip_leb128 (bytes, buffer_end);
23946       if (bytes == NULL)
23947         {
23948           dwarf2_section_buffer_overflow_complaint (section);
23949           return NULL;
23950         }
23951       break;
23952
23953     case DW_FORM_implicit_const:
23954       break;
23955
23956     default:
23957       {
23958         complaint (_("invalid form 0x%x in `%s'"),
23959                    form, get_section_name (section));
23960         return NULL;
23961       }
23962     }
23963
23964   return bytes;
23965 }
23966
23967 /* A helper for dwarf_decode_macros that handles skipping an unknown
23968    opcode.  Returns an updated pointer to the macro data buffer; or,
23969    on error, issues a complaint and returns NULL.  */
23970
23971 static const gdb_byte *
23972 skip_unknown_opcode (unsigned int opcode,
23973                      const gdb_byte **opcode_definitions,
23974                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
23975                      bfd *abfd,
23976                      unsigned int offset_size,
23977                      struct dwarf2_section_info *section)
23978 {
23979   unsigned int bytes_read, i;
23980   unsigned long arg;
23981   const gdb_byte *defn;
23982
23983   if (opcode_definitions[opcode] == NULL)
23984     {
23985       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
23986                  opcode);
23987       return NULL;
23988     }
23989
23990   defn = opcode_definitions[opcode];
23991   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
23992   defn += bytes_read;
23993
23994   for (i = 0; i < arg; ++i)
23995     {
23996       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
23997                                  (enum dwarf_form) defn[i], offset_size,
23998                                  section);
23999       if (mac_ptr == NULL)
24000         {
24001           /* skip_form_bytes already issued the complaint.  */
24002           return NULL;
24003         }
24004     }
24005
24006   return mac_ptr;
24007 }
24008
24009 /* A helper function which parses the header of a macro section.
24010    If the macro section is the extended (for now called "GNU") type,
24011    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24012    the header, or issues a complaint and returns NULL on error.  */
24013
24014 static const gdb_byte *
24015 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24016                           bfd *abfd,
24017                           const gdb_byte *mac_ptr,
24018                           unsigned int *offset_size,
24019                           int section_is_gnu)
24020 {
24021   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24022
24023   if (section_is_gnu)
24024     {
24025       unsigned int version, flags;
24026
24027       version = read_2_bytes (abfd, mac_ptr);
24028       if (version != 4 && version != 5)
24029         {
24030           complaint (_("unrecognized version `%d' in .debug_macro section"),
24031                      version);
24032           return NULL;
24033         }
24034       mac_ptr += 2;
24035
24036       flags = read_1_byte (abfd, mac_ptr);
24037       ++mac_ptr;
24038       *offset_size = (flags & 1) ? 8 : 4;
24039
24040       if ((flags & 2) != 0)
24041         /* We don't need the line table offset.  */
24042         mac_ptr += *offset_size;
24043
24044       /* Vendor opcode descriptions.  */
24045       if ((flags & 4) != 0)
24046         {
24047           unsigned int i, count;
24048
24049           count = read_1_byte (abfd, mac_ptr);
24050           ++mac_ptr;
24051           for (i = 0; i < count; ++i)
24052             {
24053               unsigned int opcode, bytes_read;
24054               unsigned long arg;
24055
24056               opcode = read_1_byte (abfd, mac_ptr);
24057               ++mac_ptr;
24058               opcode_definitions[opcode] = mac_ptr;
24059               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24060               mac_ptr += bytes_read;
24061               mac_ptr += arg;
24062             }
24063         }
24064     }
24065
24066   return mac_ptr;
24067 }
24068
24069 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24070    including DW_MACRO_import.  */
24071
24072 static void
24073 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24074                           bfd *abfd,
24075                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24076                           struct macro_source_file *current_file,
24077                           struct line_header *lh,
24078                           struct dwarf2_section_info *section,
24079                           int section_is_gnu, int section_is_dwz,
24080                           unsigned int offset_size,
24081                           htab_t include_hash)
24082 {
24083   struct objfile *objfile = dwarf2_per_objfile->objfile;
24084   enum dwarf_macro_record_type macinfo_type;
24085   int at_commandline;
24086   const gdb_byte *opcode_definitions[256];
24087
24088   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24089                                       &offset_size, section_is_gnu);
24090   if (mac_ptr == NULL)
24091     {
24092       /* We already issued a complaint.  */
24093       return;
24094     }
24095
24096   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24097      GDB is still reading the definitions from command line.  First
24098      DW_MACINFO_start_file will need to be ignored as it was already executed
24099      to create CURRENT_FILE for the main source holding also the command line
24100      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24101      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24102
24103   at_commandline = 1;
24104
24105   do
24106     {
24107       /* Do we at least have room for a macinfo type byte?  */
24108       if (mac_ptr >= mac_end)
24109         {
24110           dwarf2_section_buffer_overflow_complaint (section);
24111           break;
24112         }
24113
24114       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24115       mac_ptr++;
24116
24117       /* Note that we rely on the fact that the corresponding GNU and
24118          DWARF constants are the same.  */
24119       DIAGNOSTIC_PUSH
24120       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24121       switch (macinfo_type)
24122         {
24123           /* A zero macinfo type indicates the end of the macro
24124              information.  */
24125         case 0:
24126           break;
24127
24128         case DW_MACRO_define:
24129         case DW_MACRO_undef:
24130         case DW_MACRO_define_strp:
24131         case DW_MACRO_undef_strp:
24132         case DW_MACRO_define_sup:
24133         case DW_MACRO_undef_sup:
24134           {
24135             unsigned int bytes_read;
24136             int line;
24137             const char *body;
24138             int is_define;
24139
24140             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24141             mac_ptr += bytes_read;
24142
24143             if (macinfo_type == DW_MACRO_define
24144                 || macinfo_type == DW_MACRO_undef)
24145               {
24146                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24147                 mac_ptr += bytes_read;
24148               }
24149             else
24150               {
24151                 LONGEST str_offset;
24152
24153                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24154                 mac_ptr += offset_size;
24155
24156                 if (macinfo_type == DW_MACRO_define_sup
24157                     || macinfo_type == DW_MACRO_undef_sup
24158                     || section_is_dwz)
24159                   {
24160                     struct dwz_file *dwz
24161                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24162
24163                     body = read_indirect_string_from_dwz (objfile,
24164                                                           dwz, str_offset);
24165                   }
24166                 else
24167                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24168                                                          abfd, str_offset);
24169               }
24170
24171             is_define = (macinfo_type == DW_MACRO_define
24172                          || macinfo_type == DW_MACRO_define_strp
24173                          || macinfo_type == DW_MACRO_define_sup);
24174             if (! current_file)
24175               {
24176                 /* DWARF violation as no main source is present.  */
24177                 complaint (_("debug info with no main source gives macro %s "
24178                              "on line %d: %s"),
24179                            is_define ? _("definition") : _("undefinition"),
24180                            line, body);
24181                 break;
24182               }
24183             if ((line == 0 && !at_commandline)
24184                 || (line != 0 && at_commandline))
24185               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24186                          at_commandline ? _("command-line") : _("in-file"),
24187                          is_define ? _("definition") : _("undefinition"),
24188                          line == 0 ? _("zero") : _("non-zero"), line, body);
24189
24190             if (is_define)
24191               parse_macro_definition (current_file, line, body);
24192             else
24193               {
24194                 gdb_assert (macinfo_type == DW_MACRO_undef
24195                             || macinfo_type == DW_MACRO_undef_strp
24196                             || macinfo_type == DW_MACRO_undef_sup);
24197                 macro_undef (current_file, line, body);
24198               }
24199           }
24200           break;
24201
24202         case DW_MACRO_start_file:
24203           {
24204             unsigned int bytes_read;
24205             int line, file;
24206
24207             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24208             mac_ptr += bytes_read;
24209             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24210             mac_ptr += bytes_read;
24211
24212             if ((line == 0 && !at_commandline)
24213                 || (line != 0 && at_commandline))
24214               complaint (_("debug info gives source %d included "
24215                            "from %s at %s line %d"),
24216                          file, at_commandline ? _("command-line") : _("file"),
24217                          line == 0 ? _("zero") : _("non-zero"), line);
24218
24219             if (at_commandline)
24220               {
24221                 /* This DW_MACRO_start_file was executed in the
24222                    pass one.  */
24223                 at_commandline = 0;
24224               }
24225             else
24226               current_file = macro_start_file (file, line, current_file, lh);
24227           }
24228           break;
24229
24230         case DW_MACRO_end_file:
24231           if (! current_file)
24232             complaint (_("macro debug info has an unmatched "
24233                          "`close_file' directive"));
24234           else
24235             {
24236               current_file = current_file->included_by;
24237               if (! current_file)
24238                 {
24239                   enum dwarf_macro_record_type next_type;
24240
24241                   /* GCC circa March 2002 doesn't produce the zero
24242                      type byte marking the end of the compilation
24243                      unit.  Complain if it's not there, but exit no
24244                      matter what.  */
24245
24246                   /* Do we at least have room for a macinfo type byte?  */
24247                   if (mac_ptr >= mac_end)
24248                     {
24249                       dwarf2_section_buffer_overflow_complaint (section);
24250                       return;
24251                     }
24252
24253                   /* We don't increment mac_ptr here, so this is just
24254                      a look-ahead.  */
24255                   next_type
24256                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24257                                                                   mac_ptr);
24258                   if (next_type != 0)
24259                     complaint (_("no terminating 0-type entry for "
24260                                  "macros in `.debug_macinfo' section"));
24261
24262                   return;
24263                 }
24264             }
24265           break;
24266
24267         case DW_MACRO_import:
24268         case DW_MACRO_import_sup:
24269           {
24270             LONGEST offset;
24271             void **slot;
24272             bfd *include_bfd = abfd;
24273             struct dwarf2_section_info *include_section = section;
24274             const gdb_byte *include_mac_end = mac_end;
24275             int is_dwz = section_is_dwz;
24276             const gdb_byte *new_mac_ptr;
24277
24278             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24279             mac_ptr += offset_size;
24280
24281             if (macinfo_type == DW_MACRO_import_sup)
24282               {
24283                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24284
24285                 dwarf2_read_section (objfile, &dwz->macro);
24286
24287                 include_section = &dwz->macro;
24288                 include_bfd = get_section_bfd_owner (include_section);
24289                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24290                 is_dwz = 1;
24291               }
24292
24293             new_mac_ptr = include_section->buffer + offset;
24294             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24295
24296             if (*slot != NULL)
24297               {
24298                 /* This has actually happened; see
24299                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24300                 complaint (_("recursive DW_MACRO_import in "
24301                              ".debug_macro section"));
24302               }
24303             else
24304               {
24305                 *slot = (void *) new_mac_ptr;
24306
24307                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24308                                           include_bfd, new_mac_ptr,
24309                                           include_mac_end, current_file, lh,
24310                                           section, section_is_gnu, is_dwz,
24311                                           offset_size, include_hash);
24312
24313                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24314               }
24315           }
24316           break;
24317
24318         case DW_MACINFO_vendor_ext:
24319           if (!section_is_gnu)
24320             {
24321               unsigned int bytes_read;
24322
24323               /* This reads the constant, but since we don't recognize
24324                  any vendor extensions, we ignore it.  */
24325               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24326               mac_ptr += bytes_read;
24327               read_direct_string (abfd, mac_ptr, &bytes_read);
24328               mac_ptr += bytes_read;
24329
24330               /* We don't recognize any vendor extensions.  */
24331               break;
24332             }
24333           /* FALLTHROUGH */
24334
24335         default:
24336           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24337                                          mac_ptr, mac_end, abfd, offset_size,
24338                                          section);
24339           if (mac_ptr == NULL)
24340             return;
24341           break;
24342         }
24343       DIAGNOSTIC_POP
24344     } while (macinfo_type != 0);
24345 }
24346
24347 static void
24348 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24349                      int section_is_gnu)
24350 {
24351   struct dwarf2_per_objfile *dwarf2_per_objfile
24352     = cu->per_cu->dwarf2_per_objfile;
24353   struct objfile *objfile = dwarf2_per_objfile->objfile;
24354   struct line_header *lh = cu->line_header;
24355   bfd *abfd;
24356   const gdb_byte *mac_ptr, *mac_end;
24357   struct macro_source_file *current_file = 0;
24358   enum dwarf_macro_record_type macinfo_type;
24359   unsigned int offset_size = cu->header.offset_size;
24360   const gdb_byte *opcode_definitions[256];
24361   void **slot;
24362   struct dwarf2_section_info *section;
24363   const char *section_name;
24364
24365   if (cu->dwo_unit != NULL)
24366     {
24367       if (section_is_gnu)
24368         {
24369           section = &cu->dwo_unit->dwo_file->sections.macro;
24370           section_name = ".debug_macro.dwo";
24371         }
24372       else
24373         {
24374           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24375           section_name = ".debug_macinfo.dwo";
24376         }
24377     }
24378   else
24379     {
24380       if (section_is_gnu)
24381         {
24382           section = &dwarf2_per_objfile->macro;
24383           section_name = ".debug_macro";
24384         }
24385       else
24386         {
24387           section = &dwarf2_per_objfile->macinfo;
24388           section_name = ".debug_macinfo";
24389         }
24390     }
24391
24392   dwarf2_read_section (objfile, section);
24393   if (section->buffer == NULL)
24394     {
24395       complaint (_("missing %s section"), section_name);
24396       return;
24397     }
24398   abfd = get_section_bfd_owner (section);
24399
24400   /* First pass: Find the name of the base filename.
24401      This filename is needed in order to process all macros whose definition
24402      (or undefinition) comes from the command line.  These macros are defined
24403      before the first DW_MACINFO_start_file entry, and yet still need to be
24404      associated to the base file.
24405
24406      To determine the base file name, we scan the macro definitions until we
24407      reach the first DW_MACINFO_start_file entry.  We then initialize
24408      CURRENT_FILE accordingly so that any macro definition found before the
24409      first DW_MACINFO_start_file can still be associated to the base file.  */
24410
24411   mac_ptr = section->buffer + offset;
24412   mac_end = section->buffer + section->size;
24413
24414   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24415                                       &offset_size, section_is_gnu);
24416   if (mac_ptr == NULL)
24417     {
24418       /* We already issued a complaint.  */
24419       return;
24420     }
24421
24422   do
24423     {
24424       /* Do we at least have room for a macinfo type byte?  */
24425       if (mac_ptr >= mac_end)
24426         {
24427           /* Complaint is printed during the second pass as GDB will probably
24428              stop the first pass earlier upon finding
24429              DW_MACINFO_start_file.  */
24430           break;
24431         }
24432
24433       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24434       mac_ptr++;
24435
24436       /* Note that we rely on the fact that the corresponding GNU and
24437          DWARF constants are the same.  */
24438       DIAGNOSTIC_PUSH
24439       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24440       switch (macinfo_type)
24441         {
24442           /* A zero macinfo type indicates the end of the macro
24443              information.  */
24444         case 0:
24445           break;
24446
24447         case DW_MACRO_define:
24448         case DW_MACRO_undef:
24449           /* Only skip the data by MAC_PTR.  */
24450           {
24451             unsigned int bytes_read;
24452
24453             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24454             mac_ptr += bytes_read;
24455             read_direct_string (abfd, mac_ptr, &bytes_read);
24456             mac_ptr += bytes_read;
24457           }
24458           break;
24459
24460         case DW_MACRO_start_file:
24461           {
24462             unsigned int bytes_read;
24463             int line, file;
24464
24465             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24466             mac_ptr += bytes_read;
24467             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24468             mac_ptr += bytes_read;
24469
24470             current_file = macro_start_file (file, line, current_file, lh);
24471           }
24472           break;
24473
24474         case DW_MACRO_end_file:
24475           /* No data to skip by MAC_PTR.  */
24476           break;
24477
24478         case DW_MACRO_define_strp:
24479         case DW_MACRO_undef_strp:
24480         case DW_MACRO_define_sup:
24481         case DW_MACRO_undef_sup:
24482           {
24483             unsigned int bytes_read;
24484
24485             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24486             mac_ptr += bytes_read;
24487             mac_ptr += offset_size;
24488           }
24489           break;
24490
24491         case DW_MACRO_import:
24492         case DW_MACRO_import_sup:
24493           /* Note that, according to the spec, a transparent include
24494              chain cannot call DW_MACRO_start_file.  So, we can just
24495              skip this opcode.  */
24496           mac_ptr += offset_size;
24497           break;
24498
24499         case DW_MACINFO_vendor_ext:
24500           /* Only skip the data by MAC_PTR.  */
24501           if (!section_is_gnu)
24502             {
24503               unsigned int bytes_read;
24504
24505               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24506               mac_ptr += bytes_read;
24507               read_direct_string (abfd, mac_ptr, &bytes_read);
24508               mac_ptr += bytes_read;
24509             }
24510           /* FALLTHROUGH */
24511
24512         default:
24513           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24514                                          mac_ptr, mac_end, abfd, offset_size,
24515                                          section);
24516           if (mac_ptr == NULL)
24517             return;
24518           break;
24519         }
24520       DIAGNOSTIC_POP
24521     } while (macinfo_type != 0 && current_file == NULL);
24522
24523   /* Second pass: Process all entries.
24524
24525      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24526      command-line macro definitions/undefinitions.  This flag is unset when we
24527      reach the first DW_MACINFO_start_file entry.  */
24528
24529   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24530                                            htab_eq_pointer,
24531                                            NULL, xcalloc, xfree));
24532   mac_ptr = section->buffer + offset;
24533   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24534   *slot = (void *) mac_ptr;
24535   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24536                             abfd, mac_ptr, mac_end,
24537                             current_file, lh, section,
24538                             section_is_gnu, 0, offset_size,
24539                             include_hash.get ());
24540 }
24541
24542 /* Check if the attribute's form is a DW_FORM_block*
24543    if so return true else false.  */
24544
24545 static int
24546 attr_form_is_block (const struct attribute *attr)
24547 {
24548   return (attr == NULL ? 0 :
24549       attr->form == DW_FORM_block1
24550       || attr->form == DW_FORM_block2
24551       || attr->form == DW_FORM_block4
24552       || attr->form == DW_FORM_block
24553       || attr->form == DW_FORM_exprloc);
24554 }
24555
24556 /* Return non-zero if ATTR's value is a section offset --- classes
24557    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24558    You may use DW_UNSND (attr) to retrieve such offsets.
24559
24560    Section 7.5.4, "Attribute Encodings", explains that no attribute
24561    may have a value that belongs to more than one of these classes; it
24562    would be ambiguous if we did, because we use the same forms for all
24563    of them.  */
24564
24565 static int
24566 attr_form_is_section_offset (const struct attribute *attr)
24567 {
24568   return (attr->form == DW_FORM_data4
24569           || attr->form == DW_FORM_data8
24570           || attr->form == DW_FORM_sec_offset);
24571 }
24572
24573 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24574    zero otherwise.  When this function returns true, you can apply
24575    dwarf2_get_attr_constant_value to it.
24576
24577    However, note that for some attributes you must check
24578    attr_form_is_section_offset before using this test.  DW_FORM_data4
24579    and DW_FORM_data8 are members of both the constant class, and of
24580    the classes that contain offsets into other debug sections
24581    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24582    that, if an attribute's can be either a constant or one of the
24583    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24584    taken as section offsets, not constants.
24585
24586    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24587    cannot handle that.  */
24588
24589 static int
24590 attr_form_is_constant (const struct attribute *attr)
24591 {
24592   switch (attr->form)
24593     {
24594     case DW_FORM_sdata:
24595     case DW_FORM_udata:
24596     case DW_FORM_data1:
24597     case DW_FORM_data2:
24598     case DW_FORM_data4:
24599     case DW_FORM_data8:
24600     case DW_FORM_implicit_const:
24601       return 1;
24602     default:
24603       return 0;
24604     }
24605 }
24606
24607
24608 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24609    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24610
24611 static int
24612 attr_form_is_ref (const struct attribute *attr)
24613 {
24614   switch (attr->form)
24615     {
24616     case DW_FORM_ref_addr:
24617     case DW_FORM_ref1:
24618     case DW_FORM_ref2:
24619     case DW_FORM_ref4:
24620     case DW_FORM_ref8:
24621     case DW_FORM_ref_udata:
24622     case DW_FORM_GNU_ref_alt:
24623       return 1;
24624     default:
24625       return 0;
24626     }
24627 }
24628
24629 /* Return the .debug_loc section to use for CU.
24630    For DWO files use .debug_loc.dwo.  */
24631
24632 static struct dwarf2_section_info *
24633 cu_debug_loc_section (struct dwarf2_cu *cu)
24634 {
24635   struct dwarf2_per_objfile *dwarf2_per_objfile
24636     = cu->per_cu->dwarf2_per_objfile;
24637
24638   if (cu->dwo_unit)
24639     {
24640       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24641       
24642       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24643     }
24644   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24645                                   : &dwarf2_per_objfile->loc);
24646 }
24647
24648 /* A helper function that fills in a dwarf2_loclist_baton.  */
24649
24650 static void
24651 fill_in_loclist_baton (struct dwarf2_cu *cu,
24652                        struct dwarf2_loclist_baton *baton,
24653                        const struct attribute *attr)
24654 {
24655   struct dwarf2_per_objfile *dwarf2_per_objfile
24656     = cu->per_cu->dwarf2_per_objfile;
24657   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24658
24659   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24660
24661   baton->per_cu = cu->per_cu;
24662   gdb_assert (baton->per_cu);
24663   /* We don't know how long the location list is, but make sure we
24664      don't run off the edge of the section.  */
24665   baton->size = section->size - DW_UNSND (attr);
24666   baton->data = section->buffer + DW_UNSND (attr);
24667   baton->base_address = cu->base_address;
24668   baton->from_dwo = cu->dwo_unit != NULL;
24669 }
24670
24671 static void
24672 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24673                              struct dwarf2_cu *cu, int is_block)
24674 {
24675   struct dwarf2_per_objfile *dwarf2_per_objfile
24676     = cu->per_cu->dwarf2_per_objfile;
24677   struct objfile *objfile = dwarf2_per_objfile->objfile;
24678   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24679
24680   if (attr_form_is_section_offset (attr)
24681       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24682          the section.  If so, fall through to the complaint in the
24683          other branch.  */
24684       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24685     {
24686       struct dwarf2_loclist_baton *baton;
24687
24688       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24689
24690       fill_in_loclist_baton (cu, baton, attr);
24691
24692       if (cu->base_known == 0)
24693         complaint (_("Location list used without "
24694                      "specifying the CU base address."));
24695
24696       SYMBOL_ACLASS_INDEX (sym) = (is_block
24697                                    ? dwarf2_loclist_block_index
24698                                    : dwarf2_loclist_index);
24699       SYMBOL_LOCATION_BATON (sym) = baton;
24700     }
24701   else
24702     {
24703       struct dwarf2_locexpr_baton *baton;
24704
24705       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24706       baton->per_cu = cu->per_cu;
24707       gdb_assert (baton->per_cu);
24708
24709       if (attr_form_is_block (attr))
24710         {
24711           /* Note that we're just copying the block's data pointer
24712              here, not the actual data.  We're still pointing into the
24713              info_buffer for SYM's objfile; right now we never release
24714              that buffer, but when we do clean up properly this may
24715              need to change.  */
24716           baton->size = DW_BLOCK (attr)->size;
24717           baton->data = DW_BLOCK (attr)->data;
24718         }
24719       else
24720         {
24721           dwarf2_invalid_attrib_class_complaint ("location description",
24722                                                  SYMBOL_NATURAL_NAME (sym));
24723           baton->size = 0;
24724         }
24725
24726       SYMBOL_ACLASS_INDEX (sym) = (is_block
24727                                    ? dwarf2_locexpr_block_index
24728                                    : dwarf2_locexpr_index);
24729       SYMBOL_LOCATION_BATON (sym) = baton;
24730     }
24731 }
24732
24733 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24734    came from a separate debuginfo file, then the master objfile is
24735    returned.  */
24736
24737 struct objfile *
24738 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24739 {
24740   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24741
24742   /* Return the master objfile, so that we can report and look up the
24743      correct file containing this variable.  */
24744   if (objfile->separate_debug_objfile_backlink)
24745     objfile = objfile->separate_debug_objfile_backlink;
24746
24747   return objfile;
24748 }
24749
24750 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24751    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24752    CU_HEADERP first.  */
24753
24754 static const struct comp_unit_head *
24755 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24756                        struct dwarf2_per_cu_data *per_cu)
24757 {
24758   const gdb_byte *info_ptr;
24759
24760   if (per_cu->cu)
24761     return &per_cu->cu->header;
24762
24763   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24764
24765   memset (cu_headerp, 0, sizeof (*cu_headerp));
24766   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24767                        rcuh_kind::COMPILE);
24768
24769   return cu_headerp;
24770 }
24771
24772 /* Return the address size given in the compilation unit header for CU.  */
24773
24774 int
24775 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24776 {
24777   struct comp_unit_head cu_header_local;
24778   const struct comp_unit_head *cu_headerp;
24779
24780   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24781
24782   return cu_headerp->addr_size;
24783 }
24784
24785 /* Return the offset size given in the compilation unit header for CU.  */
24786
24787 int
24788 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24789 {
24790   struct comp_unit_head cu_header_local;
24791   const struct comp_unit_head *cu_headerp;
24792
24793   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24794
24795   return cu_headerp->offset_size;
24796 }
24797
24798 /* See its dwarf2loc.h declaration.  */
24799
24800 int
24801 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24802 {
24803   struct comp_unit_head cu_header_local;
24804   const struct comp_unit_head *cu_headerp;
24805
24806   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24807
24808   if (cu_headerp->version == 2)
24809     return cu_headerp->addr_size;
24810   else
24811     return cu_headerp->offset_size;
24812 }
24813
24814 /* Return the text offset of the CU.  The returned offset comes from
24815    this CU's objfile.  If this objfile came from a separate debuginfo
24816    file, then the offset may be different from the corresponding
24817    offset in the parent objfile.  */
24818
24819 CORE_ADDR
24820 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24821 {
24822   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24823
24824   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24825 }
24826
24827 /* Return DWARF version number of PER_CU.  */
24828
24829 short
24830 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24831 {
24832   return per_cu->dwarf_version;
24833 }
24834
24835 /* Locate the .debug_info compilation unit from CU's objfile which contains
24836    the DIE at OFFSET.  Raises an error on failure.  */
24837
24838 static struct dwarf2_per_cu_data *
24839 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24840                                   unsigned int offset_in_dwz,
24841                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24842 {
24843   struct dwarf2_per_cu_data *this_cu;
24844   int low, high;
24845   const sect_offset *cu_off;
24846
24847   low = 0;
24848   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24849   while (high > low)
24850     {
24851       struct dwarf2_per_cu_data *mid_cu;
24852       int mid = low + (high - low) / 2;
24853
24854       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24855       cu_off = &mid_cu->sect_off;
24856       if (mid_cu->is_dwz > offset_in_dwz
24857           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24858         high = mid;
24859       else
24860         low = mid + 1;
24861     }
24862   gdb_assert (low == high);
24863   this_cu = dwarf2_per_objfile->all_comp_units[low];
24864   cu_off = &this_cu->sect_off;
24865   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24866     {
24867       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24868         error (_("Dwarf Error: could not find partial DIE containing "
24869                "offset %s [in module %s]"),
24870                sect_offset_str (sect_off),
24871                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24872
24873       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24874                   <= sect_off);
24875       return dwarf2_per_objfile->all_comp_units[low-1];
24876     }
24877   else
24878     {
24879       this_cu = dwarf2_per_objfile->all_comp_units[low];
24880       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24881           && sect_off >= this_cu->sect_off + this_cu->length)
24882         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24883       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24884       return this_cu;
24885     }
24886 }
24887
24888 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24889
24890 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24891   : per_cu (per_cu_),
24892     mark (0),
24893     has_loclist (0),
24894     checked_producer (0),
24895     producer_is_gxx_lt_4_6 (0),
24896     producer_is_gcc_lt_4_3 (0),
24897     producer_is_icc_lt_14 (0),
24898     processing_has_namespace_info (0)
24899 {
24900   per_cu->cu = this;
24901 }
24902
24903 /* Destroy a dwarf2_cu.  */
24904
24905 dwarf2_cu::~dwarf2_cu ()
24906 {
24907   per_cu->cu = NULL;
24908 }
24909
24910 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24911
24912 static void
24913 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24914                        enum language pretend_language)
24915 {
24916   struct attribute *attr;
24917
24918   /* Set the language we're debugging.  */
24919   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24920   if (attr)
24921     set_cu_language (DW_UNSND (attr), cu);
24922   else
24923     {
24924       cu->language = pretend_language;
24925       cu->language_defn = language_def (cu->language);
24926     }
24927
24928   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24929 }
24930
24931 /* Increase the age counter on each cached compilation unit, and free
24932    any that are too old.  */
24933
24934 static void
24935 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24936 {
24937   struct dwarf2_per_cu_data *per_cu, **last_chain;
24938
24939   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24940   per_cu = dwarf2_per_objfile->read_in_chain;
24941   while (per_cu != NULL)
24942     {
24943       per_cu->cu->last_used ++;
24944       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24945         dwarf2_mark (per_cu->cu);
24946       per_cu = per_cu->cu->read_in_chain;
24947     }
24948
24949   per_cu = dwarf2_per_objfile->read_in_chain;
24950   last_chain = &dwarf2_per_objfile->read_in_chain;
24951   while (per_cu != NULL)
24952     {
24953       struct dwarf2_per_cu_data *next_cu;
24954
24955       next_cu = per_cu->cu->read_in_chain;
24956
24957       if (!per_cu->cu->mark)
24958         {
24959           delete per_cu->cu;
24960           *last_chain = next_cu;
24961         }
24962       else
24963         last_chain = &per_cu->cu->read_in_chain;
24964
24965       per_cu = next_cu;
24966     }
24967 }
24968
24969 /* Remove a single compilation unit from the cache.  */
24970
24971 static void
24972 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
24973 {
24974   struct dwarf2_per_cu_data *per_cu, **last_chain;
24975   struct dwarf2_per_objfile *dwarf2_per_objfile
24976     = target_per_cu->dwarf2_per_objfile;
24977
24978   per_cu = dwarf2_per_objfile->read_in_chain;
24979   last_chain = &dwarf2_per_objfile->read_in_chain;
24980   while (per_cu != NULL)
24981     {
24982       struct dwarf2_per_cu_data *next_cu;
24983
24984       next_cu = per_cu->cu->read_in_chain;
24985
24986       if (per_cu == target_per_cu)
24987         {
24988           delete per_cu->cu;
24989           per_cu->cu = NULL;
24990           *last_chain = next_cu;
24991           break;
24992         }
24993       else
24994         last_chain = &per_cu->cu->read_in_chain;
24995
24996       per_cu = next_cu;
24997     }
24998 }
24999
25000 /* Cleanup function for the dwarf2_per_objfile data.  */
25001
25002 static void
25003 dwarf2_free_objfile (struct objfile *objfile, void *datum)
25004 {
25005   struct dwarf2_per_objfile *dwarf2_per_objfile
25006     = static_cast<struct dwarf2_per_objfile *> (datum);
25007
25008   delete dwarf2_per_objfile;
25009 }
25010
25011 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25012    We store these in a hash table separate from the DIEs, and preserve them
25013    when the DIEs are flushed out of cache.
25014
25015    The CU "per_cu" pointer is needed because offset alone is not enough to
25016    uniquely identify the type.  A file may have multiple .debug_types sections,
25017    or the type may come from a DWO file.  Furthermore, while it's more logical
25018    to use per_cu->section+offset, with Fission the section with the data is in
25019    the DWO file but we don't know that section at the point we need it.
25020    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25021    because we can enter the lookup routine, get_die_type_at_offset, from
25022    outside this file, and thus won't necessarily have PER_CU->cu.
25023    Fortunately, PER_CU is stable for the life of the objfile.  */
25024
25025 struct dwarf2_per_cu_offset_and_type
25026 {
25027   const struct dwarf2_per_cu_data *per_cu;
25028   sect_offset sect_off;
25029   struct type *type;
25030 };
25031
25032 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25033
25034 static hashval_t
25035 per_cu_offset_and_type_hash (const void *item)
25036 {
25037   const struct dwarf2_per_cu_offset_and_type *ofs
25038     = (const struct dwarf2_per_cu_offset_and_type *) item;
25039
25040   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25041 }
25042
25043 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25044
25045 static int
25046 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25047 {
25048   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25049     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25050   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25051     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25052
25053   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25054           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25055 }
25056
25057 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25058    table if necessary.  For convenience, return TYPE.
25059
25060    The DIEs reading must have careful ordering to:
25061     * Not cause infite loops trying to read in DIEs as a prerequisite for
25062       reading current DIE.
25063     * Not trying to dereference contents of still incompletely read in types
25064       while reading in other DIEs.
25065     * Enable referencing still incompletely read in types just by a pointer to
25066       the type without accessing its fields.
25067
25068    Therefore caller should follow these rules:
25069      * Try to fetch any prerequisite types we may need to build this DIE type
25070        before building the type and calling set_die_type.
25071      * After building type call set_die_type for current DIE as soon as
25072        possible before fetching more types to complete the current type.
25073      * Make the type as complete as possible before fetching more types.  */
25074
25075 static struct type *
25076 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25077 {
25078   struct dwarf2_per_objfile *dwarf2_per_objfile
25079     = cu->per_cu->dwarf2_per_objfile;
25080   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25081   struct objfile *objfile = dwarf2_per_objfile->objfile;
25082   struct attribute *attr;
25083   struct dynamic_prop prop;
25084
25085   /* For Ada types, make sure that the gnat-specific data is always
25086      initialized (if not already set).  There are a few types where
25087      we should not be doing so, because the type-specific area is
25088      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25089      where the type-specific area is used to store the floatformat).
25090      But this is not a problem, because the gnat-specific information
25091      is actually not needed for these types.  */
25092   if (need_gnat_info (cu)
25093       && TYPE_CODE (type) != TYPE_CODE_FUNC
25094       && TYPE_CODE (type) != TYPE_CODE_FLT
25095       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25096       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25097       && TYPE_CODE (type) != TYPE_CODE_METHOD
25098       && !HAVE_GNAT_AUX_INFO (type))
25099     INIT_GNAT_SPECIFIC (type);
25100
25101   /* Read DW_AT_allocated and set in type.  */
25102   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25103   if (attr_form_is_block (attr))
25104     {
25105       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25106         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25107     }
25108   else if (attr != NULL)
25109     {
25110       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25111                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25112                  sect_offset_str (die->sect_off));
25113     }
25114
25115   /* Read DW_AT_associated and set in type.  */
25116   attr = dwarf2_attr (die, DW_AT_associated, cu);
25117   if (attr_form_is_block (attr))
25118     {
25119       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25120         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25121     }
25122   else if (attr != NULL)
25123     {
25124       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25125                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25126                  sect_offset_str (die->sect_off));
25127     }
25128
25129   /* Read DW_AT_data_location and set in type.  */
25130   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25131   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25132     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25133
25134   if (dwarf2_per_objfile->die_type_hash == NULL)
25135     {
25136       dwarf2_per_objfile->die_type_hash =
25137         htab_create_alloc_ex (127,
25138                               per_cu_offset_and_type_hash,
25139                               per_cu_offset_and_type_eq,
25140                               NULL,
25141                               &objfile->objfile_obstack,
25142                               hashtab_obstack_allocate,
25143                               dummy_obstack_deallocate);
25144     }
25145
25146   ofs.per_cu = cu->per_cu;
25147   ofs.sect_off = die->sect_off;
25148   ofs.type = type;
25149   slot = (struct dwarf2_per_cu_offset_and_type **)
25150     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25151   if (*slot)
25152     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25153                sect_offset_str (die->sect_off));
25154   *slot = XOBNEW (&objfile->objfile_obstack,
25155                   struct dwarf2_per_cu_offset_and_type);
25156   **slot = ofs;
25157   return type;
25158 }
25159
25160 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25161    or return NULL if the die does not have a saved type.  */
25162
25163 static struct type *
25164 get_die_type_at_offset (sect_offset sect_off,
25165                         struct dwarf2_per_cu_data *per_cu)
25166 {
25167   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25168   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25169
25170   if (dwarf2_per_objfile->die_type_hash == NULL)
25171     return NULL;
25172
25173   ofs.per_cu = per_cu;
25174   ofs.sect_off = sect_off;
25175   slot = ((struct dwarf2_per_cu_offset_and_type *)
25176           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25177   if (slot)
25178     return slot->type;
25179   else
25180     return NULL;
25181 }
25182
25183 /* Look up the type for DIE in CU in die_type_hash,
25184    or return NULL if DIE does not have a saved type.  */
25185
25186 static struct type *
25187 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25188 {
25189   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25190 }
25191
25192 /* Add a dependence relationship from CU to REF_PER_CU.  */
25193
25194 static void
25195 dwarf2_add_dependence (struct dwarf2_cu *cu,
25196                        struct dwarf2_per_cu_data *ref_per_cu)
25197 {
25198   void **slot;
25199
25200   if (cu->dependencies == NULL)
25201     cu->dependencies
25202       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25203                               NULL, &cu->comp_unit_obstack,
25204                               hashtab_obstack_allocate,
25205                               dummy_obstack_deallocate);
25206
25207   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25208   if (*slot == NULL)
25209     *slot = ref_per_cu;
25210 }
25211
25212 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25213    Set the mark field in every compilation unit in the
25214    cache that we must keep because we are keeping CU.  */
25215
25216 static int
25217 dwarf2_mark_helper (void **slot, void *data)
25218 {
25219   struct dwarf2_per_cu_data *per_cu;
25220
25221   per_cu = (struct dwarf2_per_cu_data *) *slot;
25222
25223   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25224      reading of the chain.  As such dependencies remain valid it is not much
25225      useful to track and undo them during QUIT cleanups.  */
25226   if (per_cu->cu == NULL)
25227     return 1;
25228
25229   if (per_cu->cu->mark)
25230     return 1;
25231   per_cu->cu->mark = 1;
25232
25233   if (per_cu->cu->dependencies != NULL)
25234     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25235
25236   return 1;
25237 }
25238
25239 /* Set the mark field in CU and in every other compilation unit in the
25240    cache that we must keep because we are keeping CU.  */
25241
25242 static void
25243 dwarf2_mark (struct dwarf2_cu *cu)
25244 {
25245   if (cu->mark)
25246     return;
25247   cu->mark = 1;
25248   if (cu->dependencies != NULL)
25249     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25250 }
25251
25252 static void
25253 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25254 {
25255   while (per_cu)
25256     {
25257       per_cu->cu->mark = 0;
25258       per_cu = per_cu->cu->read_in_chain;
25259     }
25260 }
25261
25262 /* Trivial hash function for partial_die_info: the hash value of a DIE
25263    is its offset in .debug_info for this objfile.  */
25264
25265 static hashval_t
25266 partial_die_hash (const void *item)
25267 {
25268   const struct partial_die_info *part_die
25269     = (const struct partial_die_info *) item;
25270
25271   return to_underlying (part_die->sect_off);
25272 }
25273
25274 /* Trivial comparison function for partial_die_info structures: two DIEs
25275    are equal if they have the same offset.  */
25276
25277 static int
25278 partial_die_eq (const void *item_lhs, const void *item_rhs)
25279 {
25280   const struct partial_die_info *part_die_lhs
25281     = (const struct partial_die_info *) item_lhs;
25282   const struct partial_die_info *part_die_rhs
25283     = (const struct partial_die_info *) item_rhs;
25284
25285   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25286 }
25287
25288 static struct cmd_list_element *set_dwarf_cmdlist;
25289 static struct cmd_list_element *show_dwarf_cmdlist;
25290
25291 static void
25292 set_dwarf_cmd (const char *args, int from_tty)
25293 {
25294   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25295              gdb_stdout);
25296 }
25297
25298 static void
25299 show_dwarf_cmd (const char *args, int from_tty)
25300 {
25301   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25302 }
25303
25304 int dwarf_always_disassemble;
25305
25306 static void
25307 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25308                                struct cmd_list_element *c, const char *value)
25309 {
25310   fprintf_filtered (file,
25311                     _("Whether to always disassemble "
25312                       "DWARF expressions is %s.\n"),
25313                     value);
25314 }
25315
25316 static void
25317 show_check_physname (struct ui_file *file, int from_tty,
25318                      struct cmd_list_element *c, const char *value)
25319 {
25320   fprintf_filtered (file,
25321                     _("Whether to check \"physname\" is %s.\n"),
25322                     value);
25323 }
25324
25325 void
25326 _initialize_dwarf2_read (void)
25327 {
25328   dwarf2_objfile_data_key
25329     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25330
25331   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25332 Set DWARF specific variables.\n\
25333 Configure DWARF variables such as the cache size"),
25334                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25335                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25336
25337   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25338 Show DWARF specific variables\n\
25339 Show DWARF variables such as the cache size"),
25340                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25341                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25342
25343   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25344                             &dwarf_max_cache_age, _("\
25345 Set the upper bound on the age of cached DWARF compilation units."), _("\
25346 Show the upper bound on the age of cached DWARF compilation units."), _("\
25347 A higher limit means that cached compilation units will be stored\n\
25348 in memory longer, and more total memory will be used.  Zero disables\n\
25349 caching, which can slow down startup."),
25350                             NULL,
25351                             show_dwarf_max_cache_age,
25352                             &set_dwarf_cmdlist,
25353                             &show_dwarf_cmdlist);
25354
25355   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25356                            &dwarf_always_disassemble, _("\
25357 Set whether `info address' always disassembles DWARF expressions."), _("\
25358 Show whether `info address' always disassembles DWARF expressions."), _("\
25359 When enabled, DWARF expressions are always printed in an assembly-like\n\
25360 syntax.  When disabled, expressions will be printed in a more\n\
25361 conversational style, when possible."),
25362                            NULL,
25363                            show_dwarf_always_disassemble,
25364                            &set_dwarf_cmdlist,
25365                            &show_dwarf_cmdlist);
25366
25367   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25368 Set debugging of the DWARF reader."), _("\
25369 Show debugging of the DWARF reader."), _("\
25370 When enabled (non-zero), debugging messages are printed during DWARF\n\
25371 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25372 information.  A value greater than 1 provides more verbose information."),
25373                             NULL,
25374                             NULL,
25375                             &setdebuglist, &showdebuglist);
25376
25377   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25378 Set debugging of the DWARF DIE reader."), _("\
25379 Show debugging of the DWARF DIE reader."), _("\
25380 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25381 The value is the maximum depth to print."),
25382                              NULL,
25383                              NULL,
25384                              &setdebuglist, &showdebuglist);
25385
25386   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25387 Set debugging of the dwarf line reader."), _("\
25388 Show debugging of the dwarf line reader."), _("\
25389 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25390 A value of 1 (one) provides basic information.\n\
25391 A value greater than 1 provides more verbose information."),
25392                              NULL,
25393                              NULL,
25394                              &setdebuglist, &showdebuglist);
25395
25396   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25397 Set cross-checking of \"physname\" code against demangler."), _("\
25398 Show cross-checking of \"physname\" code against demangler."), _("\
25399 When enabled, GDB's internal \"physname\" code is checked against\n\
25400 the demangler."),
25401                            NULL, show_check_physname,
25402                            &setdebuglist, &showdebuglist);
25403
25404   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25405                            no_class, &use_deprecated_index_sections, _("\
25406 Set whether to use deprecated gdb_index sections."), _("\
25407 Show whether to use deprecated gdb_index sections."), _("\
25408 When enabled, deprecated .gdb_index sections are used anyway.\n\
25409 Normally they are ignored either because of a missing feature or\n\
25410 performance issue.\n\
25411 Warning: This option must be enabled before gdb reads the file."),
25412                            NULL,
25413                            NULL,
25414                            &setlist, &showlist);
25415
25416   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25417                                                         &dwarf2_locexpr_funcs);
25418   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25419                                                         &dwarf2_loclist_funcs);
25420
25421   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25422                                         &dwarf2_block_frame_base_locexpr_funcs);
25423   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25424                                         &dwarf2_block_frame_base_loclist_funcs);
25425
25426 #if GDB_SELF_TEST
25427   selftests::register_test ("dw2_expand_symtabs_matching",
25428                             selftests::dw2_expand_symtabs_matching::run_test);
25429 #endif
25430 }