Fix "fall through" comments
[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   /* The name_component table (a sorted vector).  See name_component's
151      description above.  */
152   std::vector<name_component> name_components;
153
154   /* How NAME_COMPONENTS is sorted.  */
155   enum case_sensitivity name_components_casing;
156
157   /* Return the number of names in the symbol table.  */
158   virtual size_t symbol_name_count () const = 0;
159
160   /* Get the name of the symbol at IDX in the symbol table.  */
161   virtual const char *symbol_name_at (offset_type idx) const = 0;
162
163   /* Return whether the name at IDX in the symbol table should be
164      ignored.  */
165   virtual bool symbol_name_slot_invalid (offset_type idx) const
166   {
167     return false;
168   }
169
170   /* Build the symbol name component sorted vector, if we haven't
171      yet.  */
172   void build_name_components ();
173
174   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
175      possible matches for LN_NO_PARAMS in the name component
176      vector.  */
177   std::pair<std::vector<name_component>::const_iterator,
178             std::vector<name_component>::const_iterator>
179     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
180
181   /* Prevent deleting/destroying via a base class pointer.  */
182 protected:
183   ~mapped_index_base() = default;
184 };
185
186 /* A description of the mapped index.  The file format is described in
187    a comment by the code that writes the index.  */
188 struct mapped_index final : public mapped_index_base
189 {
190   /* A slot/bucket in the symbol table hash.  */
191   struct symbol_table_slot
192   {
193     const offset_type name;
194     const offset_type vec;
195   };
196
197   /* Index data format version.  */
198   int version;
199
200   /* The total length of the buffer.  */
201   off_t total_size;
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;
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   /* Name of the file.  */
814   const char *name;
815
816   /* File format version.  */
817   int version;
818
819   /* The bfd.  */
820   bfd *dbfd;
821
822   /* Section info for this file.  */
823   struct dwp_sections sections;
824
825   /* Table of CUs in the file.  */
826   const struct dwp_hash_table *cus;
827
828   /* Table of TUs in the file.  */
829   const struct dwp_hash_table *tus;
830
831   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
832   htab_t loaded_cus;
833   htab_t loaded_tus;
834
835   /* Table to map ELF section numbers to their sections.
836      This is only needed for the DWP V1 file format.  */
837   unsigned int num_sections;
838   asection **elf_sections;
839 };
840
841 /* This represents a '.dwz' file.  */
842
843 struct dwz_file
844 {
845   /* A dwz file can only contain a few sections.  */
846   struct dwarf2_section_info abbrev;
847   struct dwarf2_section_info info;
848   struct dwarf2_section_info str;
849   struct dwarf2_section_info line;
850   struct dwarf2_section_info macro;
851   struct dwarf2_section_info gdb_index;
852   struct dwarf2_section_info debug_names;
853
854   /* The dwz's BFD.  */
855   bfd *dwz_bfd;
856 };
857
858 /* Struct used to pass misc. parameters to read_die_and_children, et
859    al.  which are used for both .debug_info and .debug_types dies.
860    All parameters here are unchanging for the life of the call.  This
861    struct exists to abstract away the constant parameters of die reading.  */
862
863 struct die_reader_specs
864 {
865   /* The bfd of die_section.  */
866   bfd* abfd;
867
868   /* The CU of the DIE we are parsing.  */
869   struct dwarf2_cu *cu;
870
871   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
872   struct dwo_file *dwo_file;
873
874   /* The section the die comes from.
875      This is either .debug_info or .debug_types, or the .dwo variants.  */
876   struct dwarf2_section_info *die_section;
877
878   /* die_section->buffer.  */
879   const gdb_byte *buffer;
880
881   /* The end of the buffer.  */
882   const gdb_byte *buffer_end;
883
884   /* The value of the DW_AT_comp_dir attribute.  */
885   const char *comp_dir;
886
887   /* The abbreviation table to use when reading the DIEs.  */
888   struct abbrev_table *abbrev_table;
889 };
890
891 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
892 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
893                                       const gdb_byte *info_ptr,
894                                       struct die_info *comp_unit_die,
895                                       int has_children,
896                                       void *data);
897
898 /* A 1-based directory index.  This is a strong typedef to prevent
899    accidentally using a directory index as a 0-based index into an
900    array/vector.  */
901 enum class dir_index : unsigned int {};
902
903 /* Likewise, a 1-based file name index.  */
904 enum class file_name_index : unsigned int {};
905
906 struct file_entry
907 {
908   file_entry () = default;
909
910   file_entry (const char *name_, dir_index d_index_,
911               unsigned int mod_time_, unsigned int length_)
912     : name (name_),
913       d_index (d_index_),
914       mod_time (mod_time_),
915       length (length_)
916   {}
917
918   /* Return the include directory at D_INDEX stored in LH.  Returns
919      NULL if D_INDEX is out of bounds.  */
920   const char *include_dir (const line_header *lh) const;
921
922   /* The file name.  Note this is an observing pointer.  The memory is
923      owned by debug_line_buffer.  */
924   const char *name {};
925
926   /* The directory index (1-based).  */
927   dir_index d_index {};
928
929   unsigned int mod_time {};
930
931   unsigned int length {};
932
933   /* True if referenced by the Line Number Program.  */
934   bool included_p {};
935
936   /* The associated symbol table, if any.  */
937   struct symtab *symtab {};
938 };
939
940 /* The line number information for a compilation unit (found in the
941    .debug_line section) begins with a "statement program header",
942    which contains the following information.  */
943 struct line_header
944 {
945   line_header ()
946     : offset_in_dwz {}
947   {}
948
949   /* Add an entry to the include directory table.  */
950   void add_include_dir (const char *include_dir);
951
952   /* Add an entry to the file name table.  */
953   void add_file_name (const char *name, dir_index d_index,
954                       unsigned int mod_time, unsigned int length);
955
956   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
957      is out of bounds.  */
958   const char *include_dir_at (dir_index index) const
959   {
960     /* Convert directory index number (1-based) to vector index
961        (0-based).  */
962     size_t vec_index = to_underlying (index) - 1;
963
964     if (vec_index >= include_dirs.size ())
965       return NULL;
966     return include_dirs[vec_index];
967   }
968
969   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
970      is out of bounds.  */
971   file_entry *file_name_at (file_name_index index)
972   {
973     /* Convert file name index number (1-based) to vector index
974        (0-based).  */
975     size_t vec_index = to_underlying (index) - 1;
976
977     if (vec_index >= file_names.size ())
978       return NULL;
979     return &file_names[vec_index];
980   }
981
982   /* Const version of the above.  */
983   const file_entry *file_name_at (unsigned int index) const
984   {
985     if (index >= file_names.size ())
986       return NULL;
987     return &file_names[index];
988   }
989
990   /* Offset of line number information in .debug_line section.  */
991   sect_offset sect_off {};
992
993   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
994   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
995
996   unsigned int total_length {};
997   unsigned short version {};
998   unsigned int header_length {};
999   unsigned char minimum_instruction_length {};
1000   unsigned char maximum_ops_per_instruction {};
1001   unsigned char default_is_stmt {};
1002   int line_base {};
1003   unsigned char line_range {};
1004   unsigned char opcode_base {};
1005
1006   /* standard_opcode_lengths[i] is the number of operands for the
1007      standard opcode whose value is i.  This means that
1008      standard_opcode_lengths[0] is unused, and the last meaningful
1009      element is standard_opcode_lengths[opcode_base - 1].  */
1010   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1011
1012   /* The include_directories table.  Note these are observing
1013      pointers.  The memory is owned by debug_line_buffer.  */
1014   std::vector<const char *> include_dirs;
1015
1016   /* The file_names table.  */
1017   std::vector<file_entry> file_names;
1018
1019   /* The start and end of the statement program following this
1020      header.  These point into dwarf2_per_objfile->line_buffer.  */
1021   const gdb_byte *statement_program_start {}, *statement_program_end {};
1022 };
1023
1024 typedef std::unique_ptr<line_header> line_header_up;
1025
1026 const char *
1027 file_entry::include_dir (const line_header *lh) const
1028 {
1029   return lh->include_dir_at (d_index);
1030 }
1031
1032 /* When we construct a partial symbol table entry we only
1033    need this much information.  */
1034 struct partial_die_info : public allocate_on_obstack
1035   {
1036     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1037
1038     /* Disable assign but still keep copy ctor, which is needed
1039        load_partial_dies.   */
1040     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1041
1042     /* Adjust the partial die before generating a symbol for it.  This
1043        function may set the is_external flag or change the DIE's
1044        name.  */
1045     void fixup (struct dwarf2_cu *cu);
1046
1047     /* Read a minimal amount of information into the minimal die
1048        structure.  */
1049     const gdb_byte *read (const struct die_reader_specs *reader,
1050                           const struct abbrev_info &abbrev,
1051                           const gdb_byte *info_ptr);
1052
1053     /* Offset of this DIE.  */
1054     const sect_offset sect_off;
1055
1056     /* DWARF-2 tag for this DIE.  */
1057     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1058
1059     /* Assorted flags describing the data found in this DIE.  */
1060     const unsigned int has_children : 1;
1061
1062     unsigned int is_external : 1;
1063     unsigned int is_declaration : 1;
1064     unsigned int has_type : 1;
1065     unsigned int has_specification : 1;
1066     unsigned int has_pc_info : 1;
1067     unsigned int may_be_inlined : 1;
1068
1069     /* This DIE has been marked DW_AT_main_subprogram.  */
1070     unsigned int main_subprogram : 1;
1071
1072     /* Flag set if the SCOPE field of this structure has been
1073        computed.  */
1074     unsigned int scope_set : 1;
1075
1076     /* Flag set if the DIE has a byte_size attribute.  */
1077     unsigned int has_byte_size : 1;
1078
1079     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1080     unsigned int has_const_value : 1;
1081
1082     /* Flag set if any of the DIE's children are template arguments.  */
1083     unsigned int has_template_arguments : 1;
1084
1085     /* Flag set if fixup has been called on this die.  */
1086     unsigned int fixup_called : 1;
1087
1088     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1089     unsigned int is_dwz : 1;
1090
1091     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1092     unsigned int spec_is_dwz : 1;
1093
1094     /* The name of this DIE.  Normally the value of DW_AT_name, but
1095        sometimes a default name for unnamed DIEs.  */
1096     const char *name = nullptr;
1097
1098     /* The linkage name, if present.  */
1099     const char *linkage_name = nullptr;
1100
1101     /* The scope to prepend to our children.  This is generally
1102        allocated on the comp_unit_obstack, so will disappear
1103        when this compilation unit leaves the cache.  */
1104     const char *scope = nullptr;
1105
1106     /* Some data associated with the partial DIE.  The tag determines
1107        which field is live.  */
1108     union
1109     {
1110       /* The location description associated with this DIE, if any.  */
1111       struct dwarf_block *locdesc;
1112       /* The offset of an import, for DW_TAG_imported_unit.  */
1113       sect_offset sect_off;
1114     } d {};
1115
1116     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1117     CORE_ADDR lowpc = 0;
1118     CORE_ADDR highpc = 0;
1119
1120     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1121        DW_AT_sibling, if any.  */
1122     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1123        could return DW_AT_sibling values to its caller load_partial_dies.  */
1124     const gdb_byte *sibling = nullptr;
1125
1126     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1127        DW_AT_specification (or DW_AT_abstract_origin or
1128        DW_AT_extension).  */
1129     sect_offset spec_offset {};
1130
1131     /* Pointers to this DIE's parent, first child, and next sibling,
1132        if any.  */
1133     struct partial_die_info *die_parent = nullptr;
1134     struct partial_die_info *die_child = nullptr;
1135     struct partial_die_info *die_sibling = nullptr;
1136
1137     friend struct partial_die_info *
1138     dwarf2_cu::find_partial_die (sect_offset sect_off);
1139
1140   private:
1141     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1142     partial_die_info (sect_offset sect_off)
1143       : partial_die_info (sect_off, DW_TAG_padding, 0)
1144     {
1145     }
1146
1147     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1148                       int has_children_)
1149       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1150     {
1151       is_external = 0;
1152       is_declaration = 0;
1153       has_type = 0;
1154       has_specification = 0;
1155       has_pc_info = 0;
1156       may_be_inlined = 0;
1157       main_subprogram = 0;
1158       scope_set = 0;
1159       has_byte_size = 0;
1160       has_const_value = 0;
1161       has_template_arguments = 0;
1162       fixup_called = 0;
1163       is_dwz = 0;
1164       spec_is_dwz = 0;
1165     }
1166   };
1167
1168 /* This data structure holds the information of an abbrev.  */
1169 struct abbrev_info
1170   {
1171     unsigned int number;        /* number identifying abbrev */
1172     enum dwarf_tag tag;         /* dwarf tag */
1173     unsigned short has_children;                /* boolean */
1174     unsigned short num_attrs;   /* number of attributes */
1175     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1176     struct abbrev_info *next;   /* next in chain */
1177   };
1178
1179 struct attr_abbrev
1180   {
1181     ENUM_BITFIELD(dwarf_attribute) name : 16;
1182     ENUM_BITFIELD(dwarf_form) form : 16;
1183
1184     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1185     LONGEST implicit_const;
1186   };
1187
1188 /* Size of abbrev_table.abbrev_hash_table.  */
1189 #define ABBREV_HASH_SIZE 121
1190
1191 /* Top level data structure to contain an abbreviation table.  */
1192
1193 struct abbrev_table
1194 {
1195   explicit abbrev_table (sect_offset off)
1196     : sect_off (off)
1197   {
1198     m_abbrevs =
1199       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1200     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1201   }
1202
1203   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1204
1205   /* Allocate space for a struct abbrev_info object in
1206      ABBREV_TABLE.  */
1207   struct abbrev_info *alloc_abbrev ();
1208
1209   /* Add an abbreviation to the table.  */
1210   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1211
1212   /* Look up an abbrev in the table.
1213      Returns NULL if the abbrev is not found.  */
1214
1215   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1216
1217
1218   /* Where the abbrev table came from.
1219      This is used as a sanity check when the table is used.  */
1220   const sect_offset sect_off;
1221
1222   /* Storage for the abbrev table.  */
1223   auto_obstack abbrev_obstack;
1224
1225 private:
1226
1227   /* Hash table of abbrevs.
1228      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1229      It could be statically allocated, but the previous code didn't so we
1230      don't either.  */
1231   struct abbrev_info **m_abbrevs;
1232 };
1233
1234 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1235
1236 /* Attributes have a name and a value.  */
1237 struct attribute
1238   {
1239     ENUM_BITFIELD(dwarf_attribute) name : 16;
1240     ENUM_BITFIELD(dwarf_form) form : 15;
1241
1242     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1243        field should be in u.str (existing only for DW_STRING) but it is kept
1244        here for better struct attribute alignment.  */
1245     unsigned int string_is_canonical : 1;
1246
1247     union
1248       {
1249         const char *str;
1250         struct dwarf_block *blk;
1251         ULONGEST unsnd;
1252         LONGEST snd;
1253         CORE_ADDR addr;
1254         ULONGEST signature;
1255       }
1256     u;
1257   };
1258
1259 /* This data structure holds a complete die structure.  */
1260 struct die_info
1261   {
1262     /* DWARF-2 tag for this DIE.  */
1263     ENUM_BITFIELD(dwarf_tag) tag : 16;
1264
1265     /* Number of attributes */
1266     unsigned char num_attrs;
1267
1268     /* True if we're presently building the full type name for the
1269        type derived from this DIE.  */
1270     unsigned char building_fullname : 1;
1271
1272     /* True if this die is in process.  PR 16581.  */
1273     unsigned char in_process : 1;
1274
1275     /* Abbrev number */
1276     unsigned int abbrev;
1277
1278     /* Offset in .debug_info or .debug_types section.  */
1279     sect_offset sect_off;
1280
1281     /* The dies in a compilation unit form an n-ary tree.  PARENT
1282        points to this die's parent; CHILD points to the first child of
1283        this node; and all the children of a given node are chained
1284        together via their SIBLING fields.  */
1285     struct die_info *child;     /* Its first child, if any.  */
1286     struct die_info *sibling;   /* Its next sibling, if any.  */
1287     struct die_info *parent;    /* Its parent, if any.  */
1288
1289     /* An array of attributes, with NUM_ATTRS elements.  There may be
1290        zero, but it's not common and zero-sized arrays are not
1291        sufficiently portable C.  */
1292     struct attribute attrs[1];
1293   };
1294
1295 /* Get at parts of an attribute structure.  */
1296
1297 #define DW_STRING(attr)    ((attr)->u.str)
1298 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1299 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1300 #define DW_BLOCK(attr)     ((attr)->u.blk)
1301 #define DW_SND(attr)       ((attr)->u.snd)
1302 #define DW_ADDR(attr)      ((attr)->u.addr)
1303 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1304
1305 /* Blocks are a bunch of untyped bytes.  */
1306 struct dwarf_block
1307   {
1308     size_t size;
1309
1310     /* Valid only if SIZE is not zero.  */
1311     const gdb_byte *data;
1312   };
1313
1314 #ifndef ATTR_ALLOC_CHUNK
1315 #define ATTR_ALLOC_CHUNK 4
1316 #endif
1317
1318 /* Allocate fields for structs, unions and enums in this size.  */
1319 #ifndef DW_FIELD_ALLOC_CHUNK
1320 #define DW_FIELD_ALLOC_CHUNK 4
1321 #endif
1322
1323 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1324    but this would require a corresponding change in unpack_field_as_long
1325    and friends.  */
1326 static int bits_per_byte = 8;
1327
1328 /* When reading a variant or variant part, we track a bit more
1329    information about the field, and store it in an object of this
1330    type.  */
1331
1332 struct variant_field
1333 {
1334   /* If we see a DW_TAG_variant, then this will be the discriminant
1335      value.  */
1336   ULONGEST discriminant_value;
1337   /* If we see a DW_TAG_variant, then this will be set if this is the
1338      default branch.  */
1339   bool default_branch;
1340   /* While reading a DW_TAG_variant_part, this will be set if this
1341      field is the discriminant.  */
1342   bool is_discriminant;
1343 };
1344
1345 struct nextfield
1346 {
1347   int accessibility = 0;
1348   int virtuality = 0;
1349   /* Extra information to describe a variant or variant part.  */
1350   struct variant_field variant {};
1351   struct field field {};
1352 };
1353
1354 struct fnfieldlist
1355 {
1356   const char *name = nullptr;
1357   std::vector<struct fn_field> fnfields;
1358 };
1359
1360 /* The routines that read and process dies for a C struct or C++ class
1361    pass lists of data member fields and lists of member function fields
1362    in an instance of a field_info structure, as defined below.  */
1363 struct field_info
1364   {
1365     /* List of data member and baseclasses fields.  */
1366     std::vector<struct nextfield> fields;
1367     std::vector<struct nextfield> baseclasses;
1368
1369     /* Number of fields (including baseclasses).  */
1370     int nfields = 0;
1371
1372     /* Set if the accesibility of one of the fields is not public.  */
1373     int non_public_fields = 0;
1374
1375     /* Member function fieldlist array, contains name of possibly overloaded
1376        member function, number of overloaded member functions and a pointer
1377        to the head of the member function field chain.  */
1378     std::vector<struct fnfieldlist> fnfieldlists;
1379
1380     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1381        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1382     std::vector<struct decl_field> typedef_field_list;
1383
1384     /* Nested types defined by this class and the number of elements in this
1385        list.  */
1386     std::vector<struct decl_field> nested_types_list;
1387   };
1388
1389 /* One item on the queue of compilation units to read in full symbols
1390    for.  */
1391 struct dwarf2_queue_item
1392 {
1393   struct dwarf2_per_cu_data *per_cu;
1394   enum language pretend_language;
1395   struct dwarf2_queue_item *next;
1396 };
1397
1398 /* The current queue.  */
1399 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1400
1401 /* Loaded secondary compilation units are kept in memory until they
1402    have not been referenced for the processing of this many
1403    compilation units.  Set this to zero to disable caching.  Cache
1404    sizes of up to at least twenty will improve startup time for
1405    typical inter-CU-reference binaries, at an obvious memory cost.  */
1406 static int dwarf_max_cache_age = 5;
1407 static void
1408 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1409                           struct cmd_list_element *c, const char *value)
1410 {
1411   fprintf_filtered (file, _("The upper bound on the age of cached "
1412                             "DWARF compilation units is %s.\n"),
1413                     value);
1414 }
1415 \f
1416 /* local function prototypes */
1417
1418 static const char *get_section_name (const struct dwarf2_section_info *);
1419
1420 static const char *get_section_file_name (const struct dwarf2_section_info *);
1421
1422 static void dwarf2_find_base_address (struct die_info *die,
1423                                       struct dwarf2_cu *cu);
1424
1425 static struct partial_symtab *create_partial_symtab
1426   (struct dwarf2_per_cu_data *per_cu, const char *name);
1427
1428 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1429                                         const gdb_byte *info_ptr,
1430                                         struct die_info *type_unit_die,
1431                                         int has_children, void *data);
1432
1433 static void dwarf2_build_psymtabs_hard
1434   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1435
1436 static void scan_partial_symbols (struct partial_die_info *,
1437                                   CORE_ADDR *, CORE_ADDR *,
1438                                   int, struct dwarf2_cu *);
1439
1440 static void add_partial_symbol (struct partial_die_info *,
1441                                 struct dwarf2_cu *);
1442
1443 static void add_partial_namespace (struct partial_die_info *pdi,
1444                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1445                                    int set_addrmap, struct dwarf2_cu *cu);
1446
1447 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1448                                 CORE_ADDR *highpc, int set_addrmap,
1449                                 struct dwarf2_cu *cu);
1450
1451 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1452                                      struct dwarf2_cu *cu);
1453
1454 static void add_partial_subprogram (struct partial_die_info *pdi,
1455                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1456                                     int need_pc, struct dwarf2_cu *cu);
1457
1458 static void dwarf2_read_symtab (struct partial_symtab *,
1459                                 struct objfile *);
1460
1461 static void psymtab_to_symtab_1 (struct partial_symtab *);
1462
1463 static abbrev_table_up abbrev_table_read_table
1464   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1465    sect_offset);
1466
1467 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1468
1469 static struct partial_die_info *load_partial_dies
1470   (const struct die_reader_specs *, const gdb_byte *, int);
1471
1472 static struct partial_die_info *find_partial_die (sect_offset, int,
1473                                                   struct dwarf2_cu *);
1474
1475 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1476                                        struct attribute *, struct attr_abbrev *,
1477                                        const gdb_byte *);
1478
1479 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1480
1481 static int read_1_signed_byte (bfd *, const gdb_byte *);
1482
1483 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1484
1485 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1486
1487 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1488
1489 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1490                                unsigned int *);
1491
1492 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1493
1494 static LONGEST read_checked_initial_length_and_offset
1495   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1496    unsigned int *, unsigned int *);
1497
1498 static LONGEST read_offset (bfd *, const gdb_byte *,
1499                             const struct comp_unit_head *,
1500                             unsigned int *);
1501
1502 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1503
1504 static sect_offset read_abbrev_offset
1505   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1506    struct dwarf2_section_info *, sect_offset);
1507
1508 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1509
1510 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1511
1512 static const char *read_indirect_string
1513   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1514    const struct comp_unit_head *, unsigned int *);
1515
1516 static const char *read_indirect_line_string
1517   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1518    const struct comp_unit_head *, unsigned int *);
1519
1520 static const char *read_indirect_string_at_offset
1521   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1522    LONGEST str_offset);
1523
1524 static const char *read_indirect_string_from_dwz
1525   (struct objfile *objfile, struct dwz_file *, LONGEST);
1526
1527 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1528
1529 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1530                                               const gdb_byte *,
1531                                               unsigned int *);
1532
1533 static const char *read_str_index (const struct die_reader_specs *reader,
1534                                    ULONGEST str_index);
1535
1536 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1537
1538 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1539                                       struct dwarf2_cu *);
1540
1541 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1542                                                 unsigned int);
1543
1544 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1545                                        struct dwarf2_cu *cu);
1546
1547 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1548                                struct dwarf2_cu *cu);
1549
1550 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1551
1552 static struct die_info *die_specification (struct die_info *die,
1553                                            struct dwarf2_cu **);
1554
1555 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1556                                                 struct dwarf2_cu *cu);
1557
1558 static void dwarf_decode_lines (struct line_header *, const char *,
1559                                 struct dwarf2_cu *, struct partial_symtab *,
1560                                 CORE_ADDR, int decode_mapping);
1561
1562 static void dwarf2_start_subfile (const char *, const char *);
1563
1564 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1565                                                     const char *, const char *,
1566                                                     CORE_ADDR);
1567
1568 static struct symbol *new_symbol (struct die_info *, struct type *,
1569                                   struct dwarf2_cu *, struct symbol * = NULL);
1570
1571 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1572                                 struct dwarf2_cu *);
1573
1574 static void dwarf2_const_value_attr (const struct attribute *attr,
1575                                      struct type *type,
1576                                      const char *name,
1577                                      struct obstack *obstack,
1578                                      struct dwarf2_cu *cu, LONGEST *value,
1579                                      const gdb_byte **bytes,
1580                                      struct dwarf2_locexpr_baton **baton);
1581
1582 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1583
1584 static int need_gnat_info (struct dwarf2_cu *);
1585
1586 static struct type *die_descriptive_type (struct die_info *,
1587                                           struct dwarf2_cu *);
1588
1589 static void set_descriptive_type (struct type *, struct die_info *,
1590                                   struct dwarf2_cu *);
1591
1592 static struct type *die_containing_type (struct die_info *,
1593                                          struct dwarf2_cu *);
1594
1595 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1596                                      struct dwarf2_cu *);
1597
1598 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1599
1600 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1601
1602 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1603
1604 static char *typename_concat (struct obstack *obs, const char *prefix,
1605                               const char *suffix, int physname,
1606                               struct dwarf2_cu *cu);
1607
1608 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1609
1610 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1611
1612 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1613
1614 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1615
1616 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1617
1618 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1619
1620 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1621                                struct dwarf2_cu *, struct partial_symtab *);
1622
1623 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1624    values.  Keep the items ordered with increasing constraints compliance.  */
1625 enum pc_bounds_kind
1626 {
1627   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1628   PC_BOUNDS_NOT_PRESENT,
1629
1630   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1631      were present but they do not form a valid range of PC addresses.  */
1632   PC_BOUNDS_INVALID,
1633
1634   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1635   PC_BOUNDS_RANGES,
1636
1637   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1638   PC_BOUNDS_HIGH_LOW,
1639 };
1640
1641 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1642                                                  CORE_ADDR *, CORE_ADDR *,
1643                                                  struct dwarf2_cu *,
1644                                                  struct partial_symtab *);
1645
1646 static void get_scope_pc_bounds (struct die_info *,
1647                                  CORE_ADDR *, CORE_ADDR *,
1648                                  struct dwarf2_cu *);
1649
1650 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1651                                         CORE_ADDR, struct dwarf2_cu *);
1652
1653 static void dwarf2_add_field (struct field_info *, struct die_info *,
1654                               struct dwarf2_cu *);
1655
1656 static void dwarf2_attach_fields_to_type (struct field_info *,
1657                                           struct type *, struct dwarf2_cu *);
1658
1659 static void dwarf2_add_member_fn (struct field_info *,
1660                                   struct die_info *, struct type *,
1661                                   struct dwarf2_cu *);
1662
1663 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1664                                              struct type *,
1665                                              struct dwarf2_cu *);
1666
1667 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1668
1669 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1670
1671 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1672
1673 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1674
1675 static struct using_direct **using_directives (enum language);
1676
1677 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1678
1679 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1680
1681 static struct type *read_module_type (struct die_info *die,
1682                                       struct dwarf2_cu *cu);
1683
1684 static const char *namespace_name (struct die_info *die,
1685                                    int *is_anonymous, struct dwarf2_cu *);
1686
1687 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1688
1689 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1690
1691 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1692                                                        struct dwarf2_cu *);
1693
1694 static struct die_info *read_die_and_siblings_1
1695   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1696    struct die_info *);
1697
1698 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1699                                                const gdb_byte *info_ptr,
1700                                                const gdb_byte **new_info_ptr,
1701                                                struct die_info *parent);
1702
1703 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1704                                         struct die_info **, const gdb_byte *,
1705                                         int *, int);
1706
1707 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1708                                       struct die_info **, const gdb_byte *,
1709                                       int *);
1710
1711 static void process_die (struct die_info *, struct dwarf2_cu *);
1712
1713 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1714                                              struct obstack *);
1715
1716 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1717
1718 static const char *dwarf2_full_name (const char *name,
1719                                      struct die_info *die,
1720                                      struct dwarf2_cu *cu);
1721
1722 static const char *dwarf2_physname (const char *name, struct die_info *die,
1723                                     struct dwarf2_cu *cu);
1724
1725 static struct die_info *dwarf2_extension (struct die_info *die,
1726                                           struct dwarf2_cu **);
1727
1728 static const char *dwarf_tag_name (unsigned int);
1729
1730 static const char *dwarf_attr_name (unsigned int);
1731
1732 static const char *dwarf_form_name (unsigned int);
1733
1734 static const char *dwarf_bool_name (unsigned int);
1735
1736 static const char *dwarf_type_encoding_name (unsigned int);
1737
1738 static struct die_info *sibling_die (struct die_info *);
1739
1740 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1741
1742 static void dump_die_for_error (struct die_info *);
1743
1744 static void dump_die_1 (struct ui_file *, int level, int max_level,
1745                         struct die_info *);
1746
1747 /*static*/ void dump_die (struct die_info *, int max_level);
1748
1749 static void store_in_ref_table (struct die_info *,
1750                                 struct dwarf2_cu *);
1751
1752 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1753
1754 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1755
1756 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1757                                                const struct attribute *,
1758                                                struct dwarf2_cu **);
1759
1760 static struct die_info *follow_die_ref (struct die_info *,
1761                                         const struct attribute *,
1762                                         struct dwarf2_cu **);
1763
1764 static struct die_info *follow_die_sig (struct die_info *,
1765                                         const struct attribute *,
1766                                         struct dwarf2_cu **);
1767
1768 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1769                                          struct dwarf2_cu *);
1770
1771 static struct type *get_DW_AT_signature_type (struct die_info *,
1772                                               const struct attribute *,
1773                                               struct dwarf2_cu *);
1774
1775 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1776
1777 static void read_signatured_type (struct signatured_type *);
1778
1779 static int attr_to_dynamic_prop (const struct attribute *attr,
1780                                  struct die_info *die, struct dwarf2_cu *cu,
1781                                  struct dynamic_prop *prop);
1782
1783 /* memory allocation interface */
1784
1785 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1786
1787 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1788
1789 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1790
1791 static int attr_form_is_block (const struct attribute *);
1792
1793 static int attr_form_is_section_offset (const struct attribute *);
1794
1795 static int attr_form_is_constant (const struct attribute *);
1796
1797 static int attr_form_is_ref (const struct attribute *);
1798
1799 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1800                                    struct dwarf2_loclist_baton *baton,
1801                                    const struct attribute *attr);
1802
1803 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1804                                          struct symbol *sym,
1805                                          struct dwarf2_cu *cu,
1806                                          int is_block);
1807
1808 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1809                                      const gdb_byte *info_ptr,
1810                                      struct abbrev_info *abbrev);
1811
1812 static hashval_t partial_die_hash (const void *item);
1813
1814 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1815
1816 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1817   (sect_offset sect_off, unsigned int offset_in_dwz,
1818    struct dwarf2_per_objfile *dwarf2_per_objfile);
1819
1820 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1821                                    struct die_info *comp_unit_die,
1822                                    enum language pretend_language);
1823
1824 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1825
1826 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1827
1828 static struct type *set_die_type (struct die_info *, struct type *,
1829                                   struct dwarf2_cu *);
1830
1831 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1832
1833 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1834
1835 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1836                                  enum language);
1837
1838 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1839                                     enum language);
1840
1841 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1842                                     enum language);
1843
1844 static void dwarf2_add_dependence (struct dwarf2_cu *,
1845                                    struct dwarf2_per_cu_data *);
1846
1847 static void dwarf2_mark (struct dwarf2_cu *);
1848
1849 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1850
1851 static struct type *get_die_type_at_offset (sect_offset,
1852                                             struct dwarf2_per_cu_data *);
1853
1854 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1855
1856 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1857                              enum language pretend_language);
1858
1859 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1860
1861 /* Class, the destructor of which frees all allocated queue entries.  This
1862    will only have work to do if an error was thrown while processing the
1863    dwarf.  If no error was thrown then the queue entries should have all
1864    been processed, and freed, as we went along.  */
1865
1866 class dwarf2_queue_guard
1867 {
1868 public:
1869   dwarf2_queue_guard () = default;
1870
1871   /* Free any entries remaining on the queue.  There should only be
1872      entries left if we hit an error while processing the dwarf.  */
1873   ~dwarf2_queue_guard ()
1874   {
1875     struct dwarf2_queue_item *item, *last;
1876
1877     item = dwarf2_queue;
1878     while (item)
1879       {
1880         /* Anything still marked queued is likely to be in an
1881            inconsistent state, so discard it.  */
1882         if (item->per_cu->queued)
1883           {
1884             if (item->per_cu->cu != NULL)
1885               free_one_cached_comp_unit (item->per_cu);
1886             item->per_cu->queued = 0;
1887           }
1888
1889         last = item;
1890         item = item->next;
1891         xfree (last);
1892       }
1893
1894     dwarf2_queue = dwarf2_queue_tail = NULL;
1895   }
1896 };
1897
1898 /* The return type of find_file_and_directory.  Note, the enclosed
1899    string pointers are only valid while this object is valid.  */
1900
1901 struct file_and_directory
1902 {
1903   /* The filename.  This is never NULL.  */
1904   const char *name;
1905
1906   /* The compilation directory.  NULL if not known.  If we needed to
1907      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1908      points directly to the DW_AT_comp_dir string attribute owned by
1909      the obstack that owns the DIE.  */
1910   const char *comp_dir;
1911
1912   /* If we needed to build a new string for comp_dir, this is what
1913      owns the storage.  */
1914   std::string comp_dir_storage;
1915 };
1916
1917 static file_and_directory find_file_and_directory (struct die_info *die,
1918                                                    struct dwarf2_cu *cu);
1919
1920 static char *file_full_name (int file, struct line_header *lh,
1921                              const char *comp_dir);
1922
1923 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1924 enum class rcuh_kind { COMPILE, TYPE };
1925
1926 static const gdb_byte *read_and_check_comp_unit_head
1927   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1928    struct comp_unit_head *header,
1929    struct dwarf2_section_info *section,
1930    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1931    rcuh_kind section_kind);
1932
1933 static void init_cutu_and_read_dies
1934   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1935    int use_existing_cu, int keep,
1936    die_reader_func_ftype *die_reader_func, void *data);
1937
1938 static void init_cutu_and_read_dies_simple
1939   (struct dwarf2_per_cu_data *this_cu,
1940    die_reader_func_ftype *die_reader_func, void *data);
1941
1942 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1943
1944 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1945
1946 static struct dwo_unit *lookup_dwo_unit_in_dwp
1947   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1948    struct dwp_file *dwp_file, const char *comp_dir,
1949    ULONGEST signature, int is_debug_types);
1950
1951 static struct dwp_file *get_dwp_file
1952   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1953
1954 static struct dwo_unit *lookup_dwo_comp_unit
1955   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1956
1957 static struct dwo_unit *lookup_dwo_type_unit
1958   (struct signatured_type *, const char *, const char *);
1959
1960 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1961
1962 static void free_dwo_file (struct dwo_file *);
1963
1964 /* A unique_ptr helper to free a dwo_file.  */
1965
1966 struct dwo_file_deleter
1967 {
1968   void operator() (struct dwo_file *df) const
1969   {
1970     free_dwo_file (df);
1971   }
1972 };
1973
1974 /* A unique pointer to a dwo_file.  */
1975
1976 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
1977
1978 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1979
1980 static void check_producer (struct dwarf2_cu *cu);
1981
1982 static void free_line_header_voidp (void *arg);
1983 \f
1984 /* Various complaints about symbol reading that don't abort the process.  */
1985
1986 static void
1987 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1988 {
1989   complaint (&symfile_complaints,
1990              _("statement list doesn't fit in .debug_line section"));
1991 }
1992
1993 static void
1994 dwarf2_debug_line_missing_file_complaint (void)
1995 {
1996   complaint (&symfile_complaints,
1997              _(".debug_line section has line data without a file"));
1998 }
1999
2000 static void
2001 dwarf2_debug_line_missing_end_sequence_complaint (void)
2002 {
2003   complaint (&symfile_complaints,
2004              _(".debug_line section has line "
2005                "program sequence without an end"));
2006 }
2007
2008 static void
2009 dwarf2_complex_location_expr_complaint (void)
2010 {
2011   complaint (&symfile_complaints, _("location expression too complex"));
2012 }
2013
2014 static void
2015 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2016                                               int arg3)
2017 {
2018   complaint (&symfile_complaints,
2019              _("const value length mismatch for '%s', got %d, expected %d"),
2020              arg1, arg2, arg3);
2021 }
2022
2023 static void
2024 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2025 {
2026   complaint (&symfile_complaints,
2027              _("debug info runs off end of %s section"
2028                " [in module %s]"),
2029              get_section_name (section),
2030              get_section_file_name (section));
2031 }
2032
2033 static void
2034 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2035 {
2036   complaint (&symfile_complaints,
2037              _("macro debug info contains a "
2038                "malformed macro definition:\n`%s'"),
2039              arg1);
2040 }
2041
2042 static void
2043 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2044 {
2045   complaint (&symfile_complaints,
2046              _("invalid attribute class or form for '%s' in '%s'"),
2047              arg1, arg2);
2048 }
2049
2050 /* Hash function for line_header_hash.  */
2051
2052 static hashval_t
2053 line_header_hash (const struct line_header *ofs)
2054 {
2055   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2056 }
2057
2058 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2059
2060 static hashval_t
2061 line_header_hash_voidp (const void *item)
2062 {
2063   const struct line_header *ofs = (const struct line_header *) item;
2064
2065   return line_header_hash (ofs);
2066 }
2067
2068 /* Equality function for line_header_hash.  */
2069
2070 static int
2071 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2072 {
2073   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2074   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2075
2076   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2077           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2078 }
2079
2080 \f
2081
2082 /* Read the given attribute value as an address, taking the attribute's
2083    form into account.  */
2084
2085 static CORE_ADDR
2086 attr_value_as_address (struct attribute *attr)
2087 {
2088   CORE_ADDR addr;
2089
2090   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2091     {
2092       /* Aside from a few clearly defined exceptions, attributes that
2093          contain an address must always be in DW_FORM_addr form.
2094          Unfortunately, some compilers happen to be violating this
2095          requirement by encoding addresses using other forms, such
2096          as DW_FORM_data4 for example.  For those broken compilers,
2097          we try to do our best, without any guarantee of success,
2098          to interpret the address correctly.  It would also be nice
2099          to generate a complaint, but that would require us to maintain
2100          a list of legitimate cases where a non-address form is allowed,
2101          as well as update callers to pass in at least the CU's DWARF
2102          version.  This is more overhead than what we're willing to
2103          expand for a pretty rare case.  */
2104       addr = DW_UNSND (attr);
2105     }
2106   else
2107     addr = DW_ADDR (attr);
2108
2109   return addr;
2110 }
2111
2112 /* See declaration.  */
2113
2114 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2115                                         const dwarf2_debug_sections *names)
2116   : objfile (objfile_)
2117 {
2118   if (names == NULL)
2119     names = &dwarf2_elf_names;
2120
2121   bfd *obfd = objfile->obfd;
2122
2123   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2124     locate_sections (obfd, sec, *names);
2125 }
2126
2127 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2128
2129 dwarf2_per_objfile::~dwarf2_per_objfile ()
2130 {
2131   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2132   free_cached_comp_units ();
2133
2134   if (quick_file_names_table)
2135     htab_delete (quick_file_names_table);
2136
2137   if (line_header_hash)
2138     htab_delete (line_header_hash);
2139
2140   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2141     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2142
2143   for (signatured_type *sig_type : all_type_units)
2144     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2145
2146   VEC_free (dwarf2_section_info_def, types);
2147
2148   if (dwo_files != NULL)
2149     free_dwo_files (dwo_files, objfile);
2150   if (dwp_file != NULL)
2151     gdb_bfd_unref (dwp_file->dbfd);
2152
2153   if (dwz_file != NULL && dwz_file->dwz_bfd)
2154     gdb_bfd_unref (dwz_file->dwz_bfd);
2155
2156   if (index_table != NULL)
2157     index_table->~mapped_index ();
2158
2159   /* Everything else should be on the objfile obstack.  */
2160 }
2161
2162 /* See declaration.  */
2163
2164 void
2165 dwarf2_per_objfile::free_cached_comp_units ()
2166 {
2167   dwarf2_per_cu_data *per_cu = read_in_chain;
2168   dwarf2_per_cu_data **last_chain = &read_in_chain;
2169   while (per_cu != NULL)
2170     {
2171       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2172
2173       delete per_cu->cu;
2174       *last_chain = next_cu;
2175       per_cu = next_cu;
2176     }
2177 }
2178
2179 /* A helper class that calls free_cached_comp_units on
2180    destruction.  */
2181
2182 class free_cached_comp_units
2183 {
2184 public:
2185
2186   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2187     : m_per_objfile (per_objfile)
2188   {
2189   }
2190
2191   ~free_cached_comp_units ()
2192   {
2193     m_per_objfile->free_cached_comp_units ();
2194   }
2195
2196   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2197
2198 private:
2199
2200   dwarf2_per_objfile *m_per_objfile;
2201 };
2202
2203 /* Try to locate the sections we need for DWARF 2 debugging
2204    information and return true if we have enough to do something.
2205    NAMES points to the dwarf2 section names, or is NULL if the standard
2206    ELF names are used.  */
2207
2208 int
2209 dwarf2_has_info (struct objfile *objfile,
2210                  const struct dwarf2_debug_sections *names)
2211 {
2212   if (objfile->flags & OBJF_READNEVER)
2213     return 0;
2214
2215   struct dwarf2_per_objfile *dwarf2_per_objfile
2216     = get_dwarf2_per_objfile (objfile);
2217
2218   if (dwarf2_per_objfile == NULL)
2219     {
2220       /* Initialize per-objfile state.  */
2221       dwarf2_per_objfile
2222         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2223                                                                      names);
2224       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2225     }
2226   return (!dwarf2_per_objfile->info.is_virtual
2227           && dwarf2_per_objfile->info.s.section != NULL
2228           && !dwarf2_per_objfile->abbrev.is_virtual
2229           && dwarf2_per_objfile->abbrev.s.section != NULL);
2230 }
2231
2232 /* Return the containing section of virtual section SECTION.  */
2233
2234 static struct dwarf2_section_info *
2235 get_containing_section (const struct dwarf2_section_info *section)
2236 {
2237   gdb_assert (section->is_virtual);
2238   return section->s.containing_section;
2239 }
2240
2241 /* Return the bfd owner of SECTION.  */
2242
2243 static struct bfd *
2244 get_section_bfd_owner (const struct dwarf2_section_info *section)
2245 {
2246   if (section->is_virtual)
2247     {
2248       section = get_containing_section (section);
2249       gdb_assert (!section->is_virtual);
2250     }
2251   return section->s.section->owner;
2252 }
2253
2254 /* Return the bfd section of SECTION.
2255    Returns NULL if the section is not present.  */
2256
2257 static asection *
2258 get_section_bfd_section (const struct dwarf2_section_info *section)
2259 {
2260   if (section->is_virtual)
2261     {
2262       section = get_containing_section (section);
2263       gdb_assert (!section->is_virtual);
2264     }
2265   return section->s.section;
2266 }
2267
2268 /* Return the name of SECTION.  */
2269
2270 static const char *
2271 get_section_name (const struct dwarf2_section_info *section)
2272 {
2273   asection *sectp = get_section_bfd_section (section);
2274
2275   gdb_assert (sectp != NULL);
2276   return bfd_section_name (get_section_bfd_owner (section), sectp);
2277 }
2278
2279 /* Return the name of the file SECTION is in.  */
2280
2281 static const char *
2282 get_section_file_name (const struct dwarf2_section_info *section)
2283 {
2284   bfd *abfd = get_section_bfd_owner (section);
2285
2286   return bfd_get_filename (abfd);
2287 }
2288
2289 /* Return the id of SECTION.
2290    Returns 0 if SECTION doesn't exist.  */
2291
2292 static int
2293 get_section_id (const struct dwarf2_section_info *section)
2294 {
2295   asection *sectp = get_section_bfd_section (section);
2296
2297   if (sectp == NULL)
2298     return 0;
2299   return sectp->id;
2300 }
2301
2302 /* Return the flags of SECTION.
2303    SECTION (or containing section if this is a virtual section) must exist.  */
2304
2305 static int
2306 get_section_flags (const struct dwarf2_section_info *section)
2307 {
2308   asection *sectp = get_section_bfd_section (section);
2309
2310   gdb_assert (sectp != NULL);
2311   return bfd_get_section_flags (sectp->owner, sectp);
2312 }
2313
2314 /* When loading sections, we look either for uncompressed section or for
2315    compressed section names.  */
2316
2317 static int
2318 section_is_p (const char *section_name,
2319               const struct dwarf2_section_names *names)
2320 {
2321   if (names->normal != NULL
2322       && strcmp (section_name, names->normal) == 0)
2323     return 1;
2324   if (names->compressed != NULL
2325       && strcmp (section_name, names->compressed) == 0)
2326     return 1;
2327   return 0;
2328 }
2329
2330 /* See declaration.  */
2331
2332 void
2333 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2334                                      const dwarf2_debug_sections &names)
2335 {
2336   flagword aflag = bfd_get_section_flags (abfd, sectp);
2337
2338   if ((aflag & SEC_HAS_CONTENTS) == 0)
2339     {
2340     }
2341   else if (section_is_p (sectp->name, &names.info))
2342     {
2343       this->info.s.section = sectp;
2344       this->info.size = bfd_get_section_size (sectp);
2345     }
2346   else if (section_is_p (sectp->name, &names.abbrev))
2347     {
2348       this->abbrev.s.section = sectp;
2349       this->abbrev.size = bfd_get_section_size (sectp);
2350     }
2351   else if (section_is_p (sectp->name, &names.line))
2352     {
2353       this->line.s.section = sectp;
2354       this->line.size = bfd_get_section_size (sectp);
2355     }
2356   else if (section_is_p (sectp->name, &names.loc))
2357     {
2358       this->loc.s.section = sectp;
2359       this->loc.size = bfd_get_section_size (sectp);
2360     }
2361   else if (section_is_p (sectp->name, &names.loclists))
2362     {
2363       this->loclists.s.section = sectp;
2364       this->loclists.size = bfd_get_section_size (sectp);
2365     }
2366   else if (section_is_p (sectp->name, &names.macinfo))
2367     {
2368       this->macinfo.s.section = sectp;
2369       this->macinfo.size = bfd_get_section_size (sectp);
2370     }
2371   else if (section_is_p (sectp->name, &names.macro))
2372     {
2373       this->macro.s.section = sectp;
2374       this->macro.size = bfd_get_section_size (sectp);
2375     }
2376   else if (section_is_p (sectp->name, &names.str))
2377     {
2378       this->str.s.section = sectp;
2379       this->str.size = bfd_get_section_size (sectp);
2380     }
2381   else if (section_is_p (sectp->name, &names.line_str))
2382     {
2383       this->line_str.s.section = sectp;
2384       this->line_str.size = bfd_get_section_size (sectp);
2385     }
2386   else if (section_is_p (sectp->name, &names.addr))
2387     {
2388       this->addr.s.section = sectp;
2389       this->addr.size = bfd_get_section_size (sectp);
2390     }
2391   else if (section_is_p (sectp->name, &names.frame))
2392     {
2393       this->frame.s.section = sectp;
2394       this->frame.size = bfd_get_section_size (sectp);
2395     }
2396   else if (section_is_p (sectp->name, &names.eh_frame))
2397     {
2398       this->eh_frame.s.section = sectp;
2399       this->eh_frame.size = bfd_get_section_size (sectp);
2400     }
2401   else if (section_is_p (sectp->name, &names.ranges))
2402     {
2403       this->ranges.s.section = sectp;
2404       this->ranges.size = bfd_get_section_size (sectp);
2405     }
2406   else if (section_is_p (sectp->name, &names.rnglists))
2407     {
2408       this->rnglists.s.section = sectp;
2409       this->rnglists.size = bfd_get_section_size (sectp);
2410     }
2411   else if (section_is_p (sectp->name, &names.types))
2412     {
2413       struct dwarf2_section_info type_section;
2414
2415       memset (&type_section, 0, sizeof (type_section));
2416       type_section.s.section = sectp;
2417       type_section.size = bfd_get_section_size (sectp);
2418
2419       VEC_safe_push (dwarf2_section_info_def, this->types,
2420                      &type_section);
2421     }
2422   else if (section_is_p (sectp->name, &names.gdb_index))
2423     {
2424       this->gdb_index.s.section = sectp;
2425       this->gdb_index.size = bfd_get_section_size (sectp);
2426     }
2427   else if (section_is_p (sectp->name, &names.debug_names))
2428     {
2429       this->debug_names.s.section = sectp;
2430       this->debug_names.size = bfd_get_section_size (sectp);
2431     }
2432   else if (section_is_p (sectp->name, &names.debug_aranges))
2433     {
2434       this->debug_aranges.s.section = sectp;
2435       this->debug_aranges.size = bfd_get_section_size (sectp);
2436     }
2437
2438   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2439       && bfd_section_vma (abfd, sectp) == 0)
2440     this->has_section_at_zero = true;
2441 }
2442
2443 /* A helper function that decides whether a section is empty,
2444    or not present.  */
2445
2446 static int
2447 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2448 {
2449   if (section->is_virtual)
2450     return section->size == 0;
2451   return section->s.section == NULL || section->size == 0;
2452 }
2453
2454 /* See dwarf2read.h.  */
2455
2456 void
2457 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2458 {
2459   asection *sectp;
2460   bfd *abfd;
2461   gdb_byte *buf, *retbuf;
2462
2463   if (info->readin)
2464     return;
2465   info->buffer = NULL;
2466   info->readin = 1;
2467
2468   if (dwarf2_section_empty_p (info))
2469     return;
2470
2471   sectp = get_section_bfd_section (info);
2472
2473   /* If this is a virtual section we need to read in the real one first.  */
2474   if (info->is_virtual)
2475     {
2476       struct dwarf2_section_info *containing_section =
2477         get_containing_section (info);
2478
2479       gdb_assert (sectp != NULL);
2480       if ((sectp->flags & SEC_RELOC) != 0)
2481         {
2482           error (_("Dwarf Error: DWP format V2 with relocations is not"
2483                    " supported in section %s [in module %s]"),
2484                  get_section_name (info), get_section_file_name (info));
2485         }
2486       dwarf2_read_section (objfile, containing_section);
2487       /* Other code should have already caught virtual sections that don't
2488          fit.  */
2489       gdb_assert (info->virtual_offset + info->size
2490                   <= containing_section->size);
2491       /* If the real section is empty or there was a problem reading the
2492          section we shouldn't get here.  */
2493       gdb_assert (containing_section->buffer != NULL);
2494       info->buffer = containing_section->buffer + info->virtual_offset;
2495       return;
2496     }
2497
2498   /* If the section has relocations, we must read it ourselves.
2499      Otherwise we attach it to the BFD.  */
2500   if ((sectp->flags & SEC_RELOC) == 0)
2501     {
2502       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2503       return;
2504     }
2505
2506   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2507   info->buffer = buf;
2508
2509   /* When debugging .o files, we may need to apply relocations; see
2510      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2511      We never compress sections in .o files, so we only need to
2512      try this when the section is not compressed.  */
2513   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2514   if (retbuf != NULL)
2515     {
2516       info->buffer = retbuf;
2517       return;
2518     }
2519
2520   abfd = get_section_bfd_owner (info);
2521   gdb_assert (abfd != NULL);
2522
2523   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2524       || bfd_bread (buf, info->size, abfd) != info->size)
2525     {
2526       error (_("Dwarf Error: Can't read DWARF data"
2527                " in section %s [in module %s]"),
2528              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2529     }
2530 }
2531
2532 /* A helper function that returns the size of a section in a safe way.
2533    If you are positive that the section has been read before using the
2534    size, then it is safe to refer to the dwarf2_section_info object's
2535    "size" field directly.  In other cases, you must call this
2536    function, because for compressed sections the size field is not set
2537    correctly until the section has been read.  */
2538
2539 static bfd_size_type
2540 dwarf2_section_size (struct objfile *objfile,
2541                      struct dwarf2_section_info *info)
2542 {
2543   if (!info->readin)
2544     dwarf2_read_section (objfile, info);
2545   return info->size;
2546 }
2547
2548 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2549    SECTION_NAME.  */
2550
2551 void
2552 dwarf2_get_section_info (struct objfile *objfile,
2553                          enum dwarf2_section_enum sect,
2554                          asection **sectp, const gdb_byte **bufp,
2555                          bfd_size_type *sizep)
2556 {
2557   struct dwarf2_per_objfile *data
2558     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2559                                                   dwarf2_objfile_data_key);
2560   struct dwarf2_section_info *info;
2561
2562   /* We may see an objfile without any DWARF, in which case we just
2563      return nothing.  */
2564   if (data == NULL)
2565     {
2566       *sectp = NULL;
2567       *bufp = NULL;
2568       *sizep = 0;
2569       return;
2570     }
2571   switch (sect)
2572     {
2573     case DWARF2_DEBUG_FRAME:
2574       info = &data->frame;
2575       break;
2576     case DWARF2_EH_FRAME:
2577       info = &data->eh_frame;
2578       break;
2579     default:
2580       gdb_assert_not_reached ("unexpected section");
2581     }
2582
2583   dwarf2_read_section (objfile, info);
2584
2585   *sectp = get_section_bfd_section (info);
2586   *bufp = info->buffer;
2587   *sizep = info->size;
2588 }
2589
2590 /* A helper function to find the sections for a .dwz file.  */
2591
2592 static void
2593 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2594 {
2595   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2596
2597   /* Note that we only support the standard ELF names, because .dwz
2598      is ELF-only (at the time of writing).  */
2599   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2600     {
2601       dwz_file->abbrev.s.section = sectp;
2602       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2603     }
2604   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2605     {
2606       dwz_file->info.s.section = sectp;
2607       dwz_file->info.size = bfd_get_section_size (sectp);
2608     }
2609   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2610     {
2611       dwz_file->str.s.section = sectp;
2612       dwz_file->str.size = bfd_get_section_size (sectp);
2613     }
2614   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2615     {
2616       dwz_file->line.s.section = sectp;
2617       dwz_file->line.size = bfd_get_section_size (sectp);
2618     }
2619   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2620     {
2621       dwz_file->macro.s.section = sectp;
2622       dwz_file->macro.size = bfd_get_section_size (sectp);
2623     }
2624   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2625     {
2626       dwz_file->gdb_index.s.section = sectp;
2627       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2628     }
2629   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2630     {
2631       dwz_file->debug_names.s.section = sectp;
2632       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2633     }
2634 }
2635
2636 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2637    there is no .gnu_debugaltlink section in the file.  Error if there
2638    is such a section but the file cannot be found.  */
2639
2640 static struct dwz_file *
2641 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2642 {
2643   const char *filename;
2644   struct dwz_file *result;
2645   bfd_size_type buildid_len_arg;
2646   size_t buildid_len;
2647   bfd_byte *buildid;
2648
2649   if (dwarf2_per_objfile->dwz_file != NULL)
2650     return dwarf2_per_objfile->dwz_file;
2651
2652   bfd_set_error (bfd_error_no_error);
2653   gdb::unique_xmalloc_ptr<char> data
2654     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2655                                   &buildid_len_arg, &buildid));
2656   if (data == NULL)
2657     {
2658       if (bfd_get_error () == bfd_error_no_error)
2659         return NULL;
2660       error (_("could not read '.gnu_debugaltlink' section: %s"),
2661              bfd_errmsg (bfd_get_error ()));
2662     }
2663
2664   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2665
2666   buildid_len = (size_t) buildid_len_arg;
2667
2668   filename = data.get ();
2669
2670   std::string abs_storage;
2671   if (!IS_ABSOLUTE_PATH (filename))
2672     {
2673       gdb::unique_xmalloc_ptr<char> abs
2674         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2675
2676       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2677       filename = abs_storage.c_str ();
2678     }
2679
2680   /* First try the file name given in the section.  If that doesn't
2681      work, try to use the build-id instead.  */
2682   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2683   if (dwz_bfd != NULL)
2684     {
2685       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2686         dwz_bfd.release ();
2687     }
2688
2689   if (dwz_bfd == NULL)
2690     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2691
2692   if (dwz_bfd == NULL)
2693     error (_("could not find '.gnu_debugaltlink' file for %s"),
2694            objfile_name (dwarf2_per_objfile->objfile));
2695
2696   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2697                            struct dwz_file);
2698   result->dwz_bfd = dwz_bfd.release ();
2699
2700   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2701
2702   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2703   dwarf2_per_objfile->dwz_file = result;
2704   return result;
2705 }
2706 \f
2707 /* DWARF quick_symbols_functions support.  */
2708
2709 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2710    unique line tables, so we maintain a separate table of all .debug_line
2711    derived entries to support the sharing.
2712    All the quick functions need is the list of file names.  We discard the
2713    line_header when we're done and don't need to record it here.  */
2714 struct quick_file_names
2715 {
2716   /* The data used to construct the hash key.  */
2717   struct stmt_list_hash hash;
2718
2719   /* The number of entries in file_names, real_names.  */
2720   unsigned int num_file_names;
2721
2722   /* The file names from the line table, after being run through
2723      file_full_name.  */
2724   const char **file_names;
2725
2726   /* The file names from the line table after being run through
2727      gdb_realpath.  These are computed lazily.  */
2728   const char **real_names;
2729 };
2730
2731 /* When using the index (and thus not using psymtabs), each CU has an
2732    object of this type.  This is used to hold information needed by
2733    the various "quick" methods.  */
2734 struct dwarf2_per_cu_quick_data
2735 {
2736   /* The file table.  This can be NULL if there was no file table
2737      or it's currently not read in.
2738      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2739   struct quick_file_names *file_names;
2740
2741   /* The corresponding symbol table.  This is NULL if symbols for this
2742      CU have not yet been read.  */
2743   struct compunit_symtab *compunit_symtab;
2744
2745   /* A temporary mark bit used when iterating over all CUs in
2746      expand_symtabs_matching.  */
2747   unsigned int mark : 1;
2748
2749   /* True if we've tried to read the file table and found there isn't one.
2750      There will be no point in trying to read it again next time.  */
2751   unsigned int no_file_data : 1;
2752 };
2753
2754 /* Utility hash function for a stmt_list_hash.  */
2755
2756 static hashval_t
2757 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2758 {
2759   hashval_t v = 0;
2760
2761   if (stmt_list_hash->dwo_unit != NULL)
2762     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2763   v += to_underlying (stmt_list_hash->line_sect_off);
2764   return v;
2765 }
2766
2767 /* Utility equality function for a stmt_list_hash.  */
2768
2769 static int
2770 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2771                     const struct stmt_list_hash *rhs)
2772 {
2773   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2774     return 0;
2775   if (lhs->dwo_unit != NULL
2776       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2777     return 0;
2778
2779   return lhs->line_sect_off == rhs->line_sect_off;
2780 }
2781
2782 /* Hash function for a quick_file_names.  */
2783
2784 static hashval_t
2785 hash_file_name_entry (const void *e)
2786 {
2787   const struct quick_file_names *file_data
2788     = (const struct quick_file_names *) e;
2789
2790   return hash_stmt_list_entry (&file_data->hash);
2791 }
2792
2793 /* Equality function for a quick_file_names.  */
2794
2795 static int
2796 eq_file_name_entry (const void *a, const void *b)
2797 {
2798   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2799   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2800
2801   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2802 }
2803
2804 /* Delete function for a quick_file_names.  */
2805
2806 static void
2807 delete_file_name_entry (void *e)
2808 {
2809   struct quick_file_names *file_data = (struct quick_file_names *) e;
2810   int i;
2811
2812   for (i = 0; i < file_data->num_file_names; ++i)
2813     {
2814       xfree ((void*) file_data->file_names[i]);
2815       if (file_data->real_names)
2816         xfree ((void*) file_data->real_names[i]);
2817     }
2818
2819   /* The space for the struct itself lives on objfile_obstack,
2820      so we don't free it here.  */
2821 }
2822
2823 /* Create a quick_file_names hash table.  */
2824
2825 static htab_t
2826 create_quick_file_names_table (unsigned int nr_initial_entries)
2827 {
2828   return htab_create_alloc (nr_initial_entries,
2829                             hash_file_name_entry, eq_file_name_entry,
2830                             delete_file_name_entry, xcalloc, xfree);
2831 }
2832
2833 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2834    have to be created afterwards.  You should call age_cached_comp_units after
2835    processing PER_CU->CU.  dw2_setup must have been already called.  */
2836
2837 static void
2838 load_cu (struct dwarf2_per_cu_data *per_cu)
2839 {
2840   if (per_cu->is_debug_types)
2841     load_full_type_unit (per_cu);
2842   else
2843     load_full_comp_unit (per_cu, language_minimal);
2844
2845   if (per_cu->cu == NULL)
2846     return;  /* Dummy CU.  */
2847
2848   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2849 }
2850
2851 /* Read in the symbols for PER_CU.  */
2852
2853 static void
2854 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2855 {
2856   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2857
2858   /* Skip type_unit_groups, reading the type units they contain
2859      is handled elsewhere.  */
2860   if (IS_TYPE_UNIT_GROUP (per_cu))
2861     return;
2862
2863   /* The destructor of dwarf2_queue_guard frees any entries left on
2864      the queue.  After this point we're guaranteed to leave this function
2865      with the dwarf queue empty.  */
2866   dwarf2_queue_guard q_guard;
2867
2868   if (dwarf2_per_objfile->using_index
2869       ? per_cu->v.quick->compunit_symtab == NULL
2870       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2871     {
2872       queue_comp_unit (per_cu, language_minimal);
2873       load_cu (per_cu);
2874
2875       /* If we just loaded a CU from a DWO, and we're working with an index
2876          that may badly handle TUs, load all the TUs in that DWO as well.
2877          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2878       if (!per_cu->is_debug_types
2879           && per_cu->cu != NULL
2880           && per_cu->cu->dwo_unit != NULL
2881           && dwarf2_per_objfile->index_table != NULL
2882           && dwarf2_per_objfile->index_table->version <= 7
2883           /* DWP files aren't supported yet.  */
2884           && get_dwp_file (dwarf2_per_objfile) == NULL)
2885         queue_and_load_all_dwo_tus (per_cu);
2886     }
2887
2888   process_queue (dwarf2_per_objfile);
2889
2890   /* Age the cache, releasing compilation units that have not
2891      been used recently.  */
2892   age_cached_comp_units (dwarf2_per_objfile);
2893 }
2894
2895 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2896    the objfile from which this CU came.  Returns the resulting symbol
2897    table.  */
2898
2899 static struct compunit_symtab *
2900 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2901 {
2902   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2903
2904   gdb_assert (dwarf2_per_objfile->using_index);
2905   if (!per_cu->v.quick->compunit_symtab)
2906     {
2907       free_cached_comp_units freer (dwarf2_per_objfile);
2908       scoped_restore decrementer = increment_reading_symtab ();
2909       dw2_do_instantiate_symtab (per_cu);
2910       process_cu_includes (dwarf2_per_objfile);
2911     }
2912
2913   return per_cu->v.quick->compunit_symtab;
2914 }
2915
2916 /* See declaration.  */
2917
2918 dwarf2_per_cu_data *
2919 dwarf2_per_objfile::get_cutu (int index)
2920 {
2921   if (index >= this->all_comp_units.size ())
2922     {
2923       index -= this->all_comp_units.size ();
2924       gdb_assert (index < this->all_type_units.size ());
2925       return &this->all_type_units[index]->per_cu;
2926     }
2927
2928   return this->all_comp_units[index];
2929 }
2930
2931 /* See declaration.  */
2932
2933 dwarf2_per_cu_data *
2934 dwarf2_per_objfile::get_cu (int index)
2935 {
2936   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2937
2938   return this->all_comp_units[index];
2939 }
2940
2941 /* See declaration.  */
2942
2943 signatured_type *
2944 dwarf2_per_objfile::get_tu (int index)
2945 {
2946   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2947
2948   return this->all_type_units[index];
2949 }
2950
2951 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2952    objfile_obstack, and constructed with the specified field
2953    values.  */
2954
2955 static dwarf2_per_cu_data *
2956 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2957                           struct dwarf2_section_info *section,
2958                           int is_dwz,
2959                           sect_offset sect_off, ULONGEST length)
2960 {
2961   struct objfile *objfile = dwarf2_per_objfile->objfile;
2962   dwarf2_per_cu_data *the_cu
2963     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2964                      struct dwarf2_per_cu_data);
2965   the_cu->sect_off = sect_off;
2966   the_cu->length = length;
2967   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2968   the_cu->section = section;
2969   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2970                                    struct dwarf2_per_cu_quick_data);
2971   the_cu->is_dwz = is_dwz;
2972   return the_cu;
2973 }
2974
2975 /* A helper for create_cus_from_index that handles a given list of
2976    CUs.  */
2977
2978 static void
2979 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2980                             const gdb_byte *cu_list, offset_type n_elements,
2981                             struct dwarf2_section_info *section,
2982                             int is_dwz)
2983 {
2984   for (offset_type i = 0; i < n_elements; i += 2)
2985     {
2986       gdb_static_assert (sizeof (ULONGEST) >= 8);
2987
2988       sect_offset sect_off
2989         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2990       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2991       cu_list += 2 * 8;
2992
2993       dwarf2_per_cu_data *per_cu
2994         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2995                                      sect_off, length);
2996       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2997     }
2998 }
2999
3000 /* Read the CU list from the mapped index, and use it to create all
3001    the CU objects for this objfile.  */
3002
3003 static void
3004 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3005                        const gdb_byte *cu_list, offset_type cu_list_elements,
3006                        const gdb_byte *dwz_list, offset_type dwz_elements)
3007 {
3008   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3009   dwarf2_per_objfile->all_comp_units.reserve
3010     ((cu_list_elements + dwz_elements) / 2);
3011
3012   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3013                               &dwarf2_per_objfile->info, 0);
3014
3015   if (dwz_elements == 0)
3016     return;
3017
3018   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3019   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3020                               &dwz->info, 1);
3021 }
3022
3023 /* Create the signatured type hash table from the index.  */
3024
3025 static void
3026 create_signatured_type_table_from_index
3027   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3028    struct dwarf2_section_info *section,
3029    const gdb_byte *bytes,
3030    offset_type elements)
3031 {
3032   struct objfile *objfile = dwarf2_per_objfile->objfile;
3033
3034   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3035   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3036
3037   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3038
3039   for (offset_type i = 0; i < elements; i += 3)
3040     {
3041       struct signatured_type *sig_type;
3042       ULONGEST signature;
3043       void **slot;
3044       cu_offset type_offset_in_tu;
3045
3046       gdb_static_assert (sizeof (ULONGEST) >= 8);
3047       sect_offset sect_off
3048         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3049       type_offset_in_tu
3050         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3051                                                 BFD_ENDIAN_LITTLE);
3052       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3053       bytes += 3 * 8;
3054
3055       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3056                                  struct signatured_type);
3057       sig_type->signature = signature;
3058       sig_type->type_offset_in_tu = type_offset_in_tu;
3059       sig_type->per_cu.is_debug_types = 1;
3060       sig_type->per_cu.section = section;
3061       sig_type->per_cu.sect_off = sect_off;
3062       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3063       sig_type->per_cu.v.quick
3064         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3065                           struct dwarf2_per_cu_quick_data);
3066
3067       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3068       *slot = sig_type;
3069
3070       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3071     }
3072
3073   dwarf2_per_objfile->signatured_types = sig_types_hash;
3074 }
3075
3076 /* Create the signatured type hash table from .debug_names.  */
3077
3078 static void
3079 create_signatured_type_table_from_debug_names
3080   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3081    const mapped_debug_names &map,
3082    struct dwarf2_section_info *section,
3083    struct dwarf2_section_info *abbrev_section)
3084 {
3085   struct objfile *objfile = dwarf2_per_objfile->objfile;
3086
3087   dwarf2_read_section (objfile, section);
3088   dwarf2_read_section (objfile, abbrev_section);
3089
3090   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3091   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3092
3093   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3094
3095   for (uint32_t i = 0; i < map.tu_count; ++i)
3096     {
3097       struct signatured_type *sig_type;
3098       void **slot;
3099
3100       sect_offset sect_off
3101         = (sect_offset) (extract_unsigned_integer
3102                          (map.tu_table_reordered + i * map.offset_size,
3103                           map.offset_size,
3104                           map.dwarf5_byte_order));
3105
3106       comp_unit_head cu_header;
3107       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3108                                      abbrev_section,
3109                                      section->buffer + to_underlying (sect_off),
3110                                      rcuh_kind::TYPE);
3111
3112       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3113                                  struct signatured_type);
3114       sig_type->signature = cu_header.signature;
3115       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3116       sig_type->per_cu.is_debug_types = 1;
3117       sig_type->per_cu.section = section;
3118       sig_type->per_cu.sect_off = sect_off;
3119       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3120       sig_type->per_cu.v.quick
3121         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3122                           struct dwarf2_per_cu_quick_data);
3123
3124       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3125       *slot = sig_type;
3126
3127       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3128     }
3129
3130   dwarf2_per_objfile->signatured_types = sig_types_hash;
3131 }
3132
3133 /* Read the address map data from the mapped index, and use it to
3134    populate the objfile's psymtabs_addrmap.  */
3135
3136 static void
3137 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3138                            struct mapped_index *index)
3139 {
3140   struct objfile *objfile = dwarf2_per_objfile->objfile;
3141   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3142   const gdb_byte *iter, *end;
3143   struct addrmap *mutable_map;
3144   CORE_ADDR baseaddr;
3145
3146   auto_obstack temp_obstack;
3147
3148   mutable_map = addrmap_create_mutable (&temp_obstack);
3149
3150   iter = index->address_table.data ();
3151   end = iter + index->address_table.size ();
3152
3153   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3154
3155   while (iter < end)
3156     {
3157       ULONGEST hi, lo, cu_index;
3158       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3159       iter += 8;
3160       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3161       iter += 8;
3162       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3163       iter += 4;
3164
3165       if (lo > hi)
3166         {
3167           complaint (&symfile_complaints,
3168                      _(".gdb_index address table has invalid range (%s - %s)"),
3169                      hex_string (lo), hex_string (hi));
3170           continue;
3171         }
3172
3173       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3174         {
3175           complaint (&symfile_complaints,
3176                      _(".gdb_index address table has invalid CU number %u"),
3177                      (unsigned) cu_index);
3178           continue;
3179         }
3180
3181       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3182       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3183       addrmap_set_empty (mutable_map, lo, hi - 1,
3184                          dwarf2_per_objfile->get_cu (cu_index));
3185     }
3186
3187   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3188                                                     &objfile->objfile_obstack);
3189 }
3190
3191 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3192    populate the objfile's psymtabs_addrmap.  */
3193
3194 static void
3195 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3196                              struct dwarf2_section_info *section)
3197 {
3198   struct objfile *objfile = dwarf2_per_objfile->objfile;
3199   bfd *abfd = objfile->obfd;
3200   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3201   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3202                                        SECT_OFF_TEXT (objfile));
3203
3204   auto_obstack temp_obstack;
3205   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3206
3207   std::unordered_map<sect_offset,
3208                      dwarf2_per_cu_data *,
3209                      gdb::hash_enum<sect_offset>>
3210     debug_info_offset_to_per_cu;
3211   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3212     {
3213       const auto insertpair
3214         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3215       if (!insertpair.second)
3216         {
3217           warning (_("Section .debug_aranges in %s has duplicate "
3218                      "debug_info_offset %s, ignoring .debug_aranges."),
3219                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3220           return;
3221         }
3222     }
3223
3224   dwarf2_read_section (objfile, section);
3225
3226   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3227
3228   const gdb_byte *addr = section->buffer;
3229
3230   while (addr < section->buffer + section->size)
3231     {
3232       const gdb_byte *const entry_addr = addr;
3233       unsigned int bytes_read;
3234
3235       const LONGEST entry_length = read_initial_length (abfd, addr,
3236                                                         &bytes_read);
3237       addr += bytes_read;
3238
3239       const gdb_byte *const entry_end = addr + entry_length;
3240       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3241       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3242       if (addr + entry_length > section->buffer + section->size)
3243         {
3244           warning (_("Section .debug_aranges in %s entry at offset %zu "
3245                      "length %s exceeds section length %s, "
3246                      "ignoring .debug_aranges."),
3247                    objfile_name (objfile), entry_addr - section->buffer,
3248                    plongest (bytes_read + entry_length),
3249                    pulongest (section->size));
3250           return;
3251         }
3252
3253       /* The version number.  */
3254       const uint16_t version = read_2_bytes (abfd, addr);
3255       addr += 2;
3256       if (version != 2)
3257         {
3258           warning (_("Section .debug_aranges in %s entry at offset %zu "
3259                      "has unsupported version %d, ignoring .debug_aranges."),
3260                    objfile_name (objfile), entry_addr - section->buffer,
3261                    version);
3262           return;
3263         }
3264
3265       const uint64_t debug_info_offset
3266         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3267       addr += offset_size;
3268       const auto per_cu_it
3269         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3270       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3271         {
3272           warning (_("Section .debug_aranges in %s entry at offset %zu "
3273                      "debug_info_offset %s does not exists, "
3274                      "ignoring .debug_aranges."),
3275                    objfile_name (objfile), entry_addr - section->buffer,
3276                    pulongest (debug_info_offset));
3277           return;
3278         }
3279       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3280
3281       const uint8_t address_size = *addr++;
3282       if (address_size < 1 || address_size > 8)
3283         {
3284           warning (_("Section .debug_aranges in %s entry at offset %zu "
3285                      "address_size %u is invalid, ignoring .debug_aranges."),
3286                    objfile_name (objfile), entry_addr - section->buffer,
3287                    address_size);
3288           return;
3289         }
3290
3291       const uint8_t segment_selector_size = *addr++;
3292       if (segment_selector_size != 0)
3293         {
3294           warning (_("Section .debug_aranges in %s entry at offset %zu "
3295                      "segment_selector_size %u is not supported, "
3296                      "ignoring .debug_aranges."),
3297                    objfile_name (objfile), entry_addr - section->buffer,
3298                    segment_selector_size);
3299           return;
3300         }
3301
3302       /* Must pad to an alignment boundary that is twice the address
3303          size.  It is undocumented by the DWARF standard but GCC does
3304          use it.  */
3305       for (size_t padding = ((-(addr - section->buffer))
3306                              & (2 * address_size - 1));
3307            padding > 0; padding--)
3308         if (*addr++ != 0)
3309           {
3310             warning (_("Section .debug_aranges in %s entry at offset %zu "
3311                        "padding is not zero, ignoring .debug_aranges."),
3312                      objfile_name (objfile), entry_addr - section->buffer);
3313             return;
3314           }
3315
3316       for (;;)
3317         {
3318           if (addr + 2 * address_size > entry_end)
3319             {
3320               warning (_("Section .debug_aranges in %s entry at offset %zu "
3321                          "address list is not properly terminated, "
3322                          "ignoring .debug_aranges."),
3323                        objfile_name (objfile), entry_addr - section->buffer);
3324               return;
3325             }
3326           ULONGEST start = extract_unsigned_integer (addr, address_size,
3327                                                      dwarf5_byte_order);
3328           addr += address_size;
3329           ULONGEST length = extract_unsigned_integer (addr, address_size,
3330                                                       dwarf5_byte_order);
3331           addr += address_size;
3332           if (start == 0 && length == 0)
3333             break;
3334           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3335             {
3336               /* Symbol was eliminated due to a COMDAT group.  */
3337               continue;
3338             }
3339           ULONGEST end = start + length;
3340           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3341           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3342           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3343         }
3344     }
3345
3346   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3347                                                     &objfile->objfile_obstack);
3348 }
3349
3350 /* Find a slot in the mapped index INDEX for the object named NAME.
3351    If NAME is found, set *VEC_OUT to point to the CU vector in the
3352    constant pool and return true.  If NAME cannot be found, return
3353    false.  */
3354
3355 static bool
3356 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3357                           offset_type **vec_out)
3358 {
3359   offset_type hash;
3360   offset_type slot, step;
3361   int (*cmp) (const char *, const char *);
3362
3363   gdb::unique_xmalloc_ptr<char> without_params;
3364   if (current_language->la_language == language_cplus
3365       || current_language->la_language == language_fortran
3366       || current_language->la_language == language_d)
3367     {
3368       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3369          not contain any.  */
3370
3371       if (strchr (name, '(') != NULL)
3372         {
3373           without_params = cp_remove_params (name);
3374
3375           if (without_params != NULL)
3376             name = without_params.get ();
3377         }
3378     }
3379
3380   /* Index version 4 did not support case insensitive searches.  But the
3381      indices for case insensitive languages are built in lowercase, therefore
3382      simulate our NAME being searched is also lowercased.  */
3383   hash = mapped_index_string_hash ((index->version == 4
3384                                     && case_sensitivity == case_sensitive_off
3385                                     ? 5 : index->version),
3386                                    name);
3387
3388   slot = hash & (index->symbol_table.size () - 1);
3389   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3390   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3391
3392   for (;;)
3393     {
3394       const char *str;
3395
3396       const auto &bucket = index->symbol_table[slot];
3397       if (bucket.name == 0 && bucket.vec == 0)
3398         return false;
3399
3400       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3401       if (!cmp (name, str))
3402         {
3403           *vec_out = (offset_type *) (index->constant_pool
3404                                       + MAYBE_SWAP (bucket.vec));
3405           return true;
3406         }
3407
3408       slot = (slot + step) & (index->symbol_table.size () - 1);
3409     }
3410 }
3411
3412 /* A helper function that reads the .gdb_index from SECTION and fills
3413    in MAP.  FILENAME is the name of the file containing the section;
3414    it is used for error reporting.  DEPRECATED_OK is true if it is
3415    ok to use deprecated sections.
3416
3417    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3418    out parameters that are filled in with information about the CU and
3419    TU lists in the section.
3420
3421    Returns 1 if all went well, 0 otherwise.  */
3422
3423 static bool
3424 read_index_from_section (struct objfile *objfile,
3425                          const char *filename,
3426                          bool deprecated_ok,
3427                          struct dwarf2_section_info *section,
3428                          struct mapped_index *map,
3429                          const gdb_byte **cu_list,
3430                          offset_type *cu_list_elements,
3431                          const gdb_byte **types_list,
3432                          offset_type *types_list_elements)
3433 {
3434   const gdb_byte *addr;
3435   offset_type version;
3436   offset_type *metadata;
3437   int i;
3438
3439   if (dwarf2_section_empty_p (section))
3440     return 0;
3441
3442   /* Older elfutils strip versions could keep the section in the main
3443      executable while splitting it for the separate debug info file.  */
3444   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3445     return 0;
3446
3447   dwarf2_read_section (objfile, section);
3448
3449   addr = section->buffer;
3450   /* Version check.  */
3451   version = MAYBE_SWAP (*(offset_type *) addr);
3452   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3453      causes the index to behave very poorly for certain requests.  Version 3
3454      contained incomplete addrmap.  So, it seems better to just ignore such
3455      indices.  */
3456   if (version < 4)
3457     {
3458       static int warning_printed = 0;
3459       if (!warning_printed)
3460         {
3461           warning (_("Skipping obsolete .gdb_index section in %s."),
3462                    filename);
3463           warning_printed = 1;
3464         }
3465       return 0;
3466     }
3467   /* Index version 4 uses a different hash function than index version
3468      5 and later.
3469
3470      Versions earlier than 6 did not emit psymbols for inlined
3471      functions.  Using these files will cause GDB not to be able to
3472      set breakpoints on inlined functions by name, so we ignore these
3473      indices unless the user has done
3474      "set use-deprecated-index-sections on".  */
3475   if (version < 6 && !deprecated_ok)
3476     {
3477       static int warning_printed = 0;
3478       if (!warning_printed)
3479         {
3480           warning (_("\
3481 Skipping deprecated .gdb_index section in %s.\n\
3482 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3483 to use the section anyway."),
3484                    filename);
3485           warning_printed = 1;
3486         }
3487       return 0;
3488     }
3489   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3490      of the TU (for symbols coming from TUs),
3491      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3492      Plus gold-generated indices can have duplicate entries for global symbols,
3493      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3494      These are just performance bugs, and we can't distinguish gdb-generated
3495      indices from gold-generated ones, so issue no warning here.  */
3496
3497   /* Indexes with higher version than the one supported by GDB may be no
3498      longer backward compatible.  */
3499   if (version > 8)
3500     return 0;
3501
3502   map->version = version;
3503   map->total_size = section->size;
3504
3505   metadata = (offset_type *) (addr + sizeof (offset_type));
3506
3507   i = 0;
3508   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3509   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3510                        / 8);
3511   ++i;
3512
3513   *types_list = addr + MAYBE_SWAP (metadata[i]);
3514   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3515                            - MAYBE_SWAP (metadata[i]))
3516                           / 8);
3517   ++i;
3518
3519   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3520   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3521   map->address_table
3522     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3523   ++i;
3524
3525   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3526   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3527   map->symbol_table
3528     = gdb::array_view<mapped_index::symbol_table_slot>
3529        ((mapped_index::symbol_table_slot *) symbol_table,
3530         (mapped_index::symbol_table_slot *) symbol_table_end);
3531
3532   ++i;
3533   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3534
3535   return 1;
3536 }
3537
3538 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3539    elements of all the CUs and return 1.  Otherwise, return 0.  */
3540
3541 static int
3542 dwarf2_read_index (struct dwarf2_per_objfile *dwarf2_per_objfile)
3543 {
3544   struct mapped_index local_map, *map;
3545   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3546   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3547   struct dwz_file *dwz;
3548   struct objfile *objfile = dwarf2_per_objfile->objfile;
3549
3550   if (!read_index_from_section (objfile, objfile_name (objfile),
3551                                 use_deprecated_index_sections,
3552                                 &dwarf2_per_objfile->gdb_index, &local_map,
3553                                 &cu_list, &cu_list_elements,
3554                                 &types_list, &types_list_elements))
3555     return 0;
3556
3557   /* Don't use the index if it's empty.  */
3558   if (local_map.symbol_table.empty ())
3559     return 0;
3560
3561   /* If there is a .dwz file, read it so we can get its CU list as
3562      well.  */
3563   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3564   if (dwz != NULL)
3565     {
3566       struct mapped_index dwz_map;
3567       const gdb_byte *dwz_types_ignore;
3568       offset_type dwz_types_elements_ignore;
3569
3570       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3571                                     1,
3572                                     &dwz->gdb_index, &dwz_map,
3573                                     &dwz_list, &dwz_list_elements,
3574                                     &dwz_types_ignore,
3575                                     &dwz_types_elements_ignore))
3576         {
3577           warning (_("could not read '.gdb_index' section from %s; skipping"),
3578                    bfd_get_filename (dwz->dwz_bfd));
3579           return 0;
3580         }
3581     }
3582
3583   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3584                          dwz_list, dwz_list_elements);
3585
3586   if (types_list_elements)
3587     {
3588       struct dwarf2_section_info *section;
3589
3590       /* We can only handle a single .debug_types when we have an
3591          index.  */
3592       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3593         return 0;
3594
3595       section = VEC_index (dwarf2_section_info_def,
3596                            dwarf2_per_objfile->types, 0);
3597
3598       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3599                                                types_list, types_list_elements);
3600     }
3601
3602   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3603
3604   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3605   map = new (map) mapped_index ();
3606   *map = local_map;
3607
3608   dwarf2_per_objfile->index_table = map;
3609   dwarf2_per_objfile->using_index = 1;
3610   dwarf2_per_objfile->quick_file_names_table =
3611     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3612
3613   return 1;
3614 }
3615
3616 /* die_reader_func for dw2_get_file_names.  */
3617
3618 static void
3619 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3620                            const gdb_byte *info_ptr,
3621                            struct die_info *comp_unit_die,
3622                            int has_children,
3623                            void *data)
3624 {
3625   struct dwarf2_cu *cu = reader->cu;
3626   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3627   struct dwarf2_per_objfile *dwarf2_per_objfile
3628     = cu->per_cu->dwarf2_per_objfile;
3629   struct objfile *objfile = dwarf2_per_objfile->objfile;
3630   struct dwarf2_per_cu_data *lh_cu;
3631   struct attribute *attr;
3632   int i;
3633   void **slot;
3634   struct quick_file_names *qfn;
3635
3636   gdb_assert (! this_cu->is_debug_types);
3637
3638   /* Our callers never want to match partial units -- instead they
3639      will match the enclosing full CU.  */
3640   if (comp_unit_die->tag == DW_TAG_partial_unit)
3641     {
3642       this_cu->v.quick->no_file_data = 1;
3643       return;
3644     }
3645
3646   lh_cu = this_cu;
3647   slot = NULL;
3648
3649   line_header_up lh;
3650   sect_offset line_offset {};
3651
3652   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3653   if (attr)
3654     {
3655       struct quick_file_names find_entry;
3656
3657       line_offset = (sect_offset) DW_UNSND (attr);
3658
3659       /* We may have already read in this line header (TU line header sharing).
3660          If we have we're done.  */
3661       find_entry.hash.dwo_unit = cu->dwo_unit;
3662       find_entry.hash.line_sect_off = line_offset;
3663       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3664                              &find_entry, INSERT);
3665       if (*slot != NULL)
3666         {
3667           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3668           return;
3669         }
3670
3671       lh = dwarf_decode_line_header (line_offset, cu);
3672     }
3673   if (lh == NULL)
3674     {
3675       lh_cu->v.quick->no_file_data = 1;
3676       return;
3677     }
3678
3679   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3680   qfn->hash.dwo_unit = cu->dwo_unit;
3681   qfn->hash.line_sect_off = line_offset;
3682   gdb_assert (slot != NULL);
3683   *slot = qfn;
3684
3685   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3686
3687   qfn->num_file_names = lh->file_names.size ();
3688   qfn->file_names =
3689     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3690   for (i = 0; i < lh->file_names.size (); ++i)
3691     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3692   qfn->real_names = NULL;
3693
3694   lh_cu->v.quick->file_names = qfn;
3695 }
3696
3697 /* A helper for the "quick" functions which attempts to read the line
3698    table for THIS_CU.  */
3699
3700 static struct quick_file_names *
3701 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3702 {
3703   /* This should never be called for TUs.  */
3704   gdb_assert (! this_cu->is_debug_types);
3705   /* Nor type unit groups.  */
3706   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3707
3708   if (this_cu->v.quick->file_names != NULL)
3709     return this_cu->v.quick->file_names;
3710   /* If we know there is no line data, no point in looking again.  */
3711   if (this_cu->v.quick->no_file_data)
3712     return NULL;
3713
3714   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3715
3716   if (this_cu->v.quick->no_file_data)
3717     return NULL;
3718   return this_cu->v.quick->file_names;
3719 }
3720
3721 /* A helper for the "quick" functions which computes and caches the
3722    real path for a given file name from the line table.  */
3723
3724 static const char *
3725 dw2_get_real_path (struct objfile *objfile,
3726                    struct quick_file_names *qfn, int index)
3727 {
3728   if (qfn->real_names == NULL)
3729     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3730                                       qfn->num_file_names, const char *);
3731
3732   if (qfn->real_names[index] == NULL)
3733     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3734
3735   return qfn->real_names[index];
3736 }
3737
3738 static struct symtab *
3739 dw2_find_last_source_symtab (struct objfile *objfile)
3740 {
3741   struct dwarf2_per_objfile *dwarf2_per_objfile
3742     = get_dwarf2_per_objfile (objfile);
3743   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3744   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
3745
3746   if (cust == NULL)
3747     return NULL;
3748
3749   return compunit_primary_filetab (cust);
3750 }
3751
3752 /* Traversal function for dw2_forget_cached_source_info.  */
3753
3754 static int
3755 dw2_free_cached_file_names (void **slot, void *info)
3756 {
3757   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3758
3759   if (file_data->real_names)
3760     {
3761       int i;
3762
3763       for (i = 0; i < file_data->num_file_names; ++i)
3764         {
3765           xfree ((void*) file_data->real_names[i]);
3766           file_data->real_names[i] = NULL;
3767         }
3768     }
3769
3770   return 1;
3771 }
3772
3773 static void
3774 dw2_forget_cached_source_info (struct objfile *objfile)
3775 {
3776   struct dwarf2_per_objfile *dwarf2_per_objfile
3777     = get_dwarf2_per_objfile (objfile);
3778
3779   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3780                           dw2_free_cached_file_names, NULL);
3781 }
3782
3783 /* Helper function for dw2_map_symtabs_matching_filename that expands
3784    the symtabs and calls the iterator.  */
3785
3786 static int
3787 dw2_map_expand_apply (struct objfile *objfile,
3788                       struct dwarf2_per_cu_data *per_cu,
3789                       const char *name, const char *real_path,
3790                       gdb::function_view<bool (symtab *)> callback)
3791 {
3792   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3793
3794   /* Don't visit already-expanded CUs.  */
3795   if (per_cu->v.quick->compunit_symtab)
3796     return 0;
3797
3798   /* This may expand more than one symtab, and we want to iterate over
3799      all of them.  */
3800   dw2_instantiate_symtab (per_cu);
3801
3802   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3803                                     last_made, callback);
3804 }
3805
3806 /* Implementation of the map_symtabs_matching_filename method.  */
3807
3808 static bool
3809 dw2_map_symtabs_matching_filename
3810   (struct objfile *objfile, const char *name, const char *real_path,
3811    gdb::function_view<bool (symtab *)> callback)
3812 {
3813   const char *name_basename = lbasename (name);
3814   struct dwarf2_per_objfile *dwarf2_per_objfile
3815     = get_dwarf2_per_objfile (objfile);
3816
3817   /* The rule is CUs specify all the files, including those used by
3818      any TU, so there's no need to scan TUs here.  */
3819
3820   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3821     {
3822       /* We only need to look at symtabs not already expanded.  */
3823       if (per_cu->v.quick->compunit_symtab)
3824         continue;
3825
3826       quick_file_names *file_data = dw2_get_file_names (per_cu);
3827       if (file_data == NULL)
3828         continue;
3829
3830       for (int j = 0; j < file_data->num_file_names; ++j)
3831         {
3832           const char *this_name = file_data->file_names[j];
3833           const char *this_real_name;
3834
3835           if (compare_filenames_for_search (this_name, name))
3836             {
3837               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3838                                         callback))
3839                 return true;
3840               continue;
3841             }
3842
3843           /* Before we invoke realpath, which can get expensive when many
3844              files are involved, do a quick comparison of the basenames.  */
3845           if (! basenames_may_differ
3846               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3847             continue;
3848
3849           this_real_name = dw2_get_real_path (objfile, file_data, j);
3850           if (compare_filenames_for_search (this_real_name, name))
3851             {
3852               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3853                                         callback))
3854                 return true;
3855               continue;
3856             }
3857
3858           if (real_path != NULL)
3859             {
3860               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3861               gdb_assert (IS_ABSOLUTE_PATH (name));
3862               if (this_real_name != NULL
3863                   && FILENAME_CMP (real_path, this_real_name) == 0)
3864                 {
3865                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3866                                             callback))
3867                     return true;
3868                   continue;
3869                 }
3870             }
3871         }
3872     }
3873
3874   return false;
3875 }
3876
3877 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3878
3879 struct dw2_symtab_iterator
3880 {
3881   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3882   struct dwarf2_per_objfile *dwarf2_per_objfile;
3883   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3884   int want_specific_block;
3885   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3886      Unused if !WANT_SPECIFIC_BLOCK.  */
3887   int block_index;
3888   /* The kind of symbol we're looking for.  */
3889   domain_enum domain;
3890   /* The list of CUs from the index entry of the symbol,
3891      or NULL if not found.  */
3892   offset_type *vec;
3893   /* The next element in VEC to look at.  */
3894   int next;
3895   /* The number of elements in VEC, or zero if there is no match.  */
3896   int length;
3897   /* Have we seen a global version of the symbol?
3898      If so we can ignore all further global instances.
3899      This is to work around gold/15646, inefficient gold-generated
3900      indices.  */
3901   int global_seen;
3902 };
3903
3904 /* Initialize the index symtab iterator ITER.
3905    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3906    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3907
3908 static void
3909 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3910                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3911                       int want_specific_block,
3912                       int block_index,
3913                       domain_enum domain,
3914                       const char *name)
3915 {
3916   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3917   iter->want_specific_block = want_specific_block;
3918   iter->block_index = block_index;
3919   iter->domain = domain;
3920   iter->next = 0;
3921   iter->global_seen = 0;
3922
3923   mapped_index *index = dwarf2_per_objfile->index_table;
3924
3925   /* index is NULL if OBJF_READNOW.  */
3926   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3927     iter->length = MAYBE_SWAP (*iter->vec);
3928   else
3929     {
3930       iter->vec = NULL;
3931       iter->length = 0;
3932     }
3933 }
3934
3935 /* Return the next matching CU or NULL if there are no more.  */
3936
3937 static struct dwarf2_per_cu_data *
3938 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3939 {
3940   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3941
3942   for ( ; iter->next < iter->length; ++iter->next)
3943     {
3944       offset_type cu_index_and_attrs =
3945         MAYBE_SWAP (iter->vec[iter->next + 1]);
3946       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3947       int want_static = iter->block_index != GLOBAL_BLOCK;
3948       /* This value is only valid for index versions >= 7.  */
3949       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3950       gdb_index_symbol_kind symbol_kind =
3951         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3952       /* Only check the symbol attributes if they're present.
3953          Indices prior to version 7 don't record them,
3954          and indices >= 7 may elide them for certain symbols
3955          (gold does this).  */
3956       int attrs_valid =
3957         (dwarf2_per_objfile->index_table->version >= 7
3958          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3959
3960       /* Don't crash on bad data.  */
3961       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3962                        + dwarf2_per_objfile->all_type_units.size ()))
3963         {
3964           complaint (&symfile_complaints,
3965                      _(".gdb_index entry has bad CU index"
3966                        " [in module %s]"),
3967                      objfile_name (dwarf2_per_objfile->objfile));
3968           continue;
3969         }
3970
3971       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3972
3973       /* Skip if already read in.  */
3974       if (per_cu->v.quick->compunit_symtab)
3975         continue;
3976
3977       /* Check static vs global.  */
3978       if (attrs_valid)
3979         {
3980           if (iter->want_specific_block
3981               && want_static != is_static)
3982             continue;
3983           /* Work around gold/15646.  */
3984           if (!is_static && iter->global_seen)
3985             continue;
3986           if (!is_static)
3987             iter->global_seen = 1;
3988         }
3989
3990       /* Only check the symbol's kind if it has one.  */
3991       if (attrs_valid)
3992         {
3993           switch (iter->domain)
3994             {
3995             case VAR_DOMAIN:
3996               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3997                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3998                   /* Some types are also in VAR_DOMAIN.  */
3999                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4000                 continue;
4001               break;
4002             case STRUCT_DOMAIN:
4003               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4004                 continue;
4005               break;
4006             case LABEL_DOMAIN:
4007               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4008                 continue;
4009               break;
4010             default:
4011               break;
4012             }
4013         }
4014
4015       ++iter->next;
4016       return per_cu;
4017     }
4018
4019   return NULL;
4020 }
4021
4022 static struct compunit_symtab *
4023 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4024                    const char *name, domain_enum domain)
4025 {
4026   struct compunit_symtab *stab_best = NULL;
4027   struct dwarf2_per_objfile *dwarf2_per_objfile
4028     = get_dwarf2_per_objfile (objfile);
4029
4030   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4031
4032   struct dw2_symtab_iterator iter;
4033   struct dwarf2_per_cu_data *per_cu;
4034
4035   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4036
4037   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4038     {
4039       struct symbol *sym, *with_opaque = NULL;
4040       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4041       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4042       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4043
4044       sym = block_find_symbol (block, name, domain,
4045                                block_find_non_opaque_type_preferred,
4046                                &with_opaque);
4047
4048       /* Some caution must be observed with overloaded functions
4049          and methods, since the index will not contain any overload
4050          information (but NAME might contain it).  */
4051
4052       if (sym != NULL
4053           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4054         return stab;
4055       if (with_opaque != NULL
4056           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4057         stab_best = stab;
4058
4059       /* Keep looking through other CUs.  */
4060     }
4061
4062   return stab_best;
4063 }
4064
4065 static void
4066 dw2_print_stats (struct objfile *objfile)
4067 {
4068   struct dwarf2_per_objfile *dwarf2_per_objfile
4069     = get_dwarf2_per_objfile (objfile);
4070   int total = (dwarf2_per_objfile->all_comp_units.size ()
4071                + dwarf2_per_objfile->all_type_units.size ());
4072   int count = 0;
4073
4074   for (int i = 0; i < total; ++i)
4075     {
4076       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4077
4078       if (!per_cu->v.quick->compunit_symtab)
4079         ++count;
4080     }
4081   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4082   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4083 }
4084
4085 /* This dumps minimal information about the index.
4086    It is called via "mt print objfiles".
4087    One use is to verify .gdb_index has been loaded by the
4088    gdb.dwarf2/gdb-index.exp testcase.  */
4089
4090 static void
4091 dw2_dump (struct objfile *objfile)
4092 {
4093   struct dwarf2_per_objfile *dwarf2_per_objfile
4094     = get_dwarf2_per_objfile (objfile);
4095
4096   gdb_assert (dwarf2_per_objfile->using_index);
4097   printf_filtered (".gdb_index:");
4098   if (dwarf2_per_objfile->index_table != NULL)
4099     {
4100       printf_filtered (" version %d\n",
4101                        dwarf2_per_objfile->index_table->version);
4102     }
4103   else
4104     printf_filtered (" faked for \"readnow\"\n");
4105   printf_filtered ("\n");
4106 }
4107
4108 static void
4109 dw2_relocate (struct objfile *objfile,
4110               const struct section_offsets *new_offsets,
4111               const struct section_offsets *delta)
4112 {
4113   /* There's nothing to relocate here.  */
4114 }
4115
4116 static void
4117 dw2_expand_symtabs_for_function (struct objfile *objfile,
4118                                  const char *func_name)
4119 {
4120   struct dwarf2_per_objfile *dwarf2_per_objfile
4121     = get_dwarf2_per_objfile (objfile);
4122
4123   struct dw2_symtab_iterator iter;
4124   struct dwarf2_per_cu_data *per_cu;
4125
4126   /* Note: It doesn't matter what we pass for block_index here.  */
4127   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4128                         func_name);
4129
4130   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4131     dw2_instantiate_symtab (per_cu);
4132
4133 }
4134
4135 static void
4136 dw2_expand_all_symtabs (struct objfile *objfile)
4137 {
4138   struct dwarf2_per_objfile *dwarf2_per_objfile
4139     = get_dwarf2_per_objfile (objfile);
4140   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4141                      + dwarf2_per_objfile->all_type_units.size ());
4142
4143   for (int i = 0; i < total_units; ++i)
4144     {
4145       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4146
4147       dw2_instantiate_symtab (per_cu);
4148     }
4149 }
4150
4151 static void
4152 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4153                                   const char *fullname)
4154 {
4155   struct dwarf2_per_objfile *dwarf2_per_objfile
4156     = get_dwarf2_per_objfile (objfile);
4157
4158   /* We don't need to consider type units here.
4159      This is only called for examining code, e.g. expand_line_sal.
4160      There can be an order of magnitude (or more) more type units
4161      than comp units, and we avoid them if we can.  */
4162
4163   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4164     {
4165       /* We only need to look at symtabs not already expanded.  */
4166       if (per_cu->v.quick->compunit_symtab)
4167         continue;
4168
4169       quick_file_names *file_data = dw2_get_file_names (per_cu);
4170       if (file_data == NULL)
4171         continue;
4172
4173       for (int j = 0; j < file_data->num_file_names; ++j)
4174         {
4175           const char *this_fullname = file_data->file_names[j];
4176
4177           if (filename_cmp (this_fullname, fullname) == 0)
4178             {
4179               dw2_instantiate_symtab (per_cu);
4180               break;
4181             }
4182         }
4183     }
4184 }
4185
4186 static void
4187 dw2_map_matching_symbols (struct objfile *objfile,
4188                           const char * name, domain_enum domain,
4189                           int global,
4190                           int (*callback) (struct block *,
4191                                            struct symbol *, void *),
4192                           void *data, symbol_name_match_type match,
4193                           symbol_compare_ftype *ordered_compare)
4194 {
4195   /* Currently unimplemented; used for Ada.  The function can be called if the
4196      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4197      does not look for non-Ada symbols this function should just return.  */
4198 }
4199
4200 /* Symbol name matcher for .gdb_index names.
4201
4202    Symbol names in .gdb_index have a few particularities:
4203
4204    - There's no indication of which is the language of each symbol.
4205
4206      Since each language has its own symbol name matching algorithm,
4207      and we don't know which language is the right one, we must match
4208      each symbol against all languages.  This would be a potential
4209      performance problem if it were not mitigated by the
4210      mapped_index::name_components lookup table, which significantly
4211      reduces the number of times we need to call into this matcher,
4212      making it a non-issue.
4213
4214    - Symbol names in the index have no overload (parameter)
4215      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4216      appear as "foo" in the index, for example.
4217
4218      This means that the lookup names passed to the symbol name
4219      matcher functions must have no parameter information either
4220      because (e.g.) symbol search name "foo" does not match
4221      lookup-name "foo(int)" [while swapping search name for lookup
4222      name would match].
4223 */
4224 class gdb_index_symbol_name_matcher
4225 {
4226 public:
4227   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4228   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4229
4230   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4231      Returns true if any matcher matches.  */
4232   bool matches (const char *symbol_name);
4233
4234 private:
4235   /* A reference to the lookup name we're matching against.  */
4236   const lookup_name_info &m_lookup_name;
4237
4238   /* A vector holding all the different symbol name matchers, for all
4239      languages.  */
4240   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4241 };
4242
4243 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4244   (const lookup_name_info &lookup_name)
4245     : m_lookup_name (lookup_name)
4246 {
4247   /* Prepare the vector of comparison functions upfront, to avoid
4248      doing the same work for each symbol.  Care is taken to avoid
4249      matching with the same matcher more than once if/when multiple
4250      languages use the same matcher function.  */
4251   auto &matchers = m_symbol_name_matcher_funcs;
4252   matchers.reserve (nr_languages);
4253
4254   matchers.push_back (default_symbol_name_matcher);
4255
4256   for (int i = 0; i < nr_languages; i++)
4257     {
4258       const language_defn *lang = language_def ((enum language) i);
4259       symbol_name_matcher_ftype *name_matcher
4260         = get_symbol_name_matcher (lang, m_lookup_name);
4261
4262       /* Don't insert the same comparison routine more than once.
4263          Note that we do this linear walk instead of a seemingly
4264          cheaper sorted insert, or use a std::set or something like
4265          that, because relative order of function addresses is not
4266          stable.  This is not a problem in practice because the number
4267          of supported languages is low, and the cost here is tiny
4268          compared to the number of searches we'll do afterwards using
4269          this object.  */
4270       if (name_matcher != default_symbol_name_matcher
4271           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4272               == matchers.end ()))
4273         matchers.push_back (name_matcher);
4274     }
4275 }
4276
4277 bool
4278 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4279 {
4280   for (auto matches_name : m_symbol_name_matcher_funcs)
4281     if (matches_name (symbol_name, m_lookup_name, NULL))
4282       return true;
4283
4284   return false;
4285 }
4286
4287 /* Starting from a search name, return the string that finds the upper
4288    bound of all strings that start with SEARCH_NAME in a sorted name
4289    list.  Returns the empty string to indicate that the upper bound is
4290    the end of the list.  */
4291
4292 static std::string
4293 make_sort_after_prefix_name (const char *search_name)
4294 {
4295   /* When looking to complete "func", we find the upper bound of all
4296      symbols that start with "func" by looking for where we'd insert
4297      the closest string that would follow "func" in lexicographical
4298      order.  Usually, that's "func"-with-last-character-incremented,
4299      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4300      will be UTF-8 multi-byte sequences, but we can't be certain.
4301      Especially mind the 0xff character, which is a valid character in
4302      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4303      rule out compilers allowing it in identifiers.  Note that
4304      conveniently, strcmp/strcasecmp are specified to compare
4305      characters interpreted as unsigned char.  So what we do is treat
4306      the whole string as a base 256 number composed of a sequence of
4307      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4308      to 0, and carries 1 to the following more-significant position.
4309      If the very first character in SEARCH_NAME ends up incremented
4310      and carries/overflows, then the upper bound is the end of the
4311      list.  The string after the empty string is also the empty
4312      string.
4313
4314      Some examples of this operation:
4315
4316        SEARCH_NAME  => "+1" RESULT
4317
4318        "abc"              => "abd"
4319        "ab\xff"           => "ac"
4320        "\xff" "a" "\xff"  => "\xff" "b"
4321        "\xff"             => ""
4322        "\xff\xff"         => ""
4323        ""                 => ""
4324
4325      Then, with these symbols for example:
4326
4327       func
4328       func1
4329       fund
4330
4331      completing "func" looks for symbols between "func" and
4332      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4333      which finds "func" and "func1", but not "fund".
4334
4335      And with:
4336
4337       funcÿ     (Latin1 'ÿ' [0xff])
4338       funcÿ1
4339       fund
4340
4341      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4342      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4343
4344      And with:
4345
4346       ÿÿ        (Latin1 'ÿ' [0xff])
4347       ÿÿ1
4348
4349      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4350      the end of the list.
4351   */
4352   std::string after = search_name;
4353   while (!after.empty () && (unsigned char) after.back () == 0xff)
4354     after.pop_back ();
4355   if (!after.empty ())
4356     after.back () = (unsigned char) after.back () + 1;
4357   return after;
4358 }
4359
4360 /* See declaration.  */
4361
4362 std::pair<std::vector<name_component>::const_iterator,
4363           std::vector<name_component>::const_iterator>
4364 mapped_index_base::find_name_components_bounds
4365   (const lookup_name_info &lookup_name_without_params) const
4366 {
4367   auto *name_cmp
4368     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4369
4370   const char *cplus
4371     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4372
4373   /* Comparison function object for lower_bound that matches against a
4374      given symbol name.  */
4375   auto lookup_compare_lower = [&] (const name_component &elem,
4376                                    const char *name)
4377     {
4378       const char *elem_qualified = this->symbol_name_at (elem.idx);
4379       const char *elem_name = elem_qualified + elem.name_offset;
4380       return name_cmp (elem_name, name) < 0;
4381     };
4382
4383   /* Comparison function object for upper_bound that matches against a
4384      given symbol name.  */
4385   auto lookup_compare_upper = [&] (const char *name,
4386                                    const name_component &elem)
4387     {
4388       const char *elem_qualified = this->symbol_name_at (elem.idx);
4389       const char *elem_name = elem_qualified + elem.name_offset;
4390       return name_cmp (name, elem_name) < 0;
4391     };
4392
4393   auto begin = this->name_components.begin ();
4394   auto end = this->name_components.end ();
4395
4396   /* Find the lower bound.  */
4397   auto lower = [&] ()
4398     {
4399       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4400         return begin;
4401       else
4402         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4403     } ();
4404
4405   /* Find the upper bound.  */
4406   auto upper = [&] ()
4407     {
4408       if (lookup_name_without_params.completion_mode ())
4409         {
4410           /* In completion mode, we want UPPER to point past all
4411              symbols names that have the same prefix.  I.e., with
4412              these symbols, and completing "func":
4413
4414               function        << lower bound
4415               function1
4416               other_function  << upper bound
4417
4418              We find the upper bound by looking for the insertion
4419              point of "func"-with-last-character-incremented,
4420              i.e. "fund".  */
4421           std::string after = make_sort_after_prefix_name (cplus);
4422           if (after.empty ())
4423             return end;
4424           return std::lower_bound (lower, end, after.c_str (),
4425                                    lookup_compare_lower);
4426         }
4427       else
4428         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4429     } ();
4430
4431   return {lower, upper};
4432 }
4433
4434 /* See declaration.  */
4435
4436 void
4437 mapped_index_base::build_name_components ()
4438 {
4439   if (!this->name_components.empty ())
4440     return;
4441
4442   this->name_components_casing = case_sensitivity;
4443   auto *name_cmp
4444     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4445
4446   /* The code below only knows how to break apart components of C++
4447      symbol names (and other languages that use '::' as
4448      namespace/module separator).  If we add support for wild matching
4449      to some language that uses some other operator (E.g., Ada, Go and
4450      D use '.'), then we'll need to try splitting the symbol name
4451      according to that language too.  Note that Ada does support wild
4452      matching, but doesn't currently support .gdb_index.  */
4453   auto count = this->symbol_name_count ();
4454   for (offset_type idx = 0; idx < count; idx++)
4455     {
4456       if (this->symbol_name_slot_invalid (idx))
4457         continue;
4458
4459       const char *name = this->symbol_name_at (idx);
4460
4461       /* Add each name component to the name component table.  */
4462       unsigned int previous_len = 0;
4463       for (unsigned int current_len = cp_find_first_component (name);
4464            name[current_len] != '\0';
4465            current_len += cp_find_first_component (name + current_len))
4466         {
4467           gdb_assert (name[current_len] == ':');
4468           this->name_components.push_back ({previous_len, idx});
4469           /* Skip the '::'.  */
4470           current_len += 2;
4471           previous_len = current_len;
4472         }
4473       this->name_components.push_back ({previous_len, idx});
4474     }
4475
4476   /* Sort name_components elements by name.  */
4477   auto name_comp_compare = [&] (const name_component &left,
4478                                 const name_component &right)
4479     {
4480       const char *left_qualified = this->symbol_name_at (left.idx);
4481       const char *right_qualified = this->symbol_name_at (right.idx);
4482
4483       const char *left_name = left_qualified + left.name_offset;
4484       const char *right_name = right_qualified + right.name_offset;
4485
4486       return name_cmp (left_name, right_name) < 0;
4487     };
4488
4489   std::sort (this->name_components.begin (),
4490              this->name_components.end (),
4491              name_comp_compare);
4492 }
4493
4494 /* Helper for dw2_expand_symtabs_matching that works with a
4495    mapped_index_base instead of the containing objfile.  This is split
4496    to a separate function in order to be able to unit test the
4497    name_components matching using a mock mapped_index_base.  For each
4498    symbol name that matches, calls MATCH_CALLBACK, passing it the
4499    symbol's index in the mapped_index_base symbol table.  */
4500
4501 static void
4502 dw2_expand_symtabs_matching_symbol
4503   (mapped_index_base &index,
4504    const lookup_name_info &lookup_name_in,
4505    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4506    enum search_domain kind,
4507    gdb::function_view<void (offset_type)> match_callback)
4508 {
4509   lookup_name_info lookup_name_without_params
4510     = lookup_name_in.make_ignore_params ();
4511   gdb_index_symbol_name_matcher lookup_name_matcher
4512     (lookup_name_without_params);
4513
4514   /* Build the symbol name component sorted vector, if we haven't
4515      yet.  */
4516   index.build_name_components ();
4517
4518   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4519
4520   /* Now for each symbol name in range, check to see if we have a name
4521      match, and if so, call the MATCH_CALLBACK callback.  */
4522
4523   /* The same symbol may appear more than once in the range though.
4524      E.g., if we're looking for symbols that complete "w", and we have
4525      a symbol named "w1::w2", we'll find the two name components for
4526      that same symbol in the range.  To be sure we only call the
4527      callback once per symbol, we first collect the symbol name
4528      indexes that matched in a temporary vector and ignore
4529      duplicates.  */
4530   std::vector<offset_type> matches;
4531   matches.reserve (std::distance (bounds.first, bounds.second));
4532
4533   for (; bounds.first != bounds.second; ++bounds.first)
4534     {
4535       const char *qualified = index.symbol_name_at (bounds.first->idx);
4536
4537       if (!lookup_name_matcher.matches (qualified)
4538           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4539         continue;
4540
4541       matches.push_back (bounds.first->idx);
4542     }
4543
4544   std::sort (matches.begin (), matches.end ());
4545
4546   /* Finally call the callback, once per match.  */
4547   ULONGEST prev = -1;
4548   for (offset_type idx : matches)
4549     {
4550       if (prev != idx)
4551         {
4552           match_callback (idx);
4553           prev = idx;
4554         }
4555     }
4556
4557   /* Above we use a type wider than idx's for 'prev', since 0 and
4558      (offset_type)-1 are both possible values.  */
4559   static_assert (sizeof (prev) > sizeof (offset_type), "");
4560 }
4561
4562 #if GDB_SELF_TEST
4563
4564 namespace selftests { namespace dw2_expand_symtabs_matching {
4565
4566 /* A mock .gdb_index/.debug_names-like name index table, enough to
4567    exercise dw2_expand_symtabs_matching_symbol, which works with the
4568    mapped_index_base interface.  Builds an index from the symbol list
4569    passed as parameter to the constructor.  */
4570 class mock_mapped_index : public mapped_index_base
4571 {
4572 public:
4573   mock_mapped_index (gdb::array_view<const char *> symbols)
4574     : m_symbol_table (symbols)
4575   {}
4576
4577   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4578
4579   /* Return the number of names in the symbol table.  */
4580   size_t symbol_name_count () const override
4581   {
4582     return m_symbol_table.size ();
4583   }
4584
4585   /* Get the name of the symbol at IDX in the symbol table.  */
4586   const char *symbol_name_at (offset_type idx) const override
4587   {
4588     return m_symbol_table[idx];
4589   }
4590
4591 private:
4592   gdb::array_view<const char *> m_symbol_table;
4593 };
4594
4595 /* Convenience function that converts a NULL pointer to a "<null>"
4596    string, to pass to print routines.  */
4597
4598 static const char *
4599 string_or_null (const char *str)
4600 {
4601   return str != NULL ? str : "<null>";
4602 }
4603
4604 /* Check if a lookup_name_info built from
4605    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4606    index.  EXPECTED_LIST is the list of expected matches, in expected
4607    matching order.  If no match expected, then an empty list is
4608    specified.  Returns true on success.  On failure prints a warning
4609    indicating the file:line that failed, and returns false.  */
4610
4611 static bool
4612 check_match (const char *file, int line,
4613              mock_mapped_index &mock_index,
4614              const char *name, symbol_name_match_type match_type,
4615              bool completion_mode,
4616              std::initializer_list<const char *> expected_list)
4617 {
4618   lookup_name_info lookup_name (name, match_type, completion_mode);
4619
4620   bool matched = true;
4621
4622   auto mismatch = [&] (const char *expected_str,
4623                        const char *got)
4624   {
4625     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4626                "expected=\"%s\", got=\"%s\"\n"),
4627              file, line,
4628              (match_type == symbol_name_match_type::FULL
4629               ? "FULL" : "WILD"),
4630              name, string_or_null (expected_str), string_or_null (got));
4631     matched = false;
4632   };
4633
4634   auto expected_it = expected_list.begin ();
4635   auto expected_end = expected_list.end ();
4636
4637   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4638                                       NULL, ALL_DOMAIN,
4639                                       [&] (offset_type idx)
4640   {
4641     const char *matched_name = mock_index.symbol_name_at (idx);
4642     const char *expected_str
4643       = expected_it == expected_end ? NULL : *expected_it++;
4644
4645     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4646       mismatch (expected_str, matched_name);
4647   });
4648
4649   const char *expected_str
4650   = expected_it == expected_end ? NULL : *expected_it++;
4651   if (expected_str != NULL)
4652     mismatch (expected_str, NULL);
4653
4654   return matched;
4655 }
4656
4657 /* The symbols added to the mock mapped_index for testing (in
4658    canonical form).  */
4659 static const char *test_symbols[] = {
4660   "function",
4661   "std::bar",
4662   "std::zfunction",
4663   "std::zfunction2",
4664   "w1::w2",
4665   "ns::foo<char*>",
4666   "ns::foo<int>",
4667   "ns::foo<long>",
4668   "ns2::tmpl<int>::foo2",
4669   "(anonymous namespace)::A::B::C",
4670
4671   /* These are used to check that the increment-last-char in the
4672      matching algorithm for completion doesn't match "t1_fund" when
4673      completing "t1_func".  */
4674   "t1_func",
4675   "t1_func1",
4676   "t1_fund",
4677   "t1_fund1",
4678
4679   /* A UTF-8 name with multi-byte sequences to make sure that
4680      cp-name-parser understands this as a single identifier ("função"
4681      is "function" in PT).  */
4682   u8"u8função",
4683
4684   /* \377 (0xff) is Latin1 'ÿ'.  */
4685   "yfunc\377",
4686
4687   /* \377 (0xff) is Latin1 'ÿ'.  */
4688   "\377",
4689   "\377\377123",
4690
4691   /* A name with all sorts of complications.  Starts with "z" to make
4692      it easier for the completion tests below.  */
4693 #define Z_SYM_NAME \
4694   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4695     "::tuple<(anonymous namespace)::ui*, " \
4696     "std::default_delete<(anonymous namespace)::ui>, void>"
4697
4698   Z_SYM_NAME
4699 };
4700
4701 /* Returns true if the mapped_index_base::find_name_component_bounds
4702    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4703    in completion mode.  */
4704
4705 static bool
4706 check_find_bounds_finds (mapped_index_base &index,
4707                          const char *search_name,
4708                          gdb::array_view<const char *> expected_syms)
4709 {
4710   lookup_name_info lookup_name (search_name,
4711                                 symbol_name_match_type::FULL, true);
4712
4713   auto bounds = index.find_name_components_bounds (lookup_name);
4714
4715   size_t distance = std::distance (bounds.first, bounds.second);
4716   if (distance != expected_syms.size ())
4717     return false;
4718
4719   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4720     {
4721       auto nc_elem = bounds.first + exp_elem;
4722       const char *qualified = index.symbol_name_at (nc_elem->idx);
4723       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4724         return false;
4725     }
4726
4727   return true;
4728 }
4729
4730 /* Test the lower-level mapped_index::find_name_component_bounds
4731    method.  */
4732
4733 static void
4734 test_mapped_index_find_name_component_bounds ()
4735 {
4736   mock_mapped_index mock_index (test_symbols);
4737
4738   mock_index.build_name_components ();
4739
4740   /* Test the lower-level mapped_index::find_name_component_bounds
4741      method in completion mode.  */
4742   {
4743     static const char *expected_syms[] = {
4744       "t1_func",
4745       "t1_func1",
4746     };
4747
4748     SELF_CHECK (check_find_bounds_finds (mock_index,
4749                                          "t1_func", expected_syms));
4750   }
4751
4752   /* Check that the increment-last-char in the name matching algorithm
4753      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4754   {
4755     static const char *expected_syms1[] = {
4756       "\377",
4757       "\377\377123",
4758     };
4759     SELF_CHECK (check_find_bounds_finds (mock_index,
4760                                          "\377", expected_syms1));
4761
4762     static const char *expected_syms2[] = {
4763       "\377\377123",
4764     };
4765     SELF_CHECK (check_find_bounds_finds (mock_index,
4766                                          "\377\377", expected_syms2));
4767   }
4768 }
4769
4770 /* Test dw2_expand_symtabs_matching_symbol.  */
4771
4772 static void
4773 test_dw2_expand_symtabs_matching_symbol ()
4774 {
4775   mock_mapped_index mock_index (test_symbols);
4776
4777   /* We let all tests run until the end even if some fails, for debug
4778      convenience.  */
4779   bool any_mismatch = false;
4780
4781   /* Create the expected symbols list (an initializer_list).  Needed
4782      because lists have commas, and we need to pass them to CHECK,
4783      which is a macro.  */
4784 #define EXPECT(...) { __VA_ARGS__ }
4785
4786   /* Wrapper for check_match that passes down the current
4787      __FILE__/__LINE__.  */
4788 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4789   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4790                                 mock_index,                             \
4791                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4792                                 EXPECTED_LIST)
4793
4794   /* Identity checks.  */
4795   for (const char *sym : test_symbols)
4796     {
4797       /* Should be able to match all existing symbols.  */
4798       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4799                    EXPECT (sym));
4800
4801       /* Should be able to match all existing symbols with
4802          parameters.  */
4803       std::string with_params = std::string (sym) + "(int)";
4804       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4805                    EXPECT (sym));
4806
4807       /* Should be able to match all existing symbols with
4808          parameters and qualifiers.  */
4809       with_params = std::string (sym) + " ( int ) const";
4810       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4811                    EXPECT (sym));
4812
4813       /* This should really find sym, but cp-name-parser.y doesn't
4814          know about lvalue/rvalue qualifiers yet.  */
4815       with_params = std::string (sym) + " ( int ) &&";
4816       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4817                    {});
4818     }
4819
4820   /* Check that the name matching algorithm for completion doesn't get
4821      confused with Latin1 'ÿ' / 0xff.  */
4822   {
4823     static const char str[] = "\377";
4824     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4825                  EXPECT ("\377", "\377\377123"));
4826   }
4827
4828   /* Check that the increment-last-char in the matching algorithm for
4829      completion doesn't match "t1_fund" when completing "t1_func".  */
4830   {
4831     static const char str[] = "t1_func";
4832     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4833                  EXPECT ("t1_func", "t1_func1"));
4834   }
4835
4836   /* Check that completion mode works at each prefix of the expected
4837      symbol name.  */
4838   {
4839     static const char str[] = "function(int)";
4840     size_t len = strlen (str);
4841     std::string lookup;
4842
4843     for (size_t i = 1; i < len; i++)
4844       {
4845         lookup.assign (str, i);
4846         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4847                      EXPECT ("function"));
4848       }
4849   }
4850
4851   /* While "w" is a prefix of both components, the match function
4852      should still only be called once.  */
4853   {
4854     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4855                  EXPECT ("w1::w2"));
4856     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4857                  EXPECT ("w1::w2"));
4858   }
4859
4860   /* Same, with a "complicated" symbol.  */
4861   {
4862     static const char str[] = Z_SYM_NAME;
4863     size_t len = strlen (str);
4864     std::string lookup;
4865
4866     for (size_t i = 1; i < len; i++)
4867       {
4868         lookup.assign (str, i);
4869         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4870                      EXPECT (Z_SYM_NAME));
4871       }
4872   }
4873
4874   /* In FULL mode, an incomplete symbol doesn't match.  */
4875   {
4876     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4877                  {});
4878   }
4879
4880   /* A complete symbol with parameters matches any overload, since the
4881      index has no overload info.  */
4882   {
4883     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4884                  EXPECT ("std::zfunction", "std::zfunction2"));
4885     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4886                  EXPECT ("std::zfunction", "std::zfunction2"));
4887     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4888                  EXPECT ("std::zfunction", "std::zfunction2"));
4889   }
4890
4891   /* Check that whitespace is ignored appropriately.  A symbol with a
4892      template argument list. */
4893   {
4894     static const char expected[] = "ns::foo<int>";
4895     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4896                  EXPECT (expected));
4897     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4898                  EXPECT (expected));
4899   }
4900
4901   /* Check that whitespace is ignored appropriately.  A symbol with a
4902      template argument list that includes a pointer.  */
4903   {
4904     static const char expected[] = "ns::foo<char*>";
4905     /* Try both completion and non-completion modes.  */
4906     static const bool completion_mode[2] = {false, true};
4907     for (size_t i = 0; i < 2; i++)
4908       {
4909         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4910                      completion_mode[i], EXPECT (expected));
4911         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4912                      completion_mode[i], EXPECT (expected));
4913
4914         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4915                      completion_mode[i], EXPECT (expected));
4916         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4917                      completion_mode[i], EXPECT (expected));
4918       }
4919   }
4920
4921   {
4922     /* Check method qualifiers are ignored.  */
4923     static const char expected[] = "ns::foo<char*>";
4924     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4925                  symbol_name_match_type::FULL, true, EXPECT (expected));
4926     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4927                  symbol_name_match_type::FULL, true, EXPECT (expected));
4928     CHECK_MATCH ("foo < char * >  ( int ) const",
4929                  symbol_name_match_type::WILD, true, EXPECT (expected));
4930     CHECK_MATCH ("foo < char * >  ( int ) &&",
4931                  symbol_name_match_type::WILD, true, EXPECT (expected));
4932   }
4933
4934   /* Test lookup names that don't match anything.  */
4935   {
4936     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4937                  {});
4938
4939     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4940                  {});
4941   }
4942
4943   /* Some wild matching tests, exercising "(anonymous namespace)",
4944      which should not be confused with a parameter list.  */
4945   {
4946     static const char *syms[] = {
4947       "A::B::C",
4948       "B::C",
4949       "C",
4950       "A :: B :: C ( int )",
4951       "B :: C ( int )",
4952       "C ( int )",
4953     };
4954
4955     for (const char *s : syms)
4956       {
4957         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4958                      EXPECT ("(anonymous namespace)::A::B::C"));
4959       }
4960   }
4961
4962   {
4963     static const char expected[] = "ns2::tmpl<int>::foo2";
4964     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4965                  EXPECT (expected));
4966     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4967                  EXPECT (expected));
4968   }
4969
4970   SELF_CHECK (!any_mismatch);
4971
4972 #undef EXPECT
4973 #undef CHECK_MATCH
4974 }
4975
4976 static void
4977 run_test ()
4978 {
4979   test_mapped_index_find_name_component_bounds ();
4980   test_dw2_expand_symtabs_matching_symbol ();
4981 }
4982
4983 }} // namespace selftests::dw2_expand_symtabs_matching
4984
4985 #endif /* GDB_SELF_TEST */
4986
4987 /* If FILE_MATCHER is NULL or if PER_CU has
4988    dwarf2_per_cu_quick_data::MARK set (see
4989    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4990    EXPANSION_NOTIFY on it.  */
4991
4992 static void
4993 dw2_expand_symtabs_matching_one
4994   (struct dwarf2_per_cu_data *per_cu,
4995    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4996    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4997 {
4998   if (file_matcher == NULL || per_cu->v.quick->mark)
4999     {
5000       bool symtab_was_null
5001         = (per_cu->v.quick->compunit_symtab == NULL);
5002
5003       dw2_instantiate_symtab (per_cu);
5004
5005       if (expansion_notify != NULL
5006           && symtab_was_null
5007           && per_cu->v.quick->compunit_symtab != NULL)
5008         expansion_notify (per_cu->v.quick->compunit_symtab);
5009     }
5010 }
5011
5012 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5013    matched, to expand corresponding CUs that were marked.  IDX is the
5014    index of the symbol name that matched.  */
5015
5016 static void
5017 dw2_expand_marked_cus
5018   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5019    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5020    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5021    search_domain kind)
5022 {
5023   offset_type *vec, vec_len, vec_idx;
5024   bool global_seen = false;
5025   mapped_index &index = *dwarf2_per_objfile->index_table;
5026
5027   vec = (offset_type *) (index.constant_pool
5028                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5029   vec_len = MAYBE_SWAP (vec[0]);
5030   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5031     {
5032       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5033       /* This value is only valid for index versions >= 7.  */
5034       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5035       gdb_index_symbol_kind symbol_kind =
5036         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5037       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5038       /* Only check the symbol attributes if they're present.
5039          Indices prior to version 7 don't record them,
5040          and indices >= 7 may elide them for certain symbols
5041          (gold does this).  */
5042       int attrs_valid =
5043         (index.version >= 7
5044          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5045
5046       /* Work around gold/15646.  */
5047       if (attrs_valid)
5048         {
5049           if (!is_static && global_seen)
5050             continue;
5051           if (!is_static)
5052             global_seen = true;
5053         }
5054
5055       /* Only check the symbol's kind if it has one.  */
5056       if (attrs_valid)
5057         {
5058           switch (kind)
5059             {
5060             case VARIABLES_DOMAIN:
5061               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5062                 continue;
5063               break;
5064             case FUNCTIONS_DOMAIN:
5065               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5066                 continue;
5067               break;
5068             case TYPES_DOMAIN:
5069               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5070                 continue;
5071               break;
5072             default:
5073               break;
5074             }
5075         }
5076
5077       /* Don't crash on bad data.  */
5078       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5079                        + dwarf2_per_objfile->all_type_units.size ()))
5080         {
5081           complaint (&symfile_complaints,
5082                      _(".gdb_index entry has bad CU index"
5083                        " [in module %s]"),
5084                        objfile_name (dwarf2_per_objfile->objfile));
5085           continue;
5086         }
5087
5088       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5089       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5090                                        expansion_notify);
5091     }
5092 }
5093
5094 /* If FILE_MATCHER is non-NULL, set all the
5095    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5096    that match FILE_MATCHER.  */
5097
5098 static void
5099 dw_expand_symtabs_matching_file_matcher
5100   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5101    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5102 {
5103   if (file_matcher == NULL)
5104     return;
5105
5106   objfile *const objfile = dwarf2_per_objfile->objfile;
5107
5108   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5109                                             htab_eq_pointer,
5110                                             NULL, xcalloc, xfree));
5111   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5112                                                 htab_eq_pointer,
5113                                                 NULL, xcalloc, xfree));
5114
5115   /* The rule is CUs specify all the files, including those used by
5116      any TU, so there's no need to scan TUs here.  */
5117
5118   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5119     {
5120       QUIT;
5121
5122       per_cu->v.quick->mark = 0;
5123
5124       /* We only need to look at symtabs not already expanded.  */
5125       if (per_cu->v.quick->compunit_symtab)
5126         continue;
5127
5128       quick_file_names *file_data = dw2_get_file_names (per_cu);
5129       if (file_data == NULL)
5130         continue;
5131
5132       if (htab_find (visited_not_found.get (), file_data) != NULL)
5133         continue;
5134       else if (htab_find (visited_found.get (), file_data) != NULL)
5135         {
5136           per_cu->v.quick->mark = 1;
5137           continue;
5138         }
5139
5140       for (int j = 0; j < file_data->num_file_names; ++j)
5141         {
5142           const char *this_real_name;
5143
5144           if (file_matcher (file_data->file_names[j], false))
5145             {
5146               per_cu->v.quick->mark = 1;
5147               break;
5148             }
5149
5150           /* Before we invoke realpath, which can get expensive when many
5151              files are involved, do a quick comparison of the basenames.  */
5152           if (!basenames_may_differ
5153               && !file_matcher (lbasename (file_data->file_names[j]),
5154                                 true))
5155             continue;
5156
5157           this_real_name = dw2_get_real_path (objfile, file_data, j);
5158           if (file_matcher (this_real_name, false))
5159             {
5160               per_cu->v.quick->mark = 1;
5161               break;
5162             }
5163         }
5164
5165       void **slot = htab_find_slot (per_cu->v.quick->mark
5166                                     ? visited_found.get ()
5167                                     : visited_not_found.get (),
5168                                     file_data, INSERT);
5169       *slot = file_data;
5170     }
5171 }
5172
5173 static void
5174 dw2_expand_symtabs_matching
5175   (struct objfile *objfile,
5176    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5177    const lookup_name_info &lookup_name,
5178    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5179    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5180    enum search_domain kind)
5181 {
5182   struct dwarf2_per_objfile *dwarf2_per_objfile
5183     = get_dwarf2_per_objfile (objfile);
5184
5185   /* index_table is NULL if OBJF_READNOW.  */
5186   if (!dwarf2_per_objfile->index_table)
5187     return;
5188
5189   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5190
5191   mapped_index &index = *dwarf2_per_objfile->index_table;
5192
5193   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5194                                       symbol_matcher,
5195                                       kind, [&] (offset_type idx)
5196     {
5197       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5198                              expansion_notify, kind);
5199     });
5200 }
5201
5202 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5203    symtab.  */
5204
5205 static struct compunit_symtab *
5206 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5207                                           CORE_ADDR pc)
5208 {
5209   int i;
5210
5211   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5212       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5213     return cust;
5214
5215   if (cust->includes == NULL)
5216     return NULL;
5217
5218   for (i = 0; cust->includes[i]; ++i)
5219     {
5220       struct compunit_symtab *s = cust->includes[i];
5221
5222       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5223       if (s != NULL)
5224         return s;
5225     }
5226
5227   return NULL;
5228 }
5229
5230 static struct compunit_symtab *
5231 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5232                                   struct bound_minimal_symbol msymbol,
5233                                   CORE_ADDR pc,
5234                                   struct obj_section *section,
5235                                   int warn_if_readin)
5236 {
5237   struct dwarf2_per_cu_data *data;
5238   struct compunit_symtab *result;
5239
5240   if (!objfile->psymtabs_addrmap)
5241     return NULL;
5242
5243   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5244                                                      pc);
5245   if (!data)
5246     return NULL;
5247
5248   if (warn_if_readin && data->v.quick->compunit_symtab)
5249     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5250              paddress (get_objfile_arch (objfile), pc));
5251
5252   result
5253     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5254                                                 pc);
5255   gdb_assert (result != NULL);
5256   return result;
5257 }
5258
5259 static void
5260 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5261                           void *data, int need_fullname)
5262 {
5263   struct dwarf2_per_objfile *dwarf2_per_objfile
5264     = get_dwarf2_per_objfile (objfile);
5265
5266   if (!dwarf2_per_objfile->filenames_cache)
5267     {
5268       dwarf2_per_objfile->filenames_cache.emplace ();
5269
5270       htab_up visited (htab_create_alloc (10,
5271                                           htab_hash_pointer, htab_eq_pointer,
5272                                           NULL, xcalloc, xfree));
5273
5274       /* The rule is CUs specify all the files, including those used
5275          by any TU, so there's no need to scan TUs here.  We can
5276          ignore file names coming from already-expanded CUs.  */
5277
5278       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5279         {
5280           if (per_cu->v.quick->compunit_symtab)
5281             {
5282               void **slot = htab_find_slot (visited.get (),
5283                                             per_cu->v.quick->file_names,
5284                                             INSERT);
5285
5286               *slot = per_cu->v.quick->file_names;
5287             }
5288         }
5289
5290       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5291         {
5292           /* We only need to look at symtabs not already expanded.  */
5293           if (per_cu->v.quick->compunit_symtab)
5294             continue;
5295
5296           quick_file_names *file_data = dw2_get_file_names (per_cu);
5297           if (file_data == NULL)
5298             continue;
5299
5300           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5301           if (*slot)
5302             {
5303               /* Already visited.  */
5304               continue;
5305             }
5306           *slot = file_data;
5307
5308           for (int j = 0; j < file_data->num_file_names; ++j)
5309             {
5310               const char *filename = file_data->file_names[j];
5311               dwarf2_per_objfile->filenames_cache->seen (filename);
5312             }
5313         }
5314     }
5315
5316   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5317     {
5318       gdb::unique_xmalloc_ptr<char> this_real_name;
5319
5320       if (need_fullname)
5321         this_real_name = gdb_realpath (filename);
5322       (*fun) (filename, this_real_name.get (), data);
5323     });
5324 }
5325
5326 static int
5327 dw2_has_symbols (struct objfile *objfile)
5328 {
5329   return 1;
5330 }
5331
5332 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5333 {
5334   dw2_has_symbols,
5335   dw2_find_last_source_symtab,
5336   dw2_forget_cached_source_info,
5337   dw2_map_symtabs_matching_filename,
5338   dw2_lookup_symbol,
5339   dw2_print_stats,
5340   dw2_dump,
5341   dw2_relocate,
5342   dw2_expand_symtabs_for_function,
5343   dw2_expand_all_symtabs,
5344   dw2_expand_symtabs_with_fullname,
5345   dw2_map_matching_symbols,
5346   dw2_expand_symtabs_matching,
5347   dw2_find_pc_sect_compunit_symtab,
5348   NULL,
5349   dw2_map_symbol_filenames
5350 };
5351
5352 /* DWARF-5 debug_names reader.  */
5353
5354 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5355 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5356
5357 /* A helper function that reads the .debug_names section in SECTION
5358    and fills in MAP.  FILENAME is the name of the file containing the
5359    section; it is used for error reporting.
5360
5361    Returns true if all went well, false otherwise.  */
5362
5363 static bool
5364 read_debug_names_from_section (struct objfile *objfile,
5365                                const char *filename,
5366                                struct dwarf2_section_info *section,
5367                                mapped_debug_names &map)
5368 {
5369   if (dwarf2_section_empty_p (section))
5370     return false;
5371
5372   /* Older elfutils strip versions could keep the section in the main
5373      executable while splitting it for the separate debug info file.  */
5374   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5375     return false;
5376
5377   dwarf2_read_section (objfile, section);
5378
5379   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5380
5381   const gdb_byte *addr = section->buffer;
5382
5383   bfd *const abfd = get_section_bfd_owner (section);
5384
5385   unsigned int bytes_read;
5386   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5387   addr += bytes_read;
5388
5389   map.dwarf5_is_dwarf64 = bytes_read != 4;
5390   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5391   if (bytes_read + length != section->size)
5392     {
5393       /* There may be multiple per-CU indices.  */
5394       warning (_("Section .debug_names in %s length %s does not match "
5395                  "section length %s, ignoring .debug_names."),
5396                filename, plongest (bytes_read + length),
5397                pulongest (section->size));
5398       return false;
5399     }
5400
5401   /* The version number.  */
5402   uint16_t version = read_2_bytes (abfd, addr);
5403   addr += 2;
5404   if (version != 5)
5405     {
5406       warning (_("Section .debug_names in %s has unsupported version %d, "
5407                  "ignoring .debug_names."),
5408                filename, version);
5409       return false;
5410     }
5411
5412   /* Padding.  */
5413   uint16_t padding = read_2_bytes (abfd, addr);
5414   addr += 2;
5415   if (padding != 0)
5416     {
5417       warning (_("Section .debug_names in %s has unsupported padding %d, "
5418                  "ignoring .debug_names."),
5419                filename, padding);
5420       return false;
5421     }
5422
5423   /* comp_unit_count - The number of CUs in the CU list.  */
5424   map.cu_count = read_4_bytes (abfd, addr);
5425   addr += 4;
5426
5427   /* local_type_unit_count - The number of TUs in the local TU
5428      list.  */
5429   map.tu_count = read_4_bytes (abfd, addr);
5430   addr += 4;
5431
5432   /* foreign_type_unit_count - The number of TUs in the foreign TU
5433      list.  */
5434   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5435   addr += 4;
5436   if (foreign_tu_count != 0)
5437     {
5438       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5439                  "ignoring .debug_names."),
5440                filename, static_cast<unsigned long> (foreign_tu_count));
5441       return false;
5442     }
5443
5444   /* bucket_count - The number of hash buckets in the hash lookup
5445      table.  */
5446   map.bucket_count = read_4_bytes (abfd, addr);
5447   addr += 4;
5448
5449   /* name_count - The number of unique names in the index.  */
5450   map.name_count = read_4_bytes (abfd, addr);
5451   addr += 4;
5452
5453   /* abbrev_table_size - The size in bytes of the abbreviations
5454      table.  */
5455   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5456   addr += 4;
5457
5458   /* augmentation_string_size - The size in bytes of the augmentation
5459      string.  This value is rounded up to a multiple of 4.  */
5460   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5461   addr += 4;
5462   map.augmentation_is_gdb = ((augmentation_string_size
5463                               == sizeof (dwarf5_augmentation))
5464                              && memcmp (addr, dwarf5_augmentation,
5465                                         sizeof (dwarf5_augmentation)) == 0);
5466   augmentation_string_size += (-augmentation_string_size) & 3;
5467   addr += augmentation_string_size;
5468
5469   /* List of CUs */
5470   map.cu_table_reordered = addr;
5471   addr += map.cu_count * map.offset_size;
5472
5473   /* List of Local TUs */
5474   map.tu_table_reordered = addr;
5475   addr += map.tu_count * map.offset_size;
5476
5477   /* Hash Lookup Table */
5478   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5479   addr += map.bucket_count * 4;
5480   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5481   addr += map.name_count * 4;
5482
5483   /* Name Table */
5484   map.name_table_string_offs_reordered = addr;
5485   addr += map.name_count * map.offset_size;
5486   map.name_table_entry_offs_reordered = addr;
5487   addr += map.name_count * map.offset_size;
5488
5489   const gdb_byte *abbrev_table_start = addr;
5490   for (;;)
5491     {
5492       unsigned int bytes_read;
5493       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5494       addr += bytes_read;
5495       if (index_num == 0)
5496         break;
5497
5498       const auto insertpair
5499         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5500       if (!insertpair.second)
5501         {
5502           warning (_("Section .debug_names in %s has duplicate index %s, "
5503                      "ignoring .debug_names."),
5504                    filename, pulongest (index_num));
5505           return false;
5506         }
5507       mapped_debug_names::index_val &indexval = insertpair.first->second;
5508       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5509       addr += bytes_read;
5510
5511       for (;;)
5512         {
5513           mapped_debug_names::index_val::attr attr;
5514           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5515           addr += bytes_read;
5516           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5517           addr += bytes_read;
5518           if (attr.form == DW_FORM_implicit_const)
5519             {
5520               attr.implicit_const = read_signed_leb128 (abfd, addr,
5521                                                         &bytes_read);
5522               addr += bytes_read;
5523             }
5524           if (attr.dw_idx == 0 && attr.form == 0)
5525             break;
5526           indexval.attr_vec.push_back (std::move (attr));
5527         }
5528     }
5529   if (addr != abbrev_table_start + abbrev_table_size)
5530     {
5531       warning (_("Section .debug_names in %s has abbreviation_table "
5532                  "of size %zu vs. written as %u, ignoring .debug_names."),
5533                filename, addr - abbrev_table_start, abbrev_table_size);
5534       return false;
5535     }
5536   map.entry_pool = addr;
5537
5538   return true;
5539 }
5540
5541 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5542    list.  */
5543
5544 static void
5545 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5546                                   const mapped_debug_names &map,
5547                                   dwarf2_section_info &section,
5548                                   bool is_dwz)
5549 {
5550   sect_offset sect_off_prev;
5551   for (uint32_t i = 0; i <= map.cu_count; ++i)
5552     {
5553       sect_offset sect_off_next;
5554       if (i < map.cu_count)
5555         {
5556           sect_off_next
5557             = (sect_offset) (extract_unsigned_integer
5558                              (map.cu_table_reordered + i * map.offset_size,
5559                               map.offset_size,
5560                               map.dwarf5_byte_order));
5561         }
5562       else
5563         sect_off_next = (sect_offset) section.size;
5564       if (i >= 1)
5565         {
5566           const ULONGEST length = sect_off_next - sect_off_prev;
5567           dwarf2_per_cu_data *per_cu
5568             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5569                                          sect_off_prev, length);
5570           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5571         }
5572       sect_off_prev = sect_off_next;
5573     }
5574 }
5575
5576 /* Read the CU list from the mapped index, and use it to create all
5577    the CU objects for this dwarf2_per_objfile.  */
5578
5579 static void
5580 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5581                              const mapped_debug_names &map,
5582                              const mapped_debug_names &dwz_map)
5583 {
5584   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5585   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5586
5587   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5588                                     dwarf2_per_objfile->info,
5589                                     false /* is_dwz */);
5590
5591   if (dwz_map.cu_count == 0)
5592     return;
5593
5594   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5595   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5596                                     true /* is_dwz */);
5597 }
5598
5599 /* Read .debug_names.  If everything went ok, initialize the "quick"
5600    elements of all the CUs and return true.  Otherwise, return false.  */
5601
5602 static bool
5603 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5604 {
5605   mapped_debug_names local_map (dwarf2_per_objfile);
5606   mapped_debug_names dwz_map (dwarf2_per_objfile);
5607   struct objfile *objfile = dwarf2_per_objfile->objfile;
5608
5609   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5610                                       &dwarf2_per_objfile->debug_names,
5611                                       local_map))
5612     return false;
5613
5614   /* Don't use the index if it's empty.  */
5615   if (local_map.name_count == 0)
5616     return false;
5617
5618   /* If there is a .dwz file, read it so we can get its CU list as
5619      well.  */
5620   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5621   if (dwz != NULL)
5622     {
5623       if (!read_debug_names_from_section (objfile,
5624                                           bfd_get_filename (dwz->dwz_bfd),
5625                                           &dwz->debug_names, dwz_map))
5626         {
5627           warning (_("could not read '.debug_names' section from %s; skipping"),
5628                    bfd_get_filename (dwz->dwz_bfd));
5629           return false;
5630         }
5631     }
5632
5633   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5634
5635   if (local_map.tu_count != 0)
5636     {
5637       /* We can only handle a single .debug_types when we have an
5638          index.  */
5639       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5640         return false;
5641
5642       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5643                                                 dwarf2_per_objfile->types, 0);
5644
5645       create_signatured_type_table_from_debug_names
5646         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5647     }
5648
5649   create_addrmap_from_aranges (dwarf2_per_objfile,
5650                                &dwarf2_per_objfile->debug_aranges);
5651
5652   dwarf2_per_objfile->debug_names_table.reset
5653     (new mapped_debug_names (dwarf2_per_objfile));
5654   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5655   dwarf2_per_objfile->using_index = 1;
5656   dwarf2_per_objfile->quick_file_names_table =
5657     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5658
5659   return true;
5660 }
5661
5662 /* Type used to manage iterating over all CUs looking for a symbol for
5663    .debug_names.  */
5664
5665 class dw2_debug_names_iterator
5666 {
5667 public:
5668   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5669      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5670   dw2_debug_names_iterator (const mapped_debug_names &map,
5671                             bool want_specific_block,
5672                             block_enum block_index, domain_enum domain,
5673                             const char *name)
5674     : m_map (map), m_want_specific_block (want_specific_block),
5675       m_block_index (block_index), m_domain (domain),
5676       m_addr (find_vec_in_debug_names (map, name))
5677   {}
5678
5679   dw2_debug_names_iterator (const mapped_debug_names &map,
5680                             search_domain search, uint32_t namei)
5681     : m_map (map),
5682       m_search (search),
5683       m_addr (find_vec_in_debug_names (map, namei))
5684   {}
5685
5686   /* Return the next matching CU or NULL if there are no more.  */
5687   dwarf2_per_cu_data *next ();
5688
5689 private:
5690   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5691                                                   const char *name);
5692   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5693                                                   uint32_t namei);
5694
5695   /* The internalized form of .debug_names.  */
5696   const mapped_debug_names &m_map;
5697
5698   /* If true, only look for symbols that match BLOCK_INDEX.  */
5699   const bool m_want_specific_block = false;
5700
5701   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5702      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5703      value.  */
5704   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5705
5706   /* The kind of symbol we're looking for.  */
5707   const domain_enum m_domain = UNDEF_DOMAIN;
5708   const search_domain m_search = ALL_DOMAIN;
5709
5710   /* The list of CUs from the index entry of the symbol, or NULL if
5711      not found.  */
5712   const gdb_byte *m_addr;
5713 };
5714
5715 const char *
5716 mapped_debug_names::namei_to_name (uint32_t namei) const
5717 {
5718   const ULONGEST namei_string_offs
5719     = extract_unsigned_integer ((name_table_string_offs_reordered
5720                                  + namei * offset_size),
5721                                 offset_size,
5722                                 dwarf5_byte_order);
5723   return read_indirect_string_at_offset
5724     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5725 }
5726
5727 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5728    found, return pointer to its pool data.  If NAME cannot be found,
5729    return NULL.  */
5730
5731 const gdb_byte *
5732 dw2_debug_names_iterator::find_vec_in_debug_names
5733   (const mapped_debug_names &map, const char *name)
5734 {
5735   int (*cmp) (const char *, const char *);
5736
5737   if (current_language->la_language == language_cplus
5738       || current_language->la_language == language_fortran
5739       || current_language->la_language == language_d)
5740     {
5741       /* NAME is already canonical.  Drop any qualifiers as
5742          .debug_names does not contain any.  */
5743
5744       if (strchr (name, '(') != NULL)
5745         {
5746           gdb::unique_xmalloc_ptr<char> without_params
5747             = cp_remove_params (name);
5748
5749           if (without_params != NULL)
5750             {
5751               name = without_params.get();
5752             }
5753         }
5754     }
5755
5756   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5757
5758   const uint32_t full_hash = dwarf5_djb_hash (name);
5759   uint32_t namei
5760     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5761                                 (map.bucket_table_reordered
5762                                  + (full_hash % map.bucket_count)), 4,
5763                                 map.dwarf5_byte_order);
5764   if (namei == 0)
5765     return NULL;
5766   --namei;
5767   if (namei >= map.name_count)
5768     {
5769       complaint (&symfile_complaints,
5770                  _("Wrong .debug_names with name index %u but name_count=%u "
5771                    "[in module %s]"),
5772                  namei, map.name_count,
5773                  objfile_name (map.dwarf2_per_objfile->objfile));
5774       return NULL;
5775     }
5776
5777   for (;;)
5778     {
5779       const uint32_t namei_full_hash
5780         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5781                                     (map.hash_table_reordered + namei), 4,
5782                                     map.dwarf5_byte_order);
5783       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5784         return NULL;
5785
5786       if (full_hash == namei_full_hash)
5787         {
5788           const char *const namei_string = map.namei_to_name (namei);
5789
5790 #if 0 /* An expensive sanity check.  */
5791           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5792             {
5793               complaint (&symfile_complaints,
5794                          _("Wrong .debug_names hash for string at index %u "
5795                            "[in module %s]"),
5796                          namei, objfile_name (dwarf2_per_objfile->objfile));
5797               return NULL;
5798             }
5799 #endif
5800
5801           if (cmp (namei_string, name) == 0)
5802             {
5803               const ULONGEST namei_entry_offs
5804                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5805                                              + namei * map.offset_size),
5806                                             map.offset_size, map.dwarf5_byte_order);
5807               return map.entry_pool + namei_entry_offs;
5808             }
5809         }
5810
5811       ++namei;
5812       if (namei >= map.name_count)
5813         return NULL;
5814     }
5815 }
5816
5817 const gdb_byte *
5818 dw2_debug_names_iterator::find_vec_in_debug_names
5819   (const mapped_debug_names &map, uint32_t namei)
5820 {
5821   if (namei >= map.name_count)
5822     {
5823       complaint (&symfile_complaints,
5824                  _("Wrong .debug_names with name index %u but name_count=%u "
5825                    "[in module %s]"),
5826                  namei, map.name_count,
5827                  objfile_name (map.dwarf2_per_objfile->objfile));
5828       return NULL;
5829     }
5830
5831   const ULONGEST namei_entry_offs
5832     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5833                                  + namei * map.offset_size),
5834                                 map.offset_size, map.dwarf5_byte_order);
5835   return map.entry_pool + namei_entry_offs;
5836 }
5837
5838 /* See dw2_debug_names_iterator.  */
5839
5840 dwarf2_per_cu_data *
5841 dw2_debug_names_iterator::next ()
5842 {
5843   if (m_addr == NULL)
5844     return NULL;
5845
5846   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5847   struct objfile *objfile = dwarf2_per_objfile->objfile;
5848   bfd *const abfd = objfile->obfd;
5849
5850  again:
5851
5852   unsigned int bytes_read;
5853   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5854   m_addr += bytes_read;
5855   if (abbrev == 0)
5856     return NULL;
5857
5858   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5859   if (indexval_it == m_map.abbrev_map.cend ())
5860     {
5861       complaint (&symfile_complaints,
5862                  _("Wrong .debug_names undefined abbrev code %s "
5863                    "[in module %s]"),
5864                  pulongest (abbrev), objfile_name (objfile));
5865       return NULL;
5866     }
5867   const mapped_debug_names::index_val &indexval = indexval_it->second;
5868   bool have_is_static = false;
5869   bool is_static;
5870   dwarf2_per_cu_data *per_cu = NULL;
5871   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5872     {
5873       ULONGEST ull;
5874       switch (attr.form)
5875         {
5876         case DW_FORM_implicit_const:
5877           ull = attr.implicit_const;
5878           break;
5879         case DW_FORM_flag_present:
5880           ull = 1;
5881           break;
5882         case DW_FORM_udata:
5883           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5884           m_addr += bytes_read;
5885           break;
5886         default:
5887           complaint (&symfile_complaints,
5888                      _("Unsupported .debug_names form %s [in module %s]"),
5889                      dwarf_form_name (attr.form),
5890                      objfile_name (objfile));
5891           return NULL;
5892         }
5893       switch (attr.dw_idx)
5894         {
5895         case DW_IDX_compile_unit:
5896           /* Don't crash on bad data.  */
5897           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5898             {
5899               complaint (&symfile_complaints,
5900                          _(".debug_names entry has bad CU index %s"
5901                            " [in module %s]"),
5902                          pulongest (ull),
5903                          objfile_name (dwarf2_per_objfile->objfile));
5904               continue;
5905             }
5906           per_cu = dwarf2_per_objfile->get_cutu (ull);
5907           break;
5908         case DW_IDX_type_unit:
5909           /* Don't crash on bad data.  */
5910           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5911             {
5912               complaint (&symfile_complaints,
5913                          _(".debug_names entry has bad TU index %s"
5914                            " [in module %s]"),
5915                          pulongest (ull),
5916                          objfile_name (dwarf2_per_objfile->objfile));
5917               continue;
5918             }
5919           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5920           break;
5921         case DW_IDX_GNU_internal:
5922           if (!m_map.augmentation_is_gdb)
5923             break;
5924           have_is_static = true;
5925           is_static = true;
5926           break;
5927         case DW_IDX_GNU_external:
5928           if (!m_map.augmentation_is_gdb)
5929             break;
5930           have_is_static = true;
5931           is_static = false;
5932           break;
5933         }
5934     }
5935
5936   /* Skip if already read in.  */
5937   if (per_cu->v.quick->compunit_symtab)
5938     goto again;
5939
5940   /* Check static vs global.  */
5941   if (have_is_static)
5942     {
5943       const bool want_static = m_block_index != GLOBAL_BLOCK;
5944       if (m_want_specific_block && want_static != is_static)
5945         goto again;
5946     }
5947
5948   /* Match dw2_symtab_iter_next, symbol_kind
5949      and debug_names::psymbol_tag.  */
5950   switch (m_domain)
5951     {
5952     case VAR_DOMAIN:
5953       switch (indexval.dwarf_tag)
5954         {
5955         case DW_TAG_variable:
5956         case DW_TAG_subprogram:
5957         /* Some types are also in VAR_DOMAIN.  */
5958         case DW_TAG_typedef:
5959         case DW_TAG_structure_type:
5960           break;
5961         default:
5962           goto again;
5963         }
5964       break;
5965     case STRUCT_DOMAIN:
5966       switch (indexval.dwarf_tag)
5967         {
5968         case DW_TAG_typedef:
5969         case DW_TAG_structure_type:
5970           break;
5971         default:
5972           goto again;
5973         }
5974       break;
5975     case LABEL_DOMAIN:
5976       switch (indexval.dwarf_tag)
5977         {
5978         case 0:
5979         case DW_TAG_variable:
5980           break;
5981         default:
5982           goto again;
5983         }
5984       break;
5985     default:
5986       break;
5987     }
5988
5989   /* Match dw2_expand_symtabs_matching, symbol_kind and
5990      debug_names::psymbol_tag.  */
5991   switch (m_search)
5992     {
5993     case VARIABLES_DOMAIN:
5994       switch (indexval.dwarf_tag)
5995         {
5996         case DW_TAG_variable:
5997           break;
5998         default:
5999           goto again;
6000         }
6001       break;
6002     case FUNCTIONS_DOMAIN:
6003       switch (indexval.dwarf_tag)
6004         {
6005         case DW_TAG_subprogram:
6006           break;
6007         default:
6008           goto again;
6009         }
6010       break;
6011     case TYPES_DOMAIN:
6012       switch (indexval.dwarf_tag)
6013         {
6014         case DW_TAG_typedef:
6015         case DW_TAG_structure_type:
6016           break;
6017         default:
6018           goto again;
6019         }
6020       break;
6021     default:
6022       break;
6023     }
6024
6025   return per_cu;
6026 }
6027
6028 static struct compunit_symtab *
6029 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6030                                const char *name, domain_enum domain)
6031 {
6032   const block_enum block_index = static_cast<block_enum> (block_index_int);
6033   struct dwarf2_per_objfile *dwarf2_per_objfile
6034     = get_dwarf2_per_objfile (objfile);
6035
6036   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6037   if (!mapp)
6038     {
6039       /* index is NULL if OBJF_READNOW.  */
6040       return NULL;
6041     }
6042   const auto &map = *mapp;
6043
6044   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6045                                  block_index, domain, name);
6046
6047   struct compunit_symtab *stab_best = NULL;
6048   struct dwarf2_per_cu_data *per_cu;
6049   while ((per_cu = iter.next ()) != NULL)
6050     {
6051       struct symbol *sym, *with_opaque = NULL;
6052       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6053       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6054       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6055
6056       sym = block_find_symbol (block, name, domain,
6057                                block_find_non_opaque_type_preferred,
6058                                &with_opaque);
6059
6060       /* Some caution must be observed with overloaded functions and
6061          methods, since the index will not contain any overload
6062          information (but NAME might contain it).  */
6063
6064       if (sym != NULL
6065           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6066         return stab;
6067       if (with_opaque != NULL
6068           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6069         stab_best = stab;
6070
6071       /* Keep looking through other CUs.  */
6072     }
6073
6074   return stab_best;
6075 }
6076
6077 /* This dumps minimal information about .debug_names.  It is called
6078    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6079    uses this to verify that .debug_names has been loaded.  */
6080
6081 static void
6082 dw2_debug_names_dump (struct objfile *objfile)
6083 {
6084   struct dwarf2_per_objfile *dwarf2_per_objfile
6085     = get_dwarf2_per_objfile (objfile);
6086
6087   gdb_assert (dwarf2_per_objfile->using_index);
6088   printf_filtered (".debug_names:");
6089   if (dwarf2_per_objfile->debug_names_table)
6090     printf_filtered (" exists\n");
6091   else
6092     printf_filtered (" faked for \"readnow\"\n");
6093   printf_filtered ("\n");
6094 }
6095
6096 static void
6097 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6098                                              const char *func_name)
6099 {
6100   struct dwarf2_per_objfile *dwarf2_per_objfile
6101     = get_dwarf2_per_objfile (objfile);
6102
6103   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6104   if (dwarf2_per_objfile->debug_names_table)
6105     {
6106       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6107
6108       /* Note: It doesn't matter what we pass for block_index here.  */
6109       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6110                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6111
6112       struct dwarf2_per_cu_data *per_cu;
6113       while ((per_cu = iter.next ()) != NULL)
6114         dw2_instantiate_symtab (per_cu);
6115     }
6116 }
6117
6118 static void
6119 dw2_debug_names_expand_symtabs_matching
6120   (struct objfile *objfile,
6121    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6122    const lookup_name_info &lookup_name,
6123    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6124    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6125    enum search_domain kind)
6126 {
6127   struct dwarf2_per_objfile *dwarf2_per_objfile
6128     = get_dwarf2_per_objfile (objfile);
6129
6130   /* debug_names_table is NULL if OBJF_READNOW.  */
6131   if (!dwarf2_per_objfile->debug_names_table)
6132     return;
6133
6134   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6135
6136   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6137
6138   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6139                                       symbol_matcher,
6140                                       kind, [&] (offset_type namei)
6141     {
6142       /* The name was matched, now expand corresponding CUs that were
6143          marked.  */
6144       dw2_debug_names_iterator iter (map, kind, namei);
6145
6146       struct dwarf2_per_cu_data *per_cu;
6147       while ((per_cu = iter.next ()) != NULL)
6148         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6149                                          expansion_notify);
6150     });
6151 }
6152
6153 const struct quick_symbol_functions dwarf2_debug_names_functions =
6154 {
6155   dw2_has_symbols,
6156   dw2_find_last_source_symtab,
6157   dw2_forget_cached_source_info,
6158   dw2_map_symtabs_matching_filename,
6159   dw2_debug_names_lookup_symbol,
6160   dw2_print_stats,
6161   dw2_debug_names_dump,
6162   dw2_relocate,
6163   dw2_debug_names_expand_symtabs_for_function,
6164   dw2_expand_all_symtabs,
6165   dw2_expand_symtabs_with_fullname,
6166   dw2_map_matching_symbols,
6167   dw2_debug_names_expand_symtabs_matching,
6168   dw2_find_pc_sect_compunit_symtab,
6169   NULL,
6170   dw2_map_symbol_filenames
6171 };
6172
6173 /* See symfile.h.  */
6174
6175 bool
6176 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6177 {
6178   struct dwarf2_per_objfile *dwarf2_per_objfile
6179     = get_dwarf2_per_objfile (objfile);
6180
6181   /* If we're about to read full symbols, don't bother with the
6182      indices.  In this case we also don't care if some other debug
6183      format is making psymtabs, because they are all about to be
6184      expanded anyway.  */
6185   if ((objfile->flags & OBJF_READNOW))
6186     {
6187       dwarf2_per_objfile->using_index = 1;
6188       create_all_comp_units (dwarf2_per_objfile);
6189       create_all_type_units (dwarf2_per_objfile);
6190       dwarf2_per_objfile->quick_file_names_table
6191         = create_quick_file_names_table
6192             (dwarf2_per_objfile->all_comp_units.size ());
6193
6194       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6195                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6196         {
6197           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6198
6199           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6200                                             struct dwarf2_per_cu_quick_data);
6201         }
6202
6203       /* Return 1 so that gdb sees the "quick" functions.  However,
6204          these functions will be no-ops because we will have expanded
6205          all symtabs.  */
6206       *index_kind = dw_index_kind::GDB_INDEX;
6207       return true;
6208     }
6209
6210   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6211     {
6212       *index_kind = dw_index_kind::DEBUG_NAMES;
6213       return true;
6214     }
6215
6216   if (dwarf2_read_index (dwarf2_per_objfile))
6217     {
6218       *index_kind = dw_index_kind::GDB_INDEX;
6219       return true;
6220     }
6221
6222   return false;
6223 }
6224
6225 \f
6226
6227 /* Build a partial symbol table.  */
6228
6229 void
6230 dwarf2_build_psymtabs (struct objfile *objfile)
6231 {
6232   struct dwarf2_per_objfile *dwarf2_per_objfile
6233     = get_dwarf2_per_objfile (objfile);
6234
6235   if (objfile->global_psymbols.capacity () == 0
6236       && objfile->static_psymbols.capacity () == 0)
6237     init_psymbol_list (objfile, 1024);
6238
6239   TRY
6240     {
6241       /* This isn't really ideal: all the data we allocate on the
6242          objfile's obstack is still uselessly kept around.  However,
6243          freeing it seems unsafe.  */
6244       psymtab_discarder psymtabs (objfile);
6245       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6246       psymtabs.keep ();
6247     }
6248   CATCH (except, RETURN_MASK_ERROR)
6249     {
6250       exception_print (gdb_stderr, except);
6251     }
6252   END_CATCH
6253 }
6254
6255 /* Return the total length of the CU described by HEADER.  */
6256
6257 static unsigned int
6258 get_cu_length (const struct comp_unit_head *header)
6259 {
6260   return header->initial_length_size + header->length;
6261 }
6262
6263 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6264
6265 static inline bool
6266 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6267 {
6268   sect_offset bottom = cu_header->sect_off;
6269   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6270
6271   return sect_off >= bottom && sect_off < top;
6272 }
6273
6274 /* Find the base address of the compilation unit for range lists and
6275    location lists.  It will normally be specified by DW_AT_low_pc.
6276    In DWARF-3 draft 4, the base address could be overridden by
6277    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6278    compilation units with discontinuous ranges.  */
6279
6280 static void
6281 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6282 {
6283   struct attribute *attr;
6284
6285   cu->base_known = 0;
6286   cu->base_address = 0;
6287
6288   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6289   if (attr)
6290     {
6291       cu->base_address = attr_value_as_address (attr);
6292       cu->base_known = 1;
6293     }
6294   else
6295     {
6296       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6297       if (attr)
6298         {
6299           cu->base_address = attr_value_as_address (attr);
6300           cu->base_known = 1;
6301         }
6302     }
6303 }
6304
6305 /* Read in the comp unit header information from the debug_info at info_ptr.
6306    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6307    NOTE: This leaves members offset, first_die_offset to be filled in
6308    by the caller.  */
6309
6310 static const gdb_byte *
6311 read_comp_unit_head (struct comp_unit_head *cu_header,
6312                      const gdb_byte *info_ptr,
6313                      struct dwarf2_section_info *section,
6314                      rcuh_kind section_kind)
6315 {
6316   int signed_addr;
6317   unsigned int bytes_read;
6318   const char *filename = get_section_file_name (section);
6319   bfd *abfd = get_section_bfd_owner (section);
6320
6321   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6322   cu_header->initial_length_size = bytes_read;
6323   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6324   info_ptr += bytes_read;
6325   cu_header->version = read_2_bytes (abfd, info_ptr);
6326   info_ptr += 2;
6327   if (cu_header->version < 5)
6328     switch (section_kind)
6329       {
6330       case rcuh_kind::COMPILE:
6331         cu_header->unit_type = DW_UT_compile;
6332         break;
6333       case rcuh_kind::TYPE:
6334         cu_header->unit_type = DW_UT_type;
6335         break;
6336       default:
6337         internal_error (__FILE__, __LINE__,
6338                         _("read_comp_unit_head: invalid section_kind"));
6339       }
6340   else
6341     {
6342       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6343                                                  (read_1_byte (abfd, info_ptr));
6344       info_ptr += 1;
6345       switch (cu_header->unit_type)
6346         {
6347         case DW_UT_compile:
6348           if (section_kind != rcuh_kind::COMPILE)
6349             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6350                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6351                    filename);
6352           break;
6353         case DW_UT_type:
6354           section_kind = rcuh_kind::TYPE;
6355           break;
6356         default:
6357           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6358                  "(is %d, should be %d or %d) [in module %s]"),
6359                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6360         }
6361
6362       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6363       info_ptr += 1;
6364     }
6365   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6366                                                           cu_header,
6367                                                           &bytes_read);
6368   info_ptr += bytes_read;
6369   if (cu_header->version < 5)
6370     {
6371       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6372       info_ptr += 1;
6373     }
6374   signed_addr = bfd_get_sign_extend_vma (abfd);
6375   if (signed_addr < 0)
6376     internal_error (__FILE__, __LINE__,
6377                     _("read_comp_unit_head: dwarf from non elf file"));
6378   cu_header->signed_addr_p = signed_addr;
6379
6380   if (section_kind == rcuh_kind::TYPE)
6381     {
6382       LONGEST type_offset;
6383
6384       cu_header->signature = read_8_bytes (abfd, info_ptr);
6385       info_ptr += 8;
6386
6387       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6388       info_ptr += bytes_read;
6389       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6390       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6391         error (_("Dwarf Error: Too big type_offset in compilation unit "
6392                "header (is %s) [in module %s]"), plongest (type_offset),
6393                filename);
6394     }
6395
6396   return info_ptr;
6397 }
6398
6399 /* Helper function that returns the proper abbrev section for
6400    THIS_CU.  */
6401
6402 static struct dwarf2_section_info *
6403 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6404 {
6405   struct dwarf2_section_info *abbrev;
6406   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6407
6408   if (this_cu->is_dwz)
6409     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6410   else
6411     abbrev = &dwarf2_per_objfile->abbrev;
6412
6413   return abbrev;
6414 }
6415
6416 /* Subroutine of read_and_check_comp_unit_head and
6417    read_and_check_type_unit_head to simplify them.
6418    Perform various error checking on the header.  */
6419
6420 static void
6421 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6422                             struct comp_unit_head *header,
6423                             struct dwarf2_section_info *section,
6424                             struct dwarf2_section_info *abbrev_section)
6425 {
6426   const char *filename = get_section_file_name (section);
6427
6428   if (header->version < 2 || header->version > 5)
6429     error (_("Dwarf Error: wrong version in compilation unit header "
6430            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6431            filename);
6432
6433   if (to_underlying (header->abbrev_sect_off)
6434       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6435     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6436            "(offset %s + 6) [in module %s]"),
6437            sect_offset_str (header->abbrev_sect_off),
6438            sect_offset_str (header->sect_off),
6439            filename);
6440
6441   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6442      avoid potential 32-bit overflow.  */
6443   if (((ULONGEST) header->sect_off + get_cu_length (header))
6444       > section->size)
6445     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6446            "(offset %s + 0) [in module %s]"),
6447            header->length, sect_offset_str (header->sect_off),
6448            filename);
6449 }
6450
6451 /* Read in a CU/TU header and perform some basic error checking.
6452    The contents of the header are stored in HEADER.
6453    The result is a pointer to the start of the first DIE.  */
6454
6455 static const gdb_byte *
6456 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6457                                struct comp_unit_head *header,
6458                                struct dwarf2_section_info *section,
6459                                struct dwarf2_section_info *abbrev_section,
6460                                const gdb_byte *info_ptr,
6461                                rcuh_kind section_kind)
6462 {
6463   const gdb_byte *beg_of_comp_unit = info_ptr;
6464
6465   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6466
6467   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6468
6469   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6470
6471   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6472                               abbrev_section);
6473
6474   return info_ptr;
6475 }
6476
6477 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6478
6479 static sect_offset
6480 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6481                     struct dwarf2_section_info *section,
6482                     sect_offset sect_off)
6483 {
6484   bfd *abfd = get_section_bfd_owner (section);
6485   const gdb_byte *info_ptr;
6486   unsigned int initial_length_size, offset_size;
6487   uint16_t version;
6488
6489   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6490   info_ptr = section->buffer + to_underlying (sect_off);
6491   read_initial_length (abfd, info_ptr, &initial_length_size);
6492   offset_size = initial_length_size == 4 ? 4 : 8;
6493   info_ptr += initial_length_size;
6494
6495   version = read_2_bytes (abfd, info_ptr);
6496   info_ptr += 2;
6497   if (version >= 5)
6498     {
6499       /* Skip unit type and address size.  */
6500       info_ptr += 2;
6501     }
6502
6503   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6504 }
6505
6506 /* Allocate a new partial symtab for file named NAME and mark this new
6507    partial symtab as being an include of PST.  */
6508
6509 static void
6510 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6511                                struct objfile *objfile)
6512 {
6513   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6514
6515   if (!IS_ABSOLUTE_PATH (subpst->filename))
6516     {
6517       /* It shares objfile->objfile_obstack.  */
6518       subpst->dirname = pst->dirname;
6519     }
6520
6521   subpst->textlow = 0;
6522   subpst->texthigh = 0;
6523
6524   subpst->dependencies
6525     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6526   subpst->dependencies[0] = pst;
6527   subpst->number_of_dependencies = 1;
6528
6529   subpst->globals_offset = 0;
6530   subpst->n_global_syms = 0;
6531   subpst->statics_offset = 0;
6532   subpst->n_static_syms = 0;
6533   subpst->compunit_symtab = NULL;
6534   subpst->read_symtab = pst->read_symtab;
6535   subpst->readin = 0;
6536
6537   /* No private part is necessary for include psymtabs.  This property
6538      can be used to differentiate between such include psymtabs and
6539      the regular ones.  */
6540   subpst->read_symtab_private = NULL;
6541 }
6542
6543 /* Read the Line Number Program data and extract the list of files
6544    included by the source file represented by PST.  Build an include
6545    partial symtab for each of these included files.  */
6546
6547 static void
6548 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6549                                struct die_info *die,
6550                                struct partial_symtab *pst)
6551 {
6552   line_header_up lh;
6553   struct attribute *attr;
6554
6555   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6556   if (attr)
6557     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6558   if (lh == NULL)
6559     return;  /* No linetable, so no includes.  */
6560
6561   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6562   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6563 }
6564
6565 static hashval_t
6566 hash_signatured_type (const void *item)
6567 {
6568   const struct signatured_type *sig_type
6569     = (const struct signatured_type *) item;
6570
6571   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6572   return sig_type->signature;
6573 }
6574
6575 static int
6576 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6577 {
6578   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6579   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6580
6581   return lhs->signature == rhs->signature;
6582 }
6583
6584 /* Allocate a hash table for signatured types.  */
6585
6586 static htab_t
6587 allocate_signatured_type_table (struct objfile *objfile)
6588 {
6589   return htab_create_alloc_ex (41,
6590                                hash_signatured_type,
6591                                eq_signatured_type,
6592                                NULL,
6593                                &objfile->objfile_obstack,
6594                                hashtab_obstack_allocate,
6595                                dummy_obstack_deallocate);
6596 }
6597
6598 /* A helper function to add a signatured type CU to a table.  */
6599
6600 static int
6601 add_signatured_type_cu_to_table (void **slot, void *datum)
6602 {
6603   struct signatured_type *sigt = (struct signatured_type *) *slot;
6604   std::vector<signatured_type *> *all_type_units
6605     = (std::vector<signatured_type *> *) datum;
6606
6607   all_type_units->push_back (sigt);
6608
6609   return 1;
6610 }
6611
6612 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6613    and fill them into TYPES_HTAB.  It will process only type units,
6614    therefore DW_UT_type.  */
6615
6616 static void
6617 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6618                               struct dwo_file *dwo_file,
6619                               dwarf2_section_info *section, htab_t &types_htab,
6620                               rcuh_kind section_kind)
6621 {
6622   struct objfile *objfile = dwarf2_per_objfile->objfile;
6623   struct dwarf2_section_info *abbrev_section;
6624   bfd *abfd;
6625   const gdb_byte *info_ptr, *end_ptr;
6626
6627   abbrev_section = (dwo_file != NULL
6628                     ? &dwo_file->sections.abbrev
6629                     : &dwarf2_per_objfile->abbrev);
6630
6631   if (dwarf_read_debug)
6632     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6633                         get_section_name (section),
6634                         get_section_file_name (abbrev_section));
6635
6636   dwarf2_read_section (objfile, section);
6637   info_ptr = section->buffer;
6638
6639   if (info_ptr == NULL)
6640     return;
6641
6642   /* We can't set abfd until now because the section may be empty or
6643      not present, in which case the bfd is unknown.  */
6644   abfd = get_section_bfd_owner (section);
6645
6646   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6647      because we don't need to read any dies: the signature is in the
6648      header.  */
6649
6650   end_ptr = info_ptr + section->size;
6651   while (info_ptr < end_ptr)
6652     {
6653       struct signatured_type *sig_type;
6654       struct dwo_unit *dwo_tu;
6655       void **slot;
6656       const gdb_byte *ptr = info_ptr;
6657       struct comp_unit_head header;
6658       unsigned int length;
6659
6660       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6661
6662       /* Initialize it due to a false compiler warning.  */
6663       header.signature = -1;
6664       header.type_cu_offset_in_tu = (cu_offset) -1;
6665
6666       /* We need to read the type's signature in order to build the hash
6667          table, but we don't need anything else just yet.  */
6668
6669       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6670                                            abbrev_section, ptr, section_kind);
6671
6672       length = get_cu_length (&header);
6673
6674       /* Skip dummy type units.  */
6675       if (ptr >= info_ptr + length
6676           || peek_abbrev_code (abfd, ptr) == 0
6677           || header.unit_type != DW_UT_type)
6678         {
6679           info_ptr += length;
6680           continue;
6681         }
6682
6683       if (types_htab == NULL)
6684         {
6685           if (dwo_file)
6686             types_htab = allocate_dwo_unit_table (objfile);
6687           else
6688             types_htab = allocate_signatured_type_table (objfile);
6689         }
6690
6691       if (dwo_file)
6692         {
6693           sig_type = NULL;
6694           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6695                                    struct dwo_unit);
6696           dwo_tu->dwo_file = dwo_file;
6697           dwo_tu->signature = header.signature;
6698           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6699           dwo_tu->section = section;
6700           dwo_tu->sect_off = sect_off;
6701           dwo_tu->length = length;
6702         }
6703       else
6704         {
6705           /* N.B.: type_offset is not usable if this type uses a DWO file.
6706              The real type_offset is in the DWO file.  */
6707           dwo_tu = NULL;
6708           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6709                                      struct signatured_type);
6710           sig_type->signature = header.signature;
6711           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6712           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6713           sig_type->per_cu.is_debug_types = 1;
6714           sig_type->per_cu.section = section;
6715           sig_type->per_cu.sect_off = sect_off;
6716           sig_type->per_cu.length = length;
6717         }
6718
6719       slot = htab_find_slot (types_htab,
6720                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6721                              INSERT);
6722       gdb_assert (slot != NULL);
6723       if (*slot != NULL)
6724         {
6725           sect_offset dup_sect_off;
6726
6727           if (dwo_file)
6728             {
6729               const struct dwo_unit *dup_tu
6730                 = (const struct dwo_unit *) *slot;
6731
6732               dup_sect_off = dup_tu->sect_off;
6733             }
6734           else
6735             {
6736               const struct signatured_type *dup_tu
6737                 = (const struct signatured_type *) *slot;
6738
6739               dup_sect_off = dup_tu->per_cu.sect_off;
6740             }
6741
6742           complaint (&symfile_complaints,
6743                      _("debug type entry at offset %s is duplicate to"
6744                        " the entry at offset %s, signature %s"),
6745                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6746                      hex_string (header.signature));
6747         }
6748       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6749
6750       if (dwarf_read_debug > 1)
6751         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6752                             sect_offset_str (sect_off),
6753                             hex_string (header.signature));
6754
6755       info_ptr += length;
6756     }
6757 }
6758
6759 /* Create the hash table of all entries in the .debug_types
6760    (or .debug_types.dwo) section(s).
6761    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6762    otherwise it is NULL.
6763
6764    The result is a pointer to the hash table or NULL if there are no types.
6765
6766    Note: This function processes DWO files only, not DWP files.  */
6767
6768 static void
6769 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6770                                struct dwo_file *dwo_file,
6771                                VEC (dwarf2_section_info_def) *types,
6772                                htab_t &types_htab)
6773 {
6774   int ix;
6775   struct dwarf2_section_info *section;
6776
6777   if (VEC_empty (dwarf2_section_info_def, types))
6778     return;
6779
6780   for (ix = 0;
6781        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6782        ++ix)
6783     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6784                                   types_htab, rcuh_kind::TYPE);
6785 }
6786
6787 /* Create the hash table of all entries in the .debug_types section,
6788    and initialize all_type_units.
6789    The result is zero if there is an error (e.g. missing .debug_types section),
6790    otherwise non-zero.  */
6791
6792 static int
6793 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6794 {
6795   htab_t types_htab = NULL;
6796
6797   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6798                                 &dwarf2_per_objfile->info, types_htab,
6799                                 rcuh_kind::COMPILE);
6800   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6801                                  dwarf2_per_objfile->types, types_htab);
6802   if (types_htab == NULL)
6803     {
6804       dwarf2_per_objfile->signatured_types = NULL;
6805       return 0;
6806     }
6807
6808   dwarf2_per_objfile->signatured_types = types_htab;
6809
6810   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6811   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6812
6813   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6814                           &dwarf2_per_objfile->all_type_units);
6815
6816   return 1;
6817 }
6818
6819 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6820    If SLOT is non-NULL, it is the entry to use in the hash table.
6821    Otherwise we find one.  */
6822
6823 static struct signatured_type *
6824 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6825                void **slot)
6826 {
6827   struct objfile *objfile = dwarf2_per_objfile->objfile;
6828
6829   if (dwarf2_per_objfile->all_type_units.size ()
6830       == dwarf2_per_objfile->all_type_units.capacity ())
6831     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6832
6833   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6834                                               struct signatured_type);
6835
6836   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6837   sig_type->signature = sig;
6838   sig_type->per_cu.is_debug_types = 1;
6839   if (dwarf2_per_objfile->using_index)
6840     {
6841       sig_type->per_cu.v.quick =
6842         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6843                         struct dwarf2_per_cu_quick_data);
6844     }
6845
6846   if (slot == NULL)
6847     {
6848       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6849                              sig_type, INSERT);
6850     }
6851   gdb_assert (*slot == NULL);
6852   *slot = sig_type;
6853   /* The rest of sig_type must be filled in by the caller.  */
6854   return sig_type;
6855 }
6856
6857 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6858    Fill in SIG_ENTRY with DWO_ENTRY.  */
6859
6860 static void
6861 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6862                                   struct signatured_type *sig_entry,
6863                                   struct dwo_unit *dwo_entry)
6864 {
6865   /* Make sure we're not clobbering something we don't expect to.  */
6866   gdb_assert (! sig_entry->per_cu.queued);
6867   gdb_assert (sig_entry->per_cu.cu == NULL);
6868   if (dwarf2_per_objfile->using_index)
6869     {
6870       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6871       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6872     }
6873   else
6874       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6875   gdb_assert (sig_entry->signature == dwo_entry->signature);
6876   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6877   gdb_assert (sig_entry->type_unit_group == NULL);
6878   gdb_assert (sig_entry->dwo_unit == NULL);
6879
6880   sig_entry->per_cu.section = dwo_entry->section;
6881   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6882   sig_entry->per_cu.length = dwo_entry->length;
6883   sig_entry->per_cu.reading_dwo_directly = 1;
6884   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6885   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6886   sig_entry->dwo_unit = dwo_entry;
6887 }
6888
6889 /* Subroutine of lookup_signatured_type.
6890    If we haven't read the TU yet, create the signatured_type data structure
6891    for a TU to be read in directly from a DWO file, bypassing the stub.
6892    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6893    using .gdb_index, then when reading a CU we want to stay in the DWO file
6894    containing that CU.  Otherwise we could end up reading several other DWO
6895    files (due to comdat folding) to process the transitive closure of all the
6896    mentioned TUs, and that can be slow.  The current DWO file will have every
6897    type signature that it needs.
6898    We only do this for .gdb_index because in the psymtab case we already have
6899    to read all the DWOs to build the type unit groups.  */
6900
6901 static struct signatured_type *
6902 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6903 {
6904   struct dwarf2_per_objfile *dwarf2_per_objfile
6905     = cu->per_cu->dwarf2_per_objfile;
6906   struct objfile *objfile = dwarf2_per_objfile->objfile;
6907   struct dwo_file *dwo_file;
6908   struct dwo_unit find_dwo_entry, *dwo_entry;
6909   struct signatured_type find_sig_entry, *sig_entry;
6910   void **slot;
6911
6912   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6913
6914   /* If TU skeletons have been removed then we may not have read in any
6915      TUs yet.  */
6916   if (dwarf2_per_objfile->signatured_types == NULL)
6917     {
6918       dwarf2_per_objfile->signatured_types
6919         = allocate_signatured_type_table (objfile);
6920     }
6921
6922   /* We only ever need to read in one copy of a signatured type.
6923      Use the global signatured_types array to do our own comdat-folding
6924      of types.  If this is the first time we're reading this TU, and
6925      the TU has an entry in .gdb_index, replace the recorded data from
6926      .gdb_index with this TU.  */
6927
6928   find_sig_entry.signature = sig;
6929   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6930                          &find_sig_entry, INSERT);
6931   sig_entry = (struct signatured_type *) *slot;
6932
6933   /* We can get here with the TU already read, *or* in the process of being
6934      read.  Don't reassign the global entry to point to this DWO if that's
6935      the case.  Also note that if the TU is already being read, it may not
6936      have come from a DWO, the program may be a mix of Fission-compiled
6937      code and non-Fission-compiled code.  */
6938
6939   /* Have we already tried to read this TU?
6940      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6941      needn't exist in the global table yet).  */
6942   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6943     return sig_entry;
6944
6945   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6946      dwo_unit of the TU itself.  */
6947   dwo_file = cu->dwo_unit->dwo_file;
6948
6949   /* Ok, this is the first time we're reading this TU.  */
6950   if (dwo_file->tus == NULL)
6951     return NULL;
6952   find_dwo_entry.signature = sig;
6953   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6954   if (dwo_entry == NULL)
6955     return NULL;
6956
6957   /* If the global table doesn't have an entry for this TU, add one.  */
6958   if (sig_entry == NULL)
6959     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6960
6961   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6962   sig_entry->per_cu.tu_read = 1;
6963   return sig_entry;
6964 }
6965
6966 /* Subroutine of lookup_signatured_type.
6967    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6968    then try the DWP file.  If the TU stub (skeleton) has been removed then
6969    it won't be in .gdb_index.  */
6970
6971 static struct signatured_type *
6972 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6973 {
6974   struct dwarf2_per_objfile *dwarf2_per_objfile
6975     = cu->per_cu->dwarf2_per_objfile;
6976   struct objfile *objfile = dwarf2_per_objfile->objfile;
6977   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6978   struct dwo_unit *dwo_entry;
6979   struct signatured_type find_sig_entry, *sig_entry;
6980   void **slot;
6981
6982   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6983   gdb_assert (dwp_file != NULL);
6984
6985   /* If TU skeletons have been removed then we may not have read in any
6986      TUs yet.  */
6987   if (dwarf2_per_objfile->signatured_types == NULL)
6988     {
6989       dwarf2_per_objfile->signatured_types
6990         = allocate_signatured_type_table (objfile);
6991     }
6992
6993   find_sig_entry.signature = sig;
6994   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6995                          &find_sig_entry, INSERT);
6996   sig_entry = (struct signatured_type *) *slot;
6997
6998   /* Have we already tried to read this TU?
6999      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7000      needn't exist in the global table yet).  */
7001   if (sig_entry != NULL)
7002     return sig_entry;
7003
7004   if (dwp_file->tus == NULL)
7005     return NULL;
7006   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7007                                       sig, 1 /* is_debug_types */);
7008   if (dwo_entry == NULL)
7009     return NULL;
7010
7011   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7012   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7013
7014   return sig_entry;
7015 }
7016
7017 /* Lookup a signature based type for DW_FORM_ref_sig8.
7018    Returns NULL if signature SIG is not present in the table.
7019    It is up to the caller to complain about this.  */
7020
7021 static struct signatured_type *
7022 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7023 {
7024   struct dwarf2_per_objfile *dwarf2_per_objfile
7025     = cu->per_cu->dwarf2_per_objfile;
7026
7027   if (cu->dwo_unit
7028       && dwarf2_per_objfile->using_index)
7029     {
7030       /* We're in a DWO/DWP file, and we're using .gdb_index.
7031          These cases require special processing.  */
7032       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7033         return lookup_dwo_signatured_type (cu, sig);
7034       else
7035         return lookup_dwp_signatured_type (cu, sig);
7036     }
7037   else
7038     {
7039       struct signatured_type find_entry, *entry;
7040
7041       if (dwarf2_per_objfile->signatured_types == NULL)
7042         return NULL;
7043       find_entry.signature = sig;
7044       entry = ((struct signatured_type *)
7045                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7046       return entry;
7047     }
7048 }
7049 \f
7050 /* Low level DIE reading support.  */
7051
7052 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7053
7054 static void
7055 init_cu_die_reader (struct die_reader_specs *reader,
7056                     struct dwarf2_cu *cu,
7057                     struct dwarf2_section_info *section,
7058                     struct dwo_file *dwo_file,
7059                     struct abbrev_table *abbrev_table)
7060 {
7061   gdb_assert (section->readin && section->buffer != NULL);
7062   reader->abfd = get_section_bfd_owner (section);
7063   reader->cu = cu;
7064   reader->dwo_file = dwo_file;
7065   reader->die_section = section;
7066   reader->buffer = section->buffer;
7067   reader->buffer_end = section->buffer + section->size;
7068   reader->comp_dir = NULL;
7069   reader->abbrev_table = abbrev_table;
7070 }
7071
7072 /* Subroutine of init_cutu_and_read_dies to simplify it.
7073    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7074    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7075    already.
7076
7077    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7078    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7079    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7080    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7081    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7082    STUB_COMP_DIR may be non-NULL.
7083    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7084    are filled in with the info of the DIE from the DWO file.
7085    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7086    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7087    kept around for at least as long as *RESULT_READER.
7088
7089    The result is non-zero if a valid (non-dummy) DIE was found.  */
7090
7091 static int
7092 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7093                         struct dwo_unit *dwo_unit,
7094                         struct die_info *stub_comp_unit_die,
7095                         const char *stub_comp_dir,
7096                         struct die_reader_specs *result_reader,
7097                         const gdb_byte **result_info_ptr,
7098                         struct die_info **result_comp_unit_die,
7099                         int *result_has_children,
7100                         abbrev_table_up *result_dwo_abbrev_table)
7101 {
7102   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7103   struct objfile *objfile = dwarf2_per_objfile->objfile;
7104   struct dwarf2_cu *cu = this_cu->cu;
7105   bfd *abfd;
7106   const gdb_byte *begin_info_ptr, *info_ptr;
7107   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7108   int i,num_extra_attrs;
7109   struct dwarf2_section_info *dwo_abbrev_section;
7110   struct attribute *attr;
7111   struct die_info *comp_unit_die;
7112
7113   /* At most one of these may be provided.  */
7114   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7115
7116   /* These attributes aren't processed until later:
7117      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7118      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7119      referenced later.  However, these attributes are found in the stub
7120      which we won't have later.  In order to not impose this complication
7121      on the rest of the code, we read them here and copy them to the
7122      DWO CU/TU die.  */
7123
7124   stmt_list = NULL;
7125   low_pc = NULL;
7126   high_pc = NULL;
7127   ranges = NULL;
7128   comp_dir = NULL;
7129
7130   if (stub_comp_unit_die != NULL)
7131     {
7132       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7133          DWO file.  */
7134       if (! this_cu->is_debug_types)
7135         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7136       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7137       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7138       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7139       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7140
7141       /* There should be a DW_AT_addr_base attribute here (if needed).
7142          We need the value before we can process DW_FORM_GNU_addr_index.  */
7143       cu->addr_base = 0;
7144       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7145       if (attr)
7146         cu->addr_base = DW_UNSND (attr);
7147
7148       /* There should be a DW_AT_ranges_base attribute here (if needed).
7149          We need the value before we can process DW_AT_ranges.  */
7150       cu->ranges_base = 0;
7151       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7152       if (attr)
7153         cu->ranges_base = DW_UNSND (attr);
7154     }
7155   else if (stub_comp_dir != NULL)
7156     {
7157       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7158       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7159       comp_dir->name = DW_AT_comp_dir;
7160       comp_dir->form = DW_FORM_string;
7161       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7162       DW_STRING (comp_dir) = stub_comp_dir;
7163     }
7164
7165   /* Set up for reading the DWO CU/TU.  */
7166   cu->dwo_unit = dwo_unit;
7167   dwarf2_section_info *section = dwo_unit->section;
7168   dwarf2_read_section (objfile, section);
7169   abfd = get_section_bfd_owner (section);
7170   begin_info_ptr = info_ptr = (section->buffer
7171                                + to_underlying (dwo_unit->sect_off));
7172   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7173
7174   if (this_cu->is_debug_types)
7175     {
7176       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7177
7178       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7179                                                 &cu->header, section,
7180                                                 dwo_abbrev_section,
7181                                                 info_ptr, rcuh_kind::TYPE);
7182       /* This is not an assert because it can be caused by bad debug info.  */
7183       if (sig_type->signature != cu->header.signature)
7184         {
7185           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7186                    " TU at offset %s [in module %s]"),
7187                  hex_string (sig_type->signature),
7188                  hex_string (cu->header.signature),
7189                  sect_offset_str (dwo_unit->sect_off),
7190                  bfd_get_filename (abfd));
7191         }
7192       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7193       /* For DWOs coming from DWP files, we don't know the CU length
7194          nor the type's offset in the TU until now.  */
7195       dwo_unit->length = get_cu_length (&cu->header);
7196       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7197
7198       /* Establish the type offset that can be used to lookup the type.
7199          For DWO files, we don't know it until now.  */
7200       sig_type->type_offset_in_section
7201         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7202     }
7203   else
7204     {
7205       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7206                                                 &cu->header, section,
7207                                                 dwo_abbrev_section,
7208                                                 info_ptr, rcuh_kind::COMPILE);
7209       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7210       /* For DWOs coming from DWP files, we don't know the CU length
7211          until now.  */
7212       dwo_unit->length = get_cu_length (&cu->header);
7213     }
7214
7215   *result_dwo_abbrev_table
7216     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7217                                cu->header.abbrev_sect_off);
7218   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7219                       result_dwo_abbrev_table->get ());
7220
7221   /* Read in the die, but leave space to copy over the attributes
7222      from the stub.  This has the benefit of simplifying the rest of
7223      the code - all the work to maintain the illusion of a single
7224      DW_TAG_{compile,type}_unit DIE is done here.  */
7225   num_extra_attrs = ((stmt_list != NULL)
7226                      + (low_pc != NULL)
7227                      + (high_pc != NULL)
7228                      + (ranges != NULL)
7229                      + (comp_dir != NULL));
7230   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7231                               result_has_children, num_extra_attrs);
7232
7233   /* Copy over the attributes from the stub to the DIE we just read in.  */
7234   comp_unit_die = *result_comp_unit_die;
7235   i = comp_unit_die->num_attrs;
7236   if (stmt_list != NULL)
7237     comp_unit_die->attrs[i++] = *stmt_list;
7238   if (low_pc != NULL)
7239     comp_unit_die->attrs[i++] = *low_pc;
7240   if (high_pc != NULL)
7241     comp_unit_die->attrs[i++] = *high_pc;
7242   if (ranges != NULL)
7243     comp_unit_die->attrs[i++] = *ranges;
7244   if (comp_dir != NULL)
7245     comp_unit_die->attrs[i++] = *comp_dir;
7246   comp_unit_die->num_attrs += num_extra_attrs;
7247
7248   if (dwarf_die_debug)
7249     {
7250       fprintf_unfiltered (gdb_stdlog,
7251                           "Read die from %s@0x%x of %s:\n",
7252                           get_section_name (section),
7253                           (unsigned) (begin_info_ptr - section->buffer),
7254                           bfd_get_filename (abfd));
7255       dump_die (comp_unit_die, dwarf_die_debug);
7256     }
7257
7258   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7259      TUs by skipping the stub and going directly to the entry in the DWO file.
7260      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7261      to get it via circuitous means.  Blech.  */
7262   if (comp_dir != NULL)
7263     result_reader->comp_dir = DW_STRING (comp_dir);
7264
7265   /* Skip dummy compilation units.  */
7266   if (info_ptr >= begin_info_ptr + dwo_unit->length
7267       || peek_abbrev_code (abfd, info_ptr) == 0)
7268     return 0;
7269
7270   *result_info_ptr = info_ptr;
7271   return 1;
7272 }
7273
7274 /* Subroutine of init_cutu_and_read_dies to simplify it.
7275    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7276    Returns NULL if the specified DWO unit cannot be found.  */
7277
7278 static struct dwo_unit *
7279 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7280                  struct die_info *comp_unit_die)
7281 {
7282   struct dwarf2_cu *cu = this_cu->cu;
7283   ULONGEST signature;
7284   struct dwo_unit *dwo_unit;
7285   const char *comp_dir, *dwo_name;
7286
7287   gdb_assert (cu != NULL);
7288
7289   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7290   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7291   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7292
7293   if (this_cu->is_debug_types)
7294     {
7295       struct signatured_type *sig_type;
7296
7297       /* Since this_cu is the first member of struct signatured_type,
7298          we can go from a pointer to one to a pointer to the other.  */
7299       sig_type = (struct signatured_type *) this_cu;
7300       signature = sig_type->signature;
7301       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7302     }
7303   else
7304     {
7305       struct attribute *attr;
7306
7307       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7308       if (! attr)
7309         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7310                  " [in module %s]"),
7311                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7312       signature = DW_UNSND (attr);
7313       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7314                                        signature);
7315     }
7316
7317   return dwo_unit;
7318 }
7319
7320 /* Subroutine of init_cutu_and_read_dies to simplify it.
7321    See it for a description of the parameters.
7322    Read a TU directly from a DWO file, bypassing the stub.  */
7323
7324 static void
7325 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7326                            int use_existing_cu, int keep,
7327                            die_reader_func_ftype *die_reader_func,
7328                            void *data)
7329 {
7330   std::unique_ptr<dwarf2_cu> new_cu;
7331   struct signatured_type *sig_type;
7332   struct die_reader_specs reader;
7333   const gdb_byte *info_ptr;
7334   struct die_info *comp_unit_die;
7335   int has_children;
7336   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7337
7338   /* Verify we can do the following downcast, and that we have the
7339      data we need.  */
7340   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7341   sig_type = (struct signatured_type *) this_cu;
7342   gdb_assert (sig_type->dwo_unit != NULL);
7343
7344   if (use_existing_cu && this_cu->cu != NULL)
7345     {
7346       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7347       /* There's no need to do the rereading_dwo_cu handling that
7348          init_cutu_and_read_dies does since we don't read the stub.  */
7349     }
7350   else
7351     {
7352       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7353       gdb_assert (this_cu->cu == NULL);
7354       new_cu.reset (new dwarf2_cu (this_cu));
7355     }
7356
7357   /* A future optimization, if needed, would be to use an existing
7358      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7359      could share abbrev tables.  */
7360
7361   /* The abbreviation table used by READER, this must live at least as long as
7362      READER.  */
7363   abbrev_table_up dwo_abbrev_table;
7364
7365   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7366                               NULL /* stub_comp_unit_die */,
7367                               sig_type->dwo_unit->dwo_file->comp_dir,
7368                               &reader, &info_ptr,
7369                               &comp_unit_die, &has_children,
7370                               &dwo_abbrev_table) == 0)
7371     {
7372       /* Dummy die.  */
7373       return;
7374     }
7375
7376   /* All the "real" work is done here.  */
7377   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7378
7379   /* This duplicates the code in init_cutu_and_read_dies,
7380      but the alternative is making the latter more complex.
7381      This function is only for the special case of using DWO files directly:
7382      no point in overly complicating the general case just to handle this.  */
7383   if (new_cu != NULL && keep)
7384     {
7385       /* Link this CU into read_in_chain.  */
7386       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7387       dwarf2_per_objfile->read_in_chain = this_cu;
7388       /* The chain owns it now.  */
7389       new_cu.release ();
7390     }
7391 }
7392
7393 /* Initialize a CU (or TU) and read its DIEs.
7394    If the CU defers to a DWO file, read the DWO file as well.
7395
7396    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7397    Otherwise the table specified in the comp unit header is read in and used.
7398    This is an optimization for when we already have the abbrev table.
7399
7400    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7401    Otherwise, a new CU is allocated with xmalloc.
7402
7403    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7404    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7405
7406    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7407    linker) then DIE_READER_FUNC will not get called.  */
7408
7409 static void
7410 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7411                          struct abbrev_table *abbrev_table,
7412                          int use_existing_cu, int keep,
7413                          die_reader_func_ftype *die_reader_func,
7414                          void *data)
7415 {
7416   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7417   struct objfile *objfile = dwarf2_per_objfile->objfile;
7418   struct dwarf2_section_info *section = this_cu->section;
7419   bfd *abfd = get_section_bfd_owner (section);
7420   struct dwarf2_cu *cu;
7421   const gdb_byte *begin_info_ptr, *info_ptr;
7422   struct die_reader_specs reader;
7423   struct die_info *comp_unit_die;
7424   int has_children;
7425   struct attribute *attr;
7426   struct signatured_type *sig_type = NULL;
7427   struct dwarf2_section_info *abbrev_section;
7428   /* Non-zero if CU currently points to a DWO file and we need to
7429      reread it.  When this happens we need to reread the skeleton die
7430      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7431   int rereading_dwo_cu = 0;
7432
7433   if (dwarf_die_debug)
7434     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7435                         this_cu->is_debug_types ? "type" : "comp",
7436                         sect_offset_str (this_cu->sect_off));
7437
7438   if (use_existing_cu)
7439     gdb_assert (keep);
7440
7441   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7442      file (instead of going through the stub), short-circuit all of this.  */
7443   if (this_cu->reading_dwo_directly)
7444     {
7445       /* Narrow down the scope of possibilities to have to understand.  */
7446       gdb_assert (this_cu->is_debug_types);
7447       gdb_assert (abbrev_table == NULL);
7448       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7449                                  die_reader_func, data);
7450       return;
7451     }
7452
7453   /* This is cheap if the section is already read in.  */
7454   dwarf2_read_section (objfile, section);
7455
7456   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7457
7458   abbrev_section = get_abbrev_section_for_cu (this_cu);
7459
7460   std::unique_ptr<dwarf2_cu> new_cu;
7461   if (use_existing_cu && this_cu->cu != NULL)
7462     {
7463       cu = this_cu->cu;
7464       /* If this CU is from a DWO file we need to start over, we need to
7465          refetch the attributes from the skeleton CU.
7466          This could be optimized by retrieving those attributes from when we
7467          were here the first time: the previous comp_unit_die was stored in
7468          comp_unit_obstack.  But there's no data yet that we need this
7469          optimization.  */
7470       if (cu->dwo_unit != NULL)
7471         rereading_dwo_cu = 1;
7472     }
7473   else
7474     {
7475       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7476       gdb_assert (this_cu->cu == NULL);
7477       new_cu.reset (new dwarf2_cu (this_cu));
7478       cu = new_cu.get ();
7479     }
7480
7481   /* Get the header.  */
7482   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7483     {
7484       /* We already have the header, there's no need to read it in again.  */
7485       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7486     }
7487   else
7488     {
7489       if (this_cu->is_debug_types)
7490         {
7491           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7492                                                     &cu->header, section,
7493                                                     abbrev_section, info_ptr,
7494                                                     rcuh_kind::TYPE);
7495
7496           /* Since per_cu is the first member of struct signatured_type,
7497              we can go from a pointer to one to a pointer to the other.  */
7498           sig_type = (struct signatured_type *) this_cu;
7499           gdb_assert (sig_type->signature == cu->header.signature);
7500           gdb_assert (sig_type->type_offset_in_tu
7501                       == cu->header.type_cu_offset_in_tu);
7502           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7503
7504           /* LENGTH has not been set yet for type units if we're
7505              using .gdb_index.  */
7506           this_cu->length = get_cu_length (&cu->header);
7507
7508           /* Establish the type offset that can be used to lookup the type.  */
7509           sig_type->type_offset_in_section =
7510             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7511
7512           this_cu->dwarf_version = cu->header.version;
7513         }
7514       else
7515         {
7516           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7517                                                     &cu->header, section,
7518                                                     abbrev_section,
7519                                                     info_ptr,
7520                                                     rcuh_kind::COMPILE);
7521
7522           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7523           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7524           this_cu->dwarf_version = cu->header.version;
7525         }
7526     }
7527
7528   /* Skip dummy compilation units.  */
7529   if (info_ptr >= begin_info_ptr + this_cu->length
7530       || peek_abbrev_code (abfd, info_ptr) == 0)
7531     return;
7532
7533   /* If we don't have them yet, read the abbrevs for this compilation unit.
7534      And if we need to read them now, make sure they're freed when we're
7535      done (own the table through ABBREV_TABLE_HOLDER).  */
7536   abbrev_table_up abbrev_table_holder;
7537   if (abbrev_table != NULL)
7538     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7539   else
7540     {
7541       abbrev_table_holder
7542         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7543                                    cu->header.abbrev_sect_off);
7544       abbrev_table = abbrev_table_holder.get ();
7545     }
7546
7547   /* Read the top level CU/TU die.  */
7548   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7549   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7550
7551   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7552      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7553      table from the DWO file and pass the ownership over to us.  It will be
7554      referenced from READER, so we must make sure to free it after we're done
7555      with READER.
7556
7557      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7558      DWO CU, that this test will fail (the attribute will not be present).  */
7559   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7560   abbrev_table_up dwo_abbrev_table;
7561   if (attr)
7562     {
7563       struct dwo_unit *dwo_unit;
7564       struct die_info *dwo_comp_unit_die;
7565
7566       if (has_children)
7567         {
7568           complaint (&symfile_complaints,
7569                      _("compilation unit with DW_AT_GNU_dwo_name"
7570                        " has children (offset %s) [in module %s]"),
7571                      sect_offset_str (this_cu->sect_off),
7572                      bfd_get_filename (abfd));
7573         }
7574       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7575       if (dwo_unit != NULL)
7576         {
7577           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7578                                       comp_unit_die, NULL,
7579                                       &reader, &info_ptr,
7580                                       &dwo_comp_unit_die, &has_children,
7581                                       &dwo_abbrev_table) == 0)
7582             {
7583               /* Dummy die.  */
7584               return;
7585             }
7586           comp_unit_die = dwo_comp_unit_die;
7587         }
7588       else
7589         {
7590           /* Yikes, we couldn't find the rest of the DIE, we only have
7591              the stub.  A complaint has already been logged.  There's
7592              not much more we can do except pass on the stub DIE to
7593              die_reader_func.  We don't want to throw an error on bad
7594              debug info.  */
7595         }
7596     }
7597
7598   /* All of the above is setup for this call.  Yikes.  */
7599   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7600
7601   /* Done, clean up.  */
7602   if (new_cu != NULL && keep)
7603     {
7604       /* Link this CU into read_in_chain.  */
7605       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7606       dwarf2_per_objfile->read_in_chain = this_cu;
7607       /* The chain owns it now.  */
7608       new_cu.release ();
7609     }
7610 }
7611
7612 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7613    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7614    to have already done the lookup to find the DWO file).
7615
7616    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7617    THIS_CU->is_debug_types, but nothing else.
7618
7619    We fill in THIS_CU->length.
7620
7621    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7622    linker) then DIE_READER_FUNC will not get called.
7623
7624    THIS_CU->cu is always freed when done.
7625    This is done in order to not leave THIS_CU->cu in a state where we have
7626    to care whether it refers to the "main" CU or the DWO CU.  */
7627
7628 static void
7629 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7630                                    struct dwo_file *dwo_file,
7631                                    die_reader_func_ftype *die_reader_func,
7632                                    void *data)
7633 {
7634   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7635   struct objfile *objfile = dwarf2_per_objfile->objfile;
7636   struct dwarf2_section_info *section = this_cu->section;
7637   bfd *abfd = get_section_bfd_owner (section);
7638   struct dwarf2_section_info *abbrev_section;
7639   const gdb_byte *begin_info_ptr, *info_ptr;
7640   struct die_reader_specs reader;
7641   struct die_info *comp_unit_die;
7642   int has_children;
7643
7644   if (dwarf_die_debug)
7645     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7646                         this_cu->is_debug_types ? "type" : "comp",
7647                         sect_offset_str (this_cu->sect_off));
7648
7649   gdb_assert (this_cu->cu == NULL);
7650
7651   abbrev_section = (dwo_file != NULL
7652                     ? &dwo_file->sections.abbrev
7653                     : get_abbrev_section_for_cu (this_cu));
7654
7655   /* This is cheap if the section is already read in.  */
7656   dwarf2_read_section (objfile, section);
7657
7658   struct dwarf2_cu cu (this_cu);
7659
7660   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7661   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7662                                             &cu.header, section,
7663                                             abbrev_section, info_ptr,
7664                                             (this_cu->is_debug_types
7665                                              ? rcuh_kind::TYPE
7666                                              : rcuh_kind::COMPILE));
7667
7668   this_cu->length = get_cu_length (&cu.header);
7669
7670   /* Skip dummy compilation units.  */
7671   if (info_ptr >= begin_info_ptr + this_cu->length
7672       || peek_abbrev_code (abfd, info_ptr) == 0)
7673     return;
7674
7675   abbrev_table_up abbrev_table
7676     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7677                                cu.header.abbrev_sect_off);
7678
7679   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7680   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7681
7682   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7683 }
7684
7685 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7686    does not lookup the specified DWO file.
7687    This cannot be used to read DWO files.
7688
7689    THIS_CU->cu is always freed when done.
7690    This is done in order to not leave THIS_CU->cu in a state where we have
7691    to care whether it refers to the "main" CU or the DWO CU.
7692    We can revisit this if the data shows there's a performance issue.  */
7693
7694 static void
7695 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7696                                 die_reader_func_ftype *die_reader_func,
7697                                 void *data)
7698 {
7699   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7700 }
7701 \f
7702 /* Type Unit Groups.
7703
7704    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7705    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7706    so that all types coming from the same compilation (.o file) are grouped
7707    together.  A future step could be to put the types in the same symtab as
7708    the CU the types ultimately came from.  */
7709
7710 static hashval_t
7711 hash_type_unit_group (const void *item)
7712 {
7713   const struct type_unit_group *tu_group
7714     = (const struct type_unit_group *) item;
7715
7716   return hash_stmt_list_entry (&tu_group->hash);
7717 }
7718
7719 static int
7720 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7721 {
7722   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7723   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7724
7725   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7726 }
7727
7728 /* Allocate a hash table for type unit groups.  */
7729
7730 static htab_t
7731 allocate_type_unit_groups_table (struct objfile *objfile)
7732 {
7733   return htab_create_alloc_ex (3,
7734                                hash_type_unit_group,
7735                                eq_type_unit_group,
7736                                NULL,
7737                                &objfile->objfile_obstack,
7738                                hashtab_obstack_allocate,
7739                                dummy_obstack_deallocate);
7740 }
7741
7742 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7743    partial symtabs.  We combine several TUs per psymtab to not let the size
7744    of any one psymtab grow too big.  */
7745 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7746 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7747
7748 /* Helper routine for get_type_unit_group.
7749    Create the type_unit_group object used to hold one or more TUs.  */
7750
7751 static struct type_unit_group *
7752 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7753 {
7754   struct dwarf2_per_objfile *dwarf2_per_objfile
7755     = cu->per_cu->dwarf2_per_objfile;
7756   struct objfile *objfile = dwarf2_per_objfile->objfile;
7757   struct dwarf2_per_cu_data *per_cu;
7758   struct type_unit_group *tu_group;
7759
7760   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7761                              struct type_unit_group);
7762   per_cu = &tu_group->per_cu;
7763   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7764
7765   if (dwarf2_per_objfile->using_index)
7766     {
7767       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7768                                         struct dwarf2_per_cu_quick_data);
7769     }
7770   else
7771     {
7772       unsigned int line_offset = to_underlying (line_offset_struct);
7773       struct partial_symtab *pst;
7774       char *name;
7775
7776       /* Give the symtab a useful name for debug purposes.  */
7777       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7778         name = xstrprintf ("<type_units_%d>",
7779                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7780       else
7781         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
7782
7783       pst = create_partial_symtab (per_cu, name);
7784       pst->anonymous = 1;
7785
7786       xfree (name);
7787     }
7788
7789   tu_group->hash.dwo_unit = cu->dwo_unit;
7790   tu_group->hash.line_sect_off = line_offset_struct;
7791
7792   return tu_group;
7793 }
7794
7795 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7796    STMT_LIST is a DW_AT_stmt_list attribute.  */
7797
7798 static struct type_unit_group *
7799 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7800 {
7801   struct dwarf2_per_objfile *dwarf2_per_objfile
7802     = cu->per_cu->dwarf2_per_objfile;
7803   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7804   struct type_unit_group *tu_group;
7805   void **slot;
7806   unsigned int line_offset;
7807   struct type_unit_group type_unit_group_for_lookup;
7808
7809   if (dwarf2_per_objfile->type_unit_groups == NULL)
7810     {
7811       dwarf2_per_objfile->type_unit_groups =
7812         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7813     }
7814
7815   /* Do we need to create a new group, or can we use an existing one?  */
7816
7817   if (stmt_list)
7818     {
7819       line_offset = DW_UNSND (stmt_list);
7820       ++tu_stats->nr_symtab_sharers;
7821     }
7822   else
7823     {
7824       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7825          We can do various things here like create one group per TU or
7826          spread them over multiple groups to split up the expansion work.
7827          To avoid worst case scenarios (too many groups or too large groups)
7828          we, umm, group them in bunches.  */
7829       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7830                      | (tu_stats->nr_stmt_less_type_units
7831                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7832       ++tu_stats->nr_stmt_less_type_units;
7833     }
7834
7835   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7836   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7837   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7838                          &type_unit_group_for_lookup, INSERT);
7839   if (*slot != NULL)
7840     {
7841       tu_group = (struct type_unit_group *) *slot;
7842       gdb_assert (tu_group != NULL);
7843     }
7844   else
7845     {
7846       sect_offset line_offset_struct = (sect_offset) line_offset;
7847       tu_group = create_type_unit_group (cu, line_offset_struct);
7848       *slot = tu_group;
7849       ++tu_stats->nr_symtabs;
7850     }
7851
7852   return tu_group;
7853 }
7854 \f
7855 /* Partial symbol tables.  */
7856
7857 /* Create a psymtab named NAME and assign it to PER_CU.
7858
7859    The caller must fill in the following details:
7860    dirname, textlow, texthigh.  */
7861
7862 static struct partial_symtab *
7863 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7864 {
7865   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7866   struct partial_symtab *pst;
7867
7868   pst = start_psymtab_common (objfile, name, 0,
7869                               objfile->global_psymbols,
7870                               objfile->static_psymbols);
7871
7872   pst->psymtabs_addrmap_supported = 1;
7873
7874   /* This is the glue that links PST into GDB's symbol API.  */
7875   pst->read_symtab_private = per_cu;
7876   pst->read_symtab = dwarf2_read_symtab;
7877   per_cu->v.psymtab = pst;
7878
7879   return pst;
7880 }
7881
7882 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7883    type.  */
7884
7885 struct process_psymtab_comp_unit_data
7886 {
7887   /* True if we are reading a DW_TAG_partial_unit.  */
7888
7889   int want_partial_unit;
7890
7891   /* The "pretend" language that is used if the CU doesn't declare a
7892      language.  */
7893
7894   enum language pretend_language;
7895 };
7896
7897 /* die_reader_func for process_psymtab_comp_unit.  */
7898
7899 static void
7900 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7901                                   const gdb_byte *info_ptr,
7902                                   struct die_info *comp_unit_die,
7903                                   int has_children,
7904                                   void *data)
7905 {
7906   struct dwarf2_cu *cu = reader->cu;
7907   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7908   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7909   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7910   CORE_ADDR baseaddr;
7911   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7912   struct partial_symtab *pst;
7913   enum pc_bounds_kind cu_bounds_kind;
7914   const char *filename;
7915   struct process_psymtab_comp_unit_data *info
7916     = (struct process_psymtab_comp_unit_data *) data;
7917
7918   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7919     return;
7920
7921   gdb_assert (! per_cu->is_debug_types);
7922
7923   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7924
7925   cu->list_in_scope = &file_symbols;
7926
7927   /* Allocate a new partial symbol table structure.  */
7928   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7929   if (filename == NULL)
7930     filename = "";
7931
7932   pst = create_partial_symtab (per_cu, filename);
7933
7934   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7935   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7936
7937   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7938
7939   dwarf2_find_base_address (comp_unit_die, cu);
7940
7941   /* Possibly set the default values of LOWPC and HIGHPC from
7942      `DW_AT_ranges'.  */
7943   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7944                                          &best_highpc, cu, pst);
7945   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7946     /* Store the contiguous range if it is not empty; it can be empty for
7947        CUs with no code.  */
7948     addrmap_set_empty (objfile->psymtabs_addrmap,
7949                        gdbarch_adjust_dwarf2_addr (gdbarch,
7950                                                    best_lowpc + baseaddr),
7951                        gdbarch_adjust_dwarf2_addr (gdbarch,
7952                                                    best_highpc + baseaddr) - 1,
7953                        pst);
7954
7955   /* Check if comp unit has_children.
7956      If so, read the rest of the partial symbols from this comp unit.
7957      If not, there's no more debug_info for this comp unit.  */
7958   if (has_children)
7959     {
7960       struct partial_die_info *first_die;
7961       CORE_ADDR lowpc, highpc;
7962
7963       lowpc = ((CORE_ADDR) -1);
7964       highpc = ((CORE_ADDR) 0);
7965
7966       first_die = load_partial_dies (reader, info_ptr, 1);
7967
7968       scan_partial_symbols (first_die, &lowpc, &highpc,
7969                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7970
7971       /* If we didn't find a lowpc, set it to highpc to avoid
7972          complaints from `maint check'.  */
7973       if (lowpc == ((CORE_ADDR) -1))
7974         lowpc = highpc;
7975
7976       /* If the compilation unit didn't have an explicit address range,
7977          then use the information extracted from its child dies.  */
7978       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7979         {
7980           best_lowpc = lowpc;
7981           best_highpc = highpc;
7982         }
7983     }
7984   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7985   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7986
7987   end_psymtab_common (objfile, pst);
7988
7989   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7990     {
7991       int i;
7992       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7993       struct dwarf2_per_cu_data *iter;
7994
7995       /* Fill in 'dependencies' here; we fill in 'users' in a
7996          post-pass.  */
7997       pst->number_of_dependencies = len;
7998       pst->dependencies =
7999         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8000       for (i = 0;
8001            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8002                         i, iter);
8003            ++i)
8004         pst->dependencies[i] = iter->v.psymtab;
8005
8006       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8007     }
8008
8009   /* Get the list of files included in the current compilation unit,
8010      and build a psymtab for each of them.  */
8011   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8012
8013   if (dwarf_read_debug)
8014     {
8015       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8016
8017       fprintf_unfiltered (gdb_stdlog,
8018                           "Psymtab for %s unit @%s: %s - %s"
8019                           ", %d global, %d static syms\n",
8020                           per_cu->is_debug_types ? "type" : "comp",
8021                           sect_offset_str (per_cu->sect_off),
8022                           paddress (gdbarch, pst->textlow),
8023                           paddress (gdbarch, pst->texthigh),
8024                           pst->n_global_syms, pst->n_static_syms);
8025     }
8026 }
8027
8028 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8029    Process compilation unit THIS_CU for a psymtab.  */
8030
8031 static void
8032 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8033                            int want_partial_unit,
8034                            enum language pretend_language)
8035 {
8036   /* If this compilation unit was already read in, free the
8037      cached copy in order to read it in again.  This is
8038      necessary because we skipped some symbols when we first
8039      read in the compilation unit (see load_partial_dies).
8040      This problem could be avoided, but the benefit is unclear.  */
8041   if (this_cu->cu != NULL)
8042     free_one_cached_comp_unit (this_cu);
8043
8044   if (this_cu->is_debug_types)
8045     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8046                              NULL);
8047   else
8048     {
8049       process_psymtab_comp_unit_data info;
8050       info.want_partial_unit = want_partial_unit;
8051       info.pretend_language = pretend_language;
8052       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8053                                process_psymtab_comp_unit_reader, &info);
8054     }
8055
8056   /* Age out any secondary CUs.  */
8057   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8058 }
8059
8060 /* Reader function for build_type_psymtabs.  */
8061
8062 static void
8063 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8064                             const gdb_byte *info_ptr,
8065                             struct die_info *type_unit_die,
8066                             int has_children,
8067                             void *data)
8068 {
8069   struct dwarf2_per_objfile *dwarf2_per_objfile
8070     = reader->cu->per_cu->dwarf2_per_objfile;
8071   struct objfile *objfile = dwarf2_per_objfile->objfile;
8072   struct dwarf2_cu *cu = reader->cu;
8073   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8074   struct signatured_type *sig_type;
8075   struct type_unit_group *tu_group;
8076   struct attribute *attr;
8077   struct partial_die_info *first_die;
8078   CORE_ADDR lowpc, highpc;
8079   struct partial_symtab *pst;
8080
8081   gdb_assert (data == NULL);
8082   gdb_assert (per_cu->is_debug_types);
8083   sig_type = (struct signatured_type *) per_cu;
8084
8085   if (! has_children)
8086     return;
8087
8088   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8089   tu_group = get_type_unit_group (cu, attr);
8090
8091   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8092
8093   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8094   cu->list_in_scope = &file_symbols;
8095   pst = create_partial_symtab (per_cu, "");
8096   pst->anonymous = 1;
8097
8098   first_die = load_partial_dies (reader, info_ptr, 1);
8099
8100   lowpc = (CORE_ADDR) -1;
8101   highpc = (CORE_ADDR) 0;
8102   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8103
8104   end_psymtab_common (objfile, pst);
8105 }
8106
8107 /* Struct used to sort TUs by their abbreviation table offset.  */
8108
8109 struct tu_abbrev_offset
8110 {
8111   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8112   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8113   {}
8114
8115   signatured_type *sig_type;
8116   sect_offset abbrev_offset;
8117 };
8118
8119 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8120
8121 static bool
8122 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8123                           const struct tu_abbrev_offset &b)
8124 {
8125   return a.abbrev_offset < b.abbrev_offset;
8126 }
8127
8128 /* Efficiently read all the type units.
8129    This does the bulk of the work for build_type_psymtabs.
8130
8131    The efficiency is because we sort TUs by the abbrev table they use and
8132    only read each abbrev table once.  In one program there are 200K TUs
8133    sharing 8K abbrev tables.
8134
8135    The main purpose of this function is to support building the
8136    dwarf2_per_objfile->type_unit_groups table.
8137    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8138    can collapse the search space by grouping them by stmt_list.
8139    The savings can be significant, in the same program from above the 200K TUs
8140    share 8K stmt_list tables.
8141
8142    FUNC is expected to call get_type_unit_group, which will create the
8143    struct type_unit_group if necessary and add it to
8144    dwarf2_per_objfile->type_unit_groups.  */
8145
8146 static void
8147 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8148 {
8149   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8150   abbrev_table_up abbrev_table;
8151   sect_offset abbrev_offset;
8152
8153   /* It's up to the caller to not call us multiple times.  */
8154   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8155
8156   if (dwarf2_per_objfile->all_type_units.empty ())
8157     return;
8158
8159   /* TUs typically share abbrev tables, and there can be way more TUs than
8160      abbrev tables.  Sort by abbrev table to reduce the number of times we
8161      read each abbrev table in.
8162      Alternatives are to punt or to maintain a cache of abbrev tables.
8163      This is simpler and efficient enough for now.
8164
8165      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8166      symtab to use).  Typically TUs with the same abbrev offset have the same
8167      stmt_list value too so in practice this should work well.
8168
8169      The basic algorithm here is:
8170
8171       sort TUs by abbrev table
8172       for each TU with same abbrev table:
8173         read abbrev table if first user
8174         read TU top level DIE
8175           [IWBN if DWO skeletons had DW_AT_stmt_list]
8176         call FUNC  */
8177
8178   if (dwarf_read_debug)
8179     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8180
8181   /* Sort in a separate table to maintain the order of all_type_units
8182      for .gdb_index: TU indices directly index all_type_units.  */
8183   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8184   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8185
8186   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8187     sorted_by_abbrev.emplace_back
8188       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8189                                      sig_type->per_cu.section,
8190                                      sig_type->per_cu.sect_off));
8191
8192   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8193              sort_tu_by_abbrev_offset);
8194
8195   abbrev_offset = (sect_offset) ~(unsigned) 0;
8196
8197   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8198     {
8199       /* Switch to the next abbrev table if necessary.  */
8200       if (abbrev_table == NULL
8201           || tu.abbrev_offset != abbrev_offset)
8202         {
8203           abbrev_offset = tu.abbrev_offset;
8204           abbrev_table =
8205             abbrev_table_read_table (dwarf2_per_objfile,
8206                                      &dwarf2_per_objfile->abbrev,
8207                                      abbrev_offset);
8208           ++tu_stats->nr_uniq_abbrev_tables;
8209         }
8210
8211       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8212                                0, 0, build_type_psymtabs_reader, NULL);
8213     }
8214 }
8215
8216 /* Print collected type unit statistics.  */
8217
8218 static void
8219 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8220 {
8221   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8222
8223   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8224   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8225                       dwarf2_per_objfile->all_type_units.size ());
8226   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8227                       tu_stats->nr_uniq_abbrev_tables);
8228   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8229                       tu_stats->nr_symtabs);
8230   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8231                       tu_stats->nr_symtab_sharers);
8232   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8233                       tu_stats->nr_stmt_less_type_units);
8234   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8235                       tu_stats->nr_all_type_units_reallocs);
8236 }
8237
8238 /* Traversal function for build_type_psymtabs.  */
8239
8240 static int
8241 build_type_psymtab_dependencies (void **slot, void *info)
8242 {
8243   struct dwarf2_per_objfile *dwarf2_per_objfile
8244     = (struct dwarf2_per_objfile *) info;
8245   struct objfile *objfile = dwarf2_per_objfile->objfile;
8246   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8247   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8248   struct partial_symtab *pst = per_cu->v.psymtab;
8249   int len = VEC_length (sig_type_ptr, tu_group->tus);
8250   struct signatured_type *iter;
8251   int i;
8252
8253   gdb_assert (len > 0);
8254   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8255
8256   pst->number_of_dependencies = len;
8257   pst->dependencies =
8258     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8259   for (i = 0;
8260        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8261        ++i)
8262     {
8263       gdb_assert (iter->per_cu.is_debug_types);
8264       pst->dependencies[i] = iter->per_cu.v.psymtab;
8265       iter->type_unit_group = tu_group;
8266     }
8267
8268   VEC_free (sig_type_ptr, tu_group->tus);
8269
8270   return 1;
8271 }
8272
8273 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8274    Build partial symbol tables for the .debug_types comp-units.  */
8275
8276 static void
8277 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8278 {
8279   if (! create_all_type_units (dwarf2_per_objfile))
8280     return;
8281
8282   build_type_psymtabs_1 (dwarf2_per_objfile);
8283 }
8284
8285 /* Traversal function for process_skeletonless_type_unit.
8286    Read a TU in a DWO file and build partial symbols for it.  */
8287
8288 static int
8289 process_skeletonless_type_unit (void **slot, void *info)
8290 {
8291   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8292   struct dwarf2_per_objfile *dwarf2_per_objfile
8293     = (struct dwarf2_per_objfile *) info;
8294   struct signatured_type find_entry, *entry;
8295
8296   /* If this TU doesn't exist in the global table, add it and read it in.  */
8297
8298   if (dwarf2_per_objfile->signatured_types == NULL)
8299     {
8300       dwarf2_per_objfile->signatured_types
8301         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8302     }
8303
8304   find_entry.signature = dwo_unit->signature;
8305   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8306                          INSERT);
8307   /* If we've already seen this type there's nothing to do.  What's happening
8308      is we're doing our own version of comdat-folding here.  */
8309   if (*slot != NULL)
8310     return 1;
8311
8312   /* This does the job that create_all_type_units would have done for
8313      this TU.  */
8314   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8315   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8316   *slot = entry;
8317
8318   /* This does the job that build_type_psymtabs_1 would have done.  */
8319   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8320                            build_type_psymtabs_reader, NULL);
8321
8322   return 1;
8323 }
8324
8325 /* Traversal function for process_skeletonless_type_units.  */
8326
8327 static int
8328 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8329 {
8330   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8331
8332   if (dwo_file->tus != NULL)
8333     {
8334       htab_traverse_noresize (dwo_file->tus,
8335                               process_skeletonless_type_unit, info);
8336     }
8337
8338   return 1;
8339 }
8340
8341 /* Scan all TUs of DWO files, verifying we've processed them.
8342    This is needed in case a TU was emitted without its skeleton.
8343    Note: This can't be done until we know what all the DWO files are.  */
8344
8345 static void
8346 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8347 {
8348   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8349   if (get_dwp_file (dwarf2_per_objfile) == NULL
8350       && dwarf2_per_objfile->dwo_files != NULL)
8351     {
8352       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8353                               process_dwo_file_for_skeletonless_type_units,
8354                               dwarf2_per_objfile);
8355     }
8356 }
8357
8358 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8359
8360 static void
8361 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8362 {
8363   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8364     {
8365       struct partial_symtab *pst = per_cu->v.psymtab;
8366
8367       if (pst == NULL)
8368         continue;
8369
8370       for (int j = 0; j < pst->number_of_dependencies; ++j)
8371         {
8372           /* Set the 'user' field only if it is not already set.  */
8373           if (pst->dependencies[j]->user == NULL)
8374             pst->dependencies[j]->user = pst;
8375         }
8376     }
8377 }
8378
8379 /* Build the partial symbol table by doing a quick pass through the
8380    .debug_info and .debug_abbrev sections.  */
8381
8382 static void
8383 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8384 {
8385   struct objfile *objfile = dwarf2_per_objfile->objfile;
8386
8387   if (dwarf_read_debug)
8388     {
8389       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8390                           objfile_name (objfile));
8391     }
8392
8393   dwarf2_per_objfile->reading_partial_symbols = 1;
8394
8395   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8396
8397   /* Any cached compilation units will be linked by the per-objfile
8398      read_in_chain.  Make sure to free them when we're done.  */
8399   free_cached_comp_units freer (dwarf2_per_objfile);
8400
8401   build_type_psymtabs (dwarf2_per_objfile);
8402
8403   create_all_comp_units (dwarf2_per_objfile);
8404
8405   /* Create a temporary address map on a temporary obstack.  We later
8406      copy this to the final obstack.  */
8407   auto_obstack temp_obstack;
8408
8409   scoped_restore save_psymtabs_addrmap
8410     = make_scoped_restore (&objfile->psymtabs_addrmap,
8411                            addrmap_create_mutable (&temp_obstack));
8412
8413   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8414     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8415
8416   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8417   process_skeletonless_type_units (dwarf2_per_objfile);
8418
8419   /* Now that all TUs have been processed we can fill in the dependencies.  */
8420   if (dwarf2_per_objfile->type_unit_groups != NULL)
8421     {
8422       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8423                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8424     }
8425
8426   if (dwarf_read_debug)
8427     print_tu_stats (dwarf2_per_objfile);
8428
8429   set_partial_user (dwarf2_per_objfile);
8430
8431   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8432                                                     &objfile->objfile_obstack);
8433   /* At this point we want to keep the address map.  */
8434   save_psymtabs_addrmap.release ();
8435
8436   if (dwarf_read_debug)
8437     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8438                         objfile_name (objfile));
8439 }
8440
8441 /* die_reader_func for load_partial_comp_unit.  */
8442
8443 static void
8444 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8445                                const gdb_byte *info_ptr,
8446                                struct die_info *comp_unit_die,
8447                                int has_children,
8448                                void *data)
8449 {
8450   struct dwarf2_cu *cu = reader->cu;
8451
8452   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8453
8454   /* Check if comp unit has_children.
8455      If so, read the rest of the partial symbols from this comp unit.
8456      If not, there's no more debug_info for this comp unit.  */
8457   if (has_children)
8458     load_partial_dies (reader, info_ptr, 0);
8459 }
8460
8461 /* Load the partial DIEs for a secondary CU into memory.
8462    This is also used when rereading a primary CU with load_all_dies.  */
8463
8464 static void
8465 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8466 {
8467   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8468                            load_partial_comp_unit_reader, NULL);
8469 }
8470
8471 static void
8472 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8473                               struct dwarf2_section_info *section,
8474                               struct dwarf2_section_info *abbrev_section,
8475                               unsigned int is_dwz)
8476 {
8477   const gdb_byte *info_ptr;
8478   struct objfile *objfile = dwarf2_per_objfile->objfile;
8479
8480   if (dwarf_read_debug)
8481     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8482                         get_section_name (section),
8483                         get_section_file_name (section));
8484
8485   dwarf2_read_section (objfile, section);
8486
8487   info_ptr = section->buffer;
8488
8489   while (info_ptr < section->buffer + section->size)
8490     {
8491       struct dwarf2_per_cu_data *this_cu;
8492
8493       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8494
8495       comp_unit_head cu_header;
8496       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8497                                      abbrev_section, info_ptr,
8498                                      rcuh_kind::COMPILE);
8499
8500       /* Save the compilation unit for later lookup.  */
8501       if (cu_header.unit_type != DW_UT_type)
8502         {
8503           this_cu = XOBNEW (&objfile->objfile_obstack,
8504                             struct dwarf2_per_cu_data);
8505           memset (this_cu, 0, sizeof (*this_cu));
8506         }
8507       else
8508         {
8509           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8510                                   struct signatured_type);
8511           memset (sig_type, 0, sizeof (*sig_type));
8512           sig_type->signature = cu_header.signature;
8513           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8514           this_cu = &sig_type->per_cu;
8515         }
8516       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8517       this_cu->sect_off = sect_off;
8518       this_cu->length = cu_header.length + cu_header.initial_length_size;
8519       this_cu->is_dwz = is_dwz;
8520       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8521       this_cu->section = section;
8522
8523       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8524
8525       info_ptr = info_ptr + this_cu->length;
8526     }
8527 }
8528
8529 /* Create a list of all compilation units in OBJFILE.
8530    This is only done for -readnow and building partial symtabs.  */
8531
8532 static void
8533 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8534 {
8535   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8536   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8537                                 &dwarf2_per_objfile->abbrev, 0);
8538
8539   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8540   if (dwz != NULL)
8541     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8542                                   1);
8543 }
8544
8545 /* Process all loaded DIEs for compilation unit CU, starting at
8546    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8547    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8548    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8549    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8550
8551 static void
8552 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8553                       CORE_ADDR *highpc, int set_addrmap,
8554                       struct dwarf2_cu *cu)
8555 {
8556   struct partial_die_info *pdi;
8557
8558   /* Now, march along the PDI's, descending into ones which have
8559      interesting children but skipping the children of the other ones,
8560      until we reach the end of the compilation unit.  */
8561
8562   pdi = first_die;
8563
8564   while (pdi != NULL)
8565     {
8566       pdi->fixup (cu);
8567
8568       /* Anonymous namespaces or modules have no name but have interesting
8569          children, so we need to look at them.  Ditto for anonymous
8570          enums.  */
8571
8572       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8573           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8574           || pdi->tag == DW_TAG_imported_unit
8575           || pdi->tag == DW_TAG_inlined_subroutine)
8576         {
8577           switch (pdi->tag)
8578             {
8579             case DW_TAG_subprogram:
8580             case DW_TAG_inlined_subroutine:
8581               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8582               break;
8583             case DW_TAG_constant:
8584             case DW_TAG_variable:
8585             case DW_TAG_typedef:
8586             case DW_TAG_union_type:
8587               if (!pdi->is_declaration)
8588                 {
8589                   add_partial_symbol (pdi, cu);
8590                 }
8591               break;
8592             case DW_TAG_class_type:
8593             case DW_TAG_interface_type:
8594             case DW_TAG_structure_type:
8595               if (!pdi->is_declaration)
8596                 {
8597                   add_partial_symbol (pdi, cu);
8598                 }
8599               if ((cu->language == language_rust
8600                    || cu->language == language_cplus) && pdi->has_children)
8601                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8602                                       set_addrmap, cu);
8603               break;
8604             case DW_TAG_enumeration_type:
8605               if (!pdi->is_declaration)
8606                 add_partial_enumeration (pdi, cu);
8607               break;
8608             case DW_TAG_base_type:
8609             case DW_TAG_subrange_type:
8610               /* File scope base type definitions are added to the partial
8611                  symbol table.  */
8612               add_partial_symbol (pdi, cu);
8613               break;
8614             case DW_TAG_namespace:
8615               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8616               break;
8617             case DW_TAG_module:
8618               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8619               break;
8620             case DW_TAG_imported_unit:
8621               {
8622                 struct dwarf2_per_cu_data *per_cu;
8623
8624                 /* For now we don't handle imported units in type units.  */
8625                 if (cu->per_cu->is_debug_types)
8626                   {
8627                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8628                              " supported in type units [in module %s]"),
8629                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8630                   }
8631
8632                 per_cu = dwarf2_find_containing_comp_unit
8633                            (pdi->d.sect_off, pdi->is_dwz,
8634                             cu->per_cu->dwarf2_per_objfile);
8635
8636                 /* Go read the partial unit, if needed.  */
8637                 if (per_cu->v.psymtab == NULL)
8638                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8639
8640                 VEC_safe_push (dwarf2_per_cu_ptr,
8641                                cu->per_cu->imported_symtabs, per_cu);
8642               }
8643               break;
8644             case DW_TAG_imported_declaration:
8645               add_partial_symbol (pdi, cu);
8646               break;
8647             default:
8648               break;
8649             }
8650         }
8651
8652       /* If the die has a sibling, skip to the sibling.  */
8653
8654       pdi = pdi->die_sibling;
8655     }
8656 }
8657
8658 /* Functions used to compute the fully scoped name of a partial DIE.
8659
8660    Normally, this is simple.  For C++, the parent DIE's fully scoped
8661    name is concatenated with "::" and the partial DIE's name.
8662    Enumerators are an exception; they use the scope of their parent
8663    enumeration type, i.e. the name of the enumeration type is not
8664    prepended to the enumerator.
8665
8666    There are two complexities.  One is DW_AT_specification; in this
8667    case "parent" means the parent of the target of the specification,
8668    instead of the direct parent of the DIE.  The other is compilers
8669    which do not emit DW_TAG_namespace; in this case we try to guess
8670    the fully qualified name of structure types from their members'
8671    linkage names.  This must be done using the DIE's children rather
8672    than the children of any DW_AT_specification target.  We only need
8673    to do this for structures at the top level, i.e. if the target of
8674    any DW_AT_specification (if any; otherwise the DIE itself) does not
8675    have a parent.  */
8676
8677 /* Compute the scope prefix associated with PDI's parent, in
8678    compilation unit CU.  The result will be allocated on CU's
8679    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8680    field.  NULL is returned if no prefix is necessary.  */
8681 static const char *
8682 partial_die_parent_scope (struct partial_die_info *pdi,
8683                           struct dwarf2_cu *cu)
8684 {
8685   const char *grandparent_scope;
8686   struct partial_die_info *parent, *real_pdi;
8687
8688   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8689      then this means the parent of the specification DIE.  */
8690
8691   real_pdi = pdi;
8692   while (real_pdi->has_specification)
8693     real_pdi = find_partial_die (real_pdi->spec_offset,
8694                                  real_pdi->spec_is_dwz, cu);
8695
8696   parent = real_pdi->die_parent;
8697   if (parent == NULL)
8698     return NULL;
8699
8700   if (parent->scope_set)
8701     return parent->scope;
8702
8703   parent->fixup (cu);
8704
8705   grandparent_scope = partial_die_parent_scope (parent, cu);
8706
8707   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8708      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8709      Work around this problem here.  */
8710   if (cu->language == language_cplus
8711       && parent->tag == DW_TAG_namespace
8712       && strcmp (parent->name, "::") == 0
8713       && grandparent_scope == NULL)
8714     {
8715       parent->scope = NULL;
8716       parent->scope_set = 1;
8717       return NULL;
8718     }
8719
8720   if (pdi->tag == DW_TAG_enumerator)
8721     /* Enumerators should not get the name of the enumeration as a prefix.  */
8722     parent->scope = grandparent_scope;
8723   else if (parent->tag == DW_TAG_namespace
8724       || parent->tag == DW_TAG_module
8725       || parent->tag == DW_TAG_structure_type
8726       || parent->tag == DW_TAG_class_type
8727       || parent->tag == DW_TAG_interface_type
8728       || parent->tag == DW_TAG_union_type
8729       || parent->tag == DW_TAG_enumeration_type)
8730     {
8731       if (grandparent_scope == NULL)
8732         parent->scope = parent->name;
8733       else
8734         parent->scope = typename_concat (&cu->comp_unit_obstack,
8735                                          grandparent_scope,
8736                                          parent->name, 0, cu);
8737     }
8738   else
8739     {
8740       /* FIXME drow/2004-04-01: What should we be doing with
8741          function-local names?  For partial symbols, we should probably be
8742          ignoring them.  */
8743       complaint (&symfile_complaints,
8744                  _("unhandled containing DIE tag %d for DIE at %s"),
8745                  parent->tag, sect_offset_str (pdi->sect_off));
8746       parent->scope = grandparent_scope;
8747     }
8748
8749   parent->scope_set = 1;
8750   return parent->scope;
8751 }
8752
8753 /* Return the fully scoped name associated with PDI, from compilation unit
8754    CU.  The result will be allocated with malloc.  */
8755
8756 static char *
8757 partial_die_full_name (struct partial_die_info *pdi,
8758                        struct dwarf2_cu *cu)
8759 {
8760   const char *parent_scope;
8761
8762   /* If this is a template instantiation, we can not work out the
8763      template arguments from partial DIEs.  So, unfortunately, we have
8764      to go through the full DIEs.  At least any work we do building
8765      types here will be reused if full symbols are loaded later.  */
8766   if (pdi->has_template_arguments)
8767     {
8768       pdi->fixup (cu);
8769
8770       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8771         {
8772           struct die_info *die;
8773           struct attribute attr;
8774           struct dwarf2_cu *ref_cu = cu;
8775
8776           /* DW_FORM_ref_addr is using section offset.  */
8777           attr.name = (enum dwarf_attribute) 0;
8778           attr.form = DW_FORM_ref_addr;
8779           attr.u.unsnd = to_underlying (pdi->sect_off);
8780           die = follow_die_ref (NULL, &attr, &ref_cu);
8781
8782           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8783         }
8784     }
8785
8786   parent_scope = partial_die_parent_scope (pdi, cu);
8787   if (parent_scope == NULL)
8788     return NULL;
8789   else
8790     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8791 }
8792
8793 static void
8794 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8795 {
8796   struct dwarf2_per_objfile *dwarf2_per_objfile
8797     = cu->per_cu->dwarf2_per_objfile;
8798   struct objfile *objfile = dwarf2_per_objfile->objfile;
8799   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8800   CORE_ADDR addr = 0;
8801   const char *actual_name = NULL;
8802   CORE_ADDR baseaddr;
8803   char *built_actual_name;
8804
8805   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8806
8807   built_actual_name = partial_die_full_name (pdi, cu);
8808   if (built_actual_name != NULL)
8809     actual_name = built_actual_name;
8810
8811   if (actual_name == NULL)
8812     actual_name = pdi->name;
8813
8814   switch (pdi->tag)
8815     {
8816     case DW_TAG_inlined_subroutine:
8817     case DW_TAG_subprogram:
8818       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8819       if (pdi->is_external || cu->language == language_ada)
8820         {
8821           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8822              of the global scope.  But in Ada, we want to be able to access
8823              nested procedures globally.  So all Ada subprograms are stored
8824              in the global scope.  */
8825           add_psymbol_to_list (actual_name, strlen (actual_name),
8826                                built_actual_name != NULL,
8827                                VAR_DOMAIN, LOC_BLOCK,
8828                                &objfile->global_psymbols,
8829                                addr, cu->language, objfile);
8830         }
8831       else
8832         {
8833           add_psymbol_to_list (actual_name, strlen (actual_name),
8834                                built_actual_name != NULL,
8835                                VAR_DOMAIN, LOC_BLOCK,
8836                                &objfile->static_psymbols,
8837                                addr, cu->language, objfile);
8838         }
8839
8840       if (pdi->main_subprogram && actual_name != NULL)
8841         set_objfile_main_name (objfile, actual_name, cu->language);
8842       break;
8843     case DW_TAG_constant:
8844       {
8845         std::vector<partial_symbol *> *list;
8846
8847         if (pdi->is_external)
8848           list = &objfile->global_psymbols;
8849         else
8850           list = &objfile->static_psymbols;
8851         add_psymbol_to_list (actual_name, strlen (actual_name),
8852                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8853                              list, 0, cu->language, objfile);
8854       }
8855       break;
8856     case DW_TAG_variable:
8857       if (pdi->d.locdesc)
8858         addr = decode_locdesc (pdi->d.locdesc, cu);
8859
8860       if (pdi->d.locdesc
8861           && addr == 0
8862           && !dwarf2_per_objfile->has_section_at_zero)
8863         {
8864           /* A global or static variable may also have been stripped
8865              out by the linker if unused, in which case its address
8866              will be nullified; do not add such variables into partial
8867              symbol table then.  */
8868         }
8869       else if (pdi->is_external)
8870         {
8871           /* Global Variable.
8872              Don't enter into the minimal symbol tables as there is
8873              a minimal symbol table entry from the ELF symbols already.
8874              Enter into partial symbol table if it has a location
8875              descriptor or a type.
8876              If the location descriptor is missing, new_symbol will create
8877              a LOC_UNRESOLVED symbol, the address of the variable will then
8878              be determined from the minimal symbol table whenever the variable
8879              is referenced.
8880              The address for the partial symbol table entry is not
8881              used by GDB, but it comes in handy for debugging partial symbol
8882              table building.  */
8883
8884           if (pdi->d.locdesc || pdi->has_type)
8885             add_psymbol_to_list (actual_name, strlen (actual_name),
8886                                  built_actual_name != NULL,
8887                                  VAR_DOMAIN, LOC_STATIC,
8888                                  &objfile->global_psymbols,
8889                                  addr + baseaddr,
8890                                  cu->language, objfile);
8891         }
8892       else
8893         {
8894           int has_loc = pdi->d.locdesc != NULL;
8895
8896           /* Static Variable.  Skip symbols whose value we cannot know (those
8897              without location descriptors or constant values).  */
8898           if (!has_loc && !pdi->has_const_value)
8899             {
8900               xfree (built_actual_name);
8901               return;
8902             }
8903
8904           add_psymbol_to_list (actual_name, strlen (actual_name),
8905                                built_actual_name != NULL,
8906                                VAR_DOMAIN, LOC_STATIC,
8907                                &objfile->static_psymbols,
8908                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8909                                cu->language, objfile);
8910         }
8911       break;
8912     case DW_TAG_typedef:
8913     case DW_TAG_base_type:
8914     case DW_TAG_subrange_type:
8915       add_psymbol_to_list (actual_name, strlen (actual_name),
8916                            built_actual_name != NULL,
8917                            VAR_DOMAIN, LOC_TYPEDEF,
8918                            &objfile->static_psymbols,
8919                            0, cu->language, objfile);
8920       break;
8921     case DW_TAG_imported_declaration:
8922     case DW_TAG_namespace:
8923       add_psymbol_to_list (actual_name, strlen (actual_name),
8924                            built_actual_name != NULL,
8925                            VAR_DOMAIN, LOC_TYPEDEF,
8926                            &objfile->global_psymbols,
8927                            0, cu->language, objfile);
8928       break;
8929     case DW_TAG_module:
8930       add_psymbol_to_list (actual_name, strlen (actual_name),
8931                            built_actual_name != NULL,
8932                            MODULE_DOMAIN, LOC_TYPEDEF,
8933                            &objfile->global_psymbols,
8934                            0, cu->language, objfile);
8935       break;
8936     case DW_TAG_class_type:
8937     case DW_TAG_interface_type:
8938     case DW_TAG_structure_type:
8939     case DW_TAG_union_type:
8940     case DW_TAG_enumeration_type:
8941       /* Skip external references.  The DWARF standard says in the section
8942          about "Structure, Union, and Class Type Entries": "An incomplete
8943          structure, union or class type is represented by a structure,
8944          union or class entry that does not have a byte size attribute
8945          and that has a DW_AT_declaration attribute."  */
8946       if (!pdi->has_byte_size && pdi->is_declaration)
8947         {
8948           xfree (built_actual_name);
8949           return;
8950         }
8951
8952       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8953          static vs. global.  */
8954       add_psymbol_to_list (actual_name, strlen (actual_name),
8955                            built_actual_name != NULL,
8956                            STRUCT_DOMAIN, LOC_TYPEDEF,
8957                            cu->language == language_cplus
8958                            ? &objfile->global_psymbols
8959                            : &objfile->static_psymbols,
8960                            0, cu->language, objfile);
8961
8962       break;
8963     case DW_TAG_enumerator:
8964       add_psymbol_to_list (actual_name, strlen (actual_name),
8965                            built_actual_name != NULL,
8966                            VAR_DOMAIN, LOC_CONST,
8967                            cu->language == language_cplus
8968                            ? &objfile->global_psymbols
8969                            : &objfile->static_psymbols,
8970                            0, cu->language, objfile);
8971       break;
8972     default:
8973       break;
8974     }
8975
8976   xfree (built_actual_name);
8977 }
8978
8979 /* Read a partial die corresponding to a namespace; also, add a symbol
8980    corresponding to that namespace to the symbol table.  NAMESPACE is
8981    the name of the enclosing namespace.  */
8982
8983 static void
8984 add_partial_namespace (struct partial_die_info *pdi,
8985                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8986                        int set_addrmap, struct dwarf2_cu *cu)
8987 {
8988   /* Add a symbol for the namespace.  */
8989
8990   add_partial_symbol (pdi, cu);
8991
8992   /* Now scan partial symbols in that namespace.  */
8993
8994   if (pdi->has_children)
8995     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8996 }
8997
8998 /* Read a partial die corresponding to a Fortran module.  */
8999
9000 static void
9001 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9002                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9003 {
9004   /* Add a symbol for the namespace.  */
9005
9006   add_partial_symbol (pdi, cu);
9007
9008   /* Now scan partial symbols in that module.  */
9009
9010   if (pdi->has_children)
9011     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9012 }
9013
9014 /* Read a partial die corresponding to a subprogram or an inlined
9015    subprogram and create a partial symbol for that subprogram.
9016    When the CU language allows it, this routine also defines a partial
9017    symbol for each nested subprogram that this subprogram contains.
9018    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9019    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9020
9021    PDI may also be a lexical block, in which case we simply search
9022    recursively for subprograms defined inside that lexical block.
9023    Again, this is only performed when the CU language allows this
9024    type of definitions.  */
9025
9026 static void
9027 add_partial_subprogram (struct partial_die_info *pdi,
9028                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9029                         int set_addrmap, struct dwarf2_cu *cu)
9030 {
9031   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9032     {
9033       if (pdi->has_pc_info)
9034         {
9035           if (pdi->lowpc < *lowpc)
9036             *lowpc = pdi->lowpc;
9037           if (pdi->highpc > *highpc)
9038             *highpc = pdi->highpc;
9039           if (set_addrmap)
9040             {
9041               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9042               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9043               CORE_ADDR baseaddr;
9044               CORE_ADDR highpc;
9045               CORE_ADDR lowpc;
9046
9047               baseaddr = ANOFFSET (objfile->section_offsets,
9048                                    SECT_OFF_TEXT (objfile));
9049               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9050                                                   pdi->lowpc + baseaddr);
9051               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9052                                                    pdi->highpc + baseaddr);
9053               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9054                                  cu->per_cu->v.psymtab);
9055             }
9056         }
9057
9058       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9059         {
9060           if (!pdi->is_declaration)
9061             /* Ignore subprogram DIEs that do not have a name, they are
9062                illegal.  Do not emit a complaint at this point, we will
9063                do so when we convert this psymtab into a symtab.  */
9064             if (pdi->name)
9065               add_partial_symbol (pdi, cu);
9066         }
9067     }
9068
9069   if (! pdi->has_children)
9070     return;
9071
9072   if (cu->language == language_ada)
9073     {
9074       pdi = pdi->die_child;
9075       while (pdi != NULL)
9076         {
9077           pdi->fixup (cu);
9078           if (pdi->tag == DW_TAG_subprogram
9079               || pdi->tag == DW_TAG_inlined_subroutine
9080               || pdi->tag == DW_TAG_lexical_block)
9081             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9082           pdi = pdi->die_sibling;
9083         }
9084     }
9085 }
9086
9087 /* Read a partial die corresponding to an enumeration type.  */
9088
9089 static void
9090 add_partial_enumeration (struct partial_die_info *enum_pdi,
9091                          struct dwarf2_cu *cu)
9092 {
9093   struct partial_die_info *pdi;
9094
9095   if (enum_pdi->name != NULL)
9096     add_partial_symbol (enum_pdi, cu);
9097
9098   pdi = enum_pdi->die_child;
9099   while (pdi)
9100     {
9101       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9102         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9103       else
9104         add_partial_symbol (pdi, cu);
9105       pdi = pdi->die_sibling;
9106     }
9107 }
9108
9109 /* Return the initial uleb128 in the die at INFO_PTR.  */
9110
9111 static unsigned int
9112 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9113 {
9114   unsigned int bytes_read;
9115
9116   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9117 }
9118
9119 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9120    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9121
9122    Return the corresponding abbrev, or NULL if the number is zero (indicating
9123    an empty DIE).  In either case *BYTES_READ will be set to the length of
9124    the initial number.  */
9125
9126 static struct abbrev_info *
9127 peek_die_abbrev (const die_reader_specs &reader,
9128                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9129 {
9130   dwarf2_cu *cu = reader.cu;
9131   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9132   unsigned int abbrev_number
9133     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9134
9135   if (abbrev_number == 0)
9136     return NULL;
9137
9138   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9139   if (!abbrev)
9140     {
9141       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9142                " at offset %s [in module %s]"),
9143              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9144              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9145     }
9146
9147   return abbrev;
9148 }
9149
9150 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9151    Returns a pointer to the end of a series of DIEs, terminated by an empty
9152    DIE.  Any children of the skipped DIEs will also be skipped.  */
9153
9154 static const gdb_byte *
9155 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9156 {
9157   while (1)
9158     {
9159       unsigned int bytes_read;
9160       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9161
9162       if (abbrev == NULL)
9163         return info_ptr + bytes_read;
9164       else
9165         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9166     }
9167 }
9168
9169 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9170    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9171    abbrev corresponding to that skipped uleb128 should be passed in
9172    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9173    children.  */
9174
9175 static const gdb_byte *
9176 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9177               struct abbrev_info *abbrev)
9178 {
9179   unsigned int bytes_read;
9180   struct attribute attr;
9181   bfd *abfd = reader->abfd;
9182   struct dwarf2_cu *cu = reader->cu;
9183   const gdb_byte *buffer = reader->buffer;
9184   const gdb_byte *buffer_end = reader->buffer_end;
9185   unsigned int form, i;
9186
9187   for (i = 0; i < abbrev->num_attrs; i++)
9188     {
9189       /* The only abbrev we care about is DW_AT_sibling.  */
9190       if (abbrev->attrs[i].name == DW_AT_sibling)
9191         {
9192           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9193           if (attr.form == DW_FORM_ref_addr)
9194             complaint (&symfile_complaints,
9195                        _("ignoring absolute DW_AT_sibling"));
9196           else
9197             {
9198               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9199               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9200
9201               if (sibling_ptr < info_ptr)
9202                 complaint (&symfile_complaints,
9203                            _("DW_AT_sibling points backwards"));
9204               else if (sibling_ptr > reader->buffer_end)
9205                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9206               else
9207                 return sibling_ptr;
9208             }
9209         }
9210
9211       /* If it isn't DW_AT_sibling, skip this attribute.  */
9212       form = abbrev->attrs[i].form;
9213     skip_attribute:
9214       switch (form)
9215         {
9216         case DW_FORM_ref_addr:
9217           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9218              and later it is offset sized.  */
9219           if (cu->header.version == 2)
9220             info_ptr += cu->header.addr_size;
9221           else
9222             info_ptr += cu->header.offset_size;
9223           break;
9224         case DW_FORM_GNU_ref_alt:
9225           info_ptr += cu->header.offset_size;
9226           break;
9227         case DW_FORM_addr:
9228           info_ptr += cu->header.addr_size;
9229           break;
9230         case DW_FORM_data1:
9231         case DW_FORM_ref1:
9232         case DW_FORM_flag:
9233           info_ptr += 1;
9234           break;
9235         case DW_FORM_flag_present:
9236         case DW_FORM_implicit_const:
9237           break;
9238         case DW_FORM_data2:
9239         case DW_FORM_ref2:
9240           info_ptr += 2;
9241           break;
9242         case DW_FORM_data4:
9243         case DW_FORM_ref4:
9244           info_ptr += 4;
9245           break;
9246         case DW_FORM_data8:
9247         case DW_FORM_ref8:
9248         case DW_FORM_ref_sig8:
9249           info_ptr += 8;
9250           break;
9251         case DW_FORM_data16:
9252           info_ptr += 16;
9253           break;
9254         case DW_FORM_string:
9255           read_direct_string (abfd, info_ptr, &bytes_read);
9256           info_ptr += bytes_read;
9257           break;
9258         case DW_FORM_sec_offset:
9259         case DW_FORM_strp:
9260         case DW_FORM_GNU_strp_alt:
9261           info_ptr += cu->header.offset_size;
9262           break;
9263         case DW_FORM_exprloc:
9264         case DW_FORM_block:
9265           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9266           info_ptr += bytes_read;
9267           break;
9268         case DW_FORM_block1:
9269           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9270           break;
9271         case DW_FORM_block2:
9272           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9273           break;
9274         case DW_FORM_block4:
9275           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9276           break;
9277         case DW_FORM_sdata:
9278         case DW_FORM_udata:
9279         case DW_FORM_ref_udata:
9280         case DW_FORM_GNU_addr_index:
9281         case DW_FORM_GNU_str_index:
9282           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9283           break;
9284         case DW_FORM_indirect:
9285           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9286           info_ptr += bytes_read;
9287           /* We need to continue parsing from here, so just go back to
9288              the top.  */
9289           goto skip_attribute;
9290
9291         default:
9292           error (_("Dwarf Error: Cannot handle %s "
9293                    "in DWARF reader [in module %s]"),
9294                  dwarf_form_name (form),
9295                  bfd_get_filename (abfd));
9296         }
9297     }
9298
9299   if (abbrev->has_children)
9300     return skip_children (reader, info_ptr);
9301   else
9302     return info_ptr;
9303 }
9304
9305 /* Locate ORIG_PDI's sibling.
9306    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9307
9308 static const gdb_byte *
9309 locate_pdi_sibling (const struct die_reader_specs *reader,
9310                     struct partial_die_info *orig_pdi,
9311                     const gdb_byte *info_ptr)
9312 {
9313   /* Do we know the sibling already?  */
9314
9315   if (orig_pdi->sibling)
9316     return orig_pdi->sibling;
9317
9318   /* Are there any children to deal with?  */
9319
9320   if (!orig_pdi->has_children)
9321     return info_ptr;
9322
9323   /* Skip the children the long way.  */
9324
9325   return skip_children (reader, info_ptr);
9326 }
9327
9328 /* Expand this partial symbol table into a full symbol table.  SELF is
9329    not NULL.  */
9330
9331 static void
9332 dwarf2_read_symtab (struct partial_symtab *self,
9333                     struct objfile *objfile)
9334 {
9335   struct dwarf2_per_objfile *dwarf2_per_objfile
9336     = get_dwarf2_per_objfile (objfile);
9337
9338   if (self->readin)
9339     {
9340       warning (_("bug: psymtab for %s is already read in."),
9341                self->filename);
9342     }
9343   else
9344     {
9345       if (info_verbose)
9346         {
9347           printf_filtered (_("Reading in symbols for %s..."),
9348                            self->filename);
9349           gdb_flush (gdb_stdout);
9350         }
9351
9352       /* If this psymtab is constructed from a debug-only objfile, the
9353          has_section_at_zero flag will not necessarily be correct.  We
9354          can get the correct value for this flag by looking at the data
9355          associated with the (presumably stripped) associated objfile.  */
9356       if (objfile->separate_debug_objfile_backlink)
9357         {
9358           struct dwarf2_per_objfile *dpo_backlink
9359             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9360
9361           dwarf2_per_objfile->has_section_at_zero
9362             = dpo_backlink->has_section_at_zero;
9363         }
9364
9365       dwarf2_per_objfile->reading_partial_symbols = 0;
9366
9367       psymtab_to_symtab_1 (self);
9368
9369       /* Finish up the debug error message.  */
9370       if (info_verbose)
9371         printf_filtered (_("done.\n"));
9372     }
9373
9374   process_cu_includes (dwarf2_per_objfile);
9375 }
9376 \f
9377 /* Reading in full CUs.  */
9378
9379 /* Add PER_CU to the queue.  */
9380
9381 static void
9382 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9383                  enum language pretend_language)
9384 {
9385   struct dwarf2_queue_item *item;
9386
9387   per_cu->queued = 1;
9388   item = XNEW (struct dwarf2_queue_item);
9389   item->per_cu = per_cu;
9390   item->pretend_language = pretend_language;
9391   item->next = NULL;
9392
9393   if (dwarf2_queue == NULL)
9394     dwarf2_queue = item;
9395   else
9396     dwarf2_queue_tail->next = item;
9397
9398   dwarf2_queue_tail = item;
9399 }
9400
9401 /* If PER_CU is not yet queued, add it to the queue.
9402    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9403    dependency.
9404    The result is non-zero if PER_CU was queued, otherwise the result is zero
9405    meaning either PER_CU is already queued or it is already loaded.
9406
9407    N.B. There is an invariant here that if a CU is queued then it is loaded.
9408    The caller is required to load PER_CU if we return non-zero.  */
9409
9410 static int
9411 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9412                        struct dwarf2_per_cu_data *per_cu,
9413                        enum language pretend_language)
9414 {
9415   /* We may arrive here during partial symbol reading, if we need full
9416      DIEs to process an unusual case (e.g. template arguments).  Do
9417      not queue PER_CU, just tell our caller to load its DIEs.  */
9418   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9419     {
9420       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9421         return 1;
9422       return 0;
9423     }
9424
9425   /* Mark the dependence relation so that we don't flush PER_CU
9426      too early.  */
9427   if (dependent_cu != NULL)
9428     dwarf2_add_dependence (dependent_cu, per_cu);
9429
9430   /* If it's already on the queue, we have nothing to do.  */
9431   if (per_cu->queued)
9432     return 0;
9433
9434   /* If the compilation unit is already loaded, just mark it as
9435      used.  */
9436   if (per_cu->cu != NULL)
9437     {
9438       per_cu->cu->last_used = 0;
9439       return 0;
9440     }
9441
9442   /* Add it to the queue.  */
9443   queue_comp_unit (per_cu, pretend_language);
9444
9445   return 1;
9446 }
9447
9448 /* Process the queue.  */
9449
9450 static void
9451 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9452 {
9453   struct dwarf2_queue_item *item, *next_item;
9454
9455   if (dwarf_read_debug)
9456     {
9457       fprintf_unfiltered (gdb_stdlog,
9458                           "Expanding one or more symtabs of objfile %s ...\n",
9459                           objfile_name (dwarf2_per_objfile->objfile));
9460     }
9461
9462   /* The queue starts out with one item, but following a DIE reference
9463      may load a new CU, adding it to the end of the queue.  */
9464   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9465     {
9466       if ((dwarf2_per_objfile->using_index
9467            ? !item->per_cu->v.quick->compunit_symtab
9468            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9469           /* Skip dummy CUs.  */
9470           && item->per_cu->cu != NULL)
9471         {
9472           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9473           unsigned int debug_print_threshold;
9474           char buf[100];
9475
9476           if (per_cu->is_debug_types)
9477             {
9478               struct signatured_type *sig_type =
9479                 (struct signatured_type *) per_cu;
9480
9481               sprintf (buf, "TU %s at offset %s",
9482                        hex_string (sig_type->signature),
9483                        sect_offset_str (per_cu->sect_off));
9484               /* There can be 100s of TUs.
9485                  Only print them in verbose mode.  */
9486               debug_print_threshold = 2;
9487             }
9488           else
9489             {
9490               sprintf (buf, "CU at offset %s",
9491                        sect_offset_str (per_cu->sect_off));
9492               debug_print_threshold = 1;
9493             }
9494
9495           if (dwarf_read_debug >= debug_print_threshold)
9496             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9497
9498           if (per_cu->is_debug_types)
9499             process_full_type_unit (per_cu, item->pretend_language);
9500           else
9501             process_full_comp_unit (per_cu, item->pretend_language);
9502
9503           if (dwarf_read_debug >= debug_print_threshold)
9504             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9505         }
9506
9507       item->per_cu->queued = 0;
9508       next_item = item->next;
9509       xfree (item);
9510     }
9511
9512   dwarf2_queue_tail = NULL;
9513
9514   if (dwarf_read_debug)
9515     {
9516       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9517                           objfile_name (dwarf2_per_objfile->objfile));
9518     }
9519 }
9520
9521 /* Read in full symbols for PST, and anything it depends on.  */
9522
9523 static void
9524 psymtab_to_symtab_1 (struct partial_symtab *pst)
9525 {
9526   struct dwarf2_per_cu_data *per_cu;
9527   int i;
9528
9529   if (pst->readin)
9530     return;
9531
9532   for (i = 0; i < pst->number_of_dependencies; i++)
9533     if (!pst->dependencies[i]->readin
9534         && pst->dependencies[i]->user == NULL)
9535       {
9536         /* Inform about additional files that need to be read in.  */
9537         if (info_verbose)
9538           {
9539             /* FIXME: i18n: Need to make this a single string.  */
9540             fputs_filtered (" ", gdb_stdout);
9541             wrap_here ("");
9542             fputs_filtered ("and ", gdb_stdout);
9543             wrap_here ("");
9544             printf_filtered ("%s...", pst->dependencies[i]->filename);
9545             wrap_here ("");     /* Flush output.  */
9546             gdb_flush (gdb_stdout);
9547           }
9548         psymtab_to_symtab_1 (pst->dependencies[i]);
9549       }
9550
9551   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9552
9553   if (per_cu == NULL)
9554     {
9555       /* It's an include file, no symbols to read for it.
9556          Everything is in the parent symtab.  */
9557       pst->readin = 1;
9558       return;
9559     }
9560
9561   dw2_do_instantiate_symtab (per_cu);
9562 }
9563
9564 /* Trivial hash function for die_info: the hash value of a DIE
9565    is its offset in .debug_info for this objfile.  */
9566
9567 static hashval_t
9568 die_hash (const void *item)
9569 {
9570   const struct die_info *die = (const struct die_info *) item;
9571
9572   return to_underlying (die->sect_off);
9573 }
9574
9575 /* Trivial comparison function for die_info structures: two DIEs
9576    are equal if they have the same offset.  */
9577
9578 static int
9579 die_eq (const void *item_lhs, const void *item_rhs)
9580 {
9581   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9582   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9583
9584   return die_lhs->sect_off == die_rhs->sect_off;
9585 }
9586
9587 /* die_reader_func for load_full_comp_unit.
9588    This is identical to read_signatured_type_reader,
9589    but is kept separate for now.  */
9590
9591 static void
9592 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9593                             const gdb_byte *info_ptr,
9594                             struct die_info *comp_unit_die,
9595                             int has_children,
9596                             void *data)
9597 {
9598   struct dwarf2_cu *cu = reader->cu;
9599   enum language *language_ptr = (enum language *) data;
9600
9601   gdb_assert (cu->die_hash == NULL);
9602   cu->die_hash =
9603     htab_create_alloc_ex (cu->header.length / 12,
9604                           die_hash,
9605                           die_eq,
9606                           NULL,
9607                           &cu->comp_unit_obstack,
9608                           hashtab_obstack_allocate,
9609                           dummy_obstack_deallocate);
9610
9611   if (has_children)
9612     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9613                                                   &info_ptr, comp_unit_die);
9614   cu->dies = comp_unit_die;
9615   /* comp_unit_die is not stored in die_hash, no need.  */
9616
9617   /* We try not to read any attributes in this function, because not
9618      all CUs needed for references have been loaded yet, and symbol
9619      table processing isn't initialized.  But we have to set the CU language,
9620      or we won't be able to build types correctly.
9621      Similarly, if we do not read the producer, we can not apply
9622      producer-specific interpretation.  */
9623   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9624 }
9625
9626 /* Load the DIEs associated with PER_CU into memory.  */
9627
9628 static void
9629 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9630                      enum language pretend_language)
9631 {
9632   gdb_assert (! this_cu->is_debug_types);
9633
9634   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
9635                            load_full_comp_unit_reader, &pretend_language);
9636 }
9637
9638 /* Add a DIE to the delayed physname list.  */
9639
9640 static void
9641 add_to_method_list (struct type *type, int fnfield_index, int index,
9642                     const char *name, struct die_info *die,
9643                     struct dwarf2_cu *cu)
9644 {
9645   struct delayed_method_info mi;
9646   mi.type = type;
9647   mi.fnfield_index = fnfield_index;
9648   mi.index = index;
9649   mi.name = name;
9650   mi.die = die;
9651   cu->method_list.push_back (mi);
9652 }
9653
9654 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9655    "const" / "volatile".  If so, decrements LEN by the length of the
9656    modifier and return true.  Otherwise return false.  */
9657
9658 template<size_t N>
9659 static bool
9660 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9661 {
9662   size_t mod_len = sizeof (mod) - 1;
9663   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9664     {
9665       len -= mod_len;
9666       return true;
9667     }
9668   return false;
9669 }
9670
9671 /* Compute the physnames of any methods on the CU's method list.
9672
9673    The computation of method physnames is delayed in order to avoid the
9674    (bad) condition that one of the method's formal parameters is of an as yet
9675    incomplete type.  */
9676
9677 static void
9678 compute_delayed_physnames (struct dwarf2_cu *cu)
9679 {
9680   /* Only C++ delays computing physnames.  */
9681   if (cu->method_list.empty ())
9682     return;
9683   gdb_assert (cu->language == language_cplus);
9684
9685   for (struct delayed_method_info &mi : cu->method_list)
9686     {
9687       const char *physname;
9688       struct fn_fieldlist *fn_flp
9689         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9690       physname = dwarf2_physname (mi.name, mi.die, cu);
9691       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9692         = physname ? physname : "";
9693
9694       /* Since there's no tag to indicate whether a method is a
9695          const/volatile overload, extract that information out of the
9696          demangled name.  */
9697       if (physname != NULL)
9698         {
9699           size_t len = strlen (physname);
9700
9701           while (1)
9702             {
9703               if (physname[len] == ')') /* shortcut */
9704                 break;
9705               else if (check_modifier (physname, len, " const"))
9706                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9707               else if (check_modifier (physname, len, " volatile"))
9708                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9709               else
9710                 break;
9711             }
9712         }
9713     }
9714
9715   /* The list is no longer needed.  */
9716   cu->method_list.clear ();
9717 }
9718
9719 /* Go objects should be embedded in a DW_TAG_module DIE,
9720    and it's not clear if/how imported objects will appear.
9721    To keep Go support simple until that's worked out,
9722    go back through what we've read and create something usable.
9723    We could do this while processing each DIE, and feels kinda cleaner,
9724    but that way is more invasive.
9725    This is to, for example, allow the user to type "p var" or "b main"
9726    without having to specify the package name, and allow lookups
9727    of module.object to work in contexts that use the expression
9728    parser.  */
9729
9730 static void
9731 fixup_go_packaging (struct dwarf2_cu *cu)
9732 {
9733   char *package_name = NULL;
9734   struct pending *list;
9735   int i;
9736
9737   for (list = global_symbols; list != NULL; list = list->next)
9738     {
9739       for (i = 0; i < list->nsyms; ++i)
9740         {
9741           struct symbol *sym = list->symbol[i];
9742
9743           if (SYMBOL_LANGUAGE (sym) == language_go
9744               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9745             {
9746               char *this_package_name = go_symbol_package_name (sym);
9747
9748               if (this_package_name == NULL)
9749                 continue;
9750               if (package_name == NULL)
9751                 package_name = this_package_name;
9752               else
9753                 {
9754                   struct objfile *objfile
9755                     = cu->per_cu->dwarf2_per_objfile->objfile;
9756                   if (strcmp (package_name, this_package_name) != 0)
9757                     complaint (&symfile_complaints,
9758                                _("Symtab %s has objects from two different Go packages: %s and %s"),
9759                                (symbol_symtab (sym) != NULL
9760                                 ? symtab_to_filename_for_display
9761                                     (symbol_symtab (sym))
9762                                 : objfile_name (objfile)),
9763                                this_package_name, package_name);
9764                   xfree (this_package_name);
9765                 }
9766             }
9767         }
9768     }
9769
9770   if (package_name != NULL)
9771     {
9772       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9773       const char *saved_package_name
9774         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9775                                         package_name,
9776                                         strlen (package_name));
9777       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9778                                      saved_package_name);
9779       struct symbol *sym;
9780
9781       TYPE_TAG_NAME (type) = TYPE_NAME (type);
9782
9783       sym = allocate_symbol (objfile);
9784       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9785       SYMBOL_SET_NAMES (sym, saved_package_name,
9786                         strlen (saved_package_name), 0, objfile);
9787       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9788          e.g., "main" finds the "main" module and not C's main().  */
9789       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9790       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9791       SYMBOL_TYPE (sym) = type;
9792
9793       add_symbol_to_list (sym, &global_symbols);
9794
9795       xfree (package_name);
9796     }
9797 }
9798
9799 /* Allocate a fully-qualified name consisting of the two parts on the
9800    obstack.  */
9801
9802 static const char *
9803 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9804 {
9805   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9806 }
9807
9808 /* A helper that allocates a struct discriminant_info to attach to a
9809    union type.  */
9810
9811 static struct discriminant_info *
9812 alloc_discriminant_info (struct type *type, int discriminant_index,
9813                          int default_index)
9814 {
9815   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9816   gdb_assert (discriminant_index == -1
9817               || (discriminant_index >= 0
9818                   && discriminant_index < TYPE_NFIELDS (type)));
9819   gdb_assert (default_index == -1
9820               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9821
9822   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9823
9824   struct discriminant_info *disc
9825     = ((struct discriminant_info *)
9826        TYPE_ZALLOC (type,
9827                     offsetof (struct discriminant_info, discriminants)
9828                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9829   disc->default_index = default_index;
9830   disc->discriminant_index = discriminant_index;
9831
9832   struct dynamic_prop prop;
9833   prop.kind = PROP_UNDEFINED;
9834   prop.data.baton = disc;
9835
9836   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9837
9838   return disc;
9839 }
9840
9841 /* Some versions of rustc emitted enums in an unusual way.
9842
9843    Ordinary enums were emitted as unions.  The first element of each
9844    structure in the union was named "RUST$ENUM$DISR".  This element
9845    held the discriminant.
9846
9847    These versions of Rust also implemented the "non-zero"
9848    optimization.  When the enum had two values, and one is empty and
9849    the other holds a pointer that cannot be zero, the pointer is used
9850    as the discriminant, with a zero value meaning the empty variant.
9851    Here, the union's first member is of the form
9852    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9853    where the fieldnos are the indices of the fields that should be
9854    traversed in order to find the field (which may be several fields deep)
9855    and the variantname is the name of the variant of the case when the
9856    field is zero.
9857
9858    This function recognizes whether TYPE is of one of these forms,
9859    and, if so, smashes it to be a variant type.  */
9860
9861 static void
9862 quirk_rust_enum (struct type *type, struct objfile *objfile)
9863 {
9864   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9865
9866   /* We don't need to deal with empty enums.  */
9867   if (TYPE_NFIELDS (type) == 0)
9868     return;
9869
9870 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9871   if (TYPE_NFIELDS (type) == 1
9872       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9873     {
9874       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9875
9876       /* Decode the field name to find the offset of the
9877          discriminant.  */
9878       ULONGEST bit_offset = 0;
9879       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9880       while (name[0] >= '0' && name[0] <= '9')
9881         {
9882           char *tail;
9883           unsigned long index = strtoul (name, &tail, 10);
9884           name = tail;
9885           if (*name != '$'
9886               || index >= TYPE_NFIELDS (field_type)
9887               || (TYPE_FIELD_LOC_KIND (field_type, index)
9888                   != FIELD_LOC_KIND_BITPOS))
9889             {
9890               complaint (&symfile_complaints,
9891                          _("Could not parse Rust enum encoding string \"%s\""
9892                            "[in module %s]"),
9893                          TYPE_FIELD_NAME (type, 0),
9894                          objfile_name (objfile));
9895               return;
9896             }
9897           ++name;
9898
9899           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9900           field_type = TYPE_FIELD_TYPE (field_type, index);
9901         }
9902
9903       /* Make a union to hold the variants.  */
9904       struct type *union_type = alloc_type (objfile);
9905       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9906       TYPE_NFIELDS (union_type) = 3;
9907       TYPE_FIELDS (union_type)
9908         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9909       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9910       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9911
9912       /* Put the discriminant must at index 0.  */
9913       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9914       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9915       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9916       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9917
9918       /* The order of fields doesn't really matter, so put the real
9919          field at index 1 and the data-less field at index 2.  */
9920       struct discriminant_info *disc
9921         = alloc_discriminant_info (union_type, 0, 1);
9922       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9923       TYPE_FIELD_NAME (union_type, 1)
9924         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9925       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9926         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9927                               TYPE_FIELD_NAME (union_type, 1));
9928
9929       const char *dataless_name
9930         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9931                               name);
9932       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9933                                               dataless_name);
9934       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9935       /* NAME points into the original discriminant name, which
9936          already has the correct lifetime.  */
9937       TYPE_FIELD_NAME (union_type, 2) = name;
9938       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9939       disc->discriminants[2] = 0;
9940
9941       /* Smash this type to be a structure type.  We have to do this
9942          because the type has already been recorded.  */
9943       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9944       TYPE_NFIELDS (type) = 1;
9945       TYPE_FIELDS (type)
9946         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9947
9948       /* Install the variant part.  */
9949       TYPE_FIELD_TYPE (type, 0) = union_type;
9950       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9951       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9952     }
9953   else if (TYPE_NFIELDS (type) == 1)
9954     {
9955       /* We assume that a union with a single field is a univariant
9956          enum.  */
9957       /* Smash this type to be a structure type.  We have to do this
9958          because the type has already been recorded.  */
9959       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9960
9961       /* Make a union to hold the variants.  */
9962       struct type *union_type = alloc_type (objfile);
9963       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9964       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9965       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9966       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9967       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9968
9969       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9970       const char *variant_name
9971         = rust_last_path_segment (TYPE_NAME (field_type));
9972       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9973       TYPE_NAME (field_type)
9974         = rust_fully_qualify (&objfile->objfile_obstack,
9975                               TYPE_NAME (type), variant_name);
9976
9977       /* Install the union in the outer struct type.  */
9978       TYPE_NFIELDS (type) = 1;
9979       TYPE_FIELDS (type)
9980         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9981       TYPE_FIELD_TYPE (type, 0) = union_type;
9982       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9983       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9984
9985       alloc_discriminant_info (union_type, -1, 0);
9986     }
9987   else
9988     {
9989       struct type *disr_type = nullptr;
9990       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9991         {
9992           disr_type = TYPE_FIELD_TYPE (type, i);
9993
9994           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9995             {
9996               /* All fields of a true enum will be structs.  */
9997               return;
9998             }
9999           else if (TYPE_NFIELDS (disr_type) == 0)
10000             {
10001               /* Could be data-less variant, so keep going.  */
10002               disr_type = nullptr;
10003             }
10004           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10005                            "RUST$ENUM$DISR") != 0)
10006             {
10007               /* Not a Rust enum.  */
10008               return;
10009             }
10010           else
10011             {
10012               /* Found one.  */
10013               break;
10014             }
10015         }
10016
10017       /* If we got here without a discriminant, then it's probably
10018          just a union.  */
10019       if (disr_type == nullptr)
10020         return;
10021
10022       /* Smash this type to be a structure type.  We have to do this
10023          because the type has already been recorded.  */
10024       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10025
10026       /* Make a union to hold the variants.  */
10027       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10028       struct type *union_type = alloc_type (objfile);
10029       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10030       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10031       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10032       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10033       TYPE_FIELDS (union_type)
10034         = (struct field *) TYPE_ZALLOC (union_type,
10035                                         (TYPE_NFIELDS (union_type)
10036                                          * sizeof (struct field)));
10037
10038       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10039               TYPE_NFIELDS (type) * sizeof (struct field));
10040
10041       /* Install the discriminant at index 0 in the union.  */
10042       TYPE_FIELD (union_type, 0) = *disr_field;
10043       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10044       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10045
10046       /* Install the union in the outer struct type.  */
10047       TYPE_FIELD_TYPE (type, 0) = union_type;
10048       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10049       TYPE_NFIELDS (type) = 1;
10050
10051       /* Set the size and offset of the union type.  */
10052       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10053
10054       /* We need a way to find the correct discriminant given a
10055          variant name.  For convenience we build a map here.  */
10056       struct type *enum_type = FIELD_TYPE (*disr_field);
10057       std::unordered_map<std::string, ULONGEST> discriminant_map;
10058       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10059         {
10060           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10061             {
10062               const char *name
10063                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10064               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10065             }
10066         }
10067
10068       int n_fields = TYPE_NFIELDS (union_type);
10069       struct discriminant_info *disc
10070         = alloc_discriminant_info (union_type, 0, -1);
10071       /* Skip the discriminant here.  */
10072       for (int i = 1; i < n_fields; ++i)
10073         {
10074           /* Find the final word in the name of this variant's type.
10075              That name can be used to look up the correct
10076              discriminant.  */
10077           const char *variant_name
10078             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10079                                                                   i)));
10080
10081           auto iter = discriminant_map.find (variant_name);
10082           if (iter != discriminant_map.end ())
10083             disc->discriminants[i] = iter->second;
10084
10085           /* Remove the discriminant field, if it exists.  */
10086           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10087           if (TYPE_NFIELDS (sub_type) > 0)
10088             {
10089               --TYPE_NFIELDS (sub_type);
10090               ++TYPE_FIELDS (sub_type);
10091             }
10092           TYPE_FIELD_NAME (union_type, i) = variant_name;
10093           TYPE_NAME (sub_type)
10094             = rust_fully_qualify (&objfile->objfile_obstack,
10095                                   TYPE_NAME (type), variant_name);
10096         }
10097     }
10098 }
10099
10100 /* Rewrite some Rust unions to be structures with variants parts.  */
10101
10102 static void
10103 rust_union_quirks (struct dwarf2_cu *cu)
10104 {
10105   gdb_assert (cu->language == language_rust);
10106   for (struct type *type : cu->rust_unions)
10107     quirk_rust_enum (type, cu->per_cu->dwarf2_per_objfile->objfile);
10108 }
10109
10110 /* Return the symtab for PER_CU.  This works properly regardless of
10111    whether we're using the index or psymtabs.  */
10112
10113 static struct compunit_symtab *
10114 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10115 {
10116   return (per_cu->dwarf2_per_objfile->using_index
10117           ? per_cu->v.quick->compunit_symtab
10118           : per_cu->v.psymtab->compunit_symtab);
10119 }
10120
10121 /* A helper function for computing the list of all symbol tables
10122    included by PER_CU.  */
10123
10124 static void
10125 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10126                                 htab_t all_children, htab_t all_type_symtabs,
10127                                 struct dwarf2_per_cu_data *per_cu,
10128                                 struct compunit_symtab *immediate_parent)
10129 {
10130   void **slot;
10131   int ix;
10132   struct compunit_symtab *cust;
10133   struct dwarf2_per_cu_data *iter;
10134
10135   slot = htab_find_slot (all_children, per_cu, INSERT);
10136   if (*slot != NULL)
10137     {
10138       /* This inclusion and its children have been processed.  */
10139       return;
10140     }
10141
10142   *slot = per_cu;
10143   /* Only add a CU if it has a symbol table.  */
10144   cust = get_compunit_symtab (per_cu);
10145   if (cust != NULL)
10146     {
10147       /* If this is a type unit only add its symbol table if we haven't
10148          seen it yet (type unit per_cu's can share symtabs).  */
10149       if (per_cu->is_debug_types)
10150         {
10151           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10152           if (*slot == NULL)
10153             {
10154               *slot = cust;
10155               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10156               if (cust->user == NULL)
10157                 cust->user = immediate_parent;
10158             }
10159         }
10160       else
10161         {
10162           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10163           if (cust->user == NULL)
10164             cust->user = immediate_parent;
10165         }
10166     }
10167
10168   for (ix = 0;
10169        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10170        ++ix)
10171     {
10172       recursively_compute_inclusions (result, all_children,
10173                                       all_type_symtabs, iter, cust);
10174     }
10175 }
10176
10177 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10178    PER_CU.  */
10179
10180 static void
10181 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10182 {
10183   gdb_assert (! per_cu->is_debug_types);
10184
10185   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10186     {
10187       int ix, len;
10188       struct dwarf2_per_cu_data *per_cu_iter;
10189       struct compunit_symtab *compunit_symtab_iter;
10190       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10191       htab_t all_children, all_type_symtabs;
10192       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10193
10194       /* If we don't have a symtab, we can just skip this case.  */
10195       if (cust == NULL)
10196         return;
10197
10198       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10199                                         NULL, xcalloc, xfree);
10200       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10201                                             NULL, xcalloc, xfree);
10202
10203       for (ix = 0;
10204            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10205                         ix, per_cu_iter);
10206            ++ix)
10207         {
10208           recursively_compute_inclusions (&result_symtabs, all_children,
10209                                           all_type_symtabs, per_cu_iter,
10210                                           cust);
10211         }
10212
10213       /* Now we have a transitive closure of all the included symtabs.  */
10214       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10215       cust->includes
10216         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10217                      struct compunit_symtab *, len + 1);
10218       for (ix = 0;
10219            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10220                         compunit_symtab_iter);
10221            ++ix)
10222         cust->includes[ix] = compunit_symtab_iter;
10223       cust->includes[len] = NULL;
10224
10225       VEC_free (compunit_symtab_ptr, result_symtabs);
10226       htab_delete (all_children);
10227       htab_delete (all_type_symtabs);
10228     }
10229 }
10230
10231 /* Compute the 'includes' field for the symtabs of all the CUs we just
10232    read.  */
10233
10234 static void
10235 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10236 {
10237   int ix;
10238   struct dwarf2_per_cu_data *iter;
10239
10240   for (ix = 0;
10241        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10242                     ix, iter);
10243        ++ix)
10244     {
10245       if (! iter->is_debug_types)
10246         compute_compunit_symtab_includes (iter);
10247     }
10248
10249   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10250 }
10251
10252 /* Generate full symbol information for PER_CU, whose DIEs have
10253    already been loaded into memory.  */
10254
10255 static void
10256 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10257                         enum language pretend_language)
10258 {
10259   struct dwarf2_cu *cu = per_cu->cu;
10260   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10261   struct objfile *objfile = dwarf2_per_objfile->objfile;
10262   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10263   CORE_ADDR lowpc, highpc;
10264   struct compunit_symtab *cust;
10265   CORE_ADDR baseaddr;
10266   struct block *static_block;
10267   CORE_ADDR addr;
10268
10269   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10270
10271   buildsym_init ();
10272   scoped_free_pendings free_pending;
10273
10274   /* Clear the list here in case something was left over.  */
10275   cu->method_list.clear ();
10276
10277   cu->list_in_scope = &file_symbols;
10278
10279   cu->language = pretend_language;
10280   cu->language_defn = language_def (cu->language);
10281
10282   /* Do line number decoding in read_file_scope () */
10283   process_die (cu->dies, cu);
10284
10285   /* For now fudge the Go package.  */
10286   if (cu->language == language_go)
10287     fixup_go_packaging (cu);
10288
10289   /* Now that we have processed all the DIEs in the CU, all the types 
10290      should be complete, and it should now be safe to compute all of the
10291      physnames.  */
10292   compute_delayed_physnames (cu);
10293
10294   if (cu->language == language_rust)
10295     rust_union_quirks (cu);
10296
10297   /* Some compilers don't define a DW_AT_high_pc attribute for the
10298      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10299      it, by scanning the DIE's below the compilation unit.  */
10300   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10301
10302   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10303   static_block = end_symtab_get_static_block (addr, 0, 1);
10304
10305   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10306      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10307      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10308      addrmap to help ensure it has an accurate map of pc values belonging to
10309      this comp unit.  */
10310   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10311
10312   cust = end_symtab_from_static_block (static_block,
10313                                        SECT_OFF_TEXT (objfile), 0);
10314
10315   if (cust != NULL)
10316     {
10317       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10318
10319       /* Set symtab language to language from DW_AT_language.  If the
10320          compilation is from a C file generated by language preprocessors, do
10321          not set the language if it was already deduced by start_subfile.  */
10322       if (!(cu->language == language_c
10323             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10324         COMPUNIT_FILETABS (cust)->language = cu->language;
10325
10326       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10327          produce DW_AT_location with location lists but it can be possibly
10328          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10329          there were bugs in prologue debug info, fixed later in GCC-4.5
10330          by "unwind info for epilogues" patch (which is not directly related).
10331
10332          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10333          needed, it would be wrong due to missing DW_AT_producer there.
10334
10335          Still one can confuse GDB by using non-standard GCC compilation
10336          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10337          */ 
10338       if (cu->has_loclist && gcc_4_minor >= 5)
10339         cust->locations_valid = 1;
10340
10341       if (gcc_4_minor >= 5)
10342         cust->epilogue_unwind_valid = 1;
10343
10344       cust->call_site_htab = cu->call_site_htab;
10345     }
10346
10347   if (dwarf2_per_objfile->using_index)
10348     per_cu->v.quick->compunit_symtab = cust;
10349   else
10350     {
10351       struct partial_symtab *pst = per_cu->v.psymtab;
10352       pst->compunit_symtab = cust;
10353       pst->readin = 1;
10354     }
10355
10356   /* Push it for inclusion processing later.  */
10357   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10358 }
10359
10360 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10361    already been loaded into memory.  */
10362
10363 static void
10364 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10365                         enum language pretend_language)
10366 {
10367   struct dwarf2_cu *cu = per_cu->cu;
10368   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10369   struct objfile *objfile = dwarf2_per_objfile->objfile;
10370   struct compunit_symtab *cust;
10371   struct signatured_type *sig_type;
10372
10373   gdb_assert (per_cu->is_debug_types);
10374   sig_type = (struct signatured_type *) per_cu;
10375
10376   buildsym_init ();
10377   scoped_free_pendings free_pending;
10378
10379   /* Clear the list here in case something was left over.  */
10380   cu->method_list.clear ();
10381
10382   cu->list_in_scope = &file_symbols;
10383
10384   cu->language = pretend_language;
10385   cu->language_defn = language_def (cu->language);
10386
10387   /* The symbol tables are set up in read_type_unit_scope.  */
10388   process_die (cu->dies, cu);
10389
10390   /* For now fudge the Go package.  */
10391   if (cu->language == language_go)
10392     fixup_go_packaging (cu);
10393
10394   /* Now that we have processed all the DIEs in the CU, all the types 
10395      should be complete, and it should now be safe to compute all of the
10396      physnames.  */
10397   compute_delayed_physnames (cu);
10398
10399   if (cu->language == language_rust)
10400     rust_union_quirks (cu);
10401
10402   /* TUs share symbol tables.
10403      If this is the first TU to use this symtab, complete the construction
10404      of it with end_expandable_symtab.  Otherwise, complete the addition of
10405      this TU's symbols to the existing symtab.  */
10406   if (sig_type->type_unit_group->compunit_symtab == NULL)
10407     {
10408       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10409       sig_type->type_unit_group->compunit_symtab = cust;
10410
10411       if (cust != NULL)
10412         {
10413           /* Set symtab language to language from DW_AT_language.  If the
10414              compilation is from a C file generated by language preprocessors,
10415              do not set the language if it was already deduced by
10416              start_subfile.  */
10417           if (!(cu->language == language_c
10418                 && COMPUNIT_FILETABS (cust)->language != language_c))
10419             COMPUNIT_FILETABS (cust)->language = cu->language;
10420         }
10421     }
10422   else
10423     {
10424       augment_type_symtab ();
10425       cust = sig_type->type_unit_group->compunit_symtab;
10426     }
10427
10428   if (dwarf2_per_objfile->using_index)
10429     per_cu->v.quick->compunit_symtab = cust;
10430   else
10431     {
10432       struct partial_symtab *pst = per_cu->v.psymtab;
10433       pst->compunit_symtab = cust;
10434       pst->readin = 1;
10435     }
10436 }
10437
10438 /* Process an imported unit DIE.  */
10439
10440 static void
10441 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10442 {
10443   struct attribute *attr;
10444
10445   /* For now we don't handle imported units in type units.  */
10446   if (cu->per_cu->is_debug_types)
10447     {
10448       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10449                " supported in type units [in module %s]"),
10450              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10451     }
10452
10453   attr = dwarf2_attr (die, DW_AT_import, cu);
10454   if (attr != NULL)
10455     {
10456       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10457       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10458       dwarf2_per_cu_data *per_cu
10459         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10460                                             cu->per_cu->dwarf2_per_objfile);
10461
10462       /* If necessary, add it to the queue and load its DIEs.  */
10463       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10464         load_full_comp_unit (per_cu, cu->language);
10465
10466       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10467                      per_cu);
10468     }
10469 }
10470
10471 /* RAII object that represents a process_die scope: i.e.,
10472    starts/finishes processing a DIE.  */
10473 class process_die_scope
10474 {
10475 public:
10476   process_die_scope (die_info *die, dwarf2_cu *cu)
10477     : m_die (die), m_cu (cu)
10478   {
10479     /* We should only be processing DIEs not already in process.  */
10480     gdb_assert (!m_die->in_process);
10481     m_die->in_process = true;
10482   }
10483
10484   ~process_die_scope ()
10485   {
10486     m_die->in_process = false;
10487
10488     /* If we're done processing the DIE for the CU that owns the line
10489        header, we don't need the line header anymore.  */
10490     if (m_cu->line_header_die_owner == m_die)
10491       {
10492         delete m_cu->line_header;
10493         m_cu->line_header = NULL;
10494         m_cu->line_header_die_owner = NULL;
10495       }
10496   }
10497
10498 private:
10499   die_info *m_die;
10500   dwarf2_cu *m_cu;
10501 };
10502
10503 /* Process a die and its children.  */
10504
10505 static void
10506 process_die (struct die_info *die, struct dwarf2_cu *cu)
10507 {
10508   process_die_scope scope (die, cu);
10509
10510   switch (die->tag)
10511     {
10512     case DW_TAG_padding:
10513       break;
10514     case DW_TAG_compile_unit:
10515     case DW_TAG_partial_unit:
10516       read_file_scope (die, cu);
10517       break;
10518     case DW_TAG_type_unit:
10519       read_type_unit_scope (die, cu);
10520       break;
10521     case DW_TAG_subprogram:
10522     case DW_TAG_inlined_subroutine:
10523       read_func_scope (die, cu);
10524       break;
10525     case DW_TAG_lexical_block:
10526     case DW_TAG_try_block:
10527     case DW_TAG_catch_block:
10528       read_lexical_block_scope (die, cu);
10529       break;
10530     case DW_TAG_call_site:
10531     case DW_TAG_GNU_call_site:
10532       read_call_site_scope (die, cu);
10533       break;
10534     case DW_TAG_class_type:
10535     case DW_TAG_interface_type:
10536     case DW_TAG_structure_type:
10537     case DW_TAG_union_type:
10538       process_structure_scope (die, cu);
10539       break;
10540     case DW_TAG_enumeration_type:
10541       process_enumeration_scope (die, cu);
10542       break;
10543
10544     /* These dies have a type, but processing them does not create
10545        a symbol or recurse to process the children.  Therefore we can
10546        read them on-demand through read_type_die.  */
10547     case DW_TAG_subroutine_type:
10548     case DW_TAG_set_type:
10549     case DW_TAG_array_type:
10550     case DW_TAG_pointer_type:
10551     case DW_TAG_ptr_to_member_type:
10552     case DW_TAG_reference_type:
10553     case DW_TAG_rvalue_reference_type:
10554     case DW_TAG_string_type:
10555       break;
10556
10557     case DW_TAG_base_type:
10558     case DW_TAG_subrange_type:
10559     case DW_TAG_typedef:
10560       /* Add a typedef symbol for the type definition, if it has a
10561          DW_AT_name.  */
10562       new_symbol (die, read_type_die (die, cu), cu);
10563       break;
10564     case DW_TAG_common_block:
10565       read_common_block (die, cu);
10566       break;
10567     case DW_TAG_common_inclusion:
10568       break;
10569     case DW_TAG_namespace:
10570       cu->processing_has_namespace_info = 1;
10571       read_namespace (die, cu);
10572       break;
10573     case DW_TAG_module:
10574       cu->processing_has_namespace_info = 1;
10575       read_module (die, cu);
10576       break;
10577     case DW_TAG_imported_declaration:
10578       cu->processing_has_namespace_info = 1;
10579       if (read_namespace_alias (die, cu))
10580         break;
10581       /* The declaration is not a global namespace alias.  */
10582       /* Fall through.  */
10583     case DW_TAG_imported_module:
10584       cu->processing_has_namespace_info = 1;
10585       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10586                                  || cu->language != language_fortran))
10587         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10588                    dwarf_tag_name (die->tag));
10589       read_import_statement (die, cu);
10590       break;
10591
10592     case DW_TAG_imported_unit:
10593       process_imported_unit_die (die, cu);
10594       break;
10595
10596     case DW_TAG_variable:
10597       read_variable (die, cu);
10598       break;
10599
10600     default:
10601       new_symbol (die, NULL, cu);
10602       break;
10603     }
10604 }
10605 \f
10606 /* DWARF name computation.  */
10607
10608 /* A helper function for dwarf2_compute_name which determines whether DIE
10609    needs to have the name of the scope prepended to the name listed in the
10610    die.  */
10611
10612 static int
10613 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10614 {
10615   struct attribute *attr;
10616
10617   switch (die->tag)
10618     {
10619     case DW_TAG_namespace:
10620     case DW_TAG_typedef:
10621     case DW_TAG_class_type:
10622     case DW_TAG_interface_type:
10623     case DW_TAG_structure_type:
10624     case DW_TAG_union_type:
10625     case DW_TAG_enumeration_type:
10626     case DW_TAG_enumerator:
10627     case DW_TAG_subprogram:
10628     case DW_TAG_inlined_subroutine:
10629     case DW_TAG_member:
10630     case DW_TAG_imported_declaration:
10631       return 1;
10632
10633     case DW_TAG_variable:
10634     case DW_TAG_constant:
10635       /* We only need to prefix "globally" visible variables.  These include
10636          any variable marked with DW_AT_external or any variable that
10637          lives in a namespace.  [Variables in anonymous namespaces
10638          require prefixing, but they are not DW_AT_external.]  */
10639
10640       if (dwarf2_attr (die, DW_AT_specification, cu))
10641         {
10642           struct dwarf2_cu *spec_cu = cu;
10643
10644           return die_needs_namespace (die_specification (die, &spec_cu),
10645                                       spec_cu);
10646         }
10647
10648       attr = dwarf2_attr (die, DW_AT_external, cu);
10649       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10650           && die->parent->tag != DW_TAG_module)
10651         return 0;
10652       /* A variable in a lexical block of some kind does not need a
10653          namespace, even though in C++ such variables may be external
10654          and have a mangled name.  */
10655       if (die->parent->tag ==  DW_TAG_lexical_block
10656           || die->parent->tag ==  DW_TAG_try_block
10657           || die->parent->tag ==  DW_TAG_catch_block
10658           || die->parent->tag == DW_TAG_subprogram)
10659         return 0;
10660       return 1;
10661
10662     default:
10663       return 0;
10664     }
10665 }
10666
10667 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10668    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10669    defined for the given DIE.  */
10670
10671 static struct attribute *
10672 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10673 {
10674   struct attribute *attr;
10675
10676   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10677   if (attr == NULL)
10678     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10679
10680   return attr;
10681 }
10682
10683 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10684    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10685    defined for the given DIE.  */
10686
10687 static const char *
10688 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10689 {
10690   const char *linkage_name;
10691
10692   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10693   if (linkage_name == NULL)
10694     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10695
10696   return linkage_name;
10697 }
10698
10699 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10700    compute the physname for the object, which include a method's:
10701    - formal parameters (C++),
10702    - receiver type (Go),
10703
10704    The term "physname" is a bit confusing.
10705    For C++, for example, it is the demangled name.
10706    For Go, for example, it's the mangled name.
10707
10708    For Ada, return the DIE's linkage name rather than the fully qualified
10709    name.  PHYSNAME is ignored..
10710
10711    The result is allocated on the objfile_obstack and canonicalized.  */
10712
10713 static const char *
10714 dwarf2_compute_name (const char *name,
10715                      struct die_info *die, struct dwarf2_cu *cu,
10716                      int physname)
10717 {
10718   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10719
10720   if (name == NULL)
10721     name = dwarf2_name (die, cu);
10722
10723   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10724      but otherwise compute it by typename_concat inside GDB.
10725      FIXME: Actually this is not really true, or at least not always true.
10726      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10727      Fortran names because there is no mangling standard.  So new_symbol
10728      will set the demangled name to the result of dwarf2_full_name, and it is
10729      the demangled name that GDB uses if it exists.  */
10730   if (cu->language == language_ada
10731       || (cu->language == language_fortran && physname))
10732     {
10733       /* For Ada unit, we prefer the linkage name over the name, as
10734          the former contains the exported name, which the user expects
10735          to be able to reference.  Ideally, we want the user to be able
10736          to reference this entity using either natural or linkage name,
10737          but we haven't started looking at this enhancement yet.  */
10738       const char *linkage_name = dw2_linkage_name (die, cu);
10739
10740       if (linkage_name != NULL)
10741         return linkage_name;
10742     }
10743
10744   /* These are the only languages we know how to qualify names in.  */
10745   if (name != NULL
10746       && (cu->language == language_cplus
10747           || cu->language == language_fortran || cu->language == language_d
10748           || cu->language == language_rust))
10749     {
10750       if (die_needs_namespace (die, cu))
10751         {
10752           const char *prefix;
10753           const char *canonical_name = NULL;
10754
10755           string_file buf;
10756
10757           prefix = determine_prefix (die, cu);
10758           if (*prefix != '\0')
10759             {
10760               char *prefixed_name = typename_concat (NULL, prefix, name,
10761                                                      physname, cu);
10762
10763               buf.puts (prefixed_name);
10764               xfree (prefixed_name);
10765             }
10766           else
10767             buf.puts (name);
10768
10769           /* Template parameters may be specified in the DIE's DW_AT_name, or
10770              as children with DW_TAG_template_type_param or
10771              DW_TAG_value_type_param.  If the latter, add them to the name
10772              here.  If the name already has template parameters, then
10773              skip this step; some versions of GCC emit both, and
10774              it is more efficient to use the pre-computed name.
10775
10776              Something to keep in mind about this process: it is very
10777              unlikely, or in some cases downright impossible, to produce
10778              something that will match the mangled name of a function.
10779              If the definition of the function has the same debug info,
10780              we should be able to match up with it anyway.  But fallbacks
10781              using the minimal symbol, for instance to find a method
10782              implemented in a stripped copy of libstdc++, will not work.
10783              If we do not have debug info for the definition, we will have to
10784              match them up some other way.
10785
10786              When we do name matching there is a related problem with function
10787              templates; two instantiated function templates are allowed to
10788              differ only by their return types, which we do not add here.  */
10789
10790           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10791             {
10792               struct attribute *attr;
10793               struct die_info *child;
10794               int first = 1;
10795
10796               die->building_fullname = 1;
10797
10798               for (child = die->child; child != NULL; child = child->sibling)
10799                 {
10800                   struct type *type;
10801                   LONGEST value;
10802                   const gdb_byte *bytes;
10803                   struct dwarf2_locexpr_baton *baton;
10804                   struct value *v;
10805
10806                   if (child->tag != DW_TAG_template_type_param
10807                       && child->tag != DW_TAG_template_value_param)
10808                     continue;
10809
10810                   if (first)
10811                     {
10812                       buf.puts ("<");
10813                       first = 0;
10814                     }
10815                   else
10816                     buf.puts (", ");
10817
10818                   attr = dwarf2_attr (child, DW_AT_type, cu);
10819                   if (attr == NULL)
10820                     {
10821                       complaint (&symfile_complaints,
10822                                  _("template parameter missing DW_AT_type"));
10823                       buf.puts ("UNKNOWN_TYPE");
10824                       continue;
10825                     }
10826                   type = die_type (child, cu);
10827
10828                   if (child->tag == DW_TAG_template_type_param)
10829                     {
10830                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10831                       continue;
10832                     }
10833
10834                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10835                   if (attr == NULL)
10836                     {
10837                       complaint (&symfile_complaints,
10838                                  _("template parameter missing "
10839                                    "DW_AT_const_value"));
10840                       buf.puts ("UNKNOWN_VALUE");
10841                       continue;
10842                     }
10843
10844                   dwarf2_const_value_attr (attr, type, name,
10845                                            &cu->comp_unit_obstack, cu,
10846                                            &value, &bytes, &baton);
10847
10848                   if (TYPE_NOSIGN (type))
10849                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10850                        changed, this can use value_print instead.  */
10851                     c_printchar (value, type, &buf);
10852                   else
10853                     {
10854                       struct value_print_options opts;
10855
10856                       if (baton != NULL)
10857                         v = dwarf2_evaluate_loc_desc (type, NULL,
10858                                                       baton->data,
10859                                                       baton->size,
10860                                                       baton->per_cu);
10861                       else if (bytes != NULL)
10862                         {
10863                           v = allocate_value (type);
10864                           memcpy (value_contents_writeable (v), bytes,
10865                                   TYPE_LENGTH (type));
10866                         }
10867                       else
10868                         v = value_from_longest (type, value);
10869
10870                       /* Specify decimal so that we do not depend on
10871                          the radix.  */
10872                       get_formatted_print_options (&opts, 'd');
10873                       opts.raw = 1;
10874                       value_print (v, &buf, &opts);
10875                       release_value (v);
10876                     }
10877                 }
10878
10879               die->building_fullname = 0;
10880
10881               if (!first)
10882                 {
10883                   /* Close the argument list, with a space if necessary
10884                      (nested templates).  */
10885                   if (!buf.empty () && buf.string ().back () == '>')
10886                     buf.puts (" >");
10887                   else
10888                     buf.puts (">");
10889                 }
10890             }
10891
10892           /* For C++ methods, append formal parameter type
10893              information, if PHYSNAME.  */
10894
10895           if (physname && die->tag == DW_TAG_subprogram
10896               && cu->language == language_cplus)
10897             {
10898               struct type *type = read_type_die (die, cu);
10899
10900               c_type_print_args (type, &buf, 1, cu->language,
10901                                  &type_print_raw_options);
10902
10903               if (cu->language == language_cplus)
10904                 {
10905                   /* Assume that an artificial first parameter is
10906                      "this", but do not crash if it is not.  RealView
10907                      marks unnamed (and thus unused) parameters as
10908                      artificial; there is no way to differentiate
10909                      the two cases.  */
10910                   if (TYPE_NFIELDS (type) > 0
10911                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10912                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10913                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10914                                                                         0))))
10915                     buf.puts (" const");
10916                 }
10917             }
10918
10919           const std::string &intermediate_name = buf.string ();
10920
10921           if (cu->language == language_cplus)
10922             canonical_name
10923               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10924                                           &objfile->per_bfd->storage_obstack);
10925
10926           /* If we only computed INTERMEDIATE_NAME, or if
10927              INTERMEDIATE_NAME is already canonical, then we need to
10928              copy it to the appropriate obstack.  */
10929           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10930             name = ((const char *)
10931                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10932                                    intermediate_name.c_str (),
10933                                    intermediate_name.length ()));
10934           else
10935             name = canonical_name;
10936         }
10937     }
10938
10939   return name;
10940 }
10941
10942 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10943    If scope qualifiers are appropriate they will be added.  The result
10944    will be allocated on the storage_obstack, or NULL if the DIE does
10945    not have a name.  NAME may either be from a previous call to
10946    dwarf2_name or NULL.
10947
10948    The output string will be canonicalized (if C++).  */
10949
10950 static const char *
10951 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10952 {
10953   return dwarf2_compute_name (name, die, cu, 0);
10954 }
10955
10956 /* Construct a physname for the given DIE in CU.  NAME may either be
10957    from a previous call to dwarf2_name or NULL.  The result will be
10958    allocated on the objfile_objstack or NULL if the DIE does not have a
10959    name.
10960
10961    The output string will be canonicalized (if C++).  */
10962
10963 static const char *
10964 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10965 {
10966   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10967   const char *retval, *mangled = NULL, *canon = NULL;
10968   int need_copy = 1;
10969
10970   /* In this case dwarf2_compute_name is just a shortcut not building anything
10971      on its own.  */
10972   if (!die_needs_namespace (die, cu))
10973     return dwarf2_compute_name (name, die, cu, 1);
10974
10975   mangled = dw2_linkage_name (die, cu);
10976
10977   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10978      See https://github.com/rust-lang/rust/issues/32925.  */
10979   if (cu->language == language_rust && mangled != NULL
10980       && strchr (mangled, '{') != NULL)
10981     mangled = NULL;
10982
10983   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10984      has computed.  */
10985   gdb::unique_xmalloc_ptr<char> demangled;
10986   if (mangled != NULL)
10987     {
10988
10989       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10990         {
10991           /* Do nothing (do not demangle the symbol name).  */
10992         }
10993       else if (cu->language == language_go)
10994         {
10995           /* This is a lie, but we already lie to the caller new_symbol.
10996              new_symbol assumes we return the mangled name.
10997              This just undoes that lie until things are cleaned up.  */
10998         }
10999       else
11000         {
11001           /* Use DMGL_RET_DROP for C++ template functions to suppress
11002              their return type.  It is easier for GDB users to search
11003              for such functions as `name(params)' than `long name(params)'.
11004              In such case the minimal symbol names do not match the full
11005              symbol names but for template functions there is never a need
11006              to look up their definition from their declaration so
11007              the only disadvantage remains the minimal symbol variant
11008              `long name(params)' does not have the proper inferior type.  */
11009           demangled.reset (gdb_demangle (mangled,
11010                                          (DMGL_PARAMS | DMGL_ANSI
11011                                           | DMGL_RET_DROP)));
11012         }
11013       if (demangled)
11014         canon = demangled.get ();
11015       else
11016         {
11017           canon = mangled;
11018           need_copy = 0;
11019         }
11020     }
11021
11022   if (canon == NULL || check_physname)
11023     {
11024       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11025
11026       if (canon != NULL && strcmp (physname, canon) != 0)
11027         {
11028           /* It may not mean a bug in GDB.  The compiler could also
11029              compute DW_AT_linkage_name incorrectly.  But in such case
11030              GDB would need to be bug-to-bug compatible.  */
11031
11032           complaint (&symfile_complaints,
11033                      _("Computed physname <%s> does not match demangled <%s> "
11034                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11035                      physname, canon, mangled, sect_offset_str (die->sect_off),
11036                      objfile_name (objfile));
11037
11038           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11039              is available here - over computed PHYSNAME.  It is safer
11040              against both buggy GDB and buggy compilers.  */
11041
11042           retval = canon;
11043         }
11044       else
11045         {
11046           retval = physname;
11047           need_copy = 0;
11048         }
11049     }
11050   else
11051     retval = canon;
11052
11053   if (need_copy)
11054     retval = ((const char *)
11055               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11056                              retval, strlen (retval)));
11057
11058   return retval;
11059 }
11060
11061 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11062    a new symbol for it.
11063
11064    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11065
11066 static int
11067 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11068 {
11069   struct attribute *attr;
11070
11071   /* If the die does not have a name, this is not a namespace
11072      alias.  */
11073   attr = dwarf2_attr (die, DW_AT_name, cu);
11074   if (attr != NULL)
11075     {
11076       int num;
11077       struct die_info *d = die;
11078       struct dwarf2_cu *imported_cu = cu;
11079
11080       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11081          keep inspecting DIEs until we hit the underlying import.  */
11082 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11083       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11084         {
11085           attr = dwarf2_attr (d, DW_AT_import, cu);
11086           if (attr == NULL)
11087             break;
11088
11089           d = follow_die_ref (d, attr, &imported_cu);
11090           if (d->tag != DW_TAG_imported_declaration)
11091             break;
11092         }
11093
11094       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11095         {
11096           complaint (&symfile_complaints,
11097                      _("DIE at %s has too many recursively imported "
11098                        "declarations"), sect_offset_str (d->sect_off));
11099           return 0;
11100         }
11101
11102       if (attr != NULL)
11103         {
11104           struct type *type;
11105           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11106
11107           type = get_die_type_at_offset (sect_off, cu->per_cu);
11108           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11109             {
11110               /* This declaration is a global namespace alias.  Add
11111                  a symbol for it whose type is the aliased namespace.  */
11112               new_symbol (die, type, cu);
11113               return 1;
11114             }
11115         }
11116     }
11117
11118   return 0;
11119 }
11120
11121 /* Return the using directives repository (global or local?) to use in the
11122    current context for LANGUAGE.
11123
11124    For Ada, imported declarations can materialize renamings, which *may* be
11125    global.  However it is impossible (for now?) in DWARF to distinguish
11126    "external" imported declarations and "static" ones.  As all imported
11127    declarations seem to be static in all other languages, make them all CU-wide
11128    global only in Ada.  */
11129
11130 static struct using_direct **
11131 using_directives (enum language language)
11132 {
11133   if (language == language_ada && context_stack_depth == 0)
11134     return &global_using_directives;
11135   else
11136     return &local_using_directives;
11137 }
11138
11139 /* Read the import statement specified by the given die and record it.  */
11140
11141 static void
11142 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11143 {
11144   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11145   struct attribute *import_attr;
11146   struct die_info *imported_die, *child_die;
11147   struct dwarf2_cu *imported_cu;
11148   const char *imported_name;
11149   const char *imported_name_prefix;
11150   const char *canonical_name;
11151   const char *import_alias;
11152   const char *imported_declaration = NULL;
11153   const char *import_prefix;
11154   std::vector<const char *> excludes;
11155
11156   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11157   if (import_attr == NULL)
11158     {
11159       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11160                  dwarf_tag_name (die->tag));
11161       return;
11162     }
11163
11164   imported_cu = cu;
11165   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11166   imported_name = dwarf2_name (imported_die, imported_cu);
11167   if (imported_name == NULL)
11168     {
11169       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11170
11171         The import in the following code:
11172         namespace A
11173           {
11174             typedef int B;
11175           }
11176
11177         int main ()
11178           {
11179             using A::B;
11180             B b;
11181             return b;
11182           }
11183
11184         ...
11185          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11186             <52>   DW_AT_decl_file   : 1
11187             <53>   DW_AT_decl_line   : 6
11188             <54>   DW_AT_import      : <0x75>
11189          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11190             <59>   DW_AT_name        : B
11191             <5b>   DW_AT_decl_file   : 1
11192             <5c>   DW_AT_decl_line   : 2
11193             <5d>   DW_AT_type        : <0x6e>
11194         ...
11195          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11196             <76>   DW_AT_byte_size   : 4
11197             <77>   DW_AT_encoding    : 5        (signed)
11198
11199         imports the wrong die ( 0x75 instead of 0x58 ).
11200         This case will be ignored until the gcc bug is fixed.  */
11201       return;
11202     }
11203
11204   /* Figure out the local name after import.  */
11205   import_alias = dwarf2_name (die, cu);
11206
11207   /* Figure out where the statement is being imported to.  */
11208   import_prefix = determine_prefix (die, cu);
11209
11210   /* Figure out what the scope of the imported die is and prepend it
11211      to the name of the imported die.  */
11212   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11213
11214   if (imported_die->tag != DW_TAG_namespace
11215       && imported_die->tag != DW_TAG_module)
11216     {
11217       imported_declaration = imported_name;
11218       canonical_name = imported_name_prefix;
11219     }
11220   else if (strlen (imported_name_prefix) > 0)
11221     canonical_name = obconcat (&objfile->objfile_obstack,
11222                                imported_name_prefix,
11223                                (cu->language == language_d ? "." : "::"),
11224                                imported_name, (char *) NULL);
11225   else
11226     canonical_name = imported_name;
11227
11228   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11229     for (child_die = die->child; child_die && child_die->tag;
11230          child_die = sibling_die (child_die))
11231       {
11232         /* DWARF-4: A Fortran use statement with a “rename list” may be
11233            represented by an imported module entry with an import attribute
11234            referring to the module and owned entries corresponding to those
11235            entities that are renamed as part of being imported.  */
11236
11237         if (child_die->tag != DW_TAG_imported_declaration)
11238           {
11239             complaint (&symfile_complaints,
11240                        _("child DW_TAG_imported_declaration expected "
11241                          "- DIE at %s [in module %s]"),
11242                        sect_offset_str (child_die->sect_off),
11243                        objfile_name (objfile));
11244             continue;
11245           }
11246
11247         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11248         if (import_attr == NULL)
11249           {
11250             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11251                        dwarf_tag_name (child_die->tag));
11252             continue;
11253           }
11254
11255         imported_cu = cu;
11256         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11257                                               &imported_cu);
11258         imported_name = dwarf2_name (imported_die, imported_cu);
11259         if (imported_name == NULL)
11260           {
11261             complaint (&symfile_complaints,
11262                        _("child DW_TAG_imported_declaration has unknown "
11263                          "imported name - DIE at %s [in module %s]"),
11264                        sect_offset_str (child_die->sect_off),
11265                        objfile_name (objfile));
11266             continue;
11267           }
11268
11269         excludes.push_back (imported_name);
11270
11271         process_die (child_die, cu);
11272       }
11273
11274   add_using_directive (using_directives (cu->language),
11275                        import_prefix,
11276                        canonical_name,
11277                        import_alias,
11278                        imported_declaration,
11279                        excludes,
11280                        0,
11281                        &objfile->objfile_obstack);
11282 }
11283
11284 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11285    types, but gives them a size of zero.  Starting with version 14,
11286    ICC is compatible with GCC.  */
11287
11288 static int
11289 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11290 {
11291   if (!cu->checked_producer)
11292     check_producer (cu);
11293
11294   return cu->producer_is_icc_lt_14;
11295 }
11296
11297 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11298    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11299    this, it was first present in GCC release 4.3.0.  */
11300
11301 static int
11302 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11303 {
11304   if (!cu->checked_producer)
11305     check_producer (cu);
11306
11307   return cu->producer_is_gcc_lt_4_3;
11308 }
11309
11310 static file_and_directory
11311 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11312 {
11313   file_and_directory res;
11314
11315   /* Find the filename.  Do not use dwarf2_name here, since the filename
11316      is not a source language identifier.  */
11317   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11318   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11319
11320   if (res.comp_dir == NULL
11321       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11322       && IS_ABSOLUTE_PATH (res.name))
11323     {
11324       res.comp_dir_storage = ldirname (res.name);
11325       if (!res.comp_dir_storage.empty ())
11326         res.comp_dir = res.comp_dir_storage.c_str ();
11327     }
11328   if (res.comp_dir != NULL)
11329     {
11330       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11331          directory, get rid of it.  */
11332       const char *cp = strchr (res.comp_dir, ':');
11333
11334       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11335         res.comp_dir = cp + 1;
11336     }
11337
11338   if (res.name == NULL)
11339     res.name = "<unknown>";
11340
11341   return res;
11342 }
11343
11344 /* Handle DW_AT_stmt_list for a compilation unit.
11345    DIE is the DW_TAG_compile_unit die for CU.
11346    COMP_DIR is the compilation directory.  LOWPC is passed to
11347    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11348
11349 static void
11350 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11351                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11352 {
11353   struct dwarf2_per_objfile *dwarf2_per_objfile
11354     = cu->per_cu->dwarf2_per_objfile;
11355   struct objfile *objfile = dwarf2_per_objfile->objfile;
11356   struct attribute *attr;
11357   struct line_header line_header_local;
11358   hashval_t line_header_local_hash;
11359   void **slot;
11360   int decode_mapping;
11361
11362   gdb_assert (! cu->per_cu->is_debug_types);
11363
11364   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11365   if (attr == NULL)
11366     return;
11367
11368   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11369
11370   /* The line header hash table is only created if needed (it exists to
11371      prevent redundant reading of the line table for partial_units).
11372      If we're given a partial_unit, we'll need it.  If we're given a
11373      compile_unit, then use the line header hash table if it's already
11374      created, but don't create one just yet.  */
11375
11376   if (dwarf2_per_objfile->line_header_hash == NULL
11377       && die->tag == DW_TAG_partial_unit)
11378     {
11379       dwarf2_per_objfile->line_header_hash
11380         = htab_create_alloc_ex (127, line_header_hash_voidp,
11381                                 line_header_eq_voidp,
11382                                 free_line_header_voidp,
11383                                 &objfile->objfile_obstack,
11384                                 hashtab_obstack_allocate,
11385                                 dummy_obstack_deallocate);
11386     }
11387
11388   line_header_local.sect_off = line_offset;
11389   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11390   line_header_local_hash = line_header_hash (&line_header_local);
11391   if (dwarf2_per_objfile->line_header_hash != NULL)
11392     {
11393       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11394                                        &line_header_local,
11395                                        line_header_local_hash, NO_INSERT);
11396
11397       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11398          is not present in *SLOT (since if there is something in *SLOT then
11399          it will be for a partial_unit).  */
11400       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11401         {
11402           gdb_assert (*slot != NULL);
11403           cu->line_header = (struct line_header *) *slot;
11404           return;
11405         }
11406     }
11407
11408   /* dwarf_decode_line_header does not yet provide sufficient information.
11409      We always have to call also dwarf_decode_lines for it.  */
11410   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11411   if (lh == NULL)
11412     return;
11413
11414   cu->line_header = lh.release ();
11415   cu->line_header_die_owner = die;
11416
11417   if (dwarf2_per_objfile->line_header_hash == NULL)
11418     slot = NULL;
11419   else
11420     {
11421       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11422                                        &line_header_local,
11423                                        line_header_local_hash, INSERT);
11424       gdb_assert (slot != NULL);
11425     }
11426   if (slot != NULL && *slot == NULL)
11427     {
11428       /* This newly decoded line number information unit will be owned
11429          by line_header_hash hash table.  */
11430       *slot = cu->line_header;
11431       cu->line_header_die_owner = NULL;
11432     }
11433   else
11434     {
11435       /* We cannot free any current entry in (*slot) as that struct line_header
11436          may be already used by multiple CUs.  Create only temporary decoded
11437          line_header for this CU - it may happen at most once for each line
11438          number information unit.  And if we're not using line_header_hash
11439          then this is what we want as well.  */
11440       gdb_assert (die->tag != DW_TAG_partial_unit);
11441     }
11442   decode_mapping = (die->tag != DW_TAG_partial_unit);
11443   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11444                       decode_mapping);
11445
11446 }
11447
11448 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11449
11450 static void
11451 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11452 {
11453   struct dwarf2_per_objfile *dwarf2_per_objfile
11454     = cu->per_cu->dwarf2_per_objfile;
11455   struct objfile *objfile = dwarf2_per_objfile->objfile;
11456   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11457   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11458   CORE_ADDR highpc = ((CORE_ADDR) 0);
11459   struct attribute *attr;
11460   struct die_info *child_die;
11461   CORE_ADDR baseaddr;
11462
11463   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11464
11465   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11466
11467   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11468      from finish_block.  */
11469   if (lowpc == ((CORE_ADDR) -1))
11470     lowpc = highpc;
11471   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11472
11473   file_and_directory fnd = find_file_and_directory (die, cu);
11474
11475   prepare_one_comp_unit (cu, die, cu->language);
11476
11477   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11478      standardised yet.  As a workaround for the language detection we fall
11479      back to the DW_AT_producer string.  */
11480   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11481     cu->language = language_opencl;
11482
11483   /* Similar hack for Go.  */
11484   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11485     set_cu_language (DW_LANG_Go, cu);
11486
11487   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11488
11489   /* Decode line number information if present.  We do this before
11490      processing child DIEs, so that the line header table is available
11491      for DW_AT_decl_file.  */
11492   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11493
11494   /* Process all dies in compilation unit.  */
11495   if (die->child != NULL)
11496     {
11497       child_die = die->child;
11498       while (child_die && child_die->tag)
11499         {
11500           process_die (child_die, cu);
11501           child_die = sibling_die (child_die);
11502         }
11503     }
11504
11505   /* Decode macro information, if present.  Dwarf 2 macro information
11506      refers to information in the line number info statement program
11507      header, so we can only read it if we've read the header
11508      successfully.  */
11509   attr = dwarf2_attr (die, DW_AT_macros, cu);
11510   if (attr == NULL)
11511     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11512   if (attr && cu->line_header)
11513     {
11514       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11515         complaint (&symfile_complaints,
11516                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11517
11518       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11519     }
11520   else
11521     {
11522       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11523       if (attr && cu->line_header)
11524         {
11525           unsigned int macro_offset = DW_UNSND (attr);
11526
11527           dwarf_decode_macros (cu, macro_offset, 0);
11528         }
11529     }
11530 }
11531
11532 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11533    Create the set of symtabs used by this TU, or if this TU is sharing
11534    symtabs with another TU and the symtabs have already been created
11535    then restore those symtabs in the line header.
11536    We don't need the pc/line-number mapping for type units.  */
11537
11538 static void
11539 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11540 {
11541   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11542   struct type_unit_group *tu_group;
11543   int first_time;
11544   struct attribute *attr;
11545   unsigned int i;
11546   struct signatured_type *sig_type;
11547
11548   gdb_assert (per_cu->is_debug_types);
11549   sig_type = (struct signatured_type *) per_cu;
11550
11551   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11552
11553   /* If we're using .gdb_index (includes -readnow) then
11554      per_cu->type_unit_group may not have been set up yet.  */
11555   if (sig_type->type_unit_group == NULL)
11556     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11557   tu_group = sig_type->type_unit_group;
11558
11559   /* If we've already processed this stmt_list there's no real need to
11560      do it again, we could fake it and just recreate the part we need
11561      (file name,index -> symtab mapping).  If data shows this optimization
11562      is useful we can do it then.  */
11563   first_time = tu_group->compunit_symtab == NULL;
11564
11565   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11566      debug info.  */
11567   line_header_up lh;
11568   if (attr != NULL)
11569     {
11570       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11571       lh = dwarf_decode_line_header (line_offset, cu);
11572     }
11573   if (lh == NULL)
11574     {
11575       if (first_time)
11576         dwarf2_start_symtab (cu, "", NULL, 0);
11577       else
11578         {
11579           gdb_assert (tu_group->symtabs == NULL);
11580           restart_symtab (tu_group->compunit_symtab, "", 0);
11581         }
11582       return;
11583     }
11584
11585   cu->line_header = lh.release ();
11586   cu->line_header_die_owner = die;
11587
11588   if (first_time)
11589     {
11590       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11591
11592       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11593          still initializing it, and our caller (a few levels up)
11594          process_full_type_unit still needs to know if this is the first
11595          time.  */
11596
11597       tu_group->num_symtabs = cu->line_header->file_names.size ();
11598       tu_group->symtabs = XNEWVEC (struct symtab *,
11599                                    cu->line_header->file_names.size ());
11600
11601       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11602         {
11603           file_entry &fe = cu->line_header->file_names[i];
11604
11605           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11606
11607           if (current_subfile->symtab == NULL)
11608             {
11609               /* NOTE: start_subfile will recognize when it's been
11610                  passed a file it has already seen.  So we can't
11611                  assume there's a simple mapping from
11612                  cu->line_header->file_names to subfiles, plus
11613                  cu->line_header->file_names may contain dups.  */
11614               current_subfile->symtab
11615                 = allocate_symtab (cust, current_subfile->name);
11616             }
11617
11618           fe.symtab = current_subfile->symtab;
11619           tu_group->symtabs[i] = fe.symtab;
11620         }
11621     }
11622   else
11623     {
11624       restart_symtab (tu_group->compunit_symtab, "", 0);
11625
11626       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11627         {
11628           file_entry &fe = cu->line_header->file_names[i];
11629
11630           fe.symtab = tu_group->symtabs[i];
11631         }
11632     }
11633
11634   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11635      so they don't have a "real" (so to speak) symtab anyway.
11636      There is later code that will assign the main symtab to all symbols
11637      that don't have one.  We need to handle the case of a symbol with a
11638      missing symtab (DW_AT_decl_file) anyway.  */
11639 }
11640
11641 /* Process DW_TAG_type_unit.
11642    For TUs we want to skip the first top level sibling if it's not the
11643    actual type being defined by this TU.  In this case the first top
11644    level sibling is there to provide context only.  */
11645
11646 static void
11647 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11648 {
11649   struct die_info *child_die;
11650
11651   prepare_one_comp_unit (cu, die, language_minimal);
11652
11653   /* Initialize (or reinitialize) the machinery for building symtabs.
11654      We do this before processing child DIEs, so that the line header table
11655      is available for DW_AT_decl_file.  */
11656   setup_type_unit_groups (die, cu);
11657
11658   if (die->child != NULL)
11659     {
11660       child_die = die->child;
11661       while (child_die && child_die->tag)
11662         {
11663           process_die (child_die, cu);
11664           child_die = sibling_die (child_die);
11665         }
11666     }
11667 }
11668 \f
11669 /* DWO/DWP files.
11670
11671    http://gcc.gnu.org/wiki/DebugFission
11672    http://gcc.gnu.org/wiki/DebugFissionDWP
11673
11674    To simplify handling of both DWO files ("object" files with the DWARF info)
11675    and DWP files (a file with the DWOs packaged up into one file), we treat
11676    DWP files as having a collection of virtual DWO files.  */
11677
11678 static hashval_t
11679 hash_dwo_file (const void *item)
11680 {
11681   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11682   hashval_t hash;
11683
11684   hash = htab_hash_string (dwo_file->dwo_name);
11685   if (dwo_file->comp_dir != NULL)
11686     hash += htab_hash_string (dwo_file->comp_dir);
11687   return hash;
11688 }
11689
11690 static int
11691 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11692 {
11693   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11694   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11695
11696   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11697     return 0;
11698   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11699     return lhs->comp_dir == rhs->comp_dir;
11700   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11701 }
11702
11703 /* Allocate a hash table for DWO files.  */
11704
11705 static htab_t
11706 allocate_dwo_file_hash_table (struct objfile *objfile)
11707 {
11708   return htab_create_alloc_ex (41,
11709                                hash_dwo_file,
11710                                eq_dwo_file,
11711                                NULL,
11712                                &objfile->objfile_obstack,
11713                                hashtab_obstack_allocate,
11714                                dummy_obstack_deallocate);
11715 }
11716
11717 /* Lookup DWO file DWO_NAME.  */
11718
11719 static void **
11720 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11721                       const char *dwo_name,
11722                       const char *comp_dir)
11723 {
11724   struct dwo_file find_entry;
11725   void **slot;
11726
11727   if (dwarf2_per_objfile->dwo_files == NULL)
11728     dwarf2_per_objfile->dwo_files
11729       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11730
11731   memset (&find_entry, 0, sizeof (find_entry));
11732   find_entry.dwo_name = dwo_name;
11733   find_entry.comp_dir = comp_dir;
11734   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11735
11736   return slot;
11737 }
11738
11739 static hashval_t
11740 hash_dwo_unit (const void *item)
11741 {
11742   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11743
11744   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11745   return dwo_unit->signature;
11746 }
11747
11748 static int
11749 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11750 {
11751   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11752   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11753
11754   /* The signature is assumed to be unique within the DWO file.
11755      So while object file CU dwo_id's always have the value zero,
11756      that's OK, assuming each object file DWO file has only one CU,
11757      and that's the rule for now.  */
11758   return lhs->signature == rhs->signature;
11759 }
11760
11761 /* Allocate a hash table for DWO CUs,TUs.
11762    There is one of these tables for each of CUs,TUs for each DWO file.  */
11763
11764 static htab_t
11765 allocate_dwo_unit_table (struct objfile *objfile)
11766 {
11767   /* Start out with a pretty small number.
11768      Generally DWO files contain only one CU and maybe some TUs.  */
11769   return htab_create_alloc_ex (3,
11770                                hash_dwo_unit,
11771                                eq_dwo_unit,
11772                                NULL,
11773                                &objfile->objfile_obstack,
11774                                hashtab_obstack_allocate,
11775                                dummy_obstack_deallocate);
11776 }
11777
11778 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11779
11780 struct create_dwo_cu_data
11781 {
11782   struct dwo_file *dwo_file;
11783   struct dwo_unit dwo_unit;
11784 };
11785
11786 /* die_reader_func for create_dwo_cu.  */
11787
11788 static void
11789 create_dwo_cu_reader (const struct die_reader_specs *reader,
11790                       const gdb_byte *info_ptr,
11791                       struct die_info *comp_unit_die,
11792                       int has_children,
11793                       void *datap)
11794 {
11795   struct dwarf2_cu *cu = reader->cu;
11796   sect_offset sect_off = cu->per_cu->sect_off;
11797   struct dwarf2_section_info *section = cu->per_cu->section;
11798   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11799   struct dwo_file *dwo_file = data->dwo_file;
11800   struct dwo_unit *dwo_unit = &data->dwo_unit;
11801   struct attribute *attr;
11802
11803   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11804   if (attr == NULL)
11805     {
11806       complaint (&symfile_complaints,
11807                  _("Dwarf Error: debug entry at offset %s is missing"
11808                    " its dwo_id [in module %s]"),
11809                  sect_offset_str (sect_off), dwo_file->dwo_name);
11810       return;
11811     }
11812
11813   dwo_unit->dwo_file = dwo_file;
11814   dwo_unit->signature = DW_UNSND (attr);
11815   dwo_unit->section = section;
11816   dwo_unit->sect_off = sect_off;
11817   dwo_unit->length = cu->per_cu->length;
11818
11819   if (dwarf_read_debug)
11820     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11821                         sect_offset_str (sect_off),
11822                         hex_string (dwo_unit->signature));
11823 }
11824
11825 /* Create the dwo_units for the CUs in a DWO_FILE.
11826    Note: This function processes DWO files only, not DWP files.  */
11827
11828 static void
11829 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11830                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11831                        htab_t &cus_htab)
11832 {
11833   struct objfile *objfile = dwarf2_per_objfile->objfile;
11834   const gdb_byte *info_ptr, *end_ptr;
11835
11836   dwarf2_read_section (objfile, &section);
11837   info_ptr = section.buffer;
11838
11839   if (info_ptr == NULL)
11840     return;
11841
11842   if (dwarf_read_debug)
11843     {
11844       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11845                           get_section_name (&section),
11846                           get_section_file_name (&section));
11847     }
11848
11849   end_ptr = info_ptr + section.size;
11850   while (info_ptr < end_ptr)
11851     {
11852       struct dwarf2_per_cu_data per_cu;
11853       struct create_dwo_cu_data create_dwo_cu_data;
11854       struct dwo_unit *dwo_unit;
11855       void **slot;
11856       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11857
11858       memset (&create_dwo_cu_data.dwo_unit, 0,
11859               sizeof (create_dwo_cu_data.dwo_unit));
11860       memset (&per_cu, 0, sizeof (per_cu));
11861       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11862       per_cu.is_debug_types = 0;
11863       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11864       per_cu.section = &section;
11865       create_dwo_cu_data.dwo_file = &dwo_file;
11866
11867       init_cutu_and_read_dies_no_follow (
11868           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11869       info_ptr += per_cu.length;
11870
11871       // If the unit could not be parsed, skip it.
11872       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11873         continue;
11874
11875       if (cus_htab == NULL)
11876         cus_htab = allocate_dwo_unit_table (objfile);
11877
11878       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11879       *dwo_unit = create_dwo_cu_data.dwo_unit;
11880       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11881       gdb_assert (slot != NULL);
11882       if (*slot != NULL)
11883         {
11884           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11885           sect_offset dup_sect_off = dup_cu->sect_off;
11886
11887           complaint (&symfile_complaints,
11888                      _("debug cu entry at offset %s is duplicate to"
11889                        " the entry at offset %s, signature %s"),
11890                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11891                      hex_string (dwo_unit->signature));
11892         }
11893       *slot = (void *)dwo_unit;
11894     }
11895 }
11896
11897 /* DWP file .debug_{cu,tu}_index section format:
11898    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11899
11900    DWP Version 1:
11901
11902    Both index sections have the same format, and serve to map a 64-bit
11903    signature to a set of section numbers.  Each section begins with a header,
11904    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11905    indexes, and a pool of 32-bit section numbers.  The index sections will be
11906    aligned at 8-byte boundaries in the file.
11907
11908    The index section header consists of:
11909
11910     V, 32 bit version number
11911     -, 32 bits unused
11912     N, 32 bit number of compilation units or type units in the index
11913     M, 32 bit number of slots in the hash table
11914
11915    Numbers are recorded using the byte order of the application binary.
11916
11917    The hash table begins at offset 16 in the section, and consists of an array
11918    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11919    order of the application binary).  Unused slots in the hash table are 0.
11920    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11921
11922    The parallel table begins immediately after the hash table
11923    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11924    array of 32-bit indexes (using the byte order of the application binary),
11925    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11926    table contains a 32-bit index into the pool of section numbers.  For unused
11927    hash table slots, the corresponding entry in the parallel table will be 0.
11928
11929    The pool of section numbers begins immediately following the hash table
11930    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11931    section numbers consists of an array of 32-bit words (using the byte order
11932    of the application binary).  Each item in the array is indexed starting
11933    from 0.  The hash table entry provides the index of the first section
11934    number in the set.  Additional section numbers in the set follow, and the
11935    set is terminated by a 0 entry (section number 0 is not used in ELF).
11936
11937    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11938    section must be the first entry in the set, and the .debug_abbrev.dwo must
11939    be the second entry. Other members of the set may follow in any order.
11940
11941    ---
11942
11943    DWP Version 2:
11944
11945    DWP Version 2 combines all the .debug_info, etc. sections into one,
11946    and the entries in the index tables are now offsets into these sections.
11947    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11948    section.
11949
11950    Index Section Contents:
11951     Header
11952     Hash Table of Signatures   dwp_hash_table.hash_table
11953     Parallel Table of Indices  dwp_hash_table.unit_table
11954     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11955     Table of Section Sizes     dwp_hash_table.v2.sizes
11956
11957    The index section header consists of:
11958
11959     V, 32 bit version number
11960     L, 32 bit number of columns in the table of section offsets
11961     N, 32 bit number of compilation units or type units in the index
11962     M, 32 bit number of slots in the hash table
11963
11964    Numbers are recorded using the byte order of the application binary.
11965
11966    The hash table has the same format as version 1.
11967    The parallel table of indices has the same format as version 1,
11968    except that the entries are origin-1 indices into the table of sections
11969    offsets and the table of section sizes.
11970
11971    The table of offsets begins immediately following the parallel table
11972    (at offset 16 + 12 * M from the beginning of the section).  The table is
11973    a two-dimensional array of 32-bit words (using the byte order of the
11974    application binary), with L columns and N+1 rows, in row-major order.
11975    Each row in the array is indexed starting from 0.  The first row provides
11976    a key to the remaining rows: each column in this row provides an identifier
11977    for a debug section, and the offsets in the same column of subsequent rows
11978    refer to that section.  The section identifiers are:
11979
11980     DW_SECT_INFO         1  .debug_info.dwo
11981     DW_SECT_TYPES        2  .debug_types.dwo
11982     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11983     DW_SECT_LINE         4  .debug_line.dwo
11984     DW_SECT_LOC          5  .debug_loc.dwo
11985     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11986     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11987     DW_SECT_MACRO        8  .debug_macro.dwo
11988
11989    The offsets provided by the CU and TU index sections are the base offsets
11990    for the contributions made by each CU or TU to the corresponding section
11991    in the package file.  Each CU and TU header contains an abbrev_offset
11992    field, used to find the abbreviations table for that CU or TU within the
11993    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11994    be interpreted as relative to the base offset given in the index section.
11995    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11996    should be interpreted as relative to the base offset for .debug_line.dwo,
11997    and offsets into other debug sections obtained from DWARF attributes should
11998    also be interpreted as relative to the corresponding base offset.
11999
12000    The table of sizes begins immediately following the table of offsets.
12001    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12002    with L columns and N rows, in row-major order.  Each row in the array is
12003    indexed starting from 1 (row 0 is shared by the two tables).
12004
12005    ---
12006
12007    Hash table lookup is handled the same in version 1 and 2:
12008
12009    We assume that N and M will not exceed 2^32 - 1.
12010    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12011
12012    Given a 64-bit compilation unit signature or a type signature S, an entry
12013    in the hash table is located as follows:
12014
12015    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12016       the low-order k bits all set to 1.
12017
12018    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12019
12020    3) If the hash table entry at index H matches the signature, use that
12021       entry.  If the hash table entry at index H is unused (all zeroes),
12022       terminate the search: the signature is not present in the table.
12023
12024    4) Let H = (H + H') modulo M. Repeat at Step 3.
12025
12026    Because M > N and H' and M are relatively prime, the search is guaranteed
12027    to stop at an unused slot or find the match.  */
12028
12029 /* Create a hash table to map DWO IDs to their CU/TU entry in
12030    .debug_{info,types}.dwo in DWP_FILE.
12031    Returns NULL if there isn't one.
12032    Note: This function processes DWP files only, not DWO files.  */
12033
12034 static struct dwp_hash_table *
12035 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12036                        struct dwp_file *dwp_file, int is_debug_types)
12037 {
12038   struct objfile *objfile = dwarf2_per_objfile->objfile;
12039   bfd *dbfd = dwp_file->dbfd;
12040   const gdb_byte *index_ptr, *index_end;
12041   struct dwarf2_section_info *index;
12042   uint32_t version, nr_columns, nr_units, nr_slots;
12043   struct dwp_hash_table *htab;
12044
12045   if (is_debug_types)
12046     index = &dwp_file->sections.tu_index;
12047   else
12048     index = &dwp_file->sections.cu_index;
12049
12050   if (dwarf2_section_empty_p (index))
12051     return NULL;
12052   dwarf2_read_section (objfile, index);
12053
12054   index_ptr = index->buffer;
12055   index_end = index_ptr + index->size;
12056
12057   version = read_4_bytes (dbfd, index_ptr);
12058   index_ptr += 4;
12059   if (version == 2)
12060     nr_columns = read_4_bytes (dbfd, index_ptr);
12061   else
12062     nr_columns = 0;
12063   index_ptr += 4;
12064   nr_units = read_4_bytes (dbfd, index_ptr);
12065   index_ptr += 4;
12066   nr_slots = read_4_bytes (dbfd, index_ptr);
12067   index_ptr += 4;
12068
12069   if (version != 1 && version != 2)
12070     {
12071       error (_("Dwarf Error: unsupported DWP file version (%s)"
12072                " [in module %s]"),
12073              pulongest (version), dwp_file->name);
12074     }
12075   if (nr_slots != (nr_slots & -nr_slots))
12076     {
12077       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12078                " is not power of 2 [in module %s]"),
12079              pulongest (nr_slots), dwp_file->name);
12080     }
12081
12082   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12083   htab->version = version;
12084   htab->nr_columns = nr_columns;
12085   htab->nr_units = nr_units;
12086   htab->nr_slots = nr_slots;
12087   htab->hash_table = index_ptr;
12088   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12089
12090   /* Exit early if the table is empty.  */
12091   if (nr_slots == 0 || nr_units == 0
12092       || (version == 2 && nr_columns == 0))
12093     {
12094       /* All must be zero.  */
12095       if (nr_slots != 0 || nr_units != 0
12096           || (version == 2 && nr_columns != 0))
12097         {
12098           complaint (&symfile_complaints,
12099                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12100                        " all zero [in modules %s]"),
12101                      dwp_file->name);
12102         }
12103       return htab;
12104     }
12105
12106   if (version == 1)
12107     {
12108       htab->section_pool.v1.indices =
12109         htab->unit_table + sizeof (uint32_t) * nr_slots;
12110       /* It's harder to decide whether the section is too small in v1.
12111          V1 is deprecated anyway so we punt.  */
12112     }
12113   else
12114     {
12115       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12116       int *ids = htab->section_pool.v2.section_ids;
12117       /* Reverse map for error checking.  */
12118       int ids_seen[DW_SECT_MAX + 1];
12119       int i;
12120
12121       if (nr_columns < 2)
12122         {
12123           error (_("Dwarf Error: bad DWP hash table, too few columns"
12124                    " in section table [in module %s]"),
12125                  dwp_file->name);
12126         }
12127       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12128         {
12129           error (_("Dwarf Error: bad DWP hash table, too many columns"
12130                    " in section table [in module %s]"),
12131                  dwp_file->name);
12132         }
12133       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12134       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12135       for (i = 0; i < nr_columns; ++i)
12136         {
12137           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12138
12139           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12140             {
12141               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12142                        " in section table [in module %s]"),
12143                      id, dwp_file->name);
12144             }
12145           if (ids_seen[id] != -1)
12146             {
12147               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12148                        " id %d in section table [in module %s]"),
12149                      id, dwp_file->name);
12150             }
12151           ids_seen[id] = i;
12152           ids[i] = id;
12153         }
12154       /* Must have exactly one info or types section.  */
12155       if (((ids_seen[DW_SECT_INFO] != -1)
12156            + (ids_seen[DW_SECT_TYPES] != -1))
12157           != 1)
12158         {
12159           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12160                    " DWO info/types section [in module %s]"),
12161                  dwp_file->name);
12162         }
12163       /* Must have an abbrev section.  */
12164       if (ids_seen[DW_SECT_ABBREV] == -1)
12165         {
12166           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12167                    " section [in module %s]"),
12168                  dwp_file->name);
12169         }
12170       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12171       htab->section_pool.v2.sizes =
12172         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12173                                          * nr_units * nr_columns);
12174       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12175                                           * nr_units * nr_columns))
12176           > index_end)
12177         {
12178           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12179                    " [in module %s]"),
12180                  dwp_file->name);
12181         }
12182     }
12183
12184   return htab;
12185 }
12186
12187 /* Update SECTIONS with the data from SECTP.
12188
12189    This function is like the other "locate" section routines that are
12190    passed to bfd_map_over_sections, but in this context the sections to
12191    read comes from the DWP V1 hash table, not the full ELF section table.
12192
12193    The result is non-zero for success, or zero if an error was found.  */
12194
12195 static int
12196 locate_v1_virtual_dwo_sections (asection *sectp,
12197                                 struct virtual_v1_dwo_sections *sections)
12198 {
12199   const struct dwop_section_names *names = &dwop_section_names;
12200
12201   if (section_is_p (sectp->name, &names->abbrev_dwo))
12202     {
12203       /* There can be only one.  */
12204       if (sections->abbrev.s.section != NULL)
12205         return 0;
12206       sections->abbrev.s.section = sectp;
12207       sections->abbrev.size = bfd_get_section_size (sectp);
12208     }
12209   else if (section_is_p (sectp->name, &names->info_dwo)
12210            || section_is_p (sectp->name, &names->types_dwo))
12211     {
12212       /* There can be only one.  */
12213       if (sections->info_or_types.s.section != NULL)
12214         return 0;
12215       sections->info_or_types.s.section = sectp;
12216       sections->info_or_types.size = bfd_get_section_size (sectp);
12217     }
12218   else if (section_is_p (sectp->name, &names->line_dwo))
12219     {
12220       /* There can be only one.  */
12221       if (sections->line.s.section != NULL)
12222         return 0;
12223       sections->line.s.section = sectp;
12224       sections->line.size = bfd_get_section_size (sectp);
12225     }
12226   else if (section_is_p (sectp->name, &names->loc_dwo))
12227     {
12228       /* There can be only one.  */
12229       if (sections->loc.s.section != NULL)
12230         return 0;
12231       sections->loc.s.section = sectp;
12232       sections->loc.size = bfd_get_section_size (sectp);
12233     }
12234   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12235     {
12236       /* There can be only one.  */
12237       if (sections->macinfo.s.section != NULL)
12238         return 0;
12239       sections->macinfo.s.section = sectp;
12240       sections->macinfo.size = bfd_get_section_size (sectp);
12241     }
12242   else if (section_is_p (sectp->name, &names->macro_dwo))
12243     {
12244       /* There can be only one.  */
12245       if (sections->macro.s.section != NULL)
12246         return 0;
12247       sections->macro.s.section = sectp;
12248       sections->macro.size = bfd_get_section_size (sectp);
12249     }
12250   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12251     {
12252       /* There can be only one.  */
12253       if (sections->str_offsets.s.section != NULL)
12254         return 0;
12255       sections->str_offsets.s.section = sectp;
12256       sections->str_offsets.size = bfd_get_section_size (sectp);
12257     }
12258   else
12259     {
12260       /* No other kind of section is valid.  */
12261       return 0;
12262     }
12263
12264   return 1;
12265 }
12266
12267 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12268    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12269    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12270    This is for DWP version 1 files.  */
12271
12272 static struct dwo_unit *
12273 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12274                            struct dwp_file *dwp_file,
12275                            uint32_t unit_index,
12276                            const char *comp_dir,
12277                            ULONGEST signature, int is_debug_types)
12278 {
12279   struct objfile *objfile = dwarf2_per_objfile->objfile;
12280   const struct dwp_hash_table *dwp_htab =
12281     is_debug_types ? dwp_file->tus : dwp_file->cus;
12282   bfd *dbfd = dwp_file->dbfd;
12283   const char *kind = is_debug_types ? "TU" : "CU";
12284   struct dwo_file *dwo_file;
12285   struct dwo_unit *dwo_unit;
12286   struct virtual_v1_dwo_sections sections;
12287   void **dwo_file_slot;
12288   int i;
12289
12290   gdb_assert (dwp_file->version == 1);
12291
12292   if (dwarf_read_debug)
12293     {
12294       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12295                           kind,
12296                           pulongest (unit_index), hex_string (signature),
12297                           dwp_file->name);
12298     }
12299
12300   /* Fetch the sections of this DWO unit.
12301      Put a limit on the number of sections we look for so that bad data
12302      doesn't cause us to loop forever.  */
12303
12304 #define MAX_NR_V1_DWO_SECTIONS \
12305   (1 /* .debug_info or .debug_types */ \
12306    + 1 /* .debug_abbrev */ \
12307    + 1 /* .debug_line */ \
12308    + 1 /* .debug_loc */ \
12309    + 1 /* .debug_str_offsets */ \
12310    + 1 /* .debug_macro or .debug_macinfo */ \
12311    + 1 /* trailing zero */)
12312
12313   memset (&sections, 0, sizeof (sections));
12314
12315   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12316     {
12317       asection *sectp;
12318       uint32_t section_nr =
12319         read_4_bytes (dbfd,
12320                       dwp_htab->section_pool.v1.indices
12321                       + (unit_index + i) * sizeof (uint32_t));
12322
12323       if (section_nr == 0)
12324         break;
12325       if (section_nr >= dwp_file->num_sections)
12326         {
12327           error (_("Dwarf Error: bad DWP hash table, section number too large"
12328                    " [in module %s]"),
12329                  dwp_file->name);
12330         }
12331
12332       sectp = dwp_file->elf_sections[section_nr];
12333       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12334         {
12335           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12336                    " [in module %s]"),
12337                  dwp_file->name);
12338         }
12339     }
12340
12341   if (i < 2
12342       || dwarf2_section_empty_p (&sections.info_or_types)
12343       || dwarf2_section_empty_p (&sections.abbrev))
12344     {
12345       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12346                " [in module %s]"),
12347              dwp_file->name);
12348     }
12349   if (i == MAX_NR_V1_DWO_SECTIONS)
12350     {
12351       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12352                " [in module %s]"),
12353              dwp_file->name);
12354     }
12355
12356   /* It's easier for the rest of the code if we fake a struct dwo_file and
12357      have dwo_unit "live" in that.  At least for now.
12358
12359      The DWP file can be made up of a random collection of CUs and TUs.
12360      However, for each CU + set of TUs that came from the same original DWO
12361      file, we can combine them back into a virtual DWO file to save space
12362      (fewer struct dwo_file objects to allocate).  Remember that for really
12363      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12364
12365   std::string virtual_dwo_name =
12366     string_printf ("virtual-dwo/%d-%d-%d-%d",
12367                    get_section_id (&sections.abbrev),
12368                    get_section_id (&sections.line),
12369                    get_section_id (&sections.loc),
12370                    get_section_id (&sections.str_offsets));
12371   /* Can we use an existing virtual DWO file?  */
12372   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12373                                         virtual_dwo_name.c_str (),
12374                                         comp_dir);
12375   /* Create one if necessary.  */
12376   if (*dwo_file_slot == NULL)
12377     {
12378       if (dwarf_read_debug)
12379         {
12380           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12381                               virtual_dwo_name.c_str ());
12382         }
12383       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12384       dwo_file->dwo_name
12385         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12386                                         virtual_dwo_name.c_str (),
12387                                         virtual_dwo_name.size ());
12388       dwo_file->comp_dir = comp_dir;
12389       dwo_file->sections.abbrev = sections.abbrev;
12390       dwo_file->sections.line = sections.line;
12391       dwo_file->sections.loc = sections.loc;
12392       dwo_file->sections.macinfo = sections.macinfo;
12393       dwo_file->sections.macro = sections.macro;
12394       dwo_file->sections.str_offsets = sections.str_offsets;
12395       /* The "str" section is global to the entire DWP file.  */
12396       dwo_file->sections.str = dwp_file->sections.str;
12397       /* The info or types section is assigned below to dwo_unit,
12398          there's no need to record it in dwo_file.
12399          Also, we can't simply record type sections in dwo_file because
12400          we record a pointer into the vector in dwo_unit.  As we collect more
12401          types we'll grow the vector and eventually have to reallocate space
12402          for it, invalidating all copies of pointers into the previous
12403          contents.  */
12404       *dwo_file_slot = dwo_file;
12405     }
12406   else
12407     {
12408       if (dwarf_read_debug)
12409         {
12410           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12411                               virtual_dwo_name.c_str ());
12412         }
12413       dwo_file = (struct dwo_file *) *dwo_file_slot;
12414     }
12415
12416   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12417   dwo_unit->dwo_file = dwo_file;
12418   dwo_unit->signature = signature;
12419   dwo_unit->section =
12420     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12421   *dwo_unit->section = sections.info_or_types;
12422   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12423
12424   return dwo_unit;
12425 }
12426
12427 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12428    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12429    piece within that section used by a TU/CU, return a virtual section
12430    of just that piece.  */
12431
12432 static struct dwarf2_section_info
12433 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12434                        struct dwarf2_section_info *section,
12435                        bfd_size_type offset, bfd_size_type size)
12436 {
12437   struct dwarf2_section_info result;
12438   asection *sectp;
12439
12440   gdb_assert (section != NULL);
12441   gdb_assert (!section->is_virtual);
12442
12443   memset (&result, 0, sizeof (result));
12444   result.s.containing_section = section;
12445   result.is_virtual = 1;
12446
12447   if (size == 0)
12448     return result;
12449
12450   sectp = get_section_bfd_section (section);
12451
12452   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12453      bounds of the real section.  This is a pretty-rare event, so just
12454      flag an error (easier) instead of a warning and trying to cope.  */
12455   if (sectp == NULL
12456       || offset + size > bfd_get_section_size (sectp))
12457     {
12458       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12459                " in section %s [in module %s]"),
12460              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12461              objfile_name (dwarf2_per_objfile->objfile));
12462     }
12463
12464   result.virtual_offset = offset;
12465   result.size = size;
12466   return result;
12467 }
12468
12469 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12470    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12471    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12472    This is for DWP version 2 files.  */
12473
12474 static struct dwo_unit *
12475 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12476                            struct dwp_file *dwp_file,
12477                            uint32_t unit_index,
12478                            const char *comp_dir,
12479                            ULONGEST signature, int is_debug_types)
12480 {
12481   struct objfile *objfile = dwarf2_per_objfile->objfile;
12482   const struct dwp_hash_table *dwp_htab =
12483     is_debug_types ? dwp_file->tus : dwp_file->cus;
12484   bfd *dbfd = dwp_file->dbfd;
12485   const char *kind = is_debug_types ? "TU" : "CU";
12486   struct dwo_file *dwo_file;
12487   struct dwo_unit *dwo_unit;
12488   struct virtual_v2_dwo_sections sections;
12489   void **dwo_file_slot;
12490   int i;
12491
12492   gdb_assert (dwp_file->version == 2);
12493
12494   if (dwarf_read_debug)
12495     {
12496       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12497                           kind,
12498                           pulongest (unit_index), hex_string (signature),
12499                           dwp_file->name);
12500     }
12501
12502   /* Fetch the section offsets of this DWO unit.  */
12503
12504   memset (&sections, 0, sizeof (sections));
12505
12506   for (i = 0; i < dwp_htab->nr_columns; ++i)
12507     {
12508       uint32_t offset = read_4_bytes (dbfd,
12509                                       dwp_htab->section_pool.v2.offsets
12510                                       + (((unit_index - 1) * dwp_htab->nr_columns
12511                                           + i)
12512                                          * sizeof (uint32_t)));
12513       uint32_t size = read_4_bytes (dbfd,
12514                                     dwp_htab->section_pool.v2.sizes
12515                                     + (((unit_index - 1) * dwp_htab->nr_columns
12516                                         + i)
12517                                        * sizeof (uint32_t)));
12518
12519       switch (dwp_htab->section_pool.v2.section_ids[i])
12520         {
12521         case DW_SECT_INFO:
12522         case DW_SECT_TYPES:
12523           sections.info_or_types_offset = offset;
12524           sections.info_or_types_size = size;
12525           break;
12526         case DW_SECT_ABBREV:
12527           sections.abbrev_offset = offset;
12528           sections.abbrev_size = size;
12529           break;
12530         case DW_SECT_LINE:
12531           sections.line_offset = offset;
12532           sections.line_size = size;
12533           break;
12534         case DW_SECT_LOC:
12535           sections.loc_offset = offset;
12536           sections.loc_size = size;
12537           break;
12538         case DW_SECT_STR_OFFSETS:
12539           sections.str_offsets_offset = offset;
12540           sections.str_offsets_size = size;
12541           break;
12542         case DW_SECT_MACINFO:
12543           sections.macinfo_offset = offset;
12544           sections.macinfo_size = size;
12545           break;
12546         case DW_SECT_MACRO:
12547           sections.macro_offset = offset;
12548           sections.macro_size = size;
12549           break;
12550         }
12551     }
12552
12553   /* It's easier for the rest of the code if we fake a struct dwo_file and
12554      have dwo_unit "live" in that.  At least for now.
12555
12556      The DWP file can be made up of a random collection of CUs and TUs.
12557      However, for each CU + set of TUs that came from the same original DWO
12558      file, we can combine them back into a virtual DWO file to save space
12559      (fewer struct dwo_file objects to allocate).  Remember that for really
12560      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12561
12562   std::string virtual_dwo_name =
12563     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12564                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12565                    (long) (sections.line_size ? sections.line_offset : 0),
12566                    (long) (sections.loc_size ? sections.loc_offset : 0),
12567                    (long) (sections.str_offsets_size
12568                            ? sections.str_offsets_offset : 0));
12569   /* Can we use an existing virtual DWO file?  */
12570   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12571                                         virtual_dwo_name.c_str (),
12572                                         comp_dir);
12573   /* Create one if necessary.  */
12574   if (*dwo_file_slot == NULL)
12575     {
12576       if (dwarf_read_debug)
12577         {
12578           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12579                               virtual_dwo_name.c_str ());
12580         }
12581       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12582       dwo_file->dwo_name
12583         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12584                                         virtual_dwo_name.c_str (),
12585                                         virtual_dwo_name.size ());
12586       dwo_file->comp_dir = comp_dir;
12587       dwo_file->sections.abbrev =
12588         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12589                                sections.abbrev_offset, sections.abbrev_size);
12590       dwo_file->sections.line =
12591         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12592                                sections.line_offset, sections.line_size);
12593       dwo_file->sections.loc =
12594         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12595                                sections.loc_offset, sections.loc_size);
12596       dwo_file->sections.macinfo =
12597         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12598                                sections.macinfo_offset, sections.macinfo_size);
12599       dwo_file->sections.macro =
12600         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12601                                sections.macro_offset, sections.macro_size);
12602       dwo_file->sections.str_offsets =
12603         create_dwp_v2_section (dwarf2_per_objfile,
12604                                &dwp_file->sections.str_offsets,
12605                                sections.str_offsets_offset,
12606                                sections.str_offsets_size);
12607       /* The "str" section is global to the entire DWP file.  */
12608       dwo_file->sections.str = dwp_file->sections.str;
12609       /* The info or types section is assigned below to dwo_unit,
12610          there's no need to record it in dwo_file.
12611          Also, we can't simply record type sections in dwo_file because
12612          we record a pointer into the vector in dwo_unit.  As we collect more
12613          types we'll grow the vector and eventually have to reallocate space
12614          for it, invalidating all copies of pointers into the previous
12615          contents.  */
12616       *dwo_file_slot = dwo_file;
12617     }
12618   else
12619     {
12620       if (dwarf_read_debug)
12621         {
12622           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12623                               virtual_dwo_name.c_str ());
12624         }
12625       dwo_file = (struct dwo_file *) *dwo_file_slot;
12626     }
12627
12628   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12629   dwo_unit->dwo_file = dwo_file;
12630   dwo_unit->signature = signature;
12631   dwo_unit->section =
12632     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12633   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12634                                               is_debug_types
12635                                               ? &dwp_file->sections.types
12636                                               : &dwp_file->sections.info,
12637                                               sections.info_or_types_offset,
12638                                               sections.info_or_types_size);
12639   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12640
12641   return dwo_unit;
12642 }
12643
12644 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12645    Returns NULL if the signature isn't found.  */
12646
12647 static struct dwo_unit *
12648 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12649                         struct dwp_file *dwp_file, const char *comp_dir,
12650                         ULONGEST signature, int is_debug_types)
12651 {
12652   const struct dwp_hash_table *dwp_htab =
12653     is_debug_types ? dwp_file->tus : dwp_file->cus;
12654   bfd *dbfd = dwp_file->dbfd;
12655   uint32_t mask = dwp_htab->nr_slots - 1;
12656   uint32_t hash = signature & mask;
12657   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12658   unsigned int i;
12659   void **slot;
12660   struct dwo_unit find_dwo_cu;
12661
12662   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12663   find_dwo_cu.signature = signature;
12664   slot = htab_find_slot (is_debug_types
12665                          ? dwp_file->loaded_tus
12666                          : dwp_file->loaded_cus,
12667                          &find_dwo_cu, INSERT);
12668
12669   if (*slot != NULL)
12670     return (struct dwo_unit *) *slot;
12671
12672   /* Use a for loop so that we don't loop forever on bad debug info.  */
12673   for (i = 0; i < dwp_htab->nr_slots; ++i)
12674     {
12675       ULONGEST signature_in_table;
12676
12677       signature_in_table =
12678         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12679       if (signature_in_table == signature)
12680         {
12681           uint32_t unit_index =
12682             read_4_bytes (dbfd,
12683                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12684
12685           if (dwp_file->version == 1)
12686             {
12687               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12688                                                  dwp_file, unit_index,
12689                                                  comp_dir, signature,
12690                                                  is_debug_types);
12691             }
12692           else
12693             {
12694               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12695                                                  dwp_file, unit_index,
12696                                                  comp_dir, signature,
12697                                                  is_debug_types);
12698             }
12699           return (struct dwo_unit *) *slot;
12700         }
12701       if (signature_in_table == 0)
12702         return NULL;
12703       hash = (hash + hash2) & mask;
12704     }
12705
12706   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12707            " [in module %s]"),
12708          dwp_file->name);
12709 }
12710
12711 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12712    Open the file specified by FILE_NAME and hand it off to BFD for
12713    preliminary analysis.  Return a newly initialized bfd *, which
12714    includes a canonicalized copy of FILE_NAME.
12715    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12716    SEARCH_CWD is true if the current directory is to be searched.
12717    It will be searched before debug-file-directory.
12718    If successful, the file is added to the bfd include table of the
12719    objfile's bfd (see gdb_bfd_record_inclusion).
12720    If unable to find/open the file, return NULL.
12721    NOTE: This function is derived from symfile_bfd_open.  */
12722
12723 static gdb_bfd_ref_ptr
12724 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12725                     const char *file_name, int is_dwp, int search_cwd)
12726 {
12727   int desc;
12728   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12729      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12730      to debug_file_directory.  */
12731   const char *search_path;
12732   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12733
12734   gdb::unique_xmalloc_ptr<char> search_path_holder;
12735   if (search_cwd)
12736     {
12737       if (*debug_file_directory != '\0')
12738         {
12739           search_path_holder.reset (concat (".", dirname_separator_string,
12740                                             debug_file_directory,
12741                                             (char *) NULL));
12742           search_path = search_path_holder.get ();
12743         }
12744       else
12745         search_path = ".";
12746     }
12747   else
12748     search_path = debug_file_directory;
12749
12750   openp_flags flags = OPF_RETURN_REALPATH;
12751   if (is_dwp)
12752     flags |= OPF_SEARCH_IN_PATH;
12753
12754   gdb::unique_xmalloc_ptr<char> absolute_name;
12755   desc = openp (search_path, flags, file_name,
12756                 O_RDONLY | O_BINARY, &absolute_name);
12757   if (desc < 0)
12758     return NULL;
12759
12760   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12761                                          gnutarget, desc));
12762   if (sym_bfd == NULL)
12763     return NULL;
12764   bfd_set_cacheable (sym_bfd.get (), 1);
12765
12766   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12767     return NULL;
12768
12769   /* Success.  Record the bfd as having been included by the objfile's bfd.
12770      This is important because things like demangled_names_hash lives in the
12771      objfile's per_bfd space and may have references to things like symbol
12772      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12773   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12774
12775   return sym_bfd;
12776 }
12777
12778 /* Try to open DWO file FILE_NAME.
12779    COMP_DIR is the DW_AT_comp_dir attribute.
12780    The result is the bfd handle of the file.
12781    If there is a problem finding or opening the file, return NULL.
12782    Upon success, the canonicalized path of the file is stored in the bfd,
12783    same as symfile_bfd_open.  */
12784
12785 static gdb_bfd_ref_ptr
12786 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12787                const char *file_name, const char *comp_dir)
12788 {
12789   if (IS_ABSOLUTE_PATH (file_name))
12790     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12791                                0 /*is_dwp*/, 0 /*search_cwd*/);
12792
12793   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12794
12795   if (comp_dir != NULL)
12796     {
12797       char *path_to_try = concat (comp_dir, SLASH_STRING,
12798                                   file_name, (char *) NULL);
12799
12800       /* NOTE: If comp_dir is a relative path, this will also try the
12801          search path, which seems useful.  */
12802       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12803                                                 path_to_try,
12804                                                 0 /*is_dwp*/,
12805                                                 1 /*search_cwd*/));
12806       xfree (path_to_try);
12807       if (abfd != NULL)
12808         return abfd;
12809     }
12810
12811   /* That didn't work, try debug-file-directory, which, despite its name,
12812      is a list of paths.  */
12813
12814   if (*debug_file_directory == '\0')
12815     return NULL;
12816
12817   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12818                              0 /*is_dwp*/, 1 /*search_cwd*/);
12819 }
12820
12821 /* This function is mapped across the sections and remembers the offset and
12822    size of each of the DWO debugging sections we are interested in.  */
12823
12824 static void
12825 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12826 {
12827   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12828   const struct dwop_section_names *names = &dwop_section_names;
12829
12830   if (section_is_p (sectp->name, &names->abbrev_dwo))
12831     {
12832       dwo_sections->abbrev.s.section = sectp;
12833       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12834     }
12835   else if (section_is_p (sectp->name, &names->info_dwo))
12836     {
12837       dwo_sections->info.s.section = sectp;
12838       dwo_sections->info.size = bfd_get_section_size (sectp);
12839     }
12840   else if (section_is_p (sectp->name, &names->line_dwo))
12841     {
12842       dwo_sections->line.s.section = sectp;
12843       dwo_sections->line.size = bfd_get_section_size (sectp);
12844     }
12845   else if (section_is_p (sectp->name, &names->loc_dwo))
12846     {
12847       dwo_sections->loc.s.section = sectp;
12848       dwo_sections->loc.size = bfd_get_section_size (sectp);
12849     }
12850   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12851     {
12852       dwo_sections->macinfo.s.section = sectp;
12853       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12854     }
12855   else if (section_is_p (sectp->name, &names->macro_dwo))
12856     {
12857       dwo_sections->macro.s.section = sectp;
12858       dwo_sections->macro.size = bfd_get_section_size (sectp);
12859     }
12860   else if (section_is_p (sectp->name, &names->str_dwo))
12861     {
12862       dwo_sections->str.s.section = sectp;
12863       dwo_sections->str.size = bfd_get_section_size (sectp);
12864     }
12865   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12866     {
12867       dwo_sections->str_offsets.s.section = sectp;
12868       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12869     }
12870   else if (section_is_p (sectp->name, &names->types_dwo))
12871     {
12872       struct dwarf2_section_info type_section;
12873
12874       memset (&type_section, 0, sizeof (type_section));
12875       type_section.s.section = sectp;
12876       type_section.size = bfd_get_section_size (sectp);
12877       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12878                      &type_section);
12879     }
12880 }
12881
12882 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12883    by PER_CU.  This is for the non-DWP case.
12884    The result is NULL if DWO_NAME can't be found.  */
12885
12886 static struct dwo_file *
12887 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12888                         const char *dwo_name, const char *comp_dir)
12889 {
12890   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12891   struct objfile *objfile = dwarf2_per_objfile->objfile;
12892
12893   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12894   if (dbfd == NULL)
12895     {
12896       if (dwarf_read_debug)
12897         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12898       return NULL;
12899     }
12900
12901   /* We use a unique pointer here, despite the obstack allocation,
12902      because a dwo_file needs some cleanup if it is abandoned.  */
12903   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12904                                         struct dwo_file));
12905   dwo_file->dwo_name = dwo_name;
12906   dwo_file->comp_dir = comp_dir;
12907   dwo_file->dbfd = dbfd.release ();
12908
12909   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12910                          &dwo_file->sections);
12911
12912   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12913                          dwo_file->cus);
12914
12915   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12916                                  dwo_file->sections.types, dwo_file->tus);
12917
12918   if (dwarf_read_debug)
12919     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12920
12921   return dwo_file.release ();
12922 }
12923
12924 /* This function is mapped across the sections and remembers the offset and
12925    size of each of the DWP debugging sections common to version 1 and 2 that
12926    we are interested in.  */
12927
12928 static void
12929 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12930                                    void *dwp_file_ptr)
12931 {
12932   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12933   const struct dwop_section_names *names = &dwop_section_names;
12934   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12935
12936   /* Record the ELF section number for later lookup: this is what the
12937      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12938   gdb_assert (elf_section_nr < dwp_file->num_sections);
12939   dwp_file->elf_sections[elf_section_nr] = sectp;
12940
12941   /* Look for specific sections that we need.  */
12942   if (section_is_p (sectp->name, &names->str_dwo))
12943     {
12944       dwp_file->sections.str.s.section = sectp;
12945       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12946     }
12947   else if (section_is_p (sectp->name, &names->cu_index))
12948     {
12949       dwp_file->sections.cu_index.s.section = sectp;
12950       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12951     }
12952   else if (section_is_p (sectp->name, &names->tu_index))
12953     {
12954       dwp_file->sections.tu_index.s.section = sectp;
12955       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12956     }
12957 }
12958
12959 /* This function is mapped across the sections and remembers the offset and
12960    size of each of the DWP version 2 debugging sections that we are interested
12961    in.  This is split into a separate function because we don't know if we
12962    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12963
12964 static void
12965 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12966 {
12967   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12968   const struct dwop_section_names *names = &dwop_section_names;
12969   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12970
12971   /* Record the ELF section number for later lookup: this is what the
12972      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12973   gdb_assert (elf_section_nr < dwp_file->num_sections);
12974   dwp_file->elf_sections[elf_section_nr] = sectp;
12975
12976   /* Look for specific sections that we need.  */
12977   if (section_is_p (sectp->name, &names->abbrev_dwo))
12978     {
12979       dwp_file->sections.abbrev.s.section = sectp;
12980       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12981     }
12982   else if (section_is_p (sectp->name, &names->info_dwo))
12983     {
12984       dwp_file->sections.info.s.section = sectp;
12985       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12986     }
12987   else if (section_is_p (sectp->name, &names->line_dwo))
12988     {
12989       dwp_file->sections.line.s.section = sectp;
12990       dwp_file->sections.line.size = bfd_get_section_size (sectp);
12991     }
12992   else if (section_is_p (sectp->name, &names->loc_dwo))
12993     {
12994       dwp_file->sections.loc.s.section = sectp;
12995       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
12996     }
12997   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12998     {
12999       dwp_file->sections.macinfo.s.section = sectp;
13000       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13001     }
13002   else if (section_is_p (sectp->name, &names->macro_dwo))
13003     {
13004       dwp_file->sections.macro.s.section = sectp;
13005       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13006     }
13007   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13008     {
13009       dwp_file->sections.str_offsets.s.section = sectp;
13010       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13011     }
13012   else if (section_is_p (sectp->name, &names->types_dwo))
13013     {
13014       dwp_file->sections.types.s.section = sectp;
13015       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13016     }
13017 }
13018
13019 /* Hash function for dwp_file loaded CUs/TUs.  */
13020
13021 static hashval_t
13022 hash_dwp_loaded_cutus (const void *item)
13023 {
13024   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13025
13026   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13027   return dwo_unit->signature;
13028 }
13029
13030 /* Equality function for dwp_file loaded CUs/TUs.  */
13031
13032 static int
13033 eq_dwp_loaded_cutus (const void *a, const void *b)
13034 {
13035   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13036   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13037
13038   return dua->signature == dub->signature;
13039 }
13040
13041 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13042
13043 static htab_t
13044 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13045 {
13046   return htab_create_alloc_ex (3,
13047                                hash_dwp_loaded_cutus,
13048                                eq_dwp_loaded_cutus,
13049                                NULL,
13050                                &objfile->objfile_obstack,
13051                                hashtab_obstack_allocate,
13052                                dummy_obstack_deallocate);
13053 }
13054
13055 /* Try to open DWP file FILE_NAME.
13056    The result is the bfd handle of the file.
13057    If there is a problem finding or opening the file, return NULL.
13058    Upon success, the canonicalized path of the file is stored in the bfd,
13059    same as symfile_bfd_open.  */
13060
13061 static gdb_bfd_ref_ptr
13062 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13063                const char *file_name)
13064 {
13065   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13066                                             1 /*is_dwp*/,
13067                                             1 /*search_cwd*/));
13068   if (abfd != NULL)
13069     return abfd;
13070
13071   /* Work around upstream bug 15652.
13072      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13073      [Whether that's a "bug" is debatable, but it is getting in our way.]
13074      We have no real idea where the dwp file is, because gdb's realpath-ing
13075      of the executable's path may have discarded the needed info.
13076      [IWBN if the dwp file name was recorded in the executable, akin to
13077      .gnu_debuglink, but that doesn't exist yet.]
13078      Strip the directory from FILE_NAME and search again.  */
13079   if (*debug_file_directory != '\0')
13080     {
13081       /* Don't implicitly search the current directory here.
13082          If the user wants to search "." to handle this case,
13083          it must be added to debug-file-directory.  */
13084       return try_open_dwop_file (dwarf2_per_objfile,
13085                                  lbasename (file_name), 1 /*is_dwp*/,
13086                                  0 /*search_cwd*/);
13087     }
13088
13089   return NULL;
13090 }
13091
13092 /* Initialize the use of the DWP file for the current objfile.
13093    By convention the name of the DWP file is ${objfile}.dwp.
13094    The result is NULL if it can't be found.  */
13095
13096 static struct dwp_file *
13097 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13098 {
13099   struct objfile *objfile = dwarf2_per_objfile->objfile;
13100   struct dwp_file *dwp_file;
13101
13102   /* Try to find first .dwp for the binary file before any symbolic links
13103      resolving.  */
13104
13105   /* If the objfile is a debug file, find the name of the real binary
13106      file and get the name of dwp file from there.  */
13107   std::string dwp_name;
13108   if (objfile->separate_debug_objfile_backlink != NULL)
13109     {
13110       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13111       const char *backlink_basename = lbasename (backlink->original_name);
13112
13113       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13114     }
13115   else
13116     dwp_name = objfile->original_name;
13117
13118   dwp_name += ".dwp";
13119
13120   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13121   if (dbfd == NULL
13122       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13123     {
13124       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13125       dwp_name = objfile_name (objfile);
13126       dwp_name += ".dwp";
13127       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13128     }
13129
13130   if (dbfd == NULL)
13131     {
13132       if (dwarf_read_debug)
13133         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13134       return NULL;
13135     }
13136   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13137   dwp_file->name = bfd_get_filename (dbfd.get ());
13138   dwp_file->dbfd = dbfd.release ();
13139
13140   /* +1: section 0 is unused */
13141   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13142   dwp_file->elf_sections =
13143     OBSTACK_CALLOC (&objfile->objfile_obstack,
13144                     dwp_file->num_sections, asection *);
13145
13146   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13147                          dwp_file);
13148
13149   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13150
13151   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13152
13153   /* The DWP file version is stored in the hash table.  Oh well.  */
13154   if (dwp_file->cus && dwp_file->tus
13155       && dwp_file->cus->version != dwp_file->tus->version)
13156     {
13157       /* Technically speaking, we should try to limp along, but this is
13158          pretty bizarre.  We use pulongest here because that's the established
13159          portability solution (e.g, we cannot use %u for uint32_t).  */
13160       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13161                " TU version %s [in DWP file %s]"),
13162              pulongest (dwp_file->cus->version),
13163              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13164     }
13165
13166   if (dwp_file->cus)
13167     dwp_file->version = dwp_file->cus->version;
13168   else if (dwp_file->tus)
13169     dwp_file->version = dwp_file->tus->version;
13170   else
13171     dwp_file->version = 2;
13172
13173   if (dwp_file->version == 2)
13174     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13175                            dwp_file);
13176
13177   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13178   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13179
13180   if (dwarf_read_debug)
13181     {
13182       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13183       fprintf_unfiltered (gdb_stdlog,
13184                           "    %s CUs, %s TUs\n",
13185                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13186                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13187     }
13188
13189   return dwp_file;
13190 }
13191
13192 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13193
13194 static struct dwp_file *
13195 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13196 {
13197   if (! dwarf2_per_objfile->dwp_checked)
13198     {
13199       dwarf2_per_objfile->dwp_file
13200         = open_and_init_dwp_file (dwarf2_per_objfile);
13201       dwarf2_per_objfile->dwp_checked = 1;
13202     }
13203   return dwarf2_per_objfile->dwp_file;
13204 }
13205
13206 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13207    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13208    or in the DWP file for the objfile, referenced by THIS_UNIT.
13209    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13210    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13211
13212    This is called, for example, when wanting to read a variable with a
13213    complex location.  Therefore we don't want to do file i/o for every call.
13214    Therefore we don't want to look for a DWO file on every call.
13215    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13216    then we check if we've already seen DWO_NAME, and only THEN do we check
13217    for a DWO file.
13218
13219    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13220    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13221
13222 static struct dwo_unit *
13223 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13224                  const char *dwo_name, const char *comp_dir,
13225                  ULONGEST signature, int is_debug_types)
13226 {
13227   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13228   struct objfile *objfile = dwarf2_per_objfile->objfile;
13229   const char *kind = is_debug_types ? "TU" : "CU";
13230   void **dwo_file_slot;
13231   struct dwo_file *dwo_file;
13232   struct dwp_file *dwp_file;
13233
13234   /* First see if there's a DWP file.
13235      If we have a DWP file but didn't find the DWO inside it, don't
13236      look for the original DWO file.  It makes gdb behave differently
13237      depending on whether one is debugging in the build tree.  */
13238
13239   dwp_file = get_dwp_file (dwarf2_per_objfile);
13240   if (dwp_file != NULL)
13241     {
13242       const struct dwp_hash_table *dwp_htab =
13243         is_debug_types ? dwp_file->tus : dwp_file->cus;
13244
13245       if (dwp_htab != NULL)
13246         {
13247           struct dwo_unit *dwo_cutu =
13248             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13249                                     signature, is_debug_types);
13250
13251           if (dwo_cutu != NULL)
13252             {
13253               if (dwarf_read_debug)
13254                 {
13255                   fprintf_unfiltered (gdb_stdlog,
13256                                       "Virtual DWO %s %s found: @%s\n",
13257                                       kind, hex_string (signature),
13258                                       host_address_to_string (dwo_cutu));
13259                 }
13260               return dwo_cutu;
13261             }
13262         }
13263     }
13264   else
13265     {
13266       /* No DWP file, look for the DWO file.  */
13267
13268       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13269                                             dwo_name, comp_dir);
13270       if (*dwo_file_slot == NULL)
13271         {
13272           /* Read in the file and build a table of the CUs/TUs it contains.  */
13273           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13274         }
13275       /* NOTE: This will be NULL if unable to open the file.  */
13276       dwo_file = (struct dwo_file *) *dwo_file_slot;
13277
13278       if (dwo_file != NULL)
13279         {
13280           struct dwo_unit *dwo_cutu = NULL;
13281
13282           if (is_debug_types && dwo_file->tus)
13283             {
13284               struct dwo_unit find_dwo_cutu;
13285
13286               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13287               find_dwo_cutu.signature = signature;
13288               dwo_cutu
13289                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13290             }
13291           else if (!is_debug_types && dwo_file->cus)
13292             {
13293               struct dwo_unit find_dwo_cutu;
13294
13295               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13296               find_dwo_cutu.signature = signature;
13297               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13298                                                        &find_dwo_cutu);
13299             }
13300
13301           if (dwo_cutu != NULL)
13302             {
13303               if (dwarf_read_debug)
13304                 {
13305                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13306                                       kind, dwo_name, hex_string (signature),
13307                                       host_address_to_string (dwo_cutu));
13308                 }
13309               return dwo_cutu;
13310             }
13311         }
13312     }
13313
13314   /* We didn't find it.  This could mean a dwo_id mismatch, or
13315      someone deleted the DWO/DWP file, or the search path isn't set up
13316      correctly to find the file.  */
13317
13318   if (dwarf_read_debug)
13319     {
13320       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13321                           kind, dwo_name, hex_string (signature));
13322     }
13323
13324   /* This is a warning and not a complaint because it can be caused by
13325      pilot error (e.g., user accidentally deleting the DWO).  */
13326   {
13327     /* Print the name of the DWP file if we looked there, helps the user
13328        better diagnose the problem.  */
13329     std::string dwp_text;
13330
13331     if (dwp_file != NULL)
13332       dwp_text = string_printf (" [in DWP file %s]",
13333                                 lbasename (dwp_file->name));
13334
13335     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13336                " [in module %s]"),
13337              kind, dwo_name, hex_string (signature),
13338              dwp_text.c_str (),
13339              this_unit->is_debug_types ? "TU" : "CU",
13340              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13341   }
13342   return NULL;
13343 }
13344
13345 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13346    See lookup_dwo_cutu_unit for details.  */
13347
13348 static struct dwo_unit *
13349 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13350                       const char *dwo_name, const char *comp_dir,
13351                       ULONGEST signature)
13352 {
13353   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13354 }
13355
13356 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13357    See lookup_dwo_cutu_unit for details.  */
13358
13359 static struct dwo_unit *
13360 lookup_dwo_type_unit (struct signatured_type *this_tu,
13361                       const char *dwo_name, const char *comp_dir)
13362 {
13363   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13364 }
13365
13366 /* Traversal function for queue_and_load_all_dwo_tus.  */
13367
13368 static int
13369 queue_and_load_dwo_tu (void **slot, void *info)
13370 {
13371   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13372   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13373   ULONGEST signature = dwo_unit->signature;
13374   struct signatured_type *sig_type =
13375     lookup_dwo_signatured_type (per_cu->cu, signature);
13376
13377   if (sig_type != NULL)
13378     {
13379       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13380
13381       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13382          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13383          while processing PER_CU.  */
13384       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13385         load_full_type_unit (sig_cu);
13386       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13387     }
13388
13389   return 1;
13390 }
13391
13392 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13393    The DWO may have the only definition of the type, though it may not be
13394    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13395    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13396
13397 static void
13398 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13399 {
13400   struct dwo_unit *dwo_unit;
13401   struct dwo_file *dwo_file;
13402
13403   gdb_assert (!per_cu->is_debug_types);
13404   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13405   gdb_assert (per_cu->cu != NULL);
13406
13407   dwo_unit = per_cu->cu->dwo_unit;
13408   gdb_assert (dwo_unit != NULL);
13409
13410   dwo_file = dwo_unit->dwo_file;
13411   if (dwo_file->tus != NULL)
13412     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13413 }
13414
13415 /* Free all resources associated with DWO_FILE.
13416    Close the DWO file and munmap the sections.  */
13417
13418 static void
13419 free_dwo_file (struct dwo_file *dwo_file)
13420 {
13421   /* Note: dbfd is NULL for virtual DWO files.  */
13422   gdb_bfd_unref (dwo_file->dbfd);
13423
13424   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13425 }
13426
13427 /* Traversal function for free_dwo_files.  */
13428
13429 static int
13430 free_dwo_file_from_slot (void **slot, void *info)
13431 {
13432   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13433
13434   free_dwo_file (dwo_file);
13435
13436   return 1;
13437 }
13438
13439 /* Free all resources associated with DWO_FILES.  */
13440
13441 static void
13442 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13443 {
13444   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13445 }
13446 \f
13447 /* Read in various DIEs.  */
13448
13449 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13450    Inherit only the children of the DW_AT_abstract_origin DIE not being
13451    already referenced by DW_AT_abstract_origin from the children of the
13452    current DIE.  */
13453
13454 static void
13455 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13456 {
13457   struct die_info *child_die;
13458   sect_offset *offsetp;
13459   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13460   struct die_info *origin_die;
13461   /* Iterator of the ORIGIN_DIE children.  */
13462   struct die_info *origin_child_die;
13463   struct attribute *attr;
13464   struct dwarf2_cu *origin_cu;
13465   struct pending **origin_previous_list_in_scope;
13466
13467   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13468   if (!attr)
13469     return;
13470
13471   /* Note that following die references may follow to a die in a
13472      different cu.  */
13473
13474   origin_cu = cu;
13475   origin_die = follow_die_ref (die, attr, &origin_cu);
13476
13477   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13478      symbols in.  */
13479   origin_previous_list_in_scope = origin_cu->list_in_scope;
13480   origin_cu->list_in_scope = cu->list_in_scope;
13481
13482   if (die->tag != origin_die->tag
13483       && !(die->tag == DW_TAG_inlined_subroutine
13484            && origin_die->tag == DW_TAG_subprogram))
13485     complaint (&symfile_complaints,
13486                _("DIE %s and its abstract origin %s have different tags"),
13487                sect_offset_str (die->sect_off),
13488                sect_offset_str (origin_die->sect_off));
13489
13490   std::vector<sect_offset> offsets;
13491
13492   for (child_die = die->child;
13493        child_die && child_die->tag;
13494        child_die = sibling_die (child_die))
13495     {
13496       struct die_info *child_origin_die;
13497       struct dwarf2_cu *child_origin_cu;
13498
13499       /* We are trying to process concrete instance entries:
13500          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13501          it's not relevant to our analysis here. i.e. detecting DIEs that are
13502          present in the abstract instance but not referenced in the concrete
13503          one.  */
13504       if (child_die->tag == DW_TAG_call_site
13505           || child_die->tag == DW_TAG_GNU_call_site)
13506         continue;
13507
13508       /* For each CHILD_DIE, find the corresponding child of
13509          ORIGIN_DIE.  If there is more than one layer of
13510          DW_AT_abstract_origin, follow them all; there shouldn't be,
13511          but GCC versions at least through 4.4 generate this (GCC PR
13512          40573).  */
13513       child_origin_die = child_die;
13514       child_origin_cu = cu;
13515       while (1)
13516         {
13517           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13518                               child_origin_cu);
13519           if (attr == NULL)
13520             break;
13521           child_origin_die = follow_die_ref (child_origin_die, attr,
13522                                              &child_origin_cu);
13523         }
13524
13525       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13526          counterpart may exist.  */
13527       if (child_origin_die != child_die)
13528         {
13529           if (child_die->tag != child_origin_die->tag
13530               && !(child_die->tag == DW_TAG_inlined_subroutine
13531                    && child_origin_die->tag == DW_TAG_subprogram))
13532             complaint (&symfile_complaints,
13533                        _("Child DIE %s and its abstract origin %s have "
13534                          "different tags"),
13535                        sect_offset_str (child_die->sect_off),
13536                        sect_offset_str (child_origin_die->sect_off));
13537           if (child_origin_die->parent != origin_die)
13538             complaint (&symfile_complaints,
13539                        _("Child DIE %s and its abstract origin %s have "
13540                          "different parents"),
13541                        sect_offset_str (child_die->sect_off),
13542                        sect_offset_str (child_origin_die->sect_off));
13543           else
13544             offsets.push_back (child_origin_die->sect_off);
13545         }
13546     }
13547   std::sort (offsets.begin (), offsets.end ());
13548   sect_offset *offsets_end = offsets.data () + offsets.size ();
13549   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13550     if (offsetp[-1] == *offsetp)
13551       complaint (&symfile_complaints,
13552                  _("Multiple children of DIE %s refer "
13553                    "to DIE %s as their abstract origin"),
13554                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13555
13556   offsetp = offsets.data ();
13557   origin_child_die = origin_die->child;
13558   while (origin_child_die && origin_child_die->tag)
13559     {
13560       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13561       while (offsetp < offsets_end
13562              && *offsetp < origin_child_die->sect_off)
13563         offsetp++;
13564       if (offsetp >= offsets_end
13565           || *offsetp > origin_child_die->sect_off)
13566         {
13567           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13568              Check whether we're already processing ORIGIN_CHILD_DIE.
13569              This can happen with mutually referenced abstract_origins.
13570              PR 16581.  */
13571           if (!origin_child_die->in_process)
13572             process_die (origin_child_die, origin_cu);
13573         }
13574       origin_child_die = sibling_die (origin_child_die);
13575     }
13576   origin_cu->list_in_scope = origin_previous_list_in_scope;
13577 }
13578
13579 static void
13580 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13581 {
13582   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13583   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13584   struct context_stack *newobj;
13585   CORE_ADDR lowpc;
13586   CORE_ADDR highpc;
13587   struct die_info *child_die;
13588   struct attribute *attr, *call_line, *call_file;
13589   const char *name;
13590   CORE_ADDR baseaddr;
13591   struct block *block;
13592   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13593   std::vector<struct symbol *> template_args;
13594   struct template_symbol *templ_func = NULL;
13595
13596   if (inlined_func)
13597     {
13598       /* If we do not have call site information, we can't show the
13599          caller of this inlined function.  That's too confusing, so
13600          only use the scope for local variables.  */
13601       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13602       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13603       if (call_line == NULL || call_file == NULL)
13604         {
13605           read_lexical_block_scope (die, cu);
13606           return;
13607         }
13608     }
13609
13610   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13611
13612   name = dwarf2_name (die, cu);
13613
13614   /* Ignore functions with missing or empty names.  These are actually
13615      illegal according to the DWARF standard.  */
13616   if (name == NULL)
13617     {
13618       complaint (&symfile_complaints,
13619                  _("missing name for subprogram DIE at %s"),
13620                  sect_offset_str (die->sect_off));
13621       return;
13622     }
13623
13624   /* Ignore functions with missing or invalid low and high pc attributes.  */
13625   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13626       <= PC_BOUNDS_INVALID)
13627     {
13628       attr = dwarf2_attr (die, DW_AT_external, cu);
13629       if (!attr || !DW_UNSND (attr))
13630         complaint (&symfile_complaints,
13631                    _("cannot get low and high bounds "
13632                      "for subprogram DIE at %s"),
13633                    sect_offset_str (die->sect_off));
13634       return;
13635     }
13636
13637   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13638   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13639
13640   /* If we have any template arguments, then we must allocate a
13641      different sort of symbol.  */
13642   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13643     {
13644       if (child_die->tag == DW_TAG_template_type_param
13645           || child_die->tag == DW_TAG_template_value_param)
13646         {
13647           templ_func = allocate_template_symbol (objfile);
13648           templ_func->subclass = SYMBOL_TEMPLATE;
13649           break;
13650         }
13651     }
13652
13653   newobj = push_context (0, lowpc);
13654   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13655                              (struct symbol *) templ_func);
13656
13657   /* If there is a location expression for DW_AT_frame_base, record
13658      it.  */
13659   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13660   if (attr)
13661     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13662
13663   /* If there is a location for the static link, record it.  */
13664   newobj->static_link = NULL;
13665   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13666   if (attr)
13667     {
13668       newobj->static_link
13669         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13670       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13671     }
13672
13673   cu->list_in_scope = &local_symbols;
13674
13675   if (die->child != NULL)
13676     {
13677       child_die = die->child;
13678       while (child_die && child_die->tag)
13679         {
13680           if (child_die->tag == DW_TAG_template_type_param
13681               || child_die->tag == DW_TAG_template_value_param)
13682             {
13683               struct symbol *arg = new_symbol (child_die, NULL, cu);
13684
13685               if (arg != NULL)
13686                 template_args.push_back (arg);
13687             }
13688           else
13689             process_die (child_die, cu);
13690           child_die = sibling_die (child_die);
13691         }
13692     }
13693
13694   inherit_abstract_dies (die, cu);
13695
13696   /* If we have a DW_AT_specification, we might need to import using
13697      directives from the context of the specification DIE.  See the
13698      comment in determine_prefix.  */
13699   if (cu->language == language_cplus
13700       && dwarf2_attr (die, DW_AT_specification, cu))
13701     {
13702       struct dwarf2_cu *spec_cu = cu;
13703       struct die_info *spec_die = die_specification (die, &spec_cu);
13704
13705       while (spec_die)
13706         {
13707           child_die = spec_die->child;
13708           while (child_die && child_die->tag)
13709             {
13710               if (child_die->tag == DW_TAG_imported_module)
13711                 process_die (child_die, spec_cu);
13712               child_die = sibling_die (child_die);
13713             }
13714
13715           /* In some cases, GCC generates specification DIEs that
13716              themselves contain DW_AT_specification attributes.  */
13717           spec_die = die_specification (spec_die, &spec_cu);
13718         }
13719     }
13720
13721   newobj = pop_context ();
13722   /* Make a block for the local symbols within.  */
13723   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13724                         newobj->static_link, lowpc, highpc);
13725
13726   /* For C++, set the block's scope.  */
13727   if ((cu->language == language_cplus
13728        || cu->language == language_fortran
13729        || cu->language == language_d
13730        || cu->language == language_rust)
13731       && cu->processing_has_namespace_info)
13732     block_set_scope (block, determine_prefix (die, cu),
13733                      &objfile->objfile_obstack);
13734
13735   /* If we have address ranges, record them.  */
13736   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13737
13738   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13739
13740   /* Attach template arguments to function.  */
13741   if (!template_args.empty ())
13742     {
13743       gdb_assert (templ_func != NULL);
13744
13745       templ_func->n_template_arguments = template_args.size ();
13746       templ_func->template_arguments
13747         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13748                      templ_func->n_template_arguments);
13749       memcpy (templ_func->template_arguments,
13750               template_args.data (),
13751               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13752     }
13753
13754   /* In C++, we can have functions nested inside functions (e.g., when
13755      a function declares a class that has methods).  This means that
13756      when we finish processing a function scope, we may need to go
13757      back to building a containing block's symbol lists.  */
13758   local_symbols = newobj->locals;
13759   local_using_directives = newobj->local_using_directives;
13760
13761   /* If we've finished processing a top-level function, subsequent
13762      symbols go in the file symbol list.  */
13763   if (outermost_context_p ())
13764     cu->list_in_scope = &file_symbols;
13765 }
13766
13767 /* Process all the DIES contained within a lexical block scope.  Start
13768    a new scope, process the dies, and then close the scope.  */
13769
13770 static void
13771 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13772 {
13773   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13774   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13775   struct context_stack *newobj;
13776   CORE_ADDR lowpc, highpc;
13777   struct die_info *child_die;
13778   CORE_ADDR baseaddr;
13779
13780   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13781
13782   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13783   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13784      as multiple lexical blocks?  Handling children in a sane way would
13785      be nasty.  Might be easier to properly extend generic blocks to
13786      describe ranges.  */
13787   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13788     {
13789     case PC_BOUNDS_NOT_PRESENT:
13790       /* DW_TAG_lexical_block has no attributes, process its children as if
13791          there was no wrapping by that DW_TAG_lexical_block.
13792          GCC does no longer produces such DWARF since GCC r224161.  */
13793       for (child_die = die->child;
13794            child_die != NULL && child_die->tag;
13795            child_die = sibling_die (child_die))
13796         process_die (child_die, cu);
13797       return;
13798     case PC_BOUNDS_INVALID:
13799       return;
13800     }
13801   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13802   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13803
13804   push_context (0, lowpc);
13805   if (die->child != NULL)
13806     {
13807       child_die = die->child;
13808       while (child_die && child_die->tag)
13809         {
13810           process_die (child_die, cu);
13811           child_die = sibling_die (child_die);
13812         }
13813     }
13814   inherit_abstract_dies (die, cu);
13815   newobj = pop_context ();
13816
13817   if (local_symbols != NULL || local_using_directives != NULL)
13818     {
13819       struct block *block
13820         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13821                         newobj->start_addr, highpc);
13822
13823       /* Note that recording ranges after traversing children, as we
13824          do here, means that recording a parent's ranges entails
13825          walking across all its children's ranges as they appear in
13826          the address map, which is quadratic behavior.
13827
13828          It would be nicer to record the parent's ranges before
13829          traversing its children, simply overriding whatever you find
13830          there.  But since we don't even decide whether to create a
13831          block until after we've traversed its children, that's hard
13832          to do.  */
13833       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13834     }
13835   local_symbols = newobj->locals;
13836   local_using_directives = newobj->local_using_directives;
13837 }
13838
13839 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13840
13841 static void
13842 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13843 {
13844   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13845   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13846   CORE_ADDR pc, baseaddr;
13847   struct attribute *attr;
13848   struct call_site *call_site, call_site_local;
13849   void **slot;
13850   int nparams;
13851   struct die_info *child_die;
13852
13853   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13854
13855   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13856   if (attr == NULL)
13857     {
13858       /* This was a pre-DWARF-5 GNU extension alias
13859          for DW_AT_call_return_pc.  */
13860       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13861     }
13862   if (!attr)
13863     {
13864       complaint (&symfile_complaints,
13865                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
13866                    "DIE %s [in module %s]"),
13867                  sect_offset_str (die->sect_off), objfile_name (objfile));
13868       return;
13869     }
13870   pc = attr_value_as_address (attr) + baseaddr;
13871   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13872
13873   if (cu->call_site_htab == NULL)
13874     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13875                                                NULL, &objfile->objfile_obstack,
13876                                                hashtab_obstack_allocate, NULL);
13877   call_site_local.pc = pc;
13878   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13879   if (*slot != NULL)
13880     {
13881       complaint (&symfile_complaints,
13882                  _("Duplicate PC %s for DW_TAG_call_site "
13883                    "DIE %s [in module %s]"),
13884                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13885                  objfile_name (objfile));
13886       return;
13887     }
13888
13889   /* Count parameters at the caller.  */
13890
13891   nparams = 0;
13892   for (child_die = die->child; child_die && child_die->tag;
13893        child_die = sibling_die (child_die))
13894     {
13895       if (child_die->tag != DW_TAG_call_site_parameter
13896           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13897         {
13898           complaint (&symfile_complaints,
13899                      _("Tag %d is not DW_TAG_call_site_parameter in "
13900                        "DW_TAG_call_site child DIE %s [in module %s]"),
13901                      child_die->tag, sect_offset_str (child_die->sect_off),
13902                      objfile_name (objfile));
13903           continue;
13904         }
13905
13906       nparams++;
13907     }
13908
13909   call_site
13910     = ((struct call_site *)
13911        obstack_alloc (&objfile->objfile_obstack,
13912                       sizeof (*call_site)
13913                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13914   *slot = call_site;
13915   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13916   call_site->pc = pc;
13917
13918   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13919       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13920     {
13921       struct die_info *func_die;
13922
13923       /* Skip also over DW_TAG_inlined_subroutine.  */
13924       for (func_die = die->parent;
13925            func_die && func_die->tag != DW_TAG_subprogram
13926            && func_die->tag != DW_TAG_subroutine_type;
13927            func_die = func_die->parent);
13928
13929       /* DW_AT_call_all_calls is a superset
13930          of DW_AT_call_all_tail_calls.  */
13931       if (func_die
13932           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13933           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13934           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13935           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13936         {
13937           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13938              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13939              both the initial caller containing the real return address PC and
13940              the final callee containing the current PC of a chain of tail
13941              calls do not need to have the tail call list complete.  But any
13942              function candidate for a virtual tail call frame searched via
13943              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13944              determined unambiguously.  */
13945         }
13946       else
13947         {
13948           struct type *func_type = NULL;
13949
13950           if (func_die)
13951             func_type = get_die_type (func_die, cu);
13952           if (func_type != NULL)
13953             {
13954               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13955
13956               /* Enlist this call site to the function.  */
13957               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13958               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13959             }
13960           else
13961             complaint (&symfile_complaints,
13962                        _("Cannot find function owning DW_TAG_call_site "
13963                          "DIE %s [in module %s]"),
13964                        sect_offset_str (die->sect_off), objfile_name (objfile));
13965         }
13966     }
13967
13968   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13969   if (attr == NULL)
13970     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13971   if (attr == NULL)
13972     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13973   if (attr == NULL)
13974     {
13975       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13976       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13977     }
13978   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13979   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13980     /* Keep NULL DWARF_BLOCK.  */;
13981   else if (attr_form_is_block (attr))
13982     {
13983       struct dwarf2_locexpr_baton *dlbaton;
13984
13985       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13986       dlbaton->data = DW_BLOCK (attr)->data;
13987       dlbaton->size = DW_BLOCK (attr)->size;
13988       dlbaton->per_cu = cu->per_cu;
13989
13990       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13991     }
13992   else if (attr_form_is_ref (attr))
13993     {
13994       struct dwarf2_cu *target_cu = cu;
13995       struct die_info *target_die;
13996
13997       target_die = follow_die_ref (die, attr, &target_cu);
13998       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13999       if (die_is_declaration (target_die, target_cu))
14000         {
14001           const char *target_physname;
14002
14003           /* Prefer the mangled name; otherwise compute the demangled one.  */
14004           target_physname = dw2_linkage_name (target_die, target_cu);
14005           if (target_physname == NULL)
14006             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14007           if (target_physname == NULL)
14008             complaint (&symfile_complaints,
14009                        _("DW_AT_call_target target DIE has invalid "
14010                          "physname, for referencing DIE %s [in module %s]"),
14011                        sect_offset_str (die->sect_off), objfile_name (objfile));
14012           else
14013             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14014         }
14015       else
14016         {
14017           CORE_ADDR lowpc;
14018
14019           /* DW_AT_entry_pc should be preferred.  */
14020           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14021               <= PC_BOUNDS_INVALID)
14022             complaint (&symfile_complaints,
14023                        _("DW_AT_call_target target DIE has invalid "
14024                          "low pc, for referencing DIE %s [in module %s]"),
14025                        sect_offset_str (die->sect_off), objfile_name (objfile));
14026           else
14027             {
14028               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14029               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14030             }
14031         }
14032     }
14033   else
14034     complaint (&symfile_complaints,
14035                _("DW_TAG_call_site DW_AT_call_target is neither "
14036                  "block nor reference, for DIE %s [in module %s]"),
14037                sect_offset_str (die->sect_off), objfile_name (objfile));
14038
14039   call_site->per_cu = cu->per_cu;
14040
14041   for (child_die = die->child;
14042        child_die && child_die->tag;
14043        child_die = sibling_die (child_die))
14044     {
14045       struct call_site_parameter *parameter;
14046       struct attribute *loc, *origin;
14047
14048       if (child_die->tag != DW_TAG_call_site_parameter
14049           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14050         {
14051           /* Already printed the complaint above.  */
14052           continue;
14053         }
14054
14055       gdb_assert (call_site->parameter_count < nparams);
14056       parameter = &call_site->parameter[call_site->parameter_count];
14057
14058       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14059          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14060          register is contained in DW_AT_call_value.  */
14061
14062       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14063       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14064       if (origin == NULL)
14065         {
14066           /* This was a pre-DWARF-5 GNU extension alias
14067              for DW_AT_call_parameter.  */
14068           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14069         }
14070       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14071         {
14072           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14073
14074           sect_offset sect_off
14075             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14076           if (!offset_in_cu_p (&cu->header, sect_off))
14077             {
14078               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14079                  binding can be done only inside one CU.  Such referenced DIE
14080                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14081               complaint (&symfile_complaints,
14082                          _("DW_AT_call_parameter offset is not in CU for "
14083                            "DW_TAG_call_site child DIE %s [in module %s]"),
14084                          sect_offset_str (child_die->sect_off),
14085                          objfile_name (objfile));
14086               continue;
14087             }
14088           parameter->u.param_cu_off
14089             = (cu_offset) (sect_off - cu->header.sect_off);
14090         }
14091       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14092         {
14093           complaint (&symfile_complaints,
14094                      _("No DW_FORM_block* DW_AT_location for "
14095                        "DW_TAG_call_site child DIE %s [in module %s]"),
14096                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14097           continue;
14098         }
14099       else
14100         {
14101           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14102             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14103           if (parameter->u.dwarf_reg != -1)
14104             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14105           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14106                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14107                                              &parameter->u.fb_offset))
14108             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14109           else
14110             {
14111               complaint (&symfile_complaints,
14112                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14113                            "for DW_FORM_block* DW_AT_location is supported for "
14114                            "DW_TAG_call_site child DIE %s "
14115                            "[in module %s]"),
14116                          sect_offset_str (child_die->sect_off),
14117                          objfile_name (objfile));
14118               continue;
14119             }
14120         }
14121
14122       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14123       if (attr == NULL)
14124         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14125       if (!attr_form_is_block (attr))
14126         {
14127           complaint (&symfile_complaints,
14128                      _("No DW_FORM_block* DW_AT_call_value for "
14129                        "DW_TAG_call_site child DIE %s [in module %s]"),
14130                      sect_offset_str (child_die->sect_off),
14131                      objfile_name (objfile));
14132           continue;
14133         }
14134       parameter->value = DW_BLOCK (attr)->data;
14135       parameter->value_size = DW_BLOCK (attr)->size;
14136
14137       /* Parameters are not pre-cleared by memset above.  */
14138       parameter->data_value = NULL;
14139       parameter->data_value_size = 0;
14140       call_site->parameter_count++;
14141
14142       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14143       if (attr == NULL)
14144         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14145       if (attr)
14146         {
14147           if (!attr_form_is_block (attr))
14148             complaint (&symfile_complaints,
14149                        _("No DW_FORM_block* DW_AT_call_data_value for "
14150                          "DW_TAG_call_site child DIE %s [in module %s]"),
14151                        sect_offset_str (child_die->sect_off),
14152                        objfile_name (objfile));
14153           else
14154             {
14155               parameter->data_value = DW_BLOCK (attr)->data;
14156               parameter->data_value_size = DW_BLOCK (attr)->size;
14157             }
14158         }
14159     }
14160 }
14161
14162 /* Helper function for read_variable.  If DIE represents a virtual
14163    table, then return the type of the concrete object that is
14164    associated with the virtual table.  Otherwise, return NULL.  */
14165
14166 static struct type *
14167 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14168 {
14169   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14170   if (attr == NULL)
14171     return NULL;
14172
14173   /* Find the type DIE.  */
14174   struct die_info *type_die = NULL;
14175   struct dwarf2_cu *type_cu = cu;
14176
14177   if (attr_form_is_ref (attr))
14178     type_die = follow_die_ref (die, attr, &type_cu);
14179   if (type_die == NULL)
14180     return NULL;
14181
14182   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14183     return NULL;
14184   return die_containing_type (type_die, type_cu);
14185 }
14186
14187 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14188
14189 static void
14190 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14191 {
14192   struct rust_vtable_symbol *storage = NULL;
14193
14194   if (cu->language == language_rust)
14195     {
14196       struct type *containing_type = rust_containing_type (die, cu);
14197
14198       if (containing_type != NULL)
14199         {
14200           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14201
14202           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14203                                     struct rust_vtable_symbol);
14204           initialize_objfile_symbol (storage);
14205           storage->concrete_type = containing_type;
14206           storage->subclass = SYMBOL_RUST_VTABLE;
14207         }
14208     }
14209
14210   new_symbol (die, NULL, cu, storage);
14211 }
14212
14213 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14214    reading .debug_rnglists.
14215    Callback's type should be:
14216     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14217    Return true if the attributes are present and valid, otherwise,
14218    return false.  */
14219
14220 template <typename Callback>
14221 static bool
14222 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14223                          Callback &&callback)
14224 {
14225   struct dwarf2_per_objfile *dwarf2_per_objfile
14226     = cu->per_cu->dwarf2_per_objfile;
14227   struct objfile *objfile = dwarf2_per_objfile->objfile;
14228   bfd *obfd = objfile->obfd;
14229   /* Base address selection entry.  */
14230   CORE_ADDR base;
14231   int found_base;
14232   const gdb_byte *buffer;
14233   CORE_ADDR baseaddr;
14234   bool overflow = false;
14235
14236   found_base = cu->base_known;
14237   base = cu->base_address;
14238
14239   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14240   if (offset >= dwarf2_per_objfile->rnglists.size)
14241     {
14242       complaint (&symfile_complaints,
14243                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14244                  offset);
14245       return false;
14246     }
14247   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14248
14249   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14250
14251   while (1)
14252     {
14253       /* Initialize it due to a false compiler warning.  */
14254       CORE_ADDR range_beginning = 0, range_end = 0;
14255       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14256                                  + dwarf2_per_objfile->rnglists.size);
14257       unsigned int bytes_read;
14258
14259       if (buffer == buf_end)
14260         {
14261           overflow = true;
14262           break;
14263         }
14264       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14265       switch (rlet)
14266         {
14267         case DW_RLE_end_of_list:
14268           break;
14269         case DW_RLE_base_address:
14270           if (buffer + cu->header.addr_size > buf_end)
14271             {
14272               overflow = true;
14273               break;
14274             }
14275           base = read_address (obfd, buffer, cu, &bytes_read);
14276           found_base = 1;
14277           buffer += bytes_read;
14278           break;
14279         case DW_RLE_start_length:
14280           if (buffer + cu->header.addr_size > buf_end)
14281             {
14282               overflow = true;
14283               break;
14284             }
14285           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14286           buffer += bytes_read;
14287           range_end = (range_beginning
14288                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14289           buffer += bytes_read;
14290           if (buffer > buf_end)
14291             {
14292               overflow = true;
14293               break;
14294             }
14295           break;
14296         case DW_RLE_offset_pair:
14297           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14298           buffer += bytes_read;
14299           if (buffer > buf_end)
14300             {
14301               overflow = true;
14302               break;
14303             }
14304           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14305           buffer += bytes_read;
14306           if (buffer > buf_end)
14307             {
14308               overflow = true;
14309               break;
14310             }
14311           break;
14312         case DW_RLE_start_end:
14313           if (buffer + 2 * cu->header.addr_size > buf_end)
14314             {
14315               overflow = true;
14316               break;
14317             }
14318           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14319           buffer += bytes_read;
14320           range_end = read_address (obfd, buffer, cu, &bytes_read);
14321           buffer += bytes_read;
14322           break;
14323         default:
14324           complaint (&symfile_complaints,
14325                      _("Invalid .debug_rnglists data (no base address)"));
14326           return false;
14327         }
14328       if (rlet == DW_RLE_end_of_list || overflow)
14329         break;
14330       if (rlet == DW_RLE_base_address)
14331         continue;
14332
14333       if (!found_base)
14334         {
14335           /* We have no valid base address for the ranges
14336              data.  */
14337           complaint (&symfile_complaints,
14338                      _("Invalid .debug_rnglists data (no base address)"));
14339           return false;
14340         }
14341
14342       if (range_beginning > range_end)
14343         {
14344           /* Inverted range entries are invalid.  */
14345           complaint (&symfile_complaints,
14346                      _("Invalid .debug_rnglists data (inverted range)"));
14347           return false;
14348         }
14349
14350       /* Empty range entries have no effect.  */
14351       if (range_beginning == range_end)
14352         continue;
14353
14354       range_beginning += base;
14355       range_end += base;
14356
14357       /* A not-uncommon case of bad debug info.
14358          Don't pollute the addrmap with bad data.  */
14359       if (range_beginning + baseaddr == 0
14360           && !dwarf2_per_objfile->has_section_at_zero)
14361         {
14362           complaint (&symfile_complaints,
14363                      _(".debug_rnglists entry has start address of zero"
14364                        " [in module %s]"), objfile_name (objfile));
14365           continue;
14366         }
14367
14368       callback (range_beginning, range_end);
14369     }
14370
14371   if (overflow)
14372     {
14373       complaint (&symfile_complaints,
14374                  _("Offset %d is not terminated "
14375                    "for DW_AT_ranges attribute"),
14376                  offset);
14377       return false;
14378     }
14379
14380   return true;
14381 }
14382
14383 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14384    Callback's type should be:
14385     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14386    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14387
14388 template <typename Callback>
14389 static int
14390 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14391                        Callback &&callback)
14392 {
14393   struct dwarf2_per_objfile *dwarf2_per_objfile
14394       = cu->per_cu->dwarf2_per_objfile;
14395   struct objfile *objfile = dwarf2_per_objfile->objfile;
14396   struct comp_unit_head *cu_header = &cu->header;
14397   bfd *obfd = objfile->obfd;
14398   unsigned int addr_size = cu_header->addr_size;
14399   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14400   /* Base address selection entry.  */
14401   CORE_ADDR base;
14402   int found_base;
14403   unsigned int dummy;
14404   const gdb_byte *buffer;
14405   CORE_ADDR baseaddr;
14406
14407   if (cu_header->version >= 5)
14408     return dwarf2_rnglists_process (offset, cu, callback);
14409
14410   found_base = cu->base_known;
14411   base = cu->base_address;
14412
14413   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14414   if (offset >= dwarf2_per_objfile->ranges.size)
14415     {
14416       complaint (&symfile_complaints,
14417                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14418                  offset);
14419       return 0;
14420     }
14421   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14422
14423   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14424
14425   while (1)
14426     {
14427       CORE_ADDR range_beginning, range_end;
14428
14429       range_beginning = read_address (obfd, buffer, cu, &dummy);
14430       buffer += addr_size;
14431       range_end = read_address (obfd, buffer, cu, &dummy);
14432       buffer += addr_size;
14433       offset += 2 * addr_size;
14434
14435       /* An end of list marker is a pair of zero addresses.  */
14436       if (range_beginning == 0 && range_end == 0)
14437         /* Found the end of list entry.  */
14438         break;
14439
14440       /* Each base address selection entry is a pair of 2 values.
14441          The first is the largest possible address, the second is
14442          the base address.  Check for a base address here.  */
14443       if ((range_beginning & mask) == mask)
14444         {
14445           /* If we found the largest possible address, then we already
14446              have the base address in range_end.  */
14447           base = range_end;
14448           found_base = 1;
14449           continue;
14450         }
14451
14452       if (!found_base)
14453         {
14454           /* We have no valid base address for the ranges
14455              data.  */
14456           complaint (&symfile_complaints,
14457                      _("Invalid .debug_ranges data (no base address)"));
14458           return 0;
14459         }
14460
14461       if (range_beginning > range_end)
14462         {
14463           /* Inverted range entries are invalid.  */
14464           complaint (&symfile_complaints,
14465                      _("Invalid .debug_ranges data (inverted range)"));
14466           return 0;
14467         }
14468
14469       /* Empty range entries have no effect.  */
14470       if (range_beginning == range_end)
14471         continue;
14472
14473       range_beginning += base;
14474       range_end += base;
14475
14476       /* A not-uncommon case of bad debug info.
14477          Don't pollute the addrmap with bad data.  */
14478       if (range_beginning + baseaddr == 0
14479           && !dwarf2_per_objfile->has_section_at_zero)
14480         {
14481           complaint (&symfile_complaints,
14482                      _(".debug_ranges entry has start address of zero"
14483                        " [in module %s]"), objfile_name (objfile));
14484           continue;
14485         }
14486
14487       callback (range_beginning, range_end);
14488     }
14489
14490   return 1;
14491 }
14492
14493 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14494    Return 1 if the attributes are present and valid, otherwise, return 0.
14495    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14496
14497 static int
14498 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14499                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14500                     struct partial_symtab *ranges_pst)
14501 {
14502   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14503   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14504   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14505                                        SECT_OFF_TEXT (objfile));
14506   int low_set = 0;
14507   CORE_ADDR low = 0;
14508   CORE_ADDR high = 0;
14509   int retval;
14510
14511   retval = dwarf2_ranges_process (offset, cu,
14512     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14513     {
14514       if (ranges_pst != NULL)
14515         {
14516           CORE_ADDR lowpc;
14517           CORE_ADDR highpc;
14518
14519           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14520                                               range_beginning + baseaddr);
14521           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14522                                                range_end + baseaddr);
14523           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14524                              ranges_pst);
14525         }
14526
14527       /* FIXME: This is recording everything as a low-high
14528          segment of consecutive addresses.  We should have a
14529          data structure for discontiguous block ranges
14530          instead.  */
14531       if (! low_set)
14532         {
14533           low = range_beginning;
14534           high = range_end;
14535           low_set = 1;
14536         }
14537       else
14538         {
14539           if (range_beginning < low)
14540             low = range_beginning;
14541           if (range_end > high)
14542             high = range_end;
14543         }
14544     });
14545   if (!retval)
14546     return 0;
14547
14548   if (! low_set)
14549     /* If the first entry is an end-of-list marker, the range
14550        describes an empty scope, i.e. no instructions.  */
14551     return 0;
14552
14553   if (low_return)
14554     *low_return = low;
14555   if (high_return)
14556     *high_return = high;
14557   return 1;
14558 }
14559
14560 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14561    definition for the return value.  *LOWPC and *HIGHPC are set iff
14562    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14563
14564 static enum pc_bounds_kind
14565 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14566                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14567                       struct partial_symtab *pst)
14568 {
14569   struct dwarf2_per_objfile *dwarf2_per_objfile
14570     = cu->per_cu->dwarf2_per_objfile;
14571   struct attribute *attr;
14572   struct attribute *attr_high;
14573   CORE_ADDR low = 0;
14574   CORE_ADDR high = 0;
14575   enum pc_bounds_kind ret;
14576
14577   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14578   if (attr_high)
14579     {
14580       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14581       if (attr)
14582         {
14583           low = attr_value_as_address (attr);
14584           high = attr_value_as_address (attr_high);
14585           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14586             high += low;
14587         }
14588       else
14589         /* Found high w/o low attribute.  */
14590         return PC_BOUNDS_INVALID;
14591
14592       /* Found consecutive range of addresses.  */
14593       ret = PC_BOUNDS_HIGH_LOW;
14594     }
14595   else
14596     {
14597       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14598       if (attr != NULL)
14599         {
14600           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14601              We take advantage of the fact that DW_AT_ranges does not appear
14602              in DW_TAG_compile_unit of DWO files.  */
14603           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14604           unsigned int ranges_offset = (DW_UNSND (attr)
14605                                         + (need_ranges_base
14606                                            ? cu->ranges_base
14607                                            : 0));
14608
14609           /* Value of the DW_AT_ranges attribute is the offset in the
14610              .debug_ranges section.  */
14611           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14612             return PC_BOUNDS_INVALID;
14613           /* Found discontinuous range of addresses.  */
14614           ret = PC_BOUNDS_RANGES;
14615         }
14616       else
14617         return PC_BOUNDS_NOT_PRESENT;
14618     }
14619
14620   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14621   if (high <= low)
14622     return PC_BOUNDS_INVALID;
14623
14624   /* When using the GNU linker, .gnu.linkonce. sections are used to
14625      eliminate duplicate copies of functions and vtables and such.
14626      The linker will arbitrarily choose one and discard the others.
14627      The AT_*_pc values for such functions refer to local labels in
14628      these sections.  If the section from that file was discarded, the
14629      labels are not in the output, so the relocs get a value of 0.
14630      If this is a discarded function, mark the pc bounds as invalid,
14631      so that GDB will ignore it.  */
14632   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14633     return PC_BOUNDS_INVALID;
14634
14635   *lowpc = low;
14636   if (highpc)
14637     *highpc = high;
14638   return ret;
14639 }
14640
14641 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14642    its low and high PC addresses.  Do nothing if these addresses could not
14643    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14644    and HIGHPC to the high address if greater than HIGHPC.  */
14645
14646 static void
14647 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14648                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14649                                  struct dwarf2_cu *cu)
14650 {
14651   CORE_ADDR low, high;
14652   struct die_info *child = die->child;
14653
14654   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14655     {
14656       *lowpc = std::min (*lowpc, low);
14657       *highpc = std::max (*highpc, high);
14658     }
14659
14660   /* If the language does not allow nested subprograms (either inside
14661      subprograms or lexical blocks), we're done.  */
14662   if (cu->language != language_ada)
14663     return;
14664
14665   /* Check all the children of the given DIE.  If it contains nested
14666      subprograms, then check their pc bounds.  Likewise, we need to
14667      check lexical blocks as well, as they may also contain subprogram
14668      definitions.  */
14669   while (child && child->tag)
14670     {
14671       if (child->tag == DW_TAG_subprogram
14672           || child->tag == DW_TAG_lexical_block)
14673         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14674       child = sibling_die (child);
14675     }
14676 }
14677
14678 /* Get the low and high pc's represented by the scope DIE, and store
14679    them in *LOWPC and *HIGHPC.  If the correct values can't be
14680    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14681
14682 static void
14683 get_scope_pc_bounds (struct die_info *die,
14684                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14685                      struct dwarf2_cu *cu)
14686 {
14687   CORE_ADDR best_low = (CORE_ADDR) -1;
14688   CORE_ADDR best_high = (CORE_ADDR) 0;
14689   CORE_ADDR current_low, current_high;
14690
14691   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14692       >= PC_BOUNDS_RANGES)
14693     {
14694       best_low = current_low;
14695       best_high = current_high;
14696     }
14697   else
14698     {
14699       struct die_info *child = die->child;
14700
14701       while (child && child->tag)
14702         {
14703           switch (child->tag) {
14704           case DW_TAG_subprogram:
14705             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14706             break;
14707           case DW_TAG_namespace:
14708           case DW_TAG_module:
14709             /* FIXME: carlton/2004-01-16: Should we do this for
14710                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14711                that current GCC's always emit the DIEs corresponding
14712                to definitions of methods of classes as children of a
14713                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14714                the DIEs giving the declarations, which could be
14715                anywhere).  But I don't see any reason why the
14716                standards says that they have to be there.  */
14717             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14718
14719             if (current_low != ((CORE_ADDR) -1))
14720               {
14721                 best_low = std::min (best_low, current_low);
14722                 best_high = std::max (best_high, current_high);
14723               }
14724             break;
14725           default:
14726             /* Ignore.  */
14727             break;
14728           }
14729
14730           child = sibling_die (child);
14731         }
14732     }
14733
14734   *lowpc = best_low;
14735   *highpc = best_high;
14736 }
14737
14738 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14739    in DIE.  */
14740
14741 static void
14742 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14743                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14744 {
14745   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14746   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14747   struct attribute *attr;
14748   struct attribute *attr_high;
14749
14750   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14751   if (attr_high)
14752     {
14753       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14754       if (attr)
14755         {
14756           CORE_ADDR low = attr_value_as_address (attr);
14757           CORE_ADDR high = attr_value_as_address (attr_high);
14758
14759           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14760             high += low;
14761
14762           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14763           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14764           record_block_range (block, low, high - 1);
14765         }
14766     }
14767
14768   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14769   if (attr)
14770     {
14771       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14772          We take advantage of the fact that DW_AT_ranges does not appear
14773          in DW_TAG_compile_unit of DWO files.  */
14774       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14775
14776       /* The value of the DW_AT_ranges attribute is the offset of the
14777          address range list in the .debug_ranges section.  */
14778       unsigned long offset = (DW_UNSND (attr)
14779                               + (need_ranges_base ? cu->ranges_base : 0));
14780
14781       dwarf2_ranges_process (offset, cu,
14782         [&] (CORE_ADDR start, CORE_ADDR end)
14783         {
14784           start += baseaddr;
14785           end += baseaddr;
14786           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14787           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14788           record_block_range (block, start, end - 1);
14789         });
14790     }
14791 }
14792
14793 /* Check whether the producer field indicates either of GCC < 4.6, or the
14794    Intel C/C++ compiler, and cache the result in CU.  */
14795
14796 static void
14797 check_producer (struct dwarf2_cu *cu)
14798 {
14799   int major, minor;
14800
14801   if (cu->producer == NULL)
14802     {
14803       /* For unknown compilers expect their behavior is DWARF version
14804          compliant.
14805
14806          GCC started to support .debug_types sections by -gdwarf-4 since
14807          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14808          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14809          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14810          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14811     }
14812   else if (producer_is_gcc (cu->producer, &major, &minor))
14813     {
14814       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14815       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14816     }
14817   else if (producer_is_icc (cu->producer, &major, &minor))
14818     cu->producer_is_icc_lt_14 = major < 14;
14819   else
14820     {
14821       /* For other non-GCC compilers, expect their behavior is DWARF version
14822          compliant.  */
14823     }
14824
14825   cu->checked_producer = 1;
14826 }
14827
14828 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14829    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14830    during 4.6.0 experimental.  */
14831
14832 static int
14833 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14834 {
14835   if (!cu->checked_producer)
14836     check_producer (cu);
14837
14838   return cu->producer_is_gxx_lt_4_6;
14839 }
14840
14841 /* Return the default accessibility type if it is not overriden by
14842    DW_AT_accessibility.  */
14843
14844 static enum dwarf_access_attribute
14845 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14846 {
14847   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14848     {
14849       /* The default DWARF 2 accessibility for members is public, the default
14850          accessibility for inheritance is private.  */
14851
14852       if (die->tag != DW_TAG_inheritance)
14853         return DW_ACCESS_public;
14854       else
14855         return DW_ACCESS_private;
14856     }
14857   else
14858     {
14859       /* DWARF 3+ defines the default accessibility a different way.  The same
14860          rules apply now for DW_TAG_inheritance as for the members and it only
14861          depends on the container kind.  */
14862
14863       if (die->parent->tag == DW_TAG_class_type)
14864         return DW_ACCESS_private;
14865       else
14866         return DW_ACCESS_public;
14867     }
14868 }
14869
14870 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14871    offset.  If the attribute was not found return 0, otherwise return
14872    1.  If it was found but could not properly be handled, set *OFFSET
14873    to 0.  */
14874
14875 static int
14876 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14877                              LONGEST *offset)
14878 {
14879   struct attribute *attr;
14880
14881   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14882   if (attr != NULL)
14883     {
14884       *offset = 0;
14885
14886       /* Note that we do not check for a section offset first here.
14887          This is because DW_AT_data_member_location is new in DWARF 4,
14888          so if we see it, we can assume that a constant form is really
14889          a constant and not a section offset.  */
14890       if (attr_form_is_constant (attr))
14891         *offset = dwarf2_get_attr_constant_value (attr, 0);
14892       else if (attr_form_is_section_offset (attr))
14893         dwarf2_complex_location_expr_complaint ();
14894       else if (attr_form_is_block (attr))
14895         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14896       else
14897         dwarf2_complex_location_expr_complaint ();
14898
14899       return 1;
14900     }
14901
14902   return 0;
14903 }
14904
14905 /* Add an aggregate field to the field list.  */
14906
14907 static void
14908 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14909                   struct dwarf2_cu *cu)
14910 {
14911   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14912   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14913   struct nextfield *new_field;
14914   struct attribute *attr;
14915   struct field *fp;
14916   const char *fieldname = "";
14917
14918   if (die->tag == DW_TAG_inheritance)
14919     {
14920       fip->baseclasses.emplace_back ();
14921       new_field = &fip->baseclasses.back ();
14922     }
14923   else
14924     {
14925       fip->fields.emplace_back ();
14926       new_field = &fip->fields.back ();
14927     }
14928
14929   fip->nfields++;
14930
14931   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14932   if (attr)
14933     new_field->accessibility = DW_UNSND (attr);
14934   else
14935     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14936   if (new_field->accessibility != DW_ACCESS_public)
14937     fip->non_public_fields = 1;
14938
14939   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14940   if (attr)
14941     new_field->virtuality = DW_UNSND (attr);
14942   else
14943     new_field->virtuality = DW_VIRTUALITY_none;
14944
14945   fp = &new_field->field;
14946
14947   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14948     {
14949       LONGEST offset;
14950
14951       /* Data member other than a C++ static data member.  */
14952
14953       /* Get type of field.  */
14954       fp->type = die_type (die, cu);
14955
14956       SET_FIELD_BITPOS (*fp, 0);
14957
14958       /* Get bit size of field (zero if none).  */
14959       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14960       if (attr)
14961         {
14962           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14963         }
14964       else
14965         {
14966           FIELD_BITSIZE (*fp) = 0;
14967         }
14968
14969       /* Get bit offset of field.  */
14970       if (handle_data_member_location (die, cu, &offset))
14971         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14972       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14973       if (attr)
14974         {
14975           if (gdbarch_bits_big_endian (gdbarch))
14976             {
14977               /* For big endian bits, the DW_AT_bit_offset gives the
14978                  additional bit offset from the MSB of the containing
14979                  anonymous object to the MSB of the field.  We don't
14980                  have to do anything special since we don't need to
14981                  know the size of the anonymous object.  */
14982               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14983             }
14984           else
14985             {
14986               /* For little endian bits, compute the bit offset to the
14987                  MSB of the anonymous object, subtract off the number of
14988                  bits from the MSB of the field to the MSB of the
14989                  object, and then subtract off the number of bits of
14990                  the field itself.  The result is the bit offset of
14991                  the LSB of the field.  */
14992               int anonymous_size;
14993               int bit_offset = DW_UNSND (attr);
14994
14995               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14996               if (attr)
14997                 {
14998                   /* The size of the anonymous object containing
14999                      the bit field is explicit, so use the
15000                      indicated size (in bytes).  */
15001                   anonymous_size = DW_UNSND (attr);
15002                 }
15003               else
15004                 {
15005                   /* The size of the anonymous object containing
15006                      the bit field must be inferred from the type
15007                      attribute of the data member containing the
15008                      bit field.  */
15009                   anonymous_size = TYPE_LENGTH (fp->type);
15010                 }
15011               SET_FIELD_BITPOS (*fp,
15012                                 (FIELD_BITPOS (*fp)
15013                                  + anonymous_size * bits_per_byte
15014                                  - bit_offset - FIELD_BITSIZE (*fp)));
15015             }
15016         }
15017       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15018       if (attr != NULL)
15019         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15020                                 + dwarf2_get_attr_constant_value (attr, 0)));
15021
15022       /* Get name of field.  */
15023       fieldname = dwarf2_name (die, cu);
15024       if (fieldname == NULL)
15025         fieldname = "";
15026
15027       /* The name is already allocated along with this objfile, so we don't
15028          need to duplicate it for the type.  */
15029       fp->name = fieldname;
15030
15031       /* Change accessibility for artificial fields (e.g. virtual table
15032          pointer or virtual base class pointer) to private.  */
15033       if (dwarf2_attr (die, DW_AT_artificial, cu))
15034         {
15035           FIELD_ARTIFICIAL (*fp) = 1;
15036           new_field->accessibility = DW_ACCESS_private;
15037           fip->non_public_fields = 1;
15038         }
15039     }
15040   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15041     {
15042       /* C++ static member.  */
15043
15044       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15045          is a declaration, but all versions of G++ as of this writing
15046          (so through at least 3.2.1) incorrectly generate
15047          DW_TAG_variable tags.  */
15048
15049       const char *physname;
15050
15051       /* Get name of field.  */
15052       fieldname = dwarf2_name (die, cu);
15053       if (fieldname == NULL)
15054         return;
15055
15056       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15057       if (attr
15058           /* Only create a symbol if this is an external value.
15059              new_symbol checks this and puts the value in the global symbol
15060              table, which we want.  If it is not external, new_symbol
15061              will try to put the value in cu->list_in_scope which is wrong.  */
15062           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15063         {
15064           /* A static const member, not much different than an enum as far as
15065              we're concerned, except that we can support more types.  */
15066           new_symbol (die, NULL, cu);
15067         }
15068
15069       /* Get physical name.  */
15070       physname = dwarf2_physname (fieldname, die, cu);
15071
15072       /* The name is already allocated along with this objfile, so we don't
15073          need to duplicate it for the type.  */
15074       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15075       FIELD_TYPE (*fp) = die_type (die, cu);
15076       FIELD_NAME (*fp) = fieldname;
15077     }
15078   else if (die->tag == DW_TAG_inheritance)
15079     {
15080       LONGEST offset;
15081
15082       /* C++ base class field.  */
15083       if (handle_data_member_location (die, cu, &offset))
15084         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15085       FIELD_BITSIZE (*fp) = 0;
15086       FIELD_TYPE (*fp) = die_type (die, cu);
15087       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15088     }
15089   else if (die->tag == DW_TAG_variant_part)
15090     {
15091       /* process_structure_scope will treat this DIE as a union.  */
15092       process_structure_scope (die, cu);
15093
15094       /* The variant part is relative to the start of the enclosing
15095          structure.  */
15096       SET_FIELD_BITPOS (*fp, 0);
15097       fp->type = get_die_type (die, cu);
15098       fp->artificial = 1;
15099       fp->name = "<<variant>>";
15100     }
15101   else
15102     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15103 }
15104
15105 /* Can the type given by DIE define another type?  */
15106
15107 static bool
15108 type_can_define_types (const struct die_info *die)
15109 {
15110   switch (die->tag)
15111     {
15112     case DW_TAG_typedef:
15113     case DW_TAG_class_type:
15114     case DW_TAG_structure_type:
15115     case DW_TAG_union_type:
15116     case DW_TAG_enumeration_type:
15117       return true;
15118
15119     default:
15120       return false;
15121     }
15122 }
15123
15124 /* Add a type definition defined in the scope of the FIP's class.  */
15125
15126 static void
15127 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15128                       struct dwarf2_cu *cu)
15129 {
15130   struct decl_field fp;
15131   memset (&fp, 0, sizeof (fp));
15132
15133   gdb_assert (type_can_define_types (die));
15134
15135   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15136   fp.name = dwarf2_name (die, cu);
15137   fp.type = read_type_die (die, cu);
15138
15139   /* Save accessibility.  */
15140   enum dwarf_access_attribute accessibility;
15141   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15142   if (attr != NULL)
15143     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15144   else
15145     accessibility = dwarf2_default_access_attribute (die, cu);
15146   switch (accessibility)
15147     {
15148     case DW_ACCESS_public:
15149       /* The assumed value if neither private nor protected.  */
15150       break;
15151     case DW_ACCESS_private:
15152       fp.is_private = 1;
15153       break;
15154     case DW_ACCESS_protected:
15155       fp.is_protected = 1;
15156       break;
15157     default:
15158       complaint (&symfile_complaints,
15159                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15160     }
15161
15162   if (die->tag == DW_TAG_typedef)
15163     fip->typedef_field_list.push_back (fp);
15164   else
15165     fip->nested_types_list.push_back (fp);
15166 }
15167
15168 /* Create the vector of fields, and attach it to the type.  */
15169
15170 static void
15171 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15172                               struct dwarf2_cu *cu)
15173 {
15174   int nfields = fip->nfields;
15175
15176   /* Record the field count, allocate space for the array of fields,
15177      and create blank accessibility bitfields if necessary.  */
15178   TYPE_NFIELDS (type) = nfields;
15179   TYPE_FIELDS (type) = (struct field *)
15180     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15181
15182   if (fip->non_public_fields && cu->language != language_ada)
15183     {
15184       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15185
15186       TYPE_FIELD_PRIVATE_BITS (type) =
15187         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15188       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15189
15190       TYPE_FIELD_PROTECTED_BITS (type) =
15191         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15192       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15193
15194       TYPE_FIELD_IGNORE_BITS (type) =
15195         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15196       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15197     }
15198
15199   /* If the type has baseclasses, allocate and clear a bit vector for
15200      TYPE_FIELD_VIRTUAL_BITS.  */
15201   if (!fip->baseclasses.empty () && cu->language != language_ada)
15202     {
15203       int num_bytes = B_BYTES (fip->baseclasses.size ());
15204       unsigned char *pointer;
15205
15206       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15207       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15208       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15209       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15210       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15211     }
15212
15213   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15214     {
15215       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15216
15217       for (int index = 0; index < nfields; ++index)
15218         {
15219           struct nextfield &field = fip->fields[index];
15220
15221           if (field.variant.is_discriminant)
15222             di->discriminant_index = index;
15223           else if (field.variant.default_branch)
15224             di->default_index = index;
15225           else
15226             di->discriminants[index] = field.variant.discriminant_value;
15227         }
15228     }
15229
15230   /* Copy the saved-up fields into the field vector.  */
15231   for (int i = 0; i < nfields; ++i)
15232     {
15233       struct nextfield &field
15234         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15235            : fip->fields[i - fip->baseclasses.size ()]);
15236
15237       TYPE_FIELD (type, i) = field.field;
15238       switch (field.accessibility)
15239         {
15240         case DW_ACCESS_private:
15241           if (cu->language != language_ada)
15242             SET_TYPE_FIELD_PRIVATE (type, i);
15243           break;
15244
15245         case DW_ACCESS_protected:
15246           if (cu->language != language_ada)
15247             SET_TYPE_FIELD_PROTECTED (type, i);
15248           break;
15249
15250         case DW_ACCESS_public:
15251           break;
15252
15253         default:
15254           /* Unknown accessibility.  Complain and treat it as public.  */
15255           {
15256             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15257                        field.accessibility);
15258           }
15259           break;
15260         }
15261       if (i < fip->baseclasses.size ())
15262         {
15263           switch (field.virtuality)
15264             {
15265             case DW_VIRTUALITY_virtual:
15266             case DW_VIRTUALITY_pure_virtual:
15267               if (cu->language == language_ada)
15268                 error (_("unexpected virtuality in component of Ada type"));
15269               SET_TYPE_FIELD_VIRTUAL (type, i);
15270               break;
15271             }
15272         }
15273     }
15274 }
15275
15276 /* Return true if this member function is a constructor, false
15277    otherwise.  */
15278
15279 static int
15280 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15281 {
15282   const char *fieldname;
15283   const char *type_name;
15284   int len;
15285
15286   if (die->parent == NULL)
15287     return 0;
15288
15289   if (die->parent->tag != DW_TAG_structure_type
15290       && die->parent->tag != DW_TAG_union_type
15291       && die->parent->tag != DW_TAG_class_type)
15292     return 0;
15293
15294   fieldname = dwarf2_name (die, cu);
15295   type_name = dwarf2_name (die->parent, cu);
15296   if (fieldname == NULL || type_name == NULL)
15297     return 0;
15298
15299   len = strlen (fieldname);
15300   return (strncmp (fieldname, type_name, len) == 0
15301           && (type_name[len] == '\0' || type_name[len] == '<'));
15302 }
15303
15304 /* Add a member function to the proper fieldlist.  */
15305
15306 static void
15307 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15308                       struct type *type, struct dwarf2_cu *cu)
15309 {
15310   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15311   struct attribute *attr;
15312   int i;
15313   struct fnfieldlist *flp = nullptr;
15314   struct fn_field *fnp;
15315   const char *fieldname;
15316   struct type *this_type;
15317   enum dwarf_access_attribute accessibility;
15318
15319   if (cu->language == language_ada)
15320     error (_("unexpected member function in Ada type"));
15321
15322   /* Get name of member function.  */
15323   fieldname = dwarf2_name (die, cu);
15324   if (fieldname == NULL)
15325     return;
15326
15327   /* Look up member function name in fieldlist.  */
15328   for (i = 0; i < fip->fnfieldlists.size (); i++)
15329     {
15330       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15331         {
15332           flp = &fip->fnfieldlists[i];
15333           break;
15334         }
15335     }
15336
15337   /* Create a new fnfieldlist if necessary.  */
15338   if (flp == nullptr)
15339     {
15340       fip->fnfieldlists.emplace_back ();
15341       flp = &fip->fnfieldlists.back ();
15342       flp->name = fieldname;
15343       i = fip->fnfieldlists.size () - 1;
15344     }
15345
15346   /* Create a new member function field and add it to the vector of
15347      fnfieldlists.  */
15348   flp->fnfields.emplace_back ();
15349   fnp = &flp->fnfields.back ();
15350
15351   /* Delay processing of the physname until later.  */
15352   if (cu->language == language_cplus)
15353     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15354                         die, cu);
15355   else
15356     {
15357       const char *physname = dwarf2_physname (fieldname, die, cu);
15358       fnp->physname = physname ? physname : "";
15359     }
15360
15361   fnp->type = alloc_type (objfile);
15362   this_type = read_type_die (die, cu);
15363   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15364     {
15365       int nparams = TYPE_NFIELDS (this_type);
15366
15367       /* TYPE is the domain of this method, and THIS_TYPE is the type
15368            of the method itself (TYPE_CODE_METHOD).  */
15369       smash_to_method_type (fnp->type, type,
15370                             TYPE_TARGET_TYPE (this_type),
15371                             TYPE_FIELDS (this_type),
15372                             TYPE_NFIELDS (this_type),
15373                             TYPE_VARARGS (this_type));
15374
15375       /* Handle static member functions.
15376          Dwarf2 has no clean way to discern C++ static and non-static
15377          member functions.  G++ helps GDB by marking the first
15378          parameter for non-static member functions (which is the this
15379          pointer) as artificial.  We obtain this information from
15380          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15381       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15382         fnp->voffset = VOFFSET_STATIC;
15383     }
15384   else
15385     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15386                dwarf2_full_name (fieldname, die, cu));
15387
15388   /* Get fcontext from DW_AT_containing_type if present.  */
15389   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15390     fnp->fcontext = die_containing_type (die, cu);
15391
15392   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15393      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15394
15395   /* Get accessibility.  */
15396   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15397   if (attr)
15398     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15399   else
15400     accessibility = dwarf2_default_access_attribute (die, cu);
15401   switch (accessibility)
15402     {
15403     case DW_ACCESS_private:
15404       fnp->is_private = 1;
15405       break;
15406     case DW_ACCESS_protected:
15407       fnp->is_protected = 1;
15408       break;
15409     }
15410
15411   /* Check for artificial methods.  */
15412   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15413   if (attr && DW_UNSND (attr) != 0)
15414     fnp->is_artificial = 1;
15415
15416   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15417
15418   /* Get index in virtual function table if it is a virtual member
15419      function.  For older versions of GCC, this is an offset in the
15420      appropriate virtual table, as specified by DW_AT_containing_type.
15421      For everyone else, it is an expression to be evaluated relative
15422      to the object address.  */
15423
15424   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15425   if (attr)
15426     {
15427       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15428         {
15429           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15430             {
15431               /* Old-style GCC.  */
15432               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15433             }
15434           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15435                    || (DW_BLOCK (attr)->size > 1
15436                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15437                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15438             {
15439               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15440               if ((fnp->voffset % cu->header.addr_size) != 0)
15441                 dwarf2_complex_location_expr_complaint ();
15442               else
15443                 fnp->voffset /= cu->header.addr_size;
15444               fnp->voffset += 2;
15445             }
15446           else
15447             dwarf2_complex_location_expr_complaint ();
15448
15449           if (!fnp->fcontext)
15450             {
15451               /* If there is no `this' field and no DW_AT_containing_type,
15452                  we cannot actually find a base class context for the
15453                  vtable!  */
15454               if (TYPE_NFIELDS (this_type) == 0
15455                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15456                 {
15457                   complaint (&symfile_complaints,
15458                              _("cannot determine context for virtual member "
15459                                "function \"%s\" (offset %s)"),
15460                              fieldname, sect_offset_str (die->sect_off));
15461                 }
15462               else
15463                 {
15464                   fnp->fcontext
15465                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15466                 }
15467             }
15468         }
15469       else if (attr_form_is_section_offset (attr))
15470         {
15471           dwarf2_complex_location_expr_complaint ();
15472         }
15473       else
15474         {
15475           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15476                                                  fieldname);
15477         }
15478     }
15479   else
15480     {
15481       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15482       if (attr && DW_UNSND (attr))
15483         {
15484           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15485           complaint (&symfile_complaints,
15486                      _("Member function \"%s\" (offset %s) is virtual "
15487                        "but the vtable offset is not specified"),
15488                      fieldname, sect_offset_str (die->sect_off));
15489           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15490           TYPE_CPLUS_DYNAMIC (type) = 1;
15491         }
15492     }
15493 }
15494
15495 /* Create the vector of member function fields, and attach it to the type.  */
15496
15497 static void
15498 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15499                                  struct dwarf2_cu *cu)
15500 {
15501   if (cu->language == language_ada)
15502     error (_("unexpected member functions in Ada type"));
15503
15504   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15505   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15506     TYPE_ALLOC (type,
15507                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15508
15509   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15510     {
15511       struct fnfieldlist &nf = fip->fnfieldlists[i];
15512       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15513
15514       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15515       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15516       fn_flp->fn_fields = (struct fn_field *)
15517         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15518
15519       for (int k = 0; k < nf.fnfields.size (); ++k)
15520         fn_flp->fn_fields[k] = nf.fnfields[k];
15521     }
15522
15523   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15524 }
15525
15526 /* Returns non-zero if NAME is the name of a vtable member in CU's
15527    language, zero otherwise.  */
15528 static int
15529 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15530 {
15531   static const char vptr[] = "_vptr";
15532
15533   /* Look for the C++ form of the vtable.  */
15534   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15535     return 1;
15536
15537   return 0;
15538 }
15539
15540 /* GCC outputs unnamed structures that are really pointers to member
15541    functions, with the ABI-specified layout.  If TYPE describes
15542    such a structure, smash it into a member function type.
15543
15544    GCC shouldn't do this; it should just output pointer to member DIEs.
15545    This is GCC PR debug/28767.  */
15546
15547 static void
15548 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15549 {
15550   struct type *pfn_type, *self_type, *new_type;
15551
15552   /* Check for a structure with no name and two children.  */
15553   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15554     return;
15555
15556   /* Check for __pfn and __delta members.  */
15557   if (TYPE_FIELD_NAME (type, 0) == NULL
15558       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15559       || TYPE_FIELD_NAME (type, 1) == NULL
15560       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15561     return;
15562
15563   /* Find the type of the method.  */
15564   pfn_type = TYPE_FIELD_TYPE (type, 0);
15565   if (pfn_type == NULL
15566       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15567       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15568     return;
15569
15570   /* Look for the "this" argument.  */
15571   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15572   if (TYPE_NFIELDS (pfn_type) == 0
15573       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15574       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15575     return;
15576
15577   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15578   new_type = alloc_type (objfile);
15579   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15580                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15581                         TYPE_VARARGS (pfn_type));
15582   smash_to_methodptr_type (type, new_type);
15583 }
15584
15585 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15586    appropriate error checking and issuing complaints if there is a
15587    problem.  */
15588
15589 static ULONGEST
15590 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15591 {
15592   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15593
15594   if (attr == nullptr)
15595     return 0;
15596
15597   if (!attr_form_is_constant (attr))
15598     {
15599       complaint (&symfile_complaints,
15600                  _("DW_AT_alignment must have constant form"
15601                    " - DIE at %s [in module %s]"),
15602                  sect_offset_str (die->sect_off),
15603                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15604       return 0;
15605     }
15606
15607   ULONGEST align;
15608   if (attr->form == DW_FORM_sdata)
15609     {
15610       LONGEST val = DW_SND (attr);
15611       if (val < 0)
15612         {
15613           complaint (&symfile_complaints,
15614                      _("DW_AT_alignment value must not be negative"
15615                        " - DIE at %s [in module %s]"),
15616                      sect_offset_str (die->sect_off),
15617                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15618           return 0;
15619         }
15620       align = val;
15621     }
15622   else
15623     align = DW_UNSND (attr);
15624
15625   if (align == 0)
15626     {
15627       complaint (&symfile_complaints,
15628                  _("DW_AT_alignment value must not be zero"
15629                    " - DIE at %s [in module %s]"),
15630                  sect_offset_str (die->sect_off),
15631                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15632       return 0;
15633     }
15634   if ((align & (align - 1)) != 0)
15635     {
15636       complaint (&symfile_complaints,
15637                  _("DW_AT_alignment value must be a power of 2"
15638                    " - DIE at %s [in module %s]"),
15639                  sect_offset_str (die->sect_off),
15640                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15641       return 0;
15642     }
15643
15644   return align;
15645 }
15646
15647 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15648    the alignment for TYPE.  */
15649
15650 static void
15651 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15652                      struct type *type)
15653 {
15654   if (!set_type_align (type, get_alignment (cu, die)))
15655     complaint (&symfile_complaints,
15656                _("DW_AT_alignment value too large"
15657                  " - DIE at %s [in module %s]"),
15658                sect_offset_str (die->sect_off),
15659                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15660 }
15661
15662 /* Called when we find the DIE that starts a structure or union scope
15663    (definition) to create a type for the structure or union.  Fill in
15664    the type's name and general properties; the members will not be
15665    processed until process_structure_scope.  A symbol table entry for
15666    the type will also not be done until process_structure_scope (assuming
15667    the type has a name).
15668
15669    NOTE: we need to call these functions regardless of whether or not the
15670    DIE has a DW_AT_name attribute, since it might be an anonymous
15671    structure or union.  This gets the type entered into our set of
15672    user defined types.  */
15673
15674 static struct type *
15675 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15676 {
15677   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15678   struct type *type;
15679   struct attribute *attr;
15680   const char *name;
15681
15682   /* If the definition of this type lives in .debug_types, read that type.
15683      Don't follow DW_AT_specification though, that will take us back up
15684      the chain and we want to go down.  */
15685   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15686   if (attr)
15687     {
15688       type = get_DW_AT_signature_type (die, attr, cu);
15689
15690       /* The type's CU may not be the same as CU.
15691          Ensure TYPE is recorded with CU in die_type_hash.  */
15692       return set_die_type (die, type, cu);
15693     }
15694
15695   type = alloc_type (objfile);
15696   INIT_CPLUS_SPECIFIC (type);
15697
15698   name = dwarf2_name (die, cu);
15699   if (name != NULL)
15700     {
15701       if (cu->language == language_cplus
15702           || cu->language == language_d
15703           || cu->language == language_rust)
15704         {
15705           const char *full_name = dwarf2_full_name (name, die, cu);
15706
15707           /* dwarf2_full_name might have already finished building the DIE's
15708              type.  If so, there is no need to continue.  */
15709           if (get_die_type (die, cu) != NULL)
15710             return get_die_type (die, cu);
15711
15712           TYPE_TAG_NAME (type) = full_name;
15713           if (die->tag == DW_TAG_structure_type
15714               || die->tag == DW_TAG_class_type)
15715             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15716         }
15717       else
15718         {
15719           /* The name is already allocated along with this objfile, so
15720              we don't need to duplicate it for the type.  */
15721           TYPE_TAG_NAME (type) = name;
15722           if (die->tag == DW_TAG_class_type)
15723             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15724         }
15725     }
15726
15727   if (die->tag == DW_TAG_structure_type)
15728     {
15729       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15730     }
15731   else if (die->tag == DW_TAG_union_type)
15732     {
15733       TYPE_CODE (type) = TYPE_CODE_UNION;
15734     }
15735   else if (die->tag == DW_TAG_variant_part)
15736     {
15737       TYPE_CODE (type) = TYPE_CODE_UNION;
15738       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15739     }
15740   else
15741     {
15742       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15743     }
15744
15745   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15746     TYPE_DECLARED_CLASS (type) = 1;
15747
15748   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15749   if (attr)
15750     {
15751       if (attr_form_is_constant (attr))
15752         TYPE_LENGTH (type) = DW_UNSND (attr);
15753       else
15754         {
15755           /* For the moment, dynamic type sizes are not supported
15756              by GDB's struct type.  The actual size is determined
15757              on-demand when resolving the type of a given object,
15758              so set the type's length to zero for now.  Otherwise,
15759              we record an expression as the length, and that expression
15760              could lead to a very large value, which could eventually
15761              lead to us trying to allocate that much memory when creating
15762              a value of that type.  */
15763           TYPE_LENGTH (type) = 0;
15764         }
15765     }
15766   else
15767     {
15768       TYPE_LENGTH (type) = 0;
15769     }
15770
15771   maybe_set_alignment (cu, die, type);
15772
15773   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15774     {
15775       /* ICC<14 does not output the required DW_AT_declaration on
15776          incomplete types, but gives them a size of zero.  */
15777       TYPE_STUB (type) = 1;
15778     }
15779   else
15780     TYPE_STUB_SUPPORTED (type) = 1;
15781
15782   if (die_is_declaration (die, cu))
15783     TYPE_STUB (type) = 1;
15784   else if (attr == NULL && die->child == NULL
15785            && producer_is_realview (cu->producer))
15786     /* RealView does not output the required DW_AT_declaration
15787        on incomplete types.  */
15788     TYPE_STUB (type) = 1;
15789
15790   /* We need to add the type field to the die immediately so we don't
15791      infinitely recurse when dealing with pointers to the structure
15792      type within the structure itself.  */
15793   set_die_type (die, type, cu);
15794
15795   /* set_die_type should be already done.  */
15796   set_descriptive_type (type, die, cu);
15797
15798   return type;
15799 }
15800
15801 /* A helper for process_structure_scope that handles a single member
15802    DIE.  */
15803
15804 static void
15805 handle_struct_member_die (struct die_info *child_die, struct type *type,
15806                           struct field_info *fi,
15807                           std::vector<struct symbol *> *template_args,
15808                           struct dwarf2_cu *cu)
15809 {
15810   if (child_die->tag == DW_TAG_member
15811       || child_die->tag == DW_TAG_variable
15812       || child_die->tag == DW_TAG_variant_part)
15813     {
15814       /* NOTE: carlton/2002-11-05: A C++ static data member
15815          should be a DW_TAG_member that is a declaration, but
15816          all versions of G++ as of this writing (so through at
15817          least 3.2.1) incorrectly generate DW_TAG_variable
15818          tags for them instead.  */
15819       dwarf2_add_field (fi, child_die, cu);
15820     }
15821   else if (child_die->tag == DW_TAG_subprogram)
15822     {
15823       /* Rust doesn't have member functions in the C++ sense.
15824          However, it does emit ordinary functions as children
15825          of a struct DIE.  */
15826       if (cu->language == language_rust)
15827         read_func_scope (child_die, cu);
15828       else
15829         {
15830           /* C++ member function.  */
15831           dwarf2_add_member_fn (fi, child_die, type, cu);
15832         }
15833     }
15834   else if (child_die->tag == DW_TAG_inheritance)
15835     {
15836       /* C++ base class field.  */
15837       dwarf2_add_field (fi, child_die, cu);
15838     }
15839   else if (type_can_define_types (child_die))
15840     dwarf2_add_type_defn (fi, child_die, cu);
15841   else if (child_die->tag == DW_TAG_template_type_param
15842            || child_die->tag == DW_TAG_template_value_param)
15843     {
15844       struct symbol *arg = new_symbol (child_die, NULL, cu);
15845
15846       if (arg != NULL)
15847         template_args->push_back (arg);
15848     }
15849   else if (child_die->tag == DW_TAG_variant)
15850     {
15851       /* In a variant we want to get the discriminant and also add a
15852          field for our sole member child.  */
15853       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15854
15855       for (struct die_info *variant_child = child_die->child;
15856            variant_child != NULL;
15857            variant_child = sibling_die (variant_child))
15858         {
15859           if (variant_child->tag == DW_TAG_member)
15860             {
15861               handle_struct_member_die (variant_child, type, fi,
15862                                         template_args, cu);
15863               /* Only handle the one.  */
15864               break;
15865             }
15866         }
15867
15868       /* We don't handle this but we might as well report it if we see
15869          it.  */
15870       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15871           complaint (&symfile_complaints,
15872                      _("DW_AT_discr_list is not supported yet"
15873                        " - DIE at %s [in module %s]"),
15874                      sect_offset_str (child_die->sect_off),
15875                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15876
15877       /* The first field was just added, so we can stash the
15878          discriminant there.  */
15879       gdb_assert (!fi->fields.empty ());
15880       if (discr == NULL)
15881         fi->fields.back ().variant.default_branch = true;
15882       else
15883         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15884     }
15885 }
15886
15887 /* Finish creating a structure or union type, including filling in
15888    its members and creating a symbol for it.  */
15889
15890 static void
15891 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15892 {
15893   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15894   struct die_info *child_die;
15895   struct type *type;
15896
15897   type = get_die_type (die, cu);
15898   if (type == NULL)
15899     type = read_structure_type (die, cu);
15900
15901   /* When reading a DW_TAG_variant_part, we need to notice when we
15902      read the discriminant member, so we can record it later in the
15903      discriminant_info.  */
15904   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15905   sect_offset discr_offset;
15906
15907   if (is_variant_part)
15908     {
15909       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15910       if (discr == NULL)
15911         {
15912           /* Maybe it's a univariant form, an extension we support.
15913              In this case arrange not to check the offset.  */
15914           is_variant_part = false;
15915         }
15916       else if (attr_form_is_ref (discr))
15917         {
15918           struct dwarf2_cu *target_cu = cu;
15919           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15920
15921           discr_offset = target_die->sect_off;
15922         }
15923       else
15924         {
15925           complaint (&symfile_complaints,
15926                      _("DW_AT_discr does not have DIE reference form"
15927                        " - DIE at %s [in module %s]"),
15928                      sect_offset_str (die->sect_off),
15929                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15930           is_variant_part = false;
15931         }
15932     }
15933
15934   if (die->child != NULL && ! die_is_declaration (die, cu))
15935     {
15936       struct field_info fi;
15937       std::vector<struct symbol *> template_args;
15938
15939       child_die = die->child;
15940
15941       while (child_die && child_die->tag)
15942         {
15943           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15944
15945           if (is_variant_part && discr_offset == child_die->sect_off)
15946             fi.fields.back ().variant.is_discriminant = true;
15947
15948           child_die = sibling_die (child_die);
15949         }
15950
15951       /* Attach template arguments to type.  */
15952       if (!template_args.empty ())
15953         {
15954           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15955           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15956           TYPE_TEMPLATE_ARGUMENTS (type)
15957             = XOBNEWVEC (&objfile->objfile_obstack,
15958                          struct symbol *,
15959                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15960           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15961                   template_args.data (),
15962                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15963                    * sizeof (struct symbol *)));
15964         }
15965
15966       /* Attach fields and member functions to the type.  */
15967       if (fi.nfields)
15968         dwarf2_attach_fields_to_type (&fi, type, cu);
15969       if (!fi.fnfieldlists.empty ())
15970         {
15971           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15972
15973           /* Get the type which refers to the base class (possibly this
15974              class itself) which contains the vtable pointer for the current
15975              class from the DW_AT_containing_type attribute.  This use of
15976              DW_AT_containing_type is a GNU extension.  */
15977
15978           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15979             {
15980               struct type *t = die_containing_type (die, cu);
15981
15982               set_type_vptr_basetype (type, t);
15983               if (type == t)
15984                 {
15985                   int i;
15986
15987                   /* Our own class provides vtbl ptr.  */
15988                   for (i = TYPE_NFIELDS (t) - 1;
15989                        i >= TYPE_N_BASECLASSES (t);
15990                        --i)
15991                     {
15992                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15993
15994                       if (is_vtable_name (fieldname, cu))
15995                         {
15996                           set_type_vptr_fieldno (type, i);
15997                           break;
15998                         }
15999                     }
16000
16001                   /* Complain if virtual function table field not found.  */
16002                   if (i < TYPE_N_BASECLASSES (t))
16003                     complaint (&symfile_complaints,
16004                                _("virtual function table pointer "
16005                                  "not found when defining class '%s'"),
16006                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16007                                "");
16008                 }
16009               else
16010                 {
16011                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16012                 }
16013             }
16014           else if (cu->producer
16015                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16016             {
16017               /* The IBM XLC compiler does not provide direct indication
16018                  of the containing type, but the vtable pointer is
16019                  always named __vfp.  */
16020
16021               int i;
16022
16023               for (i = TYPE_NFIELDS (type) - 1;
16024                    i >= TYPE_N_BASECLASSES (type);
16025                    --i)
16026                 {
16027                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16028                     {
16029                       set_type_vptr_fieldno (type, i);
16030                       set_type_vptr_basetype (type, type);
16031                       break;
16032                     }
16033                 }
16034             }
16035         }
16036
16037       /* Copy fi.typedef_field_list linked list elements content into the
16038          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16039       if (!fi.typedef_field_list.empty ())
16040         {
16041           int count = fi.typedef_field_list.size ();
16042
16043           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16044           TYPE_TYPEDEF_FIELD_ARRAY (type)
16045             = ((struct decl_field *)
16046                TYPE_ALLOC (type,
16047                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16048           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16049
16050           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16051             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16052         }
16053
16054       /* Copy fi.nested_types_list linked list elements content into the
16055          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16056       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16057         {
16058           int count = fi.nested_types_list.size ();
16059
16060           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16061           TYPE_NESTED_TYPES_ARRAY (type)
16062             = ((struct decl_field *)
16063                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16064           TYPE_NESTED_TYPES_COUNT (type) = count;
16065
16066           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16067             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16068         }
16069     }
16070
16071   quirk_gcc_member_function_pointer (type, objfile);
16072   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16073     cu->rust_unions.push_back (type);
16074
16075   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16076      snapshots) has been known to create a die giving a declaration
16077      for a class that has, as a child, a die giving a definition for a
16078      nested class.  So we have to process our children even if the
16079      current die is a declaration.  Normally, of course, a declaration
16080      won't have any children at all.  */
16081
16082   child_die = die->child;
16083
16084   while (child_die != NULL && child_die->tag)
16085     {
16086       if (child_die->tag == DW_TAG_member
16087           || child_die->tag == DW_TAG_variable
16088           || child_die->tag == DW_TAG_inheritance
16089           || child_die->tag == DW_TAG_template_value_param
16090           || child_die->tag == DW_TAG_template_type_param)
16091         {
16092           /* Do nothing.  */
16093         }
16094       else
16095         process_die (child_die, cu);
16096
16097       child_die = sibling_die (child_die);
16098     }
16099
16100   /* Do not consider external references.  According to the DWARF standard,
16101      these DIEs are identified by the fact that they have no byte_size
16102      attribute, and a declaration attribute.  */
16103   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16104       || !die_is_declaration (die, cu))
16105     new_symbol (die, type, cu);
16106 }
16107
16108 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16109    update TYPE using some information only available in DIE's children.  */
16110
16111 static void
16112 update_enumeration_type_from_children (struct die_info *die,
16113                                        struct type *type,
16114                                        struct dwarf2_cu *cu)
16115 {
16116   struct die_info *child_die;
16117   int unsigned_enum = 1;
16118   int flag_enum = 1;
16119   ULONGEST mask = 0;
16120
16121   auto_obstack obstack;
16122
16123   for (child_die = die->child;
16124        child_die != NULL && child_die->tag;
16125        child_die = sibling_die (child_die))
16126     {
16127       struct attribute *attr;
16128       LONGEST value;
16129       const gdb_byte *bytes;
16130       struct dwarf2_locexpr_baton *baton;
16131       const char *name;
16132
16133       if (child_die->tag != DW_TAG_enumerator)
16134         continue;
16135
16136       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16137       if (attr == NULL)
16138         continue;
16139
16140       name = dwarf2_name (child_die, cu);
16141       if (name == NULL)
16142         name = "<anonymous enumerator>";
16143
16144       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16145                                &value, &bytes, &baton);
16146       if (value < 0)
16147         {
16148           unsigned_enum = 0;
16149           flag_enum = 0;
16150         }
16151       else if ((mask & value) != 0)
16152         flag_enum = 0;
16153       else
16154         mask |= value;
16155
16156       /* If we already know that the enum type is neither unsigned, nor
16157          a flag type, no need to look at the rest of the enumerates.  */
16158       if (!unsigned_enum && !flag_enum)
16159         break;
16160     }
16161
16162   if (unsigned_enum)
16163     TYPE_UNSIGNED (type) = 1;
16164   if (flag_enum)
16165     TYPE_FLAG_ENUM (type) = 1;
16166 }
16167
16168 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16169    complete the type's fields yet, or create any symbols.  */
16170
16171 static struct type *
16172 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16173 {
16174   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16175   struct type *type;
16176   struct attribute *attr;
16177   const char *name;
16178
16179   /* If the definition of this type lives in .debug_types, read that type.
16180      Don't follow DW_AT_specification though, that will take us back up
16181      the chain and we want to go down.  */
16182   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16183   if (attr)
16184     {
16185       type = get_DW_AT_signature_type (die, attr, cu);
16186
16187       /* The type's CU may not be the same as CU.
16188          Ensure TYPE is recorded with CU in die_type_hash.  */
16189       return set_die_type (die, type, cu);
16190     }
16191
16192   type = alloc_type (objfile);
16193
16194   TYPE_CODE (type) = TYPE_CODE_ENUM;
16195   name = dwarf2_full_name (NULL, die, cu);
16196   if (name != NULL)
16197     TYPE_TAG_NAME (type) = name;
16198
16199   attr = dwarf2_attr (die, DW_AT_type, cu);
16200   if (attr != NULL)
16201     {
16202       struct type *underlying_type = die_type (die, cu);
16203
16204       TYPE_TARGET_TYPE (type) = underlying_type;
16205     }
16206
16207   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16208   if (attr)
16209     {
16210       TYPE_LENGTH (type) = DW_UNSND (attr);
16211     }
16212   else
16213     {
16214       TYPE_LENGTH (type) = 0;
16215     }
16216
16217   maybe_set_alignment (cu, die, type);
16218
16219   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16220      declared as private in the package spec, and then defined only
16221      inside the package body.  Such types are known as Taft Amendment
16222      Types.  When another package uses such a type, an incomplete DIE
16223      may be generated by the compiler.  */
16224   if (die_is_declaration (die, cu))
16225     TYPE_STUB (type) = 1;
16226
16227   /* Finish the creation of this type by using the enum's children.
16228      We must call this even when the underlying type has been provided
16229      so that we can determine if we're looking at a "flag" enum.  */
16230   update_enumeration_type_from_children (die, type, cu);
16231
16232   /* If this type has an underlying type that is not a stub, then we
16233      may use its attributes.  We always use the "unsigned" attribute
16234      in this situation, because ordinarily we guess whether the type
16235      is unsigned -- but the guess can be wrong and the underlying type
16236      can tell us the reality.  However, we defer to a local size
16237      attribute if one exists, because this lets the compiler override
16238      the underlying type if needed.  */
16239   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16240     {
16241       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16242       if (TYPE_LENGTH (type) == 0)
16243         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16244       if (TYPE_RAW_ALIGN (type) == 0
16245           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16246         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16247     }
16248
16249   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16250
16251   return set_die_type (die, type, cu);
16252 }
16253
16254 /* Given a pointer to a die which begins an enumeration, process all
16255    the dies that define the members of the enumeration, and create the
16256    symbol for the enumeration type.
16257
16258    NOTE: We reverse the order of the element list.  */
16259
16260 static void
16261 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16262 {
16263   struct type *this_type;
16264
16265   this_type = get_die_type (die, cu);
16266   if (this_type == NULL)
16267     this_type = read_enumeration_type (die, cu);
16268
16269   if (die->child != NULL)
16270     {
16271       struct die_info *child_die;
16272       struct symbol *sym;
16273       struct field *fields = NULL;
16274       int num_fields = 0;
16275       const char *name;
16276
16277       child_die = die->child;
16278       while (child_die && child_die->tag)
16279         {
16280           if (child_die->tag != DW_TAG_enumerator)
16281             {
16282               process_die (child_die, cu);
16283             }
16284           else
16285             {
16286               name = dwarf2_name (child_die, cu);
16287               if (name)
16288                 {
16289                   sym = new_symbol (child_die, this_type, cu);
16290
16291                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16292                     {
16293                       fields = (struct field *)
16294                         xrealloc (fields,
16295                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16296                                   * sizeof (struct field));
16297                     }
16298
16299                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16300                   FIELD_TYPE (fields[num_fields]) = NULL;
16301                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16302                   FIELD_BITSIZE (fields[num_fields]) = 0;
16303
16304                   num_fields++;
16305                 }
16306             }
16307
16308           child_die = sibling_die (child_die);
16309         }
16310
16311       if (num_fields)
16312         {
16313           TYPE_NFIELDS (this_type) = num_fields;
16314           TYPE_FIELDS (this_type) = (struct field *)
16315             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16316           memcpy (TYPE_FIELDS (this_type), fields,
16317                   sizeof (struct field) * num_fields);
16318           xfree (fields);
16319         }
16320     }
16321
16322   /* If we are reading an enum from a .debug_types unit, and the enum
16323      is a declaration, and the enum is not the signatured type in the
16324      unit, then we do not want to add a symbol for it.  Adding a
16325      symbol would in some cases obscure the true definition of the
16326      enum, giving users an incomplete type when the definition is
16327      actually available.  Note that we do not want to do this for all
16328      enums which are just declarations, because C++0x allows forward
16329      enum declarations.  */
16330   if (cu->per_cu->is_debug_types
16331       && die_is_declaration (die, cu))
16332     {
16333       struct signatured_type *sig_type;
16334
16335       sig_type = (struct signatured_type *) cu->per_cu;
16336       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16337       if (sig_type->type_offset_in_section != die->sect_off)
16338         return;
16339     }
16340
16341   new_symbol (die, this_type, cu);
16342 }
16343
16344 /* Extract all information from a DW_TAG_array_type DIE and put it in
16345    the DIE's type field.  For now, this only handles one dimensional
16346    arrays.  */
16347
16348 static struct type *
16349 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16350 {
16351   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16352   struct die_info *child_die;
16353   struct type *type;
16354   struct type *element_type, *range_type, *index_type;
16355   struct attribute *attr;
16356   const char *name;
16357   struct dynamic_prop *byte_stride_prop = NULL;
16358   unsigned int bit_stride = 0;
16359
16360   element_type = die_type (die, cu);
16361
16362   /* The die_type call above may have already set the type for this DIE.  */
16363   type = get_die_type (die, cu);
16364   if (type)
16365     return type;
16366
16367   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16368   if (attr != NULL)
16369     {
16370       int stride_ok;
16371
16372       byte_stride_prop
16373         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16374       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16375       if (!stride_ok)
16376         {
16377           complaint (&symfile_complaints,
16378                      _("unable to read array DW_AT_byte_stride "
16379                        " - DIE at %s [in module %s]"),
16380                      sect_offset_str (die->sect_off),
16381                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16382           /* Ignore this attribute.  We will likely not be able to print
16383              arrays of this type correctly, but there is little we can do
16384              to help if we cannot read the attribute's value.  */
16385           byte_stride_prop = NULL;
16386         }
16387     }
16388
16389   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16390   if (attr != NULL)
16391     bit_stride = DW_UNSND (attr);
16392
16393   /* Irix 6.2 native cc creates array types without children for
16394      arrays with unspecified length.  */
16395   if (die->child == NULL)
16396     {
16397       index_type = objfile_type (objfile)->builtin_int;
16398       range_type = create_static_range_type (NULL, index_type, 0, -1);
16399       type = create_array_type_with_stride (NULL, element_type, range_type,
16400                                             byte_stride_prop, bit_stride);
16401       return set_die_type (die, type, cu);
16402     }
16403
16404   std::vector<struct type *> range_types;
16405   child_die = die->child;
16406   while (child_die && child_die->tag)
16407     {
16408       if (child_die->tag == DW_TAG_subrange_type)
16409         {
16410           struct type *child_type = read_type_die (child_die, cu);
16411
16412           if (child_type != NULL)
16413             {
16414               /* The range type was succesfully read.  Save it for the
16415                  array type creation.  */
16416               range_types.push_back (child_type);
16417             }
16418         }
16419       child_die = sibling_die (child_die);
16420     }
16421
16422   /* Dwarf2 dimensions are output from left to right, create the
16423      necessary array types in backwards order.  */
16424
16425   type = element_type;
16426
16427   if (read_array_order (die, cu) == DW_ORD_col_major)
16428     {
16429       int i = 0;
16430
16431       while (i < range_types.size ())
16432         type = create_array_type_with_stride (NULL, type, range_types[i++],
16433                                               byte_stride_prop, bit_stride);
16434     }
16435   else
16436     {
16437       size_t ndim = range_types.size ();
16438       while (ndim-- > 0)
16439         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16440                                               byte_stride_prop, bit_stride);
16441     }
16442
16443   /* Understand Dwarf2 support for vector types (like they occur on
16444      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16445      array type.  This is not part of the Dwarf2/3 standard yet, but a
16446      custom vendor extension.  The main difference between a regular
16447      array and the vector variant is that vectors are passed by value
16448      to functions.  */
16449   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16450   if (attr)
16451     make_vector_type (type);
16452
16453   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16454      implementation may choose to implement triple vectors using this
16455      attribute.  */
16456   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16457   if (attr)
16458     {
16459       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16460         TYPE_LENGTH (type) = DW_UNSND (attr);
16461       else
16462         complaint (&symfile_complaints,
16463                    _("DW_AT_byte_size for array type smaller "
16464                      "than the total size of elements"));
16465     }
16466
16467   name = dwarf2_name (die, cu);
16468   if (name)
16469     TYPE_NAME (type) = name;
16470
16471   maybe_set_alignment (cu, die, type);
16472
16473   /* Install the type in the die.  */
16474   set_die_type (die, type, cu);
16475
16476   /* set_die_type should be already done.  */
16477   set_descriptive_type (type, die, cu);
16478
16479   return type;
16480 }
16481
16482 static enum dwarf_array_dim_ordering
16483 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16484 {
16485   struct attribute *attr;
16486
16487   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16488
16489   if (attr)
16490     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16491
16492   /* GNU F77 is a special case, as at 08/2004 array type info is the
16493      opposite order to the dwarf2 specification, but data is still
16494      laid out as per normal fortran.
16495
16496      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16497      version checking.  */
16498
16499   if (cu->language == language_fortran
16500       && cu->producer && strstr (cu->producer, "GNU F77"))
16501     {
16502       return DW_ORD_row_major;
16503     }
16504
16505   switch (cu->language_defn->la_array_ordering)
16506     {
16507     case array_column_major:
16508       return DW_ORD_col_major;
16509     case array_row_major:
16510     default:
16511       return DW_ORD_row_major;
16512     };
16513 }
16514
16515 /* Extract all information from a DW_TAG_set_type DIE and put it in
16516    the DIE's type field.  */
16517
16518 static struct type *
16519 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16520 {
16521   struct type *domain_type, *set_type;
16522   struct attribute *attr;
16523
16524   domain_type = die_type (die, cu);
16525
16526   /* The die_type call above may have already set the type for this DIE.  */
16527   set_type = get_die_type (die, cu);
16528   if (set_type)
16529     return set_type;
16530
16531   set_type = create_set_type (NULL, domain_type);
16532
16533   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16534   if (attr)
16535     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16536
16537   maybe_set_alignment (cu, die, set_type);
16538
16539   return set_die_type (die, set_type, cu);
16540 }
16541
16542 /* A helper for read_common_block that creates a locexpr baton.
16543    SYM is the symbol which we are marking as computed.
16544    COMMON_DIE is the DIE for the common block.
16545    COMMON_LOC is the location expression attribute for the common
16546    block itself.
16547    MEMBER_LOC is the location expression attribute for the particular
16548    member of the common block that we are processing.
16549    CU is the CU from which the above come.  */
16550
16551 static void
16552 mark_common_block_symbol_computed (struct symbol *sym,
16553                                    struct die_info *common_die,
16554                                    struct attribute *common_loc,
16555                                    struct attribute *member_loc,
16556                                    struct dwarf2_cu *cu)
16557 {
16558   struct dwarf2_per_objfile *dwarf2_per_objfile
16559     = cu->per_cu->dwarf2_per_objfile;
16560   struct objfile *objfile = dwarf2_per_objfile->objfile;
16561   struct dwarf2_locexpr_baton *baton;
16562   gdb_byte *ptr;
16563   unsigned int cu_off;
16564   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16565   LONGEST offset = 0;
16566
16567   gdb_assert (common_loc && member_loc);
16568   gdb_assert (attr_form_is_block (common_loc));
16569   gdb_assert (attr_form_is_block (member_loc)
16570               || attr_form_is_constant (member_loc));
16571
16572   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16573   baton->per_cu = cu->per_cu;
16574   gdb_assert (baton->per_cu);
16575
16576   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16577
16578   if (attr_form_is_constant (member_loc))
16579     {
16580       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16581       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16582     }
16583   else
16584     baton->size += DW_BLOCK (member_loc)->size;
16585
16586   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16587   baton->data = ptr;
16588
16589   *ptr++ = DW_OP_call4;
16590   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16591   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16592   ptr += 4;
16593
16594   if (attr_form_is_constant (member_loc))
16595     {
16596       *ptr++ = DW_OP_addr;
16597       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16598       ptr += cu->header.addr_size;
16599     }
16600   else
16601     {
16602       /* We have to copy the data here, because DW_OP_call4 will only
16603          use a DW_AT_location attribute.  */
16604       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16605       ptr += DW_BLOCK (member_loc)->size;
16606     }
16607
16608   *ptr++ = DW_OP_plus;
16609   gdb_assert (ptr - baton->data == baton->size);
16610
16611   SYMBOL_LOCATION_BATON (sym) = baton;
16612   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16613 }
16614
16615 /* Create appropriate locally-scoped variables for all the
16616    DW_TAG_common_block entries.  Also create a struct common_block
16617    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16618    is used to sepate the common blocks name namespace from regular
16619    variable names.  */
16620
16621 static void
16622 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16623 {
16624   struct attribute *attr;
16625
16626   attr = dwarf2_attr (die, DW_AT_location, cu);
16627   if (attr)
16628     {
16629       /* Support the .debug_loc offsets.  */
16630       if (attr_form_is_block (attr))
16631         {
16632           /* Ok.  */
16633         }
16634       else if (attr_form_is_section_offset (attr))
16635         {
16636           dwarf2_complex_location_expr_complaint ();
16637           attr = NULL;
16638         }
16639       else
16640         {
16641           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16642                                                  "common block member");
16643           attr = NULL;
16644         }
16645     }
16646
16647   if (die->child != NULL)
16648     {
16649       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16650       struct die_info *child_die;
16651       size_t n_entries = 0, size;
16652       struct common_block *common_block;
16653       struct symbol *sym;
16654
16655       for (child_die = die->child;
16656            child_die && child_die->tag;
16657            child_die = sibling_die (child_die))
16658         ++n_entries;
16659
16660       size = (sizeof (struct common_block)
16661               + (n_entries - 1) * sizeof (struct symbol *));
16662       common_block
16663         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16664                                                  size);
16665       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16666       common_block->n_entries = 0;
16667
16668       for (child_die = die->child;
16669            child_die && child_die->tag;
16670            child_die = sibling_die (child_die))
16671         {
16672           /* Create the symbol in the DW_TAG_common_block block in the current
16673              symbol scope.  */
16674           sym = new_symbol (child_die, NULL, cu);
16675           if (sym != NULL)
16676             {
16677               struct attribute *member_loc;
16678
16679               common_block->contents[common_block->n_entries++] = sym;
16680
16681               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16682                                         cu);
16683               if (member_loc)
16684                 {
16685                   /* GDB has handled this for a long time, but it is
16686                      not specified by DWARF.  It seems to have been
16687                      emitted by gfortran at least as recently as:
16688                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16689                   complaint (&symfile_complaints,
16690                              _("Variable in common block has "
16691                                "DW_AT_data_member_location "
16692                                "- DIE at %s [in module %s]"),
16693                                sect_offset_str (child_die->sect_off),
16694                              objfile_name (objfile));
16695
16696                   if (attr_form_is_section_offset (member_loc))
16697                     dwarf2_complex_location_expr_complaint ();
16698                   else if (attr_form_is_constant (member_loc)
16699                            || attr_form_is_block (member_loc))
16700                     {
16701                       if (attr)
16702                         mark_common_block_symbol_computed (sym, die, attr,
16703                                                            member_loc, cu);
16704                     }
16705                   else
16706                     dwarf2_complex_location_expr_complaint ();
16707                 }
16708             }
16709         }
16710
16711       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16712       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16713     }
16714 }
16715
16716 /* Create a type for a C++ namespace.  */
16717
16718 static struct type *
16719 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16720 {
16721   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16722   const char *previous_prefix, *name;
16723   int is_anonymous;
16724   struct type *type;
16725
16726   /* For extensions, reuse the type of the original namespace.  */
16727   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16728     {
16729       struct die_info *ext_die;
16730       struct dwarf2_cu *ext_cu = cu;
16731
16732       ext_die = dwarf2_extension (die, &ext_cu);
16733       type = read_type_die (ext_die, ext_cu);
16734
16735       /* EXT_CU may not be the same as CU.
16736          Ensure TYPE is recorded with CU in die_type_hash.  */
16737       return set_die_type (die, type, cu);
16738     }
16739
16740   name = namespace_name (die, &is_anonymous, cu);
16741
16742   /* Now build the name of the current namespace.  */
16743
16744   previous_prefix = determine_prefix (die, cu);
16745   if (previous_prefix[0] != '\0')
16746     name = typename_concat (&objfile->objfile_obstack,
16747                             previous_prefix, name, 0, cu);
16748
16749   /* Create the type.  */
16750   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16751   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16752
16753   return set_die_type (die, type, cu);
16754 }
16755
16756 /* Read a namespace scope.  */
16757
16758 static void
16759 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16760 {
16761   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16762   int is_anonymous;
16763
16764   /* Add a symbol associated to this if we haven't seen the namespace
16765      before.  Also, add a using directive if it's an anonymous
16766      namespace.  */
16767
16768   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16769     {
16770       struct type *type;
16771
16772       type = read_type_die (die, cu);
16773       new_symbol (die, type, cu);
16774
16775       namespace_name (die, &is_anonymous, cu);
16776       if (is_anonymous)
16777         {
16778           const char *previous_prefix = determine_prefix (die, cu);
16779
16780           std::vector<const char *> excludes;
16781           add_using_directive (using_directives (cu->language),
16782                                previous_prefix, TYPE_NAME (type), NULL,
16783                                NULL, excludes, 0, &objfile->objfile_obstack);
16784         }
16785     }
16786
16787   if (die->child != NULL)
16788     {
16789       struct die_info *child_die = die->child;
16790
16791       while (child_die && child_die->tag)
16792         {
16793           process_die (child_die, cu);
16794           child_die = sibling_die (child_die);
16795         }
16796     }
16797 }
16798
16799 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16800    imported module.  Still we need that type as local Fortran "use ... only"
16801    declaration imports depend on the created type in determine_prefix.  */
16802
16803 static struct type *
16804 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16805 {
16806   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16807   const char *module_name;
16808   struct type *type;
16809
16810   module_name = dwarf2_name (die, cu);
16811   if (!module_name)
16812     complaint (&symfile_complaints,
16813                _("DW_TAG_module has no name, offset %s"),
16814                sect_offset_str (die->sect_off));
16815   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16816
16817   /* determine_prefix uses TYPE_TAG_NAME.  */
16818   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16819
16820   return set_die_type (die, type, cu);
16821 }
16822
16823 /* Read a Fortran module.  */
16824
16825 static void
16826 read_module (struct die_info *die, struct dwarf2_cu *cu)
16827 {
16828   struct die_info *child_die = die->child;
16829   struct type *type;
16830
16831   type = read_type_die (die, cu);
16832   new_symbol (die, type, cu);
16833
16834   while (child_die && child_die->tag)
16835     {
16836       process_die (child_die, cu);
16837       child_die = sibling_die (child_die);
16838     }
16839 }
16840
16841 /* Return the name of the namespace represented by DIE.  Set
16842    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16843    namespace.  */
16844
16845 static const char *
16846 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16847 {
16848   struct die_info *current_die;
16849   const char *name = NULL;
16850
16851   /* Loop through the extensions until we find a name.  */
16852
16853   for (current_die = die;
16854        current_die != NULL;
16855        current_die = dwarf2_extension (die, &cu))
16856     {
16857       /* We don't use dwarf2_name here so that we can detect the absence
16858          of a name -> anonymous namespace.  */
16859       name = dwarf2_string_attr (die, DW_AT_name, cu);
16860
16861       if (name != NULL)
16862         break;
16863     }
16864
16865   /* Is it an anonymous namespace?  */
16866
16867   *is_anonymous = (name == NULL);
16868   if (*is_anonymous)
16869     name = CP_ANONYMOUS_NAMESPACE_STR;
16870
16871   return name;
16872 }
16873
16874 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16875    the user defined type vector.  */
16876
16877 static struct type *
16878 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16879 {
16880   struct gdbarch *gdbarch
16881     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16882   struct comp_unit_head *cu_header = &cu->header;
16883   struct type *type;
16884   struct attribute *attr_byte_size;
16885   struct attribute *attr_address_class;
16886   int byte_size, addr_class;
16887   struct type *target_type;
16888
16889   target_type = die_type (die, cu);
16890
16891   /* The die_type call above may have already set the type for this DIE.  */
16892   type = get_die_type (die, cu);
16893   if (type)
16894     return type;
16895
16896   type = lookup_pointer_type (target_type);
16897
16898   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16899   if (attr_byte_size)
16900     byte_size = DW_UNSND (attr_byte_size);
16901   else
16902     byte_size = cu_header->addr_size;
16903
16904   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16905   if (attr_address_class)
16906     addr_class = DW_UNSND (attr_address_class);
16907   else
16908     addr_class = DW_ADDR_none;
16909
16910   ULONGEST alignment = get_alignment (cu, die);
16911
16912   /* If the pointer size, alignment, or address class is different
16913      than the default, create a type variant marked as such and set
16914      the length accordingly.  */
16915   if (TYPE_LENGTH (type) != byte_size
16916       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16917           && alignment != TYPE_RAW_ALIGN (type))
16918       || addr_class != DW_ADDR_none)
16919     {
16920       if (gdbarch_address_class_type_flags_p (gdbarch))
16921         {
16922           int type_flags;
16923
16924           type_flags = gdbarch_address_class_type_flags
16925                          (gdbarch, byte_size, addr_class);
16926           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16927                       == 0);
16928           type = make_type_with_address_space (type, type_flags);
16929         }
16930       else if (TYPE_LENGTH (type) != byte_size)
16931         {
16932           complaint (&symfile_complaints,
16933                      _("invalid pointer size %d"), byte_size);
16934         }
16935       else if (TYPE_RAW_ALIGN (type) != alignment)
16936         {
16937           complaint (&symfile_complaints,
16938                      _("Invalid DW_AT_alignment"
16939                        " - DIE at %s [in module %s]"),
16940                      sect_offset_str (die->sect_off),
16941                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16942         }
16943       else
16944         {
16945           /* Should we also complain about unhandled address classes?  */
16946         }
16947     }
16948
16949   TYPE_LENGTH (type) = byte_size;
16950   set_type_align (type, alignment);
16951   return set_die_type (die, type, cu);
16952 }
16953
16954 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16955    the user defined type vector.  */
16956
16957 static struct type *
16958 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16959 {
16960   struct type *type;
16961   struct type *to_type;
16962   struct type *domain;
16963
16964   to_type = die_type (die, cu);
16965   domain = die_containing_type (die, cu);
16966
16967   /* The calls above may have already set the type for this DIE.  */
16968   type = get_die_type (die, cu);
16969   if (type)
16970     return type;
16971
16972   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16973     type = lookup_methodptr_type (to_type);
16974   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16975     {
16976       struct type *new_type
16977         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16978
16979       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16980                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16981                             TYPE_VARARGS (to_type));
16982       type = lookup_methodptr_type (new_type);
16983     }
16984   else
16985     type = lookup_memberptr_type (to_type, domain);
16986
16987   return set_die_type (die, type, cu);
16988 }
16989
16990 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16991    the user defined type vector.  */
16992
16993 static struct type *
16994 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16995                           enum type_code refcode)
16996 {
16997   struct comp_unit_head *cu_header = &cu->header;
16998   struct type *type, *target_type;
16999   struct attribute *attr;
17000
17001   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17002
17003   target_type = die_type (die, cu);
17004
17005   /* The die_type call above may have already set the type for this DIE.  */
17006   type = get_die_type (die, cu);
17007   if (type)
17008     return type;
17009
17010   type = lookup_reference_type (target_type, refcode);
17011   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17012   if (attr)
17013     {
17014       TYPE_LENGTH (type) = DW_UNSND (attr);
17015     }
17016   else
17017     {
17018       TYPE_LENGTH (type) = cu_header->addr_size;
17019     }
17020   maybe_set_alignment (cu, die, type);
17021   return set_die_type (die, type, cu);
17022 }
17023
17024 /* Add the given cv-qualifiers to the element type of the array.  GCC
17025    outputs DWARF type qualifiers that apply to an array, not the
17026    element type.  But GDB relies on the array element type to carry
17027    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17028    specification.  */
17029
17030 static struct type *
17031 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17032                    struct type *base_type, int cnst, int voltl)
17033 {
17034   struct type *el_type, *inner_array;
17035
17036   base_type = copy_type (base_type);
17037   inner_array = base_type;
17038
17039   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17040     {
17041       TYPE_TARGET_TYPE (inner_array) =
17042         copy_type (TYPE_TARGET_TYPE (inner_array));
17043       inner_array = TYPE_TARGET_TYPE (inner_array);
17044     }
17045
17046   el_type = TYPE_TARGET_TYPE (inner_array);
17047   cnst |= TYPE_CONST (el_type);
17048   voltl |= TYPE_VOLATILE (el_type);
17049   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17050
17051   return set_die_type (die, base_type, cu);
17052 }
17053
17054 static struct type *
17055 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17056 {
17057   struct type *base_type, *cv_type;
17058
17059   base_type = die_type (die, cu);
17060
17061   /* The die_type call above may have already set the type for this DIE.  */
17062   cv_type = get_die_type (die, cu);
17063   if (cv_type)
17064     return cv_type;
17065
17066   /* In case the const qualifier is applied to an array type, the element type
17067      is so qualified, not the array type (section 6.7.3 of C99).  */
17068   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17069     return add_array_cv_type (die, cu, base_type, 1, 0);
17070
17071   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17072   return set_die_type (die, cv_type, cu);
17073 }
17074
17075 static struct type *
17076 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17077 {
17078   struct type *base_type, *cv_type;
17079
17080   base_type = die_type (die, cu);
17081
17082   /* The die_type call above may have already set the type for this DIE.  */
17083   cv_type = get_die_type (die, cu);
17084   if (cv_type)
17085     return cv_type;
17086
17087   /* In case the volatile qualifier is applied to an array type, the
17088      element type is so qualified, not the array type (section 6.7.3
17089      of C99).  */
17090   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17091     return add_array_cv_type (die, cu, base_type, 0, 1);
17092
17093   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17094   return set_die_type (die, cv_type, cu);
17095 }
17096
17097 /* Handle DW_TAG_restrict_type.  */
17098
17099 static struct type *
17100 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17101 {
17102   struct type *base_type, *cv_type;
17103
17104   base_type = die_type (die, cu);
17105
17106   /* The die_type call above may have already set the type for this DIE.  */
17107   cv_type = get_die_type (die, cu);
17108   if (cv_type)
17109     return cv_type;
17110
17111   cv_type = make_restrict_type (base_type);
17112   return set_die_type (die, cv_type, cu);
17113 }
17114
17115 /* Handle DW_TAG_atomic_type.  */
17116
17117 static struct type *
17118 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17119 {
17120   struct type *base_type, *cv_type;
17121
17122   base_type = die_type (die, cu);
17123
17124   /* The die_type call above may have already set the type for this DIE.  */
17125   cv_type = get_die_type (die, cu);
17126   if (cv_type)
17127     return cv_type;
17128
17129   cv_type = make_atomic_type (base_type);
17130   return set_die_type (die, cv_type, cu);
17131 }
17132
17133 /* Extract all information from a DW_TAG_string_type DIE and add to
17134    the user defined type vector.  It isn't really a user defined type,
17135    but it behaves like one, with other DIE's using an AT_user_def_type
17136    attribute to reference it.  */
17137
17138 static struct type *
17139 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17140 {
17141   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17142   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17143   struct type *type, *range_type, *index_type, *char_type;
17144   struct attribute *attr;
17145   unsigned int length;
17146
17147   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17148   if (attr)
17149     {
17150       length = DW_UNSND (attr);
17151     }
17152   else
17153     {
17154       /* Check for the DW_AT_byte_size attribute.  */
17155       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17156       if (attr)
17157         {
17158           length = DW_UNSND (attr);
17159         }
17160       else
17161         {
17162           length = 1;
17163         }
17164     }
17165
17166   index_type = objfile_type (objfile)->builtin_int;
17167   range_type = create_static_range_type (NULL, index_type, 1, length);
17168   char_type = language_string_char_type (cu->language_defn, gdbarch);
17169   type = create_string_type (NULL, char_type, range_type);
17170
17171   return set_die_type (die, type, cu);
17172 }
17173
17174 /* Assuming that DIE corresponds to a function, returns nonzero
17175    if the function is prototyped.  */
17176
17177 static int
17178 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17179 {
17180   struct attribute *attr;
17181
17182   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17183   if (attr && (DW_UNSND (attr) != 0))
17184     return 1;
17185
17186   /* The DWARF standard implies that the DW_AT_prototyped attribute
17187      is only meaninful for C, but the concept also extends to other
17188      languages that allow unprototyped functions (Eg: Objective C).
17189      For all other languages, assume that functions are always
17190      prototyped.  */
17191   if (cu->language != language_c
17192       && cu->language != language_objc
17193       && cu->language != language_opencl)
17194     return 1;
17195
17196   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17197      prototyped and unprototyped functions; default to prototyped,
17198      since that is more common in modern code (and RealView warns
17199      about unprototyped functions).  */
17200   if (producer_is_realview (cu->producer))
17201     return 1;
17202
17203   return 0;
17204 }
17205
17206 /* Handle DIES due to C code like:
17207
17208    struct foo
17209    {
17210    int (*funcp)(int a, long l);
17211    int b;
17212    };
17213
17214    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17215
17216 static struct type *
17217 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17218 {
17219   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17220   struct type *type;            /* Type that this function returns.  */
17221   struct type *ftype;           /* Function that returns above type.  */
17222   struct attribute *attr;
17223
17224   type = die_type (die, cu);
17225
17226   /* The die_type call above may have already set the type for this DIE.  */
17227   ftype = get_die_type (die, cu);
17228   if (ftype)
17229     return ftype;
17230
17231   ftype = lookup_function_type (type);
17232
17233   if (prototyped_function_p (die, cu))
17234     TYPE_PROTOTYPED (ftype) = 1;
17235
17236   /* Store the calling convention in the type if it's available in
17237      the subroutine die.  Otherwise set the calling convention to
17238      the default value DW_CC_normal.  */
17239   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17240   if (attr)
17241     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17242   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17243     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17244   else
17245     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17246
17247   /* Record whether the function returns normally to its caller or not
17248      if the DWARF producer set that information.  */
17249   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17250   if (attr && (DW_UNSND (attr) != 0))
17251     TYPE_NO_RETURN (ftype) = 1;
17252
17253   /* We need to add the subroutine type to the die immediately so
17254      we don't infinitely recurse when dealing with parameters
17255      declared as the same subroutine type.  */
17256   set_die_type (die, ftype, cu);
17257
17258   if (die->child != NULL)
17259     {
17260       struct type *void_type = objfile_type (objfile)->builtin_void;
17261       struct die_info *child_die;
17262       int nparams, iparams;
17263
17264       /* Count the number of parameters.
17265          FIXME: GDB currently ignores vararg functions, but knows about
17266          vararg member functions.  */
17267       nparams = 0;
17268       child_die = die->child;
17269       while (child_die && child_die->tag)
17270         {
17271           if (child_die->tag == DW_TAG_formal_parameter)
17272             nparams++;
17273           else if (child_die->tag == DW_TAG_unspecified_parameters)
17274             TYPE_VARARGS (ftype) = 1;
17275           child_die = sibling_die (child_die);
17276         }
17277
17278       /* Allocate storage for parameters and fill them in.  */
17279       TYPE_NFIELDS (ftype) = nparams;
17280       TYPE_FIELDS (ftype) = (struct field *)
17281         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17282
17283       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17284          even if we error out during the parameters reading below.  */
17285       for (iparams = 0; iparams < nparams; iparams++)
17286         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17287
17288       iparams = 0;
17289       child_die = die->child;
17290       while (child_die && child_die->tag)
17291         {
17292           if (child_die->tag == DW_TAG_formal_parameter)
17293             {
17294               struct type *arg_type;
17295
17296               /* DWARF version 2 has no clean way to discern C++
17297                  static and non-static member functions.  G++ helps
17298                  GDB by marking the first parameter for non-static
17299                  member functions (which is the this pointer) as
17300                  artificial.  We pass this information to
17301                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17302
17303                  DWARF version 3 added DW_AT_object_pointer, which GCC
17304                  4.5 does not yet generate.  */
17305               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17306               if (attr)
17307                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17308               else
17309                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17310               arg_type = die_type (child_die, cu);
17311
17312               /* RealView does not mark THIS as const, which the testsuite
17313                  expects.  GCC marks THIS as const in method definitions,
17314                  but not in the class specifications (GCC PR 43053).  */
17315               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17316                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17317                 {
17318                   int is_this = 0;
17319                   struct dwarf2_cu *arg_cu = cu;
17320                   const char *name = dwarf2_name (child_die, cu);
17321
17322                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17323                   if (attr)
17324                     {
17325                       /* If the compiler emits this, use it.  */
17326                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17327                         is_this = 1;
17328                     }
17329                   else if (name && strcmp (name, "this") == 0)
17330                     /* Function definitions will have the argument names.  */
17331                     is_this = 1;
17332                   else if (name == NULL && iparams == 0)
17333                     /* Declarations may not have the names, so like
17334                        elsewhere in GDB, assume an artificial first
17335                        argument is "this".  */
17336                     is_this = 1;
17337
17338                   if (is_this)
17339                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17340                                              arg_type, 0);
17341                 }
17342
17343               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17344               iparams++;
17345             }
17346           child_die = sibling_die (child_die);
17347         }
17348     }
17349
17350   return ftype;
17351 }
17352
17353 static struct type *
17354 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17355 {
17356   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17357   const char *name = NULL;
17358   struct type *this_type, *target_type;
17359
17360   name = dwarf2_full_name (NULL, die, cu);
17361   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17362   TYPE_TARGET_STUB (this_type) = 1;
17363   set_die_type (die, this_type, cu);
17364   target_type = die_type (die, cu);
17365   if (target_type != this_type)
17366     TYPE_TARGET_TYPE (this_type) = target_type;
17367   else
17368     {
17369       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17370          spec and cause infinite loops in GDB.  */
17371       complaint (&symfile_complaints,
17372                  _("Self-referential DW_TAG_typedef "
17373                    "- DIE at %s [in module %s]"),
17374                  sect_offset_str (die->sect_off), objfile_name (objfile));
17375       TYPE_TARGET_TYPE (this_type) = NULL;
17376     }
17377   return this_type;
17378 }
17379
17380 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17381    (which may be different from NAME) to the architecture back-end to allow
17382    it to guess the correct format if necessary.  */
17383
17384 static struct type *
17385 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17386                         const char *name_hint)
17387 {
17388   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17389   const struct floatformat **format;
17390   struct type *type;
17391
17392   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17393   if (format)
17394     type = init_float_type (objfile, bits, name, format);
17395   else
17396     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17397
17398   return type;
17399 }
17400
17401 /* Find a representation of a given base type and install
17402    it in the TYPE field of the die.  */
17403
17404 static struct type *
17405 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17406 {
17407   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17408   struct type *type;
17409   struct attribute *attr;
17410   int encoding = 0, bits = 0;
17411   const char *name;
17412
17413   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17414   if (attr)
17415     {
17416       encoding = DW_UNSND (attr);
17417     }
17418   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17419   if (attr)
17420     {
17421       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17422     }
17423   name = dwarf2_name (die, cu);
17424   if (!name)
17425     {
17426       complaint (&symfile_complaints,
17427                  _("DW_AT_name missing from DW_TAG_base_type"));
17428     }
17429
17430   switch (encoding)
17431     {
17432       case DW_ATE_address:
17433         /* Turn DW_ATE_address into a void * pointer.  */
17434         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17435         type = init_pointer_type (objfile, bits, name, type);
17436         break;
17437       case DW_ATE_boolean:
17438         type = init_boolean_type (objfile, bits, 1, name);
17439         break;
17440       case DW_ATE_complex_float:
17441         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17442         type = init_complex_type (objfile, name, type);
17443         break;
17444       case DW_ATE_decimal_float:
17445         type = init_decfloat_type (objfile, bits, name);
17446         break;
17447       case DW_ATE_float:
17448         type = dwarf2_init_float_type (objfile, bits, name, name);
17449         break;
17450       case DW_ATE_signed:
17451         type = init_integer_type (objfile, bits, 0, name);
17452         break;
17453       case DW_ATE_unsigned:
17454         if (cu->language == language_fortran
17455             && name
17456             && startswith (name, "character("))
17457           type = init_character_type (objfile, bits, 1, name);
17458         else
17459           type = init_integer_type (objfile, bits, 1, name);
17460         break;
17461       case DW_ATE_signed_char:
17462         if (cu->language == language_ada || cu->language == language_m2
17463             || cu->language == language_pascal
17464             || cu->language == language_fortran)
17465           type = init_character_type (objfile, bits, 0, name);
17466         else
17467           type = init_integer_type (objfile, bits, 0, name);
17468         break;
17469       case DW_ATE_unsigned_char:
17470         if (cu->language == language_ada || cu->language == language_m2
17471             || cu->language == language_pascal
17472             || cu->language == language_fortran
17473             || cu->language == language_rust)
17474           type = init_character_type (objfile, bits, 1, name);
17475         else
17476           type = init_integer_type (objfile, bits, 1, name);
17477         break;
17478       case DW_ATE_UTF:
17479         {
17480           gdbarch *arch = get_objfile_arch (objfile);
17481
17482           if (bits == 16)
17483             type = builtin_type (arch)->builtin_char16;
17484           else if (bits == 32)
17485             type = builtin_type (arch)->builtin_char32;
17486           else
17487             {
17488               complaint (&symfile_complaints,
17489                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17490                          bits);
17491               type = init_integer_type (objfile, bits, 1, name);
17492             }
17493           return set_die_type (die, type, cu);
17494         }
17495         break;
17496
17497       default:
17498         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17499                    dwarf_type_encoding_name (encoding));
17500         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17501         break;
17502     }
17503
17504   if (name && strcmp (name, "char") == 0)
17505     TYPE_NOSIGN (type) = 1;
17506
17507   maybe_set_alignment (cu, die, type);
17508
17509   return set_die_type (die, type, cu);
17510 }
17511
17512 /* Parse dwarf attribute if it's a block, reference or constant and put the
17513    resulting value of the attribute into struct bound_prop.
17514    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17515
17516 static int
17517 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17518                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17519 {
17520   struct dwarf2_property_baton *baton;
17521   struct obstack *obstack
17522     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17523
17524   if (attr == NULL || prop == NULL)
17525     return 0;
17526
17527   if (attr_form_is_block (attr))
17528     {
17529       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17530       baton->referenced_type = NULL;
17531       baton->locexpr.per_cu = cu->per_cu;
17532       baton->locexpr.size = DW_BLOCK (attr)->size;
17533       baton->locexpr.data = DW_BLOCK (attr)->data;
17534       prop->data.baton = baton;
17535       prop->kind = PROP_LOCEXPR;
17536       gdb_assert (prop->data.baton != NULL);
17537     }
17538   else if (attr_form_is_ref (attr))
17539     {
17540       struct dwarf2_cu *target_cu = cu;
17541       struct die_info *target_die;
17542       struct attribute *target_attr;
17543
17544       target_die = follow_die_ref (die, attr, &target_cu);
17545       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17546       if (target_attr == NULL)
17547         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17548                                    target_cu);
17549       if (target_attr == NULL)
17550         return 0;
17551
17552       switch (target_attr->name)
17553         {
17554           case DW_AT_location:
17555             if (attr_form_is_section_offset (target_attr))
17556               {
17557                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17558                 baton->referenced_type = die_type (target_die, target_cu);
17559                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17560                 prop->data.baton = baton;
17561                 prop->kind = PROP_LOCLIST;
17562                 gdb_assert (prop->data.baton != NULL);
17563               }
17564             else if (attr_form_is_block (target_attr))
17565               {
17566                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17567                 baton->referenced_type = die_type (target_die, target_cu);
17568                 baton->locexpr.per_cu = cu->per_cu;
17569                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17570                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17571                 prop->data.baton = baton;
17572                 prop->kind = PROP_LOCEXPR;
17573                 gdb_assert (prop->data.baton != NULL);
17574               }
17575             else
17576               {
17577                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17578                                                        "dynamic property");
17579                 return 0;
17580               }
17581             break;
17582           case DW_AT_data_member_location:
17583             {
17584               LONGEST offset;
17585
17586               if (!handle_data_member_location (target_die, target_cu,
17587                                                 &offset))
17588                 return 0;
17589
17590               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17591               baton->referenced_type = read_type_die (target_die->parent,
17592                                                       target_cu);
17593               baton->offset_info.offset = offset;
17594               baton->offset_info.type = die_type (target_die, target_cu);
17595               prop->data.baton = baton;
17596               prop->kind = PROP_ADDR_OFFSET;
17597               break;
17598             }
17599         }
17600     }
17601   else if (attr_form_is_constant (attr))
17602     {
17603       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17604       prop->kind = PROP_CONST;
17605     }
17606   else
17607     {
17608       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17609                                              dwarf2_name (die, cu));
17610       return 0;
17611     }
17612
17613   return 1;
17614 }
17615
17616 /* Read the given DW_AT_subrange DIE.  */
17617
17618 static struct type *
17619 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17620 {
17621   struct type *base_type, *orig_base_type;
17622   struct type *range_type;
17623   struct attribute *attr;
17624   struct dynamic_prop low, high;
17625   int low_default_is_valid;
17626   int high_bound_is_count = 0;
17627   const char *name;
17628   LONGEST negative_mask;
17629
17630   orig_base_type = die_type (die, cu);
17631   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17632      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17633      creating the range type, but we use the result of check_typedef
17634      when examining properties of the type.  */
17635   base_type = check_typedef (orig_base_type);
17636
17637   /* The die_type call above may have already set the type for this DIE.  */
17638   range_type = get_die_type (die, cu);
17639   if (range_type)
17640     return range_type;
17641
17642   low.kind = PROP_CONST;
17643   high.kind = PROP_CONST;
17644   high.data.const_val = 0;
17645
17646   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17647      omitting DW_AT_lower_bound.  */
17648   switch (cu->language)
17649     {
17650     case language_c:
17651     case language_cplus:
17652       low.data.const_val = 0;
17653       low_default_is_valid = 1;
17654       break;
17655     case language_fortran:
17656       low.data.const_val = 1;
17657       low_default_is_valid = 1;
17658       break;
17659     case language_d:
17660     case language_objc:
17661     case language_rust:
17662       low.data.const_val = 0;
17663       low_default_is_valid = (cu->header.version >= 4);
17664       break;
17665     case language_ada:
17666     case language_m2:
17667     case language_pascal:
17668       low.data.const_val = 1;
17669       low_default_is_valid = (cu->header.version >= 4);
17670       break;
17671     default:
17672       low.data.const_val = 0;
17673       low_default_is_valid = 0;
17674       break;
17675     }
17676
17677   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17678   if (attr)
17679     attr_to_dynamic_prop (attr, die, cu, &low);
17680   else if (!low_default_is_valid)
17681     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17682                                       "- DIE at %s [in module %s]"),
17683                sect_offset_str (die->sect_off),
17684                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17685
17686   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17687   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17688     {
17689       attr = dwarf2_attr (die, DW_AT_count, cu);
17690       if (attr_to_dynamic_prop (attr, die, cu, &high))
17691         {
17692           /* If bounds are constant do the final calculation here.  */
17693           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17694             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17695           else
17696             high_bound_is_count = 1;
17697         }
17698     }
17699
17700   /* Dwarf-2 specifications explicitly allows to create subrange types
17701      without specifying a base type.
17702      In that case, the base type must be set to the type of
17703      the lower bound, upper bound or count, in that order, if any of these
17704      three attributes references an object that has a type.
17705      If no base type is found, the Dwarf-2 specifications say that
17706      a signed integer type of size equal to the size of an address should
17707      be used.
17708      For the following C code: `extern char gdb_int [];'
17709      GCC produces an empty range DIE.
17710      FIXME: muller/2010-05-28: Possible references to object for low bound,
17711      high bound or count are not yet handled by this code.  */
17712   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17713     {
17714       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17715       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17716       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17717       struct type *int_type = objfile_type (objfile)->builtin_int;
17718
17719       /* Test "int", "long int", and "long long int" objfile types,
17720          and select the first one having a size above or equal to the
17721          architecture address size.  */
17722       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17723         base_type = int_type;
17724       else
17725         {
17726           int_type = objfile_type (objfile)->builtin_long;
17727           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17728             base_type = int_type;
17729           else
17730             {
17731               int_type = objfile_type (objfile)->builtin_long_long;
17732               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17733                 base_type = int_type;
17734             }
17735         }
17736     }
17737
17738   /* Normally, the DWARF producers are expected to use a signed
17739      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17740      But this is unfortunately not always the case, as witnessed
17741      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17742      is used instead.  To work around that ambiguity, we treat
17743      the bounds as signed, and thus sign-extend their values, when
17744      the base type is signed.  */
17745   negative_mask =
17746     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17747   if (low.kind == PROP_CONST
17748       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17749     low.data.const_val |= negative_mask;
17750   if (high.kind == PROP_CONST
17751       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17752     high.data.const_val |= negative_mask;
17753
17754   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17755
17756   if (high_bound_is_count)
17757     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17758
17759   /* Ada expects an empty array on no boundary attributes.  */
17760   if (attr == NULL && cu->language != language_ada)
17761     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17762
17763   name = dwarf2_name (die, cu);
17764   if (name)
17765     TYPE_NAME (range_type) = name;
17766
17767   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17768   if (attr)
17769     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17770
17771   maybe_set_alignment (cu, die, range_type);
17772
17773   set_die_type (die, range_type, cu);
17774
17775   /* set_die_type should be already done.  */
17776   set_descriptive_type (range_type, die, cu);
17777
17778   return range_type;
17779 }
17780
17781 static struct type *
17782 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17783 {
17784   struct type *type;
17785
17786   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17787                     NULL);
17788   TYPE_NAME (type) = dwarf2_name (die, cu);
17789
17790   /* In Ada, an unspecified type is typically used when the description
17791      of the type is defered to a different unit.  When encountering
17792      such a type, we treat it as a stub, and try to resolve it later on,
17793      when needed.  */
17794   if (cu->language == language_ada)
17795     TYPE_STUB (type) = 1;
17796
17797   return set_die_type (die, type, cu);
17798 }
17799
17800 /* Read a single die and all its descendents.  Set the die's sibling
17801    field to NULL; set other fields in the die correctly, and set all
17802    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17803    location of the info_ptr after reading all of those dies.  PARENT
17804    is the parent of the die in question.  */
17805
17806 static struct die_info *
17807 read_die_and_children (const struct die_reader_specs *reader,
17808                        const gdb_byte *info_ptr,
17809                        const gdb_byte **new_info_ptr,
17810                        struct die_info *parent)
17811 {
17812   struct die_info *die;
17813   const gdb_byte *cur_ptr;
17814   int has_children;
17815
17816   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17817   if (die == NULL)
17818     {
17819       *new_info_ptr = cur_ptr;
17820       return NULL;
17821     }
17822   store_in_ref_table (die, reader->cu);
17823
17824   if (has_children)
17825     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17826   else
17827     {
17828       die->child = NULL;
17829       *new_info_ptr = cur_ptr;
17830     }
17831
17832   die->sibling = NULL;
17833   die->parent = parent;
17834   return die;
17835 }
17836
17837 /* Read a die, all of its descendents, and all of its siblings; set
17838    all of the fields of all of the dies correctly.  Arguments are as
17839    in read_die_and_children.  */
17840
17841 static struct die_info *
17842 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17843                          const gdb_byte *info_ptr,
17844                          const gdb_byte **new_info_ptr,
17845                          struct die_info *parent)
17846 {
17847   struct die_info *first_die, *last_sibling;
17848   const gdb_byte *cur_ptr;
17849
17850   cur_ptr = info_ptr;
17851   first_die = last_sibling = NULL;
17852
17853   while (1)
17854     {
17855       struct die_info *die
17856         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17857
17858       if (die == NULL)
17859         {
17860           *new_info_ptr = cur_ptr;
17861           return first_die;
17862         }
17863
17864       if (!first_die)
17865         first_die = die;
17866       else
17867         last_sibling->sibling = die;
17868
17869       last_sibling = die;
17870     }
17871 }
17872
17873 /* Read a die, all of its descendents, and all of its siblings; set
17874    all of the fields of all of the dies correctly.  Arguments are as
17875    in read_die_and_children.
17876    This the main entry point for reading a DIE and all its children.  */
17877
17878 static struct die_info *
17879 read_die_and_siblings (const struct die_reader_specs *reader,
17880                        const gdb_byte *info_ptr,
17881                        const gdb_byte **new_info_ptr,
17882                        struct die_info *parent)
17883 {
17884   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17885                                                   new_info_ptr, parent);
17886
17887   if (dwarf_die_debug)
17888     {
17889       fprintf_unfiltered (gdb_stdlog,
17890                           "Read die from %s@0x%x of %s:\n",
17891                           get_section_name (reader->die_section),
17892                           (unsigned) (info_ptr - reader->die_section->buffer),
17893                           bfd_get_filename (reader->abfd));
17894       dump_die (die, dwarf_die_debug);
17895     }
17896
17897   return die;
17898 }
17899
17900 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17901    attributes.
17902    The caller is responsible for filling in the extra attributes
17903    and updating (*DIEP)->num_attrs.
17904    Set DIEP to point to a newly allocated die with its information,
17905    except for its child, sibling, and parent fields.
17906    Set HAS_CHILDREN to tell whether the die has children or not.  */
17907
17908 static const gdb_byte *
17909 read_full_die_1 (const struct die_reader_specs *reader,
17910                  struct die_info **diep, const gdb_byte *info_ptr,
17911                  int *has_children, int num_extra_attrs)
17912 {
17913   unsigned int abbrev_number, bytes_read, i;
17914   struct abbrev_info *abbrev;
17915   struct die_info *die;
17916   struct dwarf2_cu *cu = reader->cu;
17917   bfd *abfd = reader->abfd;
17918
17919   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17920   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17921   info_ptr += bytes_read;
17922   if (!abbrev_number)
17923     {
17924       *diep = NULL;
17925       *has_children = 0;
17926       return info_ptr;
17927     }
17928
17929   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17930   if (!abbrev)
17931     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17932            abbrev_number,
17933            bfd_get_filename (abfd));
17934
17935   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17936   die->sect_off = sect_off;
17937   die->tag = abbrev->tag;
17938   die->abbrev = abbrev_number;
17939
17940   /* Make the result usable.
17941      The caller needs to update num_attrs after adding the extra
17942      attributes.  */
17943   die->num_attrs = abbrev->num_attrs;
17944
17945   for (i = 0; i < abbrev->num_attrs; ++i)
17946     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17947                                info_ptr);
17948
17949   *diep = die;
17950   *has_children = abbrev->has_children;
17951   return info_ptr;
17952 }
17953
17954 /* Read a die and all its attributes.
17955    Set DIEP to point to a newly allocated die with its information,
17956    except for its child, sibling, and parent fields.
17957    Set HAS_CHILDREN to tell whether the die has children or not.  */
17958
17959 static const gdb_byte *
17960 read_full_die (const struct die_reader_specs *reader,
17961                struct die_info **diep, const gdb_byte *info_ptr,
17962                int *has_children)
17963 {
17964   const gdb_byte *result;
17965
17966   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17967
17968   if (dwarf_die_debug)
17969     {
17970       fprintf_unfiltered (gdb_stdlog,
17971                           "Read die from %s@0x%x of %s:\n",
17972                           get_section_name (reader->die_section),
17973                           (unsigned) (info_ptr - reader->die_section->buffer),
17974                           bfd_get_filename (reader->abfd));
17975       dump_die (*diep, dwarf_die_debug);
17976     }
17977
17978   return result;
17979 }
17980 \f
17981 /* Abbreviation tables.
17982
17983    In DWARF version 2, the description of the debugging information is
17984    stored in a separate .debug_abbrev section.  Before we read any
17985    dies from a section we read in all abbreviations and install them
17986    in a hash table.  */
17987
17988 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17989
17990 struct abbrev_info *
17991 abbrev_table::alloc_abbrev ()
17992 {
17993   struct abbrev_info *abbrev;
17994
17995   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
17996   memset (abbrev, 0, sizeof (struct abbrev_info));
17997
17998   return abbrev;
17999 }
18000
18001 /* Add an abbreviation to the table.  */
18002
18003 void
18004 abbrev_table::add_abbrev (unsigned int abbrev_number,
18005                           struct abbrev_info *abbrev)
18006 {
18007   unsigned int hash_number;
18008
18009   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18010   abbrev->next = m_abbrevs[hash_number];
18011   m_abbrevs[hash_number] = abbrev;
18012 }
18013
18014 /* Look up an abbrev in the table.
18015    Returns NULL if the abbrev is not found.  */
18016
18017 struct abbrev_info *
18018 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18019 {
18020   unsigned int hash_number;
18021   struct abbrev_info *abbrev;
18022
18023   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18024   abbrev = m_abbrevs[hash_number];
18025
18026   while (abbrev)
18027     {
18028       if (abbrev->number == abbrev_number)
18029         return abbrev;
18030       abbrev = abbrev->next;
18031     }
18032   return NULL;
18033 }
18034
18035 /* Read in an abbrev table.  */
18036
18037 static abbrev_table_up
18038 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18039                          struct dwarf2_section_info *section,
18040                          sect_offset sect_off)
18041 {
18042   struct objfile *objfile = dwarf2_per_objfile->objfile;
18043   bfd *abfd = get_section_bfd_owner (section);
18044   const gdb_byte *abbrev_ptr;
18045   struct abbrev_info *cur_abbrev;
18046   unsigned int abbrev_number, bytes_read, abbrev_name;
18047   unsigned int abbrev_form;
18048   struct attr_abbrev *cur_attrs;
18049   unsigned int allocated_attrs;
18050
18051   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18052
18053   dwarf2_read_section (objfile, section);
18054   abbrev_ptr = section->buffer + to_underlying (sect_off);
18055   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18056   abbrev_ptr += bytes_read;
18057
18058   allocated_attrs = ATTR_ALLOC_CHUNK;
18059   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18060
18061   /* Loop until we reach an abbrev number of 0.  */
18062   while (abbrev_number)
18063     {
18064       cur_abbrev = abbrev_table->alloc_abbrev ();
18065
18066       /* read in abbrev header */
18067       cur_abbrev->number = abbrev_number;
18068       cur_abbrev->tag
18069         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18070       abbrev_ptr += bytes_read;
18071       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18072       abbrev_ptr += 1;
18073
18074       /* now read in declarations */
18075       for (;;)
18076         {
18077           LONGEST implicit_const;
18078
18079           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18080           abbrev_ptr += bytes_read;
18081           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18082           abbrev_ptr += bytes_read;
18083           if (abbrev_form == DW_FORM_implicit_const)
18084             {
18085               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18086                                                    &bytes_read);
18087               abbrev_ptr += bytes_read;
18088             }
18089           else
18090             {
18091               /* Initialize it due to a false compiler warning.  */
18092               implicit_const = -1;
18093             }
18094
18095           if (abbrev_name == 0)
18096             break;
18097
18098           if (cur_abbrev->num_attrs == allocated_attrs)
18099             {
18100               allocated_attrs += ATTR_ALLOC_CHUNK;
18101               cur_attrs
18102                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18103             }
18104
18105           cur_attrs[cur_abbrev->num_attrs].name
18106             = (enum dwarf_attribute) abbrev_name;
18107           cur_attrs[cur_abbrev->num_attrs].form
18108             = (enum dwarf_form) abbrev_form;
18109           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18110           ++cur_abbrev->num_attrs;
18111         }
18112
18113       cur_abbrev->attrs =
18114         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18115                    cur_abbrev->num_attrs);
18116       memcpy (cur_abbrev->attrs, cur_attrs,
18117               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18118
18119       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18120
18121       /* Get next abbreviation.
18122          Under Irix6 the abbreviations for a compilation unit are not
18123          always properly terminated with an abbrev number of 0.
18124          Exit loop if we encounter an abbreviation which we have
18125          already read (which means we are about to read the abbreviations
18126          for the next compile unit) or if the end of the abbreviation
18127          table is reached.  */
18128       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18129         break;
18130       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18131       abbrev_ptr += bytes_read;
18132       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18133         break;
18134     }
18135
18136   xfree (cur_attrs);
18137   return abbrev_table;
18138 }
18139
18140 /* Returns nonzero if TAG represents a type that we might generate a partial
18141    symbol for.  */
18142
18143 static int
18144 is_type_tag_for_partial (int tag)
18145 {
18146   switch (tag)
18147     {
18148 #if 0
18149     /* Some types that would be reasonable to generate partial symbols for,
18150        that we don't at present.  */
18151     case DW_TAG_array_type:
18152     case DW_TAG_file_type:
18153     case DW_TAG_ptr_to_member_type:
18154     case DW_TAG_set_type:
18155     case DW_TAG_string_type:
18156     case DW_TAG_subroutine_type:
18157 #endif
18158     case DW_TAG_base_type:
18159     case DW_TAG_class_type:
18160     case DW_TAG_interface_type:
18161     case DW_TAG_enumeration_type:
18162     case DW_TAG_structure_type:
18163     case DW_TAG_subrange_type:
18164     case DW_TAG_typedef:
18165     case DW_TAG_union_type:
18166       return 1;
18167     default:
18168       return 0;
18169     }
18170 }
18171
18172 /* Load all DIEs that are interesting for partial symbols into memory.  */
18173
18174 static struct partial_die_info *
18175 load_partial_dies (const struct die_reader_specs *reader,
18176                    const gdb_byte *info_ptr, int building_psymtab)
18177 {
18178   struct dwarf2_cu *cu = reader->cu;
18179   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18180   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18181   unsigned int bytes_read;
18182   unsigned int load_all = 0;
18183   int nesting_level = 1;
18184
18185   parent_die = NULL;
18186   last_die = NULL;
18187
18188   gdb_assert (cu->per_cu != NULL);
18189   if (cu->per_cu->load_all_dies)
18190     load_all = 1;
18191
18192   cu->partial_dies
18193     = htab_create_alloc_ex (cu->header.length / 12,
18194                             partial_die_hash,
18195                             partial_die_eq,
18196                             NULL,
18197                             &cu->comp_unit_obstack,
18198                             hashtab_obstack_allocate,
18199                             dummy_obstack_deallocate);
18200
18201   while (1)
18202     {
18203       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18204
18205       /* A NULL abbrev means the end of a series of children.  */
18206       if (abbrev == NULL)
18207         {
18208           if (--nesting_level == 0)
18209             return first_die;
18210
18211           info_ptr += bytes_read;
18212           last_die = parent_die;
18213           parent_die = parent_die->die_parent;
18214           continue;
18215         }
18216
18217       /* Check for template arguments.  We never save these; if
18218          they're seen, we just mark the parent, and go on our way.  */
18219       if (parent_die != NULL
18220           && cu->language == language_cplus
18221           && (abbrev->tag == DW_TAG_template_type_param
18222               || abbrev->tag == DW_TAG_template_value_param))
18223         {
18224           parent_die->has_template_arguments = 1;
18225
18226           if (!load_all)
18227             {
18228               /* We don't need a partial DIE for the template argument.  */
18229               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18230               continue;
18231             }
18232         }
18233
18234       /* We only recurse into c++ subprograms looking for template arguments.
18235          Skip their other children.  */
18236       if (!load_all
18237           && cu->language == language_cplus
18238           && parent_die != NULL
18239           && parent_die->tag == DW_TAG_subprogram)
18240         {
18241           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18242           continue;
18243         }
18244
18245       /* Check whether this DIE is interesting enough to save.  Normally
18246          we would not be interested in members here, but there may be
18247          later variables referencing them via DW_AT_specification (for
18248          static members).  */
18249       if (!load_all
18250           && !is_type_tag_for_partial (abbrev->tag)
18251           && abbrev->tag != DW_TAG_constant
18252           && abbrev->tag != DW_TAG_enumerator
18253           && abbrev->tag != DW_TAG_subprogram
18254           && abbrev->tag != DW_TAG_inlined_subroutine
18255           && abbrev->tag != DW_TAG_lexical_block
18256           && abbrev->tag != DW_TAG_variable
18257           && abbrev->tag != DW_TAG_namespace
18258           && abbrev->tag != DW_TAG_module
18259           && abbrev->tag != DW_TAG_member
18260           && abbrev->tag != DW_TAG_imported_unit
18261           && abbrev->tag != DW_TAG_imported_declaration)
18262         {
18263           /* Otherwise we skip to the next sibling, if any.  */
18264           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18265           continue;
18266         }
18267
18268       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18269                                    abbrev);
18270
18271       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18272
18273       /* This two-pass algorithm for processing partial symbols has a
18274          high cost in cache pressure.  Thus, handle some simple cases
18275          here which cover the majority of C partial symbols.  DIEs
18276          which neither have specification tags in them, nor could have
18277          specification tags elsewhere pointing at them, can simply be
18278          processed and discarded.
18279
18280          This segment is also optional; scan_partial_symbols and
18281          add_partial_symbol will handle these DIEs if we chain
18282          them in normally.  When compilers which do not emit large
18283          quantities of duplicate debug information are more common,
18284          this code can probably be removed.  */
18285
18286       /* Any complete simple types at the top level (pretty much all
18287          of them, for a language without namespaces), can be processed
18288          directly.  */
18289       if (parent_die == NULL
18290           && pdi.has_specification == 0
18291           && pdi.is_declaration == 0
18292           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18293               || pdi.tag == DW_TAG_base_type
18294               || pdi.tag == DW_TAG_subrange_type))
18295         {
18296           if (building_psymtab && pdi.name != NULL)
18297             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18298                                  VAR_DOMAIN, LOC_TYPEDEF,
18299                                  &objfile->static_psymbols,
18300                                  0, cu->language, objfile);
18301           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18302           continue;
18303         }
18304
18305       /* The exception for DW_TAG_typedef with has_children above is
18306          a workaround of GCC PR debug/47510.  In the case of this complaint
18307          type_name_no_tag_or_error will error on such types later.
18308
18309          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18310          it could not find the child DIEs referenced later, this is checked
18311          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18312
18313       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18314         complaint (&symfile_complaints,
18315                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18316                      "- DIE at %s [in module %s]"),
18317                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18318
18319       /* If we're at the second level, and we're an enumerator, and
18320          our parent has no specification (meaning possibly lives in a
18321          namespace elsewhere), then we can add the partial symbol now
18322          instead of queueing it.  */
18323       if (pdi.tag == DW_TAG_enumerator
18324           && parent_die != NULL
18325           && parent_die->die_parent == NULL
18326           && parent_die->tag == DW_TAG_enumeration_type
18327           && parent_die->has_specification == 0)
18328         {
18329           if (pdi.name == NULL)
18330             complaint (&symfile_complaints,
18331                        _("malformed enumerator DIE ignored"));
18332           else if (building_psymtab)
18333             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18334                                  VAR_DOMAIN, LOC_CONST,
18335                                  cu->language == language_cplus
18336                                  ? &objfile->global_psymbols
18337                                  : &objfile->static_psymbols,
18338                                  0, cu->language, objfile);
18339
18340           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18341           continue;
18342         }
18343
18344       struct partial_die_info *part_die
18345         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18346
18347       /* We'll save this DIE so link it in.  */
18348       part_die->die_parent = parent_die;
18349       part_die->die_sibling = NULL;
18350       part_die->die_child = NULL;
18351
18352       if (last_die && last_die == parent_die)
18353         last_die->die_child = part_die;
18354       else if (last_die)
18355         last_die->die_sibling = part_die;
18356
18357       last_die = part_die;
18358
18359       if (first_die == NULL)
18360         first_die = part_die;
18361
18362       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18363          find interesting need to be in the hash table, because we
18364          also have the parent/sibling/child chains; only those that we
18365          might refer to by offset later during partial symbol reading.
18366
18367          For now this means things that might have be the target of a
18368          DW_AT_specification, DW_AT_abstract_origin, or
18369          DW_AT_extension.  DW_AT_extension will refer only to
18370          namespaces; DW_AT_abstract_origin refers to functions (and
18371          many things under the function DIE, but we do not recurse
18372          into function DIEs during partial symbol reading) and
18373          possibly variables as well; DW_AT_specification refers to
18374          declarations.  Declarations ought to have the DW_AT_declaration
18375          flag.  It happens that GCC forgets to put it in sometimes, but
18376          only for functions, not for types.
18377
18378          Adding more things than necessary to the hash table is harmless
18379          except for the performance cost.  Adding too few will result in
18380          wasted time in find_partial_die, when we reread the compilation
18381          unit with load_all_dies set.  */
18382
18383       if (load_all
18384           || abbrev->tag == DW_TAG_constant
18385           || abbrev->tag == DW_TAG_subprogram
18386           || abbrev->tag == DW_TAG_variable
18387           || abbrev->tag == DW_TAG_namespace
18388           || part_die->is_declaration)
18389         {
18390           void **slot;
18391
18392           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18393                                            to_underlying (part_die->sect_off),
18394                                            INSERT);
18395           *slot = part_die;
18396         }
18397
18398       /* For some DIEs we want to follow their children (if any).  For C
18399          we have no reason to follow the children of structures; for other
18400          languages we have to, so that we can get at method physnames
18401          to infer fully qualified class names, for DW_AT_specification,
18402          and for C++ template arguments.  For C++, we also look one level
18403          inside functions to find template arguments (if the name of the
18404          function does not already contain the template arguments).
18405
18406          For Ada, we need to scan the children of subprograms and lexical
18407          blocks as well because Ada allows the definition of nested
18408          entities that could be interesting for the debugger, such as
18409          nested subprograms for instance.  */
18410       if (last_die->has_children
18411           && (load_all
18412               || last_die->tag == DW_TAG_namespace
18413               || last_die->tag == DW_TAG_module
18414               || last_die->tag == DW_TAG_enumeration_type
18415               || (cu->language == language_cplus
18416                   && last_die->tag == DW_TAG_subprogram
18417                   && (last_die->name == NULL
18418                       || strchr (last_die->name, '<') == NULL))
18419               || (cu->language != language_c
18420                   && (last_die->tag == DW_TAG_class_type
18421                       || last_die->tag == DW_TAG_interface_type
18422                       || last_die->tag == DW_TAG_structure_type
18423                       || last_die->tag == DW_TAG_union_type))
18424               || (cu->language == language_ada
18425                   && (last_die->tag == DW_TAG_subprogram
18426                       || last_die->tag == DW_TAG_lexical_block))))
18427         {
18428           nesting_level++;
18429           parent_die = last_die;
18430           continue;
18431         }
18432
18433       /* Otherwise we skip to the next sibling, if any.  */
18434       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18435
18436       /* Back to the top, do it again.  */
18437     }
18438 }
18439
18440 partial_die_info::partial_die_info (sect_offset sect_off_,
18441                                     struct abbrev_info *abbrev)
18442   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18443 {
18444 }
18445
18446 /* Read a minimal amount of information into the minimal die structure.
18447    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18448
18449 const gdb_byte *
18450 partial_die_info::read (const struct die_reader_specs *reader,
18451                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18452 {
18453   struct dwarf2_cu *cu = reader->cu;
18454   struct dwarf2_per_objfile *dwarf2_per_objfile
18455     = cu->per_cu->dwarf2_per_objfile;
18456   unsigned int i;
18457   int has_low_pc_attr = 0;
18458   int has_high_pc_attr = 0;
18459   int high_pc_relative = 0;
18460
18461   for (i = 0; i < abbrev.num_attrs; ++i)
18462     {
18463       struct attribute attr;
18464
18465       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18466
18467       /* Store the data if it is of an attribute we want to keep in a
18468          partial symbol table.  */
18469       switch (attr.name)
18470         {
18471         case DW_AT_name:
18472           switch (tag)
18473             {
18474             case DW_TAG_compile_unit:
18475             case DW_TAG_partial_unit:
18476             case DW_TAG_type_unit:
18477               /* Compilation units have a DW_AT_name that is a filename, not
18478                  a source language identifier.  */
18479             case DW_TAG_enumeration_type:
18480             case DW_TAG_enumerator:
18481               /* These tags always have simple identifiers already; no need
18482                  to canonicalize them.  */
18483               name = DW_STRING (&attr);
18484               break;
18485             default:
18486               {
18487                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18488
18489                 name
18490                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18491                                               &objfile->per_bfd->storage_obstack);
18492               }
18493               break;
18494             }
18495           break;
18496         case DW_AT_linkage_name:
18497         case DW_AT_MIPS_linkage_name:
18498           /* Note that both forms of linkage name might appear.  We
18499              assume they will be the same, and we only store the last
18500              one we see.  */
18501           if (cu->language == language_ada)
18502             name = DW_STRING (&attr);
18503           linkage_name = DW_STRING (&attr);
18504           break;
18505         case DW_AT_low_pc:
18506           has_low_pc_attr = 1;
18507           lowpc = attr_value_as_address (&attr);
18508           break;
18509         case DW_AT_high_pc:
18510           has_high_pc_attr = 1;
18511           highpc = attr_value_as_address (&attr);
18512           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18513                 high_pc_relative = 1;
18514           break;
18515         case DW_AT_location:
18516           /* Support the .debug_loc offsets.  */
18517           if (attr_form_is_block (&attr))
18518             {
18519                d.locdesc = DW_BLOCK (&attr);
18520             }
18521           else if (attr_form_is_section_offset (&attr))
18522             {
18523               dwarf2_complex_location_expr_complaint ();
18524             }
18525           else
18526             {
18527               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18528                                                      "partial symbol information");
18529             }
18530           break;
18531         case DW_AT_external:
18532           is_external = DW_UNSND (&attr);
18533           break;
18534         case DW_AT_declaration:
18535           is_declaration = DW_UNSND (&attr);
18536           break;
18537         case DW_AT_type:
18538           has_type = 1;
18539           break;
18540         case DW_AT_abstract_origin:
18541         case DW_AT_specification:
18542         case DW_AT_extension:
18543           has_specification = 1;
18544           spec_offset = dwarf2_get_ref_die_offset (&attr);
18545           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18546                                    || cu->per_cu->is_dwz);
18547           break;
18548         case DW_AT_sibling:
18549           /* Ignore absolute siblings, they might point outside of
18550              the current compile unit.  */
18551           if (attr.form == DW_FORM_ref_addr)
18552             complaint (&symfile_complaints,
18553                        _("ignoring absolute DW_AT_sibling"));
18554           else
18555             {
18556               const gdb_byte *buffer = reader->buffer;
18557               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18558               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18559
18560               if (sibling_ptr < info_ptr)
18561                 complaint (&symfile_complaints,
18562                            _("DW_AT_sibling points backwards"));
18563               else if (sibling_ptr > reader->buffer_end)
18564                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18565               else
18566                 sibling = sibling_ptr;
18567             }
18568           break;
18569         case DW_AT_byte_size:
18570           has_byte_size = 1;
18571           break;
18572         case DW_AT_const_value:
18573           has_const_value = 1;
18574           break;
18575         case DW_AT_calling_convention:
18576           /* DWARF doesn't provide a way to identify a program's source-level
18577              entry point.  DW_AT_calling_convention attributes are only meant
18578              to describe functions' calling conventions.
18579
18580              However, because it's a necessary piece of information in
18581              Fortran, and before DWARF 4 DW_CC_program was the only
18582              piece of debugging information whose definition refers to
18583              a 'main program' at all, several compilers marked Fortran
18584              main programs with DW_CC_program --- even when those
18585              functions use the standard calling conventions.
18586
18587              Although DWARF now specifies a way to provide this
18588              information, we support this practice for backward
18589              compatibility.  */
18590           if (DW_UNSND (&attr) == DW_CC_program
18591               && cu->language == language_fortran)
18592             main_subprogram = 1;
18593           break;
18594         case DW_AT_inline:
18595           if (DW_UNSND (&attr) == DW_INL_inlined
18596               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18597             may_be_inlined = 1;
18598           break;
18599
18600         case DW_AT_import:
18601           if (tag == DW_TAG_imported_unit)
18602             {
18603               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18604               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18605                                   || cu->per_cu->is_dwz);
18606             }
18607           break;
18608
18609         case DW_AT_main_subprogram:
18610           main_subprogram = DW_UNSND (&attr);
18611           break;
18612
18613         default:
18614           break;
18615         }
18616     }
18617
18618   if (high_pc_relative)
18619     highpc += lowpc;
18620
18621   if (has_low_pc_attr && has_high_pc_attr)
18622     {
18623       /* When using the GNU linker, .gnu.linkonce. sections are used to
18624          eliminate duplicate copies of functions and vtables and such.
18625          The linker will arbitrarily choose one and discard the others.
18626          The AT_*_pc values for such functions refer to local labels in
18627          these sections.  If the section from that file was discarded, the
18628          labels are not in the output, so the relocs get a value of 0.
18629          If this is a discarded function, mark the pc bounds as invalid,
18630          so that GDB will ignore it.  */
18631       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18632         {
18633           struct objfile *objfile = dwarf2_per_objfile->objfile;
18634           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18635
18636           complaint (&symfile_complaints,
18637                      _("DW_AT_low_pc %s is zero "
18638                        "for DIE at %s [in module %s]"),
18639                      paddress (gdbarch, lowpc),
18640                      sect_offset_str (sect_off),
18641                      objfile_name (objfile));
18642         }
18643       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18644       else if (lowpc >= highpc)
18645         {
18646           struct objfile *objfile = dwarf2_per_objfile->objfile;
18647           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18648
18649           complaint (&symfile_complaints,
18650                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18651                        "for DIE at %s [in module %s]"),
18652                      paddress (gdbarch, lowpc),
18653                      paddress (gdbarch, highpc),
18654                      sect_offset_str (sect_off),
18655                      objfile_name (objfile));
18656         }
18657       else
18658         has_pc_info = 1;
18659     }
18660
18661   return info_ptr;
18662 }
18663
18664 /* Find a cached partial DIE at OFFSET in CU.  */
18665
18666 struct partial_die_info *
18667 dwarf2_cu::find_partial_die (sect_offset sect_off)
18668 {
18669   struct partial_die_info *lookup_die = NULL;
18670   struct partial_die_info part_die (sect_off);
18671
18672   lookup_die = ((struct partial_die_info *)
18673                 htab_find_with_hash (partial_dies, &part_die,
18674                                      to_underlying (sect_off)));
18675
18676   return lookup_die;
18677 }
18678
18679 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18680    except in the case of .debug_types DIEs which do not reference
18681    outside their CU (they do however referencing other types via
18682    DW_FORM_ref_sig8).  */
18683
18684 static struct partial_die_info *
18685 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18686 {
18687   struct dwarf2_per_objfile *dwarf2_per_objfile
18688     = cu->per_cu->dwarf2_per_objfile;
18689   struct objfile *objfile = dwarf2_per_objfile->objfile;
18690   struct dwarf2_per_cu_data *per_cu = NULL;
18691   struct partial_die_info *pd = NULL;
18692
18693   if (offset_in_dwz == cu->per_cu->is_dwz
18694       && offset_in_cu_p (&cu->header, sect_off))
18695     {
18696       pd = cu->find_partial_die (sect_off);
18697       if (pd != NULL)
18698         return pd;
18699       /* We missed recording what we needed.
18700          Load all dies and try again.  */
18701       per_cu = cu->per_cu;
18702     }
18703   else
18704     {
18705       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18706       if (cu->per_cu->is_debug_types)
18707         {
18708           error (_("Dwarf Error: Type Unit at offset %s contains"
18709                    " external reference to offset %s [in module %s].\n"),
18710                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18711                  bfd_get_filename (objfile->obfd));
18712         }
18713       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18714                                                  dwarf2_per_objfile);
18715
18716       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18717         load_partial_comp_unit (per_cu);
18718
18719       per_cu->cu->last_used = 0;
18720       pd = per_cu->cu->find_partial_die (sect_off);
18721     }
18722
18723   /* If we didn't find it, and not all dies have been loaded,
18724      load them all and try again.  */
18725
18726   if (pd == NULL && per_cu->load_all_dies == 0)
18727     {
18728       per_cu->load_all_dies = 1;
18729
18730       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18731          THIS_CU->cu may already be in use.  So we can't just free it and
18732          replace its DIEs with the ones we read in.  Instead, we leave those
18733          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18734          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18735          set.  */
18736       load_partial_comp_unit (per_cu);
18737
18738       pd = per_cu->cu->find_partial_die (sect_off);
18739     }
18740
18741   if (pd == NULL)
18742     internal_error (__FILE__, __LINE__,
18743                     _("could not find partial DIE %s "
18744                       "in cache [from module %s]\n"),
18745                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18746   return pd;
18747 }
18748
18749 /* See if we can figure out if the class lives in a namespace.  We do
18750    this by looking for a member function; its demangled name will
18751    contain namespace info, if there is any.  */
18752
18753 static void
18754 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18755                                   struct dwarf2_cu *cu)
18756 {
18757   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18758      what template types look like, because the demangler
18759      frequently doesn't give the same name as the debug info.  We
18760      could fix this by only using the demangled name to get the
18761      prefix (but see comment in read_structure_type).  */
18762
18763   struct partial_die_info *real_pdi;
18764   struct partial_die_info *child_pdi;
18765
18766   /* If this DIE (this DIE's specification, if any) has a parent, then
18767      we should not do this.  We'll prepend the parent's fully qualified
18768      name when we create the partial symbol.  */
18769
18770   real_pdi = struct_pdi;
18771   while (real_pdi->has_specification)
18772     real_pdi = find_partial_die (real_pdi->spec_offset,
18773                                  real_pdi->spec_is_dwz, cu);
18774
18775   if (real_pdi->die_parent != NULL)
18776     return;
18777
18778   for (child_pdi = struct_pdi->die_child;
18779        child_pdi != NULL;
18780        child_pdi = child_pdi->die_sibling)
18781     {
18782       if (child_pdi->tag == DW_TAG_subprogram
18783           && child_pdi->linkage_name != NULL)
18784         {
18785           char *actual_class_name
18786             = language_class_name_from_physname (cu->language_defn,
18787                                                  child_pdi->linkage_name);
18788           if (actual_class_name != NULL)
18789             {
18790               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18791               struct_pdi->name
18792                 = ((const char *)
18793                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18794                                   actual_class_name,
18795                                   strlen (actual_class_name)));
18796               xfree (actual_class_name);
18797             }
18798           break;
18799         }
18800     }
18801 }
18802
18803 void
18804 partial_die_info::fixup (struct dwarf2_cu *cu)
18805 {
18806   /* Once we've fixed up a die, there's no point in doing so again.
18807      This also avoids a memory leak if we were to call
18808      guess_partial_die_structure_name multiple times.  */
18809   if (fixup_called)
18810     return;
18811
18812   /* If we found a reference attribute and the DIE has no name, try
18813      to find a name in the referred to DIE.  */
18814
18815   if (name == NULL && has_specification)
18816     {
18817       struct partial_die_info *spec_die;
18818
18819       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18820
18821       spec_die->fixup (cu);
18822
18823       if (spec_die->name)
18824         {
18825           name = spec_die->name;
18826
18827           /* Copy DW_AT_external attribute if it is set.  */
18828           if (spec_die->is_external)
18829             is_external = spec_die->is_external;
18830         }
18831     }
18832
18833   /* Set default names for some unnamed DIEs.  */
18834
18835   if (name == NULL && tag == DW_TAG_namespace)
18836     name = CP_ANONYMOUS_NAMESPACE_STR;
18837
18838   /* If there is no parent die to provide a namespace, and there are
18839      children, see if we can determine the namespace from their linkage
18840      name.  */
18841   if (cu->language == language_cplus
18842       && !VEC_empty (dwarf2_section_info_def,
18843                      cu->per_cu->dwarf2_per_objfile->types)
18844       && die_parent == NULL
18845       && has_children
18846       && (tag == DW_TAG_class_type
18847           || tag == DW_TAG_structure_type
18848           || tag == DW_TAG_union_type))
18849     guess_partial_die_structure_name (this, cu);
18850
18851   /* GCC might emit a nameless struct or union that has a linkage
18852      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18853   if (name == NULL
18854       && (tag == DW_TAG_class_type
18855           || tag == DW_TAG_interface_type
18856           || tag == DW_TAG_structure_type
18857           || tag == DW_TAG_union_type)
18858       && linkage_name != NULL)
18859     {
18860       char *demangled;
18861
18862       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18863       if (demangled)
18864         {
18865           const char *base;
18866
18867           /* Strip any leading namespaces/classes, keep only the base name.
18868              DW_AT_name for named DIEs does not contain the prefixes.  */
18869           base = strrchr (demangled, ':');
18870           if (base && base > demangled && base[-1] == ':')
18871             base++;
18872           else
18873             base = demangled;
18874
18875           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18876           name
18877             = ((const char *)
18878                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18879                               base, strlen (base)));
18880           xfree (demangled);
18881         }
18882     }
18883
18884   fixup_called = 1;
18885 }
18886
18887 /* Read an attribute value described by an attribute form.  */
18888
18889 static const gdb_byte *
18890 read_attribute_value (const struct die_reader_specs *reader,
18891                       struct attribute *attr, unsigned form,
18892                       LONGEST implicit_const, const gdb_byte *info_ptr)
18893 {
18894   struct dwarf2_cu *cu = reader->cu;
18895   struct dwarf2_per_objfile *dwarf2_per_objfile
18896     = cu->per_cu->dwarf2_per_objfile;
18897   struct objfile *objfile = dwarf2_per_objfile->objfile;
18898   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18899   bfd *abfd = reader->abfd;
18900   struct comp_unit_head *cu_header = &cu->header;
18901   unsigned int bytes_read;
18902   struct dwarf_block *blk;
18903
18904   attr->form = (enum dwarf_form) form;
18905   switch (form)
18906     {
18907     case DW_FORM_ref_addr:
18908       if (cu->header.version == 2)
18909         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18910       else
18911         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18912                                        &cu->header, &bytes_read);
18913       info_ptr += bytes_read;
18914       break;
18915     case DW_FORM_GNU_ref_alt:
18916       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18917       info_ptr += bytes_read;
18918       break;
18919     case DW_FORM_addr:
18920       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18921       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18922       info_ptr += bytes_read;
18923       break;
18924     case DW_FORM_block2:
18925       blk = dwarf_alloc_block (cu);
18926       blk->size = read_2_bytes (abfd, info_ptr);
18927       info_ptr += 2;
18928       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18929       info_ptr += blk->size;
18930       DW_BLOCK (attr) = blk;
18931       break;
18932     case DW_FORM_block4:
18933       blk = dwarf_alloc_block (cu);
18934       blk->size = read_4_bytes (abfd, info_ptr);
18935       info_ptr += 4;
18936       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18937       info_ptr += blk->size;
18938       DW_BLOCK (attr) = blk;
18939       break;
18940     case DW_FORM_data2:
18941       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18942       info_ptr += 2;
18943       break;
18944     case DW_FORM_data4:
18945       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18946       info_ptr += 4;
18947       break;
18948     case DW_FORM_data8:
18949       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18950       info_ptr += 8;
18951       break;
18952     case DW_FORM_data16:
18953       blk = dwarf_alloc_block (cu);
18954       blk->size = 16;
18955       blk->data = read_n_bytes (abfd, info_ptr, 16);
18956       info_ptr += 16;
18957       DW_BLOCK (attr) = blk;
18958       break;
18959     case DW_FORM_sec_offset:
18960       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18961       info_ptr += bytes_read;
18962       break;
18963     case DW_FORM_string:
18964       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18965       DW_STRING_IS_CANONICAL (attr) = 0;
18966       info_ptr += bytes_read;
18967       break;
18968     case DW_FORM_strp:
18969       if (!cu->per_cu->is_dwz)
18970         {
18971           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18972                                                    abfd, info_ptr, cu_header,
18973                                                    &bytes_read);
18974           DW_STRING_IS_CANONICAL (attr) = 0;
18975           info_ptr += bytes_read;
18976           break;
18977         }
18978       /* FALLTHROUGH */
18979     case DW_FORM_line_strp:
18980       if (!cu->per_cu->is_dwz)
18981         {
18982           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18983                                                         abfd, info_ptr,
18984                                                         cu_header, &bytes_read);
18985           DW_STRING_IS_CANONICAL (attr) = 0;
18986           info_ptr += bytes_read;
18987           break;
18988         }
18989       /* FALLTHROUGH */
18990     case DW_FORM_GNU_strp_alt:
18991       {
18992         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18993         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18994                                           &bytes_read);
18995
18996         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18997                                                           dwz, str_offset);
18998         DW_STRING_IS_CANONICAL (attr) = 0;
18999         info_ptr += bytes_read;
19000       }
19001       break;
19002     case DW_FORM_exprloc:
19003     case DW_FORM_block:
19004       blk = dwarf_alloc_block (cu);
19005       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19006       info_ptr += bytes_read;
19007       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19008       info_ptr += blk->size;
19009       DW_BLOCK (attr) = blk;
19010       break;
19011     case DW_FORM_block1:
19012       blk = dwarf_alloc_block (cu);
19013       blk->size = read_1_byte (abfd, info_ptr);
19014       info_ptr += 1;
19015       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19016       info_ptr += blk->size;
19017       DW_BLOCK (attr) = blk;
19018       break;
19019     case DW_FORM_data1:
19020       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19021       info_ptr += 1;
19022       break;
19023     case DW_FORM_flag:
19024       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19025       info_ptr += 1;
19026       break;
19027     case DW_FORM_flag_present:
19028       DW_UNSND (attr) = 1;
19029       break;
19030     case DW_FORM_sdata:
19031       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19032       info_ptr += bytes_read;
19033       break;
19034     case DW_FORM_udata:
19035       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19036       info_ptr += bytes_read;
19037       break;
19038     case DW_FORM_ref1:
19039       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19040                          + read_1_byte (abfd, info_ptr));
19041       info_ptr += 1;
19042       break;
19043     case DW_FORM_ref2:
19044       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19045                          + read_2_bytes (abfd, info_ptr));
19046       info_ptr += 2;
19047       break;
19048     case DW_FORM_ref4:
19049       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19050                          + read_4_bytes (abfd, info_ptr));
19051       info_ptr += 4;
19052       break;
19053     case DW_FORM_ref8:
19054       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19055                          + read_8_bytes (abfd, info_ptr));
19056       info_ptr += 8;
19057       break;
19058     case DW_FORM_ref_sig8:
19059       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19060       info_ptr += 8;
19061       break;
19062     case DW_FORM_ref_udata:
19063       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19064                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19065       info_ptr += bytes_read;
19066       break;
19067     case DW_FORM_indirect:
19068       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19069       info_ptr += bytes_read;
19070       if (form == DW_FORM_implicit_const)
19071         {
19072           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19073           info_ptr += bytes_read;
19074         }
19075       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19076                                        info_ptr);
19077       break;
19078     case DW_FORM_implicit_const:
19079       DW_SND (attr) = implicit_const;
19080       break;
19081     case DW_FORM_GNU_addr_index:
19082       if (reader->dwo_file == NULL)
19083         {
19084           /* For now flag a hard error.
19085              Later we can turn this into a complaint.  */
19086           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19087                  dwarf_form_name (form),
19088                  bfd_get_filename (abfd));
19089         }
19090       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19091       info_ptr += bytes_read;
19092       break;
19093     case DW_FORM_GNU_str_index:
19094       if (reader->dwo_file == NULL)
19095         {
19096           /* For now flag a hard error.
19097              Later we can turn this into a complaint if warranted.  */
19098           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19099                  dwarf_form_name (form),
19100                  bfd_get_filename (abfd));
19101         }
19102       {
19103         ULONGEST str_index =
19104           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19105
19106         DW_STRING (attr) = read_str_index (reader, str_index);
19107         DW_STRING_IS_CANONICAL (attr) = 0;
19108         info_ptr += bytes_read;
19109       }
19110       break;
19111     default:
19112       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19113              dwarf_form_name (form),
19114              bfd_get_filename (abfd));
19115     }
19116
19117   /* Super hack.  */
19118   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19119     attr->form = DW_FORM_GNU_ref_alt;
19120
19121   /* We have seen instances where the compiler tried to emit a byte
19122      size attribute of -1 which ended up being encoded as an unsigned
19123      0xffffffff.  Although 0xffffffff is technically a valid size value,
19124      an object of this size seems pretty unlikely so we can relatively
19125      safely treat these cases as if the size attribute was invalid and
19126      treat them as zero by default.  */
19127   if (attr->name == DW_AT_byte_size
19128       && form == DW_FORM_data4
19129       && DW_UNSND (attr) >= 0xffffffff)
19130     {
19131       complaint
19132         (&symfile_complaints,
19133          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19134          hex_string (DW_UNSND (attr)));
19135       DW_UNSND (attr) = 0;
19136     }
19137
19138   return info_ptr;
19139 }
19140
19141 /* Read an attribute described by an abbreviated attribute.  */
19142
19143 static const gdb_byte *
19144 read_attribute (const struct die_reader_specs *reader,
19145                 struct attribute *attr, struct attr_abbrev *abbrev,
19146                 const gdb_byte *info_ptr)
19147 {
19148   attr->name = abbrev->name;
19149   return read_attribute_value (reader, attr, abbrev->form,
19150                                abbrev->implicit_const, info_ptr);
19151 }
19152
19153 /* Read dwarf information from a buffer.  */
19154
19155 static unsigned int
19156 read_1_byte (bfd *abfd, const gdb_byte *buf)
19157 {
19158   return bfd_get_8 (abfd, buf);
19159 }
19160
19161 static int
19162 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19163 {
19164   return bfd_get_signed_8 (abfd, buf);
19165 }
19166
19167 static unsigned int
19168 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19169 {
19170   return bfd_get_16 (abfd, buf);
19171 }
19172
19173 static int
19174 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19175 {
19176   return bfd_get_signed_16 (abfd, buf);
19177 }
19178
19179 static unsigned int
19180 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19181 {
19182   return bfd_get_32 (abfd, buf);
19183 }
19184
19185 static int
19186 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19187 {
19188   return bfd_get_signed_32 (abfd, buf);
19189 }
19190
19191 static ULONGEST
19192 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19193 {
19194   return bfd_get_64 (abfd, buf);
19195 }
19196
19197 static CORE_ADDR
19198 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19199               unsigned int *bytes_read)
19200 {
19201   struct comp_unit_head *cu_header = &cu->header;
19202   CORE_ADDR retval = 0;
19203
19204   if (cu_header->signed_addr_p)
19205     {
19206       switch (cu_header->addr_size)
19207         {
19208         case 2:
19209           retval = bfd_get_signed_16 (abfd, buf);
19210           break;
19211         case 4:
19212           retval = bfd_get_signed_32 (abfd, buf);
19213           break;
19214         case 8:
19215           retval = bfd_get_signed_64 (abfd, buf);
19216           break;
19217         default:
19218           internal_error (__FILE__, __LINE__,
19219                           _("read_address: bad switch, signed [in module %s]"),
19220                           bfd_get_filename (abfd));
19221         }
19222     }
19223   else
19224     {
19225       switch (cu_header->addr_size)
19226         {
19227         case 2:
19228           retval = bfd_get_16 (abfd, buf);
19229           break;
19230         case 4:
19231           retval = bfd_get_32 (abfd, buf);
19232           break;
19233         case 8:
19234           retval = bfd_get_64 (abfd, buf);
19235           break;
19236         default:
19237           internal_error (__FILE__, __LINE__,
19238                           _("read_address: bad switch, "
19239                             "unsigned [in module %s]"),
19240                           bfd_get_filename (abfd));
19241         }
19242     }
19243
19244   *bytes_read = cu_header->addr_size;
19245   return retval;
19246 }
19247
19248 /* Read the initial length from a section.  The (draft) DWARF 3
19249    specification allows the initial length to take up either 4 bytes
19250    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19251    bytes describe the length and all offsets will be 8 bytes in length
19252    instead of 4.
19253
19254    An older, non-standard 64-bit format is also handled by this
19255    function.  The older format in question stores the initial length
19256    as an 8-byte quantity without an escape value.  Lengths greater
19257    than 2^32 aren't very common which means that the initial 4 bytes
19258    is almost always zero.  Since a length value of zero doesn't make
19259    sense for the 32-bit format, this initial zero can be considered to
19260    be an escape value which indicates the presence of the older 64-bit
19261    format.  As written, the code can't detect (old format) lengths
19262    greater than 4GB.  If it becomes necessary to handle lengths
19263    somewhat larger than 4GB, we could allow other small values (such
19264    as the non-sensical values of 1, 2, and 3) to also be used as
19265    escape values indicating the presence of the old format.
19266
19267    The value returned via bytes_read should be used to increment the
19268    relevant pointer after calling read_initial_length().
19269
19270    [ Note:  read_initial_length() and read_offset() are based on the
19271      document entitled "DWARF Debugging Information Format", revision
19272      3, draft 8, dated November 19, 2001.  This document was obtained
19273      from:
19274
19275         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19276
19277      This document is only a draft and is subject to change.  (So beware.)
19278
19279      Details regarding the older, non-standard 64-bit format were
19280      determined empirically by examining 64-bit ELF files produced by
19281      the SGI toolchain on an IRIX 6.5 machine.
19282
19283      - Kevin, July 16, 2002
19284    ] */
19285
19286 static LONGEST
19287 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19288 {
19289   LONGEST length = bfd_get_32 (abfd, buf);
19290
19291   if (length == 0xffffffff)
19292     {
19293       length = bfd_get_64 (abfd, buf + 4);
19294       *bytes_read = 12;
19295     }
19296   else if (length == 0)
19297     {
19298       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19299       length = bfd_get_64 (abfd, buf);
19300       *bytes_read = 8;
19301     }
19302   else
19303     {
19304       *bytes_read = 4;
19305     }
19306
19307   return length;
19308 }
19309
19310 /* Cover function for read_initial_length.
19311    Returns the length of the object at BUF, and stores the size of the
19312    initial length in *BYTES_READ and stores the size that offsets will be in
19313    *OFFSET_SIZE.
19314    If the initial length size is not equivalent to that specified in
19315    CU_HEADER then issue a complaint.
19316    This is useful when reading non-comp-unit headers.  */
19317
19318 static LONGEST
19319 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19320                                         const struct comp_unit_head *cu_header,
19321                                         unsigned int *bytes_read,
19322                                         unsigned int *offset_size)
19323 {
19324   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19325
19326   gdb_assert (cu_header->initial_length_size == 4
19327               || cu_header->initial_length_size == 8
19328               || cu_header->initial_length_size == 12);
19329
19330   if (cu_header->initial_length_size != *bytes_read)
19331     complaint (&symfile_complaints,
19332                _("intermixed 32-bit and 64-bit DWARF sections"));
19333
19334   *offset_size = (*bytes_read == 4) ? 4 : 8;
19335   return length;
19336 }
19337
19338 /* Read an offset from the data stream.  The size of the offset is
19339    given by cu_header->offset_size.  */
19340
19341 static LONGEST
19342 read_offset (bfd *abfd, const gdb_byte *buf,
19343              const struct comp_unit_head *cu_header,
19344              unsigned int *bytes_read)
19345 {
19346   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19347
19348   *bytes_read = cu_header->offset_size;
19349   return offset;
19350 }
19351
19352 /* Read an offset from the data stream.  */
19353
19354 static LONGEST
19355 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19356 {
19357   LONGEST retval = 0;
19358
19359   switch (offset_size)
19360     {
19361     case 4:
19362       retval = bfd_get_32 (abfd, buf);
19363       break;
19364     case 8:
19365       retval = bfd_get_64 (abfd, buf);
19366       break;
19367     default:
19368       internal_error (__FILE__, __LINE__,
19369                       _("read_offset_1: bad switch [in module %s]"),
19370                       bfd_get_filename (abfd));
19371     }
19372
19373   return retval;
19374 }
19375
19376 static const gdb_byte *
19377 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19378 {
19379   /* If the size of a host char is 8 bits, we can return a pointer
19380      to the buffer, otherwise we have to copy the data to a buffer
19381      allocated on the temporary obstack.  */
19382   gdb_assert (HOST_CHAR_BIT == 8);
19383   return buf;
19384 }
19385
19386 static const char *
19387 read_direct_string (bfd *abfd, const gdb_byte *buf,
19388                     unsigned int *bytes_read_ptr)
19389 {
19390   /* If the size of a host char is 8 bits, we can return a pointer
19391      to the string, otherwise we have to copy the string to a buffer
19392      allocated on the temporary obstack.  */
19393   gdb_assert (HOST_CHAR_BIT == 8);
19394   if (*buf == '\0')
19395     {
19396       *bytes_read_ptr = 1;
19397       return NULL;
19398     }
19399   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19400   return (const char *) buf;
19401 }
19402
19403 /* Return pointer to string at section SECT offset STR_OFFSET with error
19404    reporting strings FORM_NAME and SECT_NAME.  */
19405
19406 static const char *
19407 read_indirect_string_at_offset_from (struct objfile *objfile,
19408                                      bfd *abfd, LONGEST str_offset,
19409                                      struct dwarf2_section_info *sect,
19410                                      const char *form_name,
19411                                      const char *sect_name)
19412 {
19413   dwarf2_read_section (objfile, sect);
19414   if (sect->buffer == NULL)
19415     error (_("%s used without %s section [in module %s]"),
19416            form_name, sect_name, bfd_get_filename (abfd));
19417   if (str_offset >= sect->size)
19418     error (_("%s pointing outside of %s section [in module %s]"),
19419            form_name, sect_name, bfd_get_filename (abfd));
19420   gdb_assert (HOST_CHAR_BIT == 8);
19421   if (sect->buffer[str_offset] == '\0')
19422     return NULL;
19423   return (const char *) (sect->buffer + str_offset);
19424 }
19425
19426 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19427
19428 static const char *
19429 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19430                                 bfd *abfd, LONGEST str_offset)
19431 {
19432   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19433                                               abfd, str_offset,
19434                                               &dwarf2_per_objfile->str,
19435                                               "DW_FORM_strp", ".debug_str");
19436 }
19437
19438 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19439
19440 static const char *
19441 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19442                                      bfd *abfd, LONGEST str_offset)
19443 {
19444   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19445                                               abfd, str_offset,
19446                                               &dwarf2_per_objfile->line_str,
19447                                               "DW_FORM_line_strp",
19448                                               ".debug_line_str");
19449 }
19450
19451 /* Read a string at offset STR_OFFSET in the .debug_str section from
19452    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19453    the string consists of a single NUL byte, return NULL; otherwise
19454    return a pointer to the string.  */
19455
19456 static const char *
19457 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19458                                LONGEST str_offset)
19459 {
19460   dwarf2_read_section (objfile, &dwz->str);
19461
19462   if (dwz->str.buffer == NULL)
19463     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19464              "section [in module %s]"),
19465            bfd_get_filename (dwz->dwz_bfd));
19466   if (str_offset >= dwz->str.size)
19467     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19468              ".debug_str section [in module %s]"),
19469            bfd_get_filename (dwz->dwz_bfd));
19470   gdb_assert (HOST_CHAR_BIT == 8);
19471   if (dwz->str.buffer[str_offset] == '\0')
19472     return NULL;
19473   return (const char *) (dwz->str.buffer + str_offset);
19474 }
19475
19476 /* Return pointer to string at .debug_str offset as read from BUF.
19477    BUF is assumed to be in a compilation unit described by CU_HEADER.
19478    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19479
19480 static const char *
19481 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19482                       const gdb_byte *buf,
19483                       const struct comp_unit_head *cu_header,
19484                       unsigned int *bytes_read_ptr)
19485 {
19486   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19487
19488   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19489 }
19490
19491 /* Return pointer to string at .debug_line_str offset as read from BUF.
19492    BUF is assumed to be in a compilation unit described by CU_HEADER.
19493    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19494
19495 static const char *
19496 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19497                            bfd *abfd, const gdb_byte *buf,
19498                            const struct comp_unit_head *cu_header,
19499                            unsigned int *bytes_read_ptr)
19500 {
19501   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19502
19503   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19504                                               str_offset);
19505 }
19506
19507 ULONGEST
19508 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19509                           unsigned int *bytes_read_ptr)
19510 {
19511   ULONGEST result;
19512   unsigned int num_read;
19513   int shift;
19514   unsigned char byte;
19515
19516   result = 0;
19517   shift = 0;
19518   num_read = 0;
19519   while (1)
19520     {
19521       byte = bfd_get_8 (abfd, buf);
19522       buf++;
19523       num_read++;
19524       result |= ((ULONGEST) (byte & 127) << shift);
19525       if ((byte & 128) == 0)
19526         {
19527           break;
19528         }
19529       shift += 7;
19530     }
19531   *bytes_read_ptr = num_read;
19532   return result;
19533 }
19534
19535 static LONGEST
19536 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19537                     unsigned int *bytes_read_ptr)
19538 {
19539   LONGEST result;
19540   int shift, num_read;
19541   unsigned char byte;
19542
19543   result = 0;
19544   shift = 0;
19545   num_read = 0;
19546   while (1)
19547     {
19548       byte = bfd_get_8 (abfd, buf);
19549       buf++;
19550       num_read++;
19551       result |= ((LONGEST) (byte & 127) << shift);
19552       shift += 7;
19553       if ((byte & 128) == 0)
19554         {
19555           break;
19556         }
19557     }
19558   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19559     result |= -(((LONGEST) 1) << shift);
19560   *bytes_read_ptr = num_read;
19561   return result;
19562 }
19563
19564 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19565    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19566    ADDR_SIZE is the size of addresses from the CU header.  */
19567
19568 static CORE_ADDR
19569 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19570                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19571 {
19572   struct objfile *objfile = dwarf2_per_objfile->objfile;
19573   bfd *abfd = objfile->obfd;
19574   const gdb_byte *info_ptr;
19575
19576   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19577   if (dwarf2_per_objfile->addr.buffer == NULL)
19578     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19579            objfile_name (objfile));
19580   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19581     error (_("DW_FORM_addr_index pointing outside of "
19582              ".debug_addr section [in module %s]"),
19583            objfile_name (objfile));
19584   info_ptr = (dwarf2_per_objfile->addr.buffer
19585               + addr_base + addr_index * addr_size);
19586   if (addr_size == 4)
19587     return bfd_get_32 (abfd, info_ptr);
19588   else
19589     return bfd_get_64 (abfd, info_ptr);
19590 }
19591
19592 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19593
19594 static CORE_ADDR
19595 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19596 {
19597   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19598                             cu->addr_base, cu->header.addr_size);
19599 }
19600
19601 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19602
19603 static CORE_ADDR
19604 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19605                              unsigned int *bytes_read)
19606 {
19607   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19608   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19609
19610   return read_addr_index (cu, addr_index);
19611 }
19612
19613 /* Data structure to pass results from dwarf2_read_addr_index_reader
19614    back to dwarf2_read_addr_index.  */
19615
19616 struct dwarf2_read_addr_index_data
19617 {
19618   ULONGEST addr_base;
19619   int addr_size;
19620 };
19621
19622 /* die_reader_func for dwarf2_read_addr_index.  */
19623
19624 static void
19625 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19626                                const gdb_byte *info_ptr,
19627                                struct die_info *comp_unit_die,
19628                                int has_children,
19629                                void *data)
19630 {
19631   struct dwarf2_cu *cu = reader->cu;
19632   struct dwarf2_read_addr_index_data *aidata =
19633     (struct dwarf2_read_addr_index_data *) data;
19634
19635   aidata->addr_base = cu->addr_base;
19636   aidata->addr_size = cu->header.addr_size;
19637 }
19638
19639 /* Given an index in .debug_addr, fetch the value.
19640    NOTE: This can be called during dwarf expression evaluation,
19641    long after the debug information has been read, and thus per_cu->cu
19642    may no longer exist.  */
19643
19644 CORE_ADDR
19645 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19646                         unsigned int addr_index)
19647 {
19648   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19649   struct dwarf2_cu *cu = per_cu->cu;
19650   ULONGEST addr_base;
19651   int addr_size;
19652
19653   /* We need addr_base and addr_size.
19654      If we don't have PER_CU->cu, we have to get it.
19655      Nasty, but the alternative is storing the needed info in PER_CU,
19656      which at this point doesn't seem justified: it's not clear how frequently
19657      it would get used and it would increase the size of every PER_CU.
19658      Entry points like dwarf2_per_cu_addr_size do a similar thing
19659      so we're not in uncharted territory here.
19660      Alas we need to be a bit more complicated as addr_base is contained
19661      in the DIE.
19662
19663      We don't need to read the entire CU(/TU).
19664      We just need the header and top level die.
19665
19666      IWBN to use the aging mechanism to let us lazily later discard the CU.
19667      For now we skip this optimization.  */
19668
19669   if (cu != NULL)
19670     {
19671       addr_base = cu->addr_base;
19672       addr_size = cu->header.addr_size;
19673     }
19674   else
19675     {
19676       struct dwarf2_read_addr_index_data aidata;
19677
19678       /* Note: We can't use init_cutu_and_read_dies_simple here,
19679          we need addr_base.  */
19680       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19681                                dwarf2_read_addr_index_reader, &aidata);
19682       addr_base = aidata.addr_base;
19683       addr_size = aidata.addr_size;
19684     }
19685
19686   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19687                             addr_size);
19688 }
19689
19690 /* Given a DW_FORM_GNU_str_index, fetch the string.
19691    This is only used by the Fission support.  */
19692
19693 static const char *
19694 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19695 {
19696   struct dwarf2_cu *cu = reader->cu;
19697   struct dwarf2_per_objfile *dwarf2_per_objfile
19698     = cu->per_cu->dwarf2_per_objfile;
19699   struct objfile *objfile = dwarf2_per_objfile->objfile;
19700   const char *objf_name = objfile_name (objfile);
19701   bfd *abfd = objfile->obfd;
19702   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19703   struct dwarf2_section_info *str_offsets_section =
19704     &reader->dwo_file->sections.str_offsets;
19705   const gdb_byte *info_ptr;
19706   ULONGEST str_offset;
19707   static const char form_name[] = "DW_FORM_GNU_str_index";
19708
19709   dwarf2_read_section (objfile, str_section);
19710   dwarf2_read_section (objfile, str_offsets_section);
19711   if (str_section->buffer == NULL)
19712     error (_("%s used without .debug_str.dwo section"
19713              " in CU at offset %s [in module %s]"),
19714            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19715   if (str_offsets_section->buffer == NULL)
19716     error (_("%s used without .debug_str_offsets.dwo section"
19717              " in CU at offset %s [in module %s]"),
19718            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19719   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19720     error (_("%s pointing outside of .debug_str_offsets.dwo"
19721              " section in CU at offset %s [in module %s]"),
19722            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19723   info_ptr = (str_offsets_section->buffer
19724               + str_index * cu->header.offset_size);
19725   if (cu->header.offset_size == 4)
19726     str_offset = bfd_get_32 (abfd, info_ptr);
19727   else
19728     str_offset = bfd_get_64 (abfd, info_ptr);
19729   if (str_offset >= str_section->size)
19730     error (_("Offset from %s pointing outside of"
19731              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19732            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19733   return (const char *) (str_section->buffer + str_offset);
19734 }
19735
19736 /* Return the length of an LEB128 number in BUF.  */
19737
19738 static int
19739 leb128_size (const gdb_byte *buf)
19740 {
19741   const gdb_byte *begin = buf;
19742   gdb_byte byte;
19743
19744   while (1)
19745     {
19746       byte = *buf++;
19747       if ((byte & 128) == 0)
19748         return buf - begin;
19749     }
19750 }
19751
19752 static void
19753 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19754 {
19755   switch (lang)
19756     {
19757     case DW_LANG_C89:
19758     case DW_LANG_C99:
19759     case DW_LANG_C11:
19760     case DW_LANG_C:
19761     case DW_LANG_UPC:
19762       cu->language = language_c;
19763       break;
19764     case DW_LANG_Java:
19765     case DW_LANG_C_plus_plus:
19766     case DW_LANG_C_plus_plus_11:
19767     case DW_LANG_C_plus_plus_14:
19768       cu->language = language_cplus;
19769       break;
19770     case DW_LANG_D:
19771       cu->language = language_d;
19772       break;
19773     case DW_LANG_Fortran77:
19774     case DW_LANG_Fortran90:
19775     case DW_LANG_Fortran95:
19776     case DW_LANG_Fortran03:
19777     case DW_LANG_Fortran08:
19778       cu->language = language_fortran;
19779       break;
19780     case DW_LANG_Go:
19781       cu->language = language_go;
19782       break;
19783     case DW_LANG_Mips_Assembler:
19784       cu->language = language_asm;
19785       break;
19786     case DW_LANG_Ada83:
19787     case DW_LANG_Ada95:
19788       cu->language = language_ada;
19789       break;
19790     case DW_LANG_Modula2:
19791       cu->language = language_m2;
19792       break;
19793     case DW_LANG_Pascal83:
19794       cu->language = language_pascal;
19795       break;
19796     case DW_LANG_ObjC:
19797       cu->language = language_objc;
19798       break;
19799     case DW_LANG_Rust:
19800     case DW_LANG_Rust_old:
19801       cu->language = language_rust;
19802       break;
19803     case DW_LANG_Cobol74:
19804     case DW_LANG_Cobol85:
19805     default:
19806       cu->language = language_minimal;
19807       break;
19808     }
19809   cu->language_defn = language_def (cu->language);
19810 }
19811
19812 /* Return the named attribute or NULL if not there.  */
19813
19814 static struct attribute *
19815 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19816 {
19817   for (;;)
19818     {
19819       unsigned int i;
19820       struct attribute *spec = NULL;
19821
19822       for (i = 0; i < die->num_attrs; ++i)
19823         {
19824           if (die->attrs[i].name == name)
19825             return &die->attrs[i];
19826           if (die->attrs[i].name == DW_AT_specification
19827               || die->attrs[i].name == DW_AT_abstract_origin)
19828             spec = &die->attrs[i];
19829         }
19830
19831       if (!spec)
19832         break;
19833
19834       die = follow_die_ref (die, spec, &cu);
19835     }
19836
19837   return NULL;
19838 }
19839
19840 /* Return the named attribute or NULL if not there,
19841    but do not follow DW_AT_specification, etc.
19842    This is for use in contexts where we're reading .debug_types dies.
19843    Following DW_AT_specification, DW_AT_abstract_origin will take us
19844    back up the chain, and we want to go down.  */
19845
19846 static struct attribute *
19847 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19848 {
19849   unsigned int i;
19850
19851   for (i = 0; i < die->num_attrs; ++i)
19852     if (die->attrs[i].name == name)
19853       return &die->attrs[i];
19854
19855   return NULL;
19856 }
19857
19858 /* Return the string associated with a string-typed attribute, or NULL if it
19859    is either not found or is of an incorrect type.  */
19860
19861 static const char *
19862 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19863 {
19864   struct attribute *attr;
19865   const char *str = NULL;
19866
19867   attr = dwarf2_attr (die, name, cu);
19868
19869   if (attr != NULL)
19870     {
19871       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19872           || attr->form == DW_FORM_string
19873           || attr->form == DW_FORM_GNU_str_index
19874           || attr->form == DW_FORM_GNU_strp_alt)
19875         str = DW_STRING (attr);
19876       else
19877         complaint (&symfile_complaints,
19878                    _("string type expected for attribute %s for "
19879                      "DIE at %s in module %s"),
19880                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19881                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19882     }
19883
19884   return str;
19885 }
19886
19887 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19888    and holds a non-zero value.  This function should only be used for
19889    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19890
19891 static int
19892 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19893 {
19894   struct attribute *attr = dwarf2_attr (die, name, cu);
19895
19896   return (attr && DW_UNSND (attr));
19897 }
19898
19899 static int
19900 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19901 {
19902   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19903      which value is non-zero.  However, we have to be careful with
19904      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19905      (via dwarf2_flag_true_p) follows this attribute.  So we may
19906      end up accidently finding a declaration attribute that belongs
19907      to a different DIE referenced by the specification attribute,
19908      even though the given DIE does not have a declaration attribute.  */
19909   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19910           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19911 }
19912
19913 /* Return the die giving the specification for DIE, if there is
19914    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19915    containing the return value on output.  If there is no
19916    specification, but there is an abstract origin, that is
19917    returned.  */
19918
19919 static struct die_info *
19920 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19921 {
19922   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19923                                              *spec_cu);
19924
19925   if (spec_attr == NULL)
19926     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19927
19928   if (spec_attr == NULL)
19929     return NULL;
19930   else
19931     return follow_die_ref (die, spec_attr, spec_cu);
19932 }
19933
19934 /* Stub for free_line_header to match void * callback types.  */
19935
19936 static void
19937 free_line_header_voidp (void *arg)
19938 {
19939   struct line_header *lh = (struct line_header *) arg;
19940
19941   delete lh;
19942 }
19943
19944 void
19945 line_header::add_include_dir (const char *include_dir)
19946 {
19947   if (dwarf_line_debug >= 2)
19948     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19949                         include_dirs.size () + 1, include_dir);
19950
19951   include_dirs.push_back (include_dir);
19952 }
19953
19954 void
19955 line_header::add_file_name (const char *name,
19956                             dir_index d_index,
19957                             unsigned int mod_time,
19958                             unsigned int length)
19959 {
19960   if (dwarf_line_debug >= 2)
19961     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19962                         (unsigned) file_names.size () + 1, name);
19963
19964   file_names.emplace_back (name, d_index, mod_time, length);
19965 }
19966
19967 /* A convenience function to find the proper .debug_line section for a CU.  */
19968
19969 static struct dwarf2_section_info *
19970 get_debug_line_section (struct dwarf2_cu *cu)
19971 {
19972   struct dwarf2_section_info *section;
19973   struct dwarf2_per_objfile *dwarf2_per_objfile
19974     = cu->per_cu->dwarf2_per_objfile;
19975
19976   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19977      DWO file.  */
19978   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19979     section = &cu->dwo_unit->dwo_file->sections.line;
19980   else if (cu->per_cu->is_dwz)
19981     {
19982       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19983
19984       section = &dwz->line;
19985     }
19986   else
19987     section = &dwarf2_per_objfile->line;
19988
19989   return section;
19990 }
19991
19992 /* Read directory or file name entry format, starting with byte of
19993    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19994    entries count and the entries themselves in the described entry
19995    format.  */
19996
19997 static void
19998 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19999                         bfd *abfd, const gdb_byte **bufp,
20000                         struct line_header *lh,
20001                         const struct comp_unit_head *cu_header,
20002                         void (*callback) (struct line_header *lh,
20003                                           const char *name,
20004                                           dir_index d_index,
20005                                           unsigned int mod_time,
20006                                           unsigned int length))
20007 {
20008   gdb_byte format_count, formati;
20009   ULONGEST data_count, datai;
20010   const gdb_byte *buf = *bufp;
20011   const gdb_byte *format_header_data;
20012   unsigned int bytes_read;
20013
20014   format_count = read_1_byte (abfd, buf);
20015   buf += 1;
20016   format_header_data = buf;
20017   for (formati = 0; formati < format_count; formati++)
20018     {
20019       read_unsigned_leb128 (abfd, buf, &bytes_read);
20020       buf += bytes_read;
20021       read_unsigned_leb128 (abfd, buf, &bytes_read);
20022       buf += bytes_read;
20023     }
20024
20025   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20026   buf += bytes_read;
20027   for (datai = 0; datai < data_count; datai++)
20028     {
20029       const gdb_byte *format = format_header_data;
20030       struct file_entry fe;
20031
20032       for (formati = 0; formati < format_count; formati++)
20033         {
20034           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20035           format += bytes_read;
20036
20037           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20038           format += bytes_read;
20039
20040           gdb::optional<const char *> string;
20041           gdb::optional<unsigned int> uint;
20042
20043           switch (form)
20044             {
20045             case DW_FORM_string:
20046               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20047               buf += bytes_read;
20048               break;
20049
20050             case DW_FORM_line_strp:
20051               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20052                                                          abfd, buf,
20053                                                          cu_header,
20054                                                          &bytes_read));
20055               buf += bytes_read;
20056               break;
20057
20058             case DW_FORM_data1:
20059               uint.emplace (read_1_byte (abfd, buf));
20060               buf += 1;
20061               break;
20062
20063             case DW_FORM_data2:
20064               uint.emplace (read_2_bytes (abfd, buf));
20065               buf += 2;
20066               break;
20067
20068             case DW_FORM_data4:
20069               uint.emplace (read_4_bytes (abfd, buf));
20070               buf += 4;
20071               break;
20072
20073             case DW_FORM_data8:
20074               uint.emplace (read_8_bytes (abfd, buf));
20075               buf += 8;
20076               break;
20077
20078             case DW_FORM_udata:
20079               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20080               buf += bytes_read;
20081               break;
20082
20083             case DW_FORM_block:
20084               /* It is valid only for DW_LNCT_timestamp which is ignored by
20085                  current GDB.  */
20086               break;
20087             }
20088
20089           switch (content_type)
20090             {
20091             case DW_LNCT_path:
20092               if (string.has_value ())
20093                 fe.name = *string;
20094               break;
20095             case DW_LNCT_directory_index:
20096               if (uint.has_value ())
20097                 fe.d_index = (dir_index) *uint;
20098               break;
20099             case DW_LNCT_timestamp:
20100               if (uint.has_value ())
20101                 fe.mod_time = *uint;
20102               break;
20103             case DW_LNCT_size:
20104               if (uint.has_value ())
20105                 fe.length = *uint;
20106               break;
20107             case DW_LNCT_MD5:
20108               break;
20109             default:
20110               complaint (&symfile_complaints,
20111                          _("Unknown format content type %s"),
20112                          pulongest (content_type));
20113             }
20114         }
20115
20116       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20117     }
20118
20119   *bufp = buf;
20120 }
20121
20122 /* Read the statement program header starting at OFFSET in
20123    .debug_line, or .debug_line.dwo.  Return a pointer
20124    to a struct line_header, allocated using xmalloc.
20125    Returns NULL if there is a problem reading the header, e.g., if it
20126    has a version we don't understand.
20127
20128    NOTE: the strings in the include directory and file name tables of
20129    the returned object point into the dwarf line section buffer,
20130    and must not be freed.  */
20131
20132 static line_header_up
20133 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20134 {
20135   const gdb_byte *line_ptr;
20136   unsigned int bytes_read, offset_size;
20137   int i;
20138   const char *cur_dir, *cur_file;
20139   struct dwarf2_section_info *section;
20140   bfd *abfd;
20141   struct dwarf2_per_objfile *dwarf2_per_objfile
20142     = cu->per_cu->dwarf2_per_objfile;
20143
20144   section = get_debug_line_section (cu);
20145   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20146   if (section->buffer == NULL)
20147     {
20148       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20149         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20150       else
20151         complaint (&symfile_complaints, _("missing .debug_line section"));
20152       return 0;
20153     }
20154
20155   /* We can't do this until we know the section is non-empty.
20156      Only then do we know we have such a section.  */
20157   abfd = get_section_bfd_owner (section);
20158
20159   /* Make sure that at least there's room for the total_length field.
20160      That could be 12 bytes long, but we're just going to fudge that.  */
20161   if (to_underlying (sect_off) + 4 >= section->size)
20162     {
20163       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20164       return 0;
20165     }
20166
20167   line_header_up lh (new line_header ());
20168
20169   lh->sect_off = sect_off;
20170   lh->offset_in_dwz = cu->per_cu->is_dwz;
20171
20172   line_ptr = section->buffer + to_underlying (sect_off);
20173
20174   /* Read in the header.  */
20175   lh->total_length =
20176     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20177                                             &bytes_read, &offset_size);
20178   line_ptr += bytes_read;
20179   if (line_ptr + lh->total_length > (section->buffer + section->size))
20180     {
20181       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20182       return 0;
20183     }
20184   lh->statement_program_end = line_ptr + lh->total_length;
20185   lh->version = read_2_bytes (abfd, line_ptr);
20186   line_ptr += 2;
20187   if (lh->version > 5)
20188     {
20189       /* This is a version we don't understand.  The format could have
20190          changed in ways we don't handle properly so just punt.  */
20191       complaint (&symfile_complaints,
20192                  _("unsupported version in .debug_line section"));
20193       return NULL;
20194     }
20195   if (lh->version >= 5)
20196     {
20197       gdb_byte segment_selector_size;
20198
20199       /* Skip address size.  */
20200       read_1_byte (abfd, line_ptr);
20201       line_ptr += 1;
20202
20203       segment_selector_size = read_1_byte (abfd, line_ptr);
20204       line_ptr += 1;
20205       if (segment_selector_size != 0)
20206         {
20207           complaint (&symfile_complaints,
20208                      _("unsupported segment selector size %u "
20209                        "in .debug_line section"),
20210                      segment_selector_size);
20211           return NULL;
20212         }
20213     }
20214   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20215   line_ptr += offset_size;
20216   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20217   line_ptr += 1;
20218   if (lh->version >= 4)
20219     {
20220       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20221       line_ptr += 1;
20222     }
20223   else
20224     lh->maximum_ops_per_instruction = 1;
20225
20226   if (lh->maximum_ops_per_instruction == 0)
20227     {
20228       lh->maximum_ops_per_instruction = 1;
20229       complaint (&symfile_complaints,
20230                  _("invalid maximum_ops_per_instruction "
20231                    "in `.debug_line' section"));
20232     }
20233
20234   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20235   line_ptr += 1;
20236   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20237   line_ptr += 1;
20238   lh->line_range = read_1_byte (abfd, line_ptr);
20239   line_ptr += 1;
20240   lh->opcode_base = read_1_byte (abfd, line_ptr);
20241   line_ptr += 1;
20242   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20243
20244   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20245   for (i = 1; i < lh->opcode_base; ++i)
20246     {
20247       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20248       line_ptr += 1;
20249     }
20250
20251   if (lh->version >= 5)
20252     {
20253       /* Read directory table.  */
20254       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20255                               &cu->header,
20256                               [] (struct line_header *lh, const char *name,
20257                                   dir_index d_index, unsigned int mod_time,
20258                                   unsigned int length)
20259         {
20260           lh->add_include_dir (name);
20261         });
20262
20263       /* Read file name table.  */
20264       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20265                               &cu->header,
20266                               [] (struct line_header *lh, const char *name,
20267                                   dir_index d_index, unsigned int mod_time,
20268                                   unsigned int length)
20269         {
20270           lh->add_file_name (name, d_index, mod_time, length);
20271         });
20272     }
20273   else
20274     {
20275       /* Read directory table.  */
20276       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20277         {
20278           line_ptr += bytes_read;
20279           lh->add_include_dir (cur_dir);
20280         }
20281       line_ptr += bytes_read;
20282
20283       /* Read file name table.  */
20284       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20285         {
20286           unsigned int mod_time, length;
20287           dir_index d_index;
20288
20289           line_ptr += bytes_read;
20290           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20291           line_ptr += bytes_read;
20292           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20293           line_ptr += bytes_read;
20294           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20295           line_ptr += bytes_read;
20296
20297           lh->add_file_name (cur_file, d_index, mod_time, length);
20298         }
20299       line_ptr += bytes_read;
20300     }
20301   lh->statement_program_start = line_ptr;
20302
20303   if (line_ptr > (section->buffer + section->size))
20304     complaint (&symfile_complaints,
20305                _("line number info header doesn't "
20306                  "fit in `.debug_line' section"));
20307
20308   return lh;
20309 }
20310
20311 /* Subroutine of dwarf_decode_lines to simplify it.
20312    Return the file name of the psymtab for included file FILE_INDEX
20313    in line header LH of PST.
20314    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20315    If space for the result is malloc'd, *NAME_HOLDER will be set.
20316    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20317
20318 static const char *
20319 psymtab_include_file_name (const struct line_header *lh, int file_index,
20320                            const struct partial_symtab *pst,
20321                            const char *comp_dir,
20322                            gdb::unique_xmalloc_ptr<char> *name_holder)
20323 {
20324   const file_entry &fe = lh->file_names[file_index];
20325   const char *include_name = fe.name;
20326   const char *include_name_to_compare = include_name;
20327   const char *pst_filename;
20328   int file_is_pst;
20329
20330   const char *dir_name = fe.include_dir (lh);
20331
20332   gdb::unique_xmalloc_ptr<char> hold_compare;
20333   if (!IS_ABSOLUTE_PATH (include_name)
20334       && (dir_name != NULL || comp_dir != NULL))
20335     {
20336       /* Avoid creating a duplicate psymtab for PST.
20337          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20338          Before we do the comparison, however, we need to account
20339          for DIR_NAME and COMP_DIR.
20340          First prepend dir_name (if non-NULL).  If we still don't
20341          have an absolute path prepend comp_dir (if non-NULL).
20342          However, the directory we record in the include-file's
20343          psymtab does not contain COMP_DIR (to match the
20344          corresponding symtab(s)).
20345
20346          Example:
20347
20348          bash$ cd /tmp
20349          bash$ gcc -g ./hello.c
20350          include_name = "hello.c"
20351          dir_name = "."
20352          DW_AT_comp_dir = comp_dir = "/tmp"
20353          DW_AT_name = "./hello.c"
20354
20355       */
20356
20357       if (dir_name != NULL)
20358         {
20359           name_holder->reset (concat (dir_name, SLASH_STRING,
20360                                       include_name, (char *) NULL));
20361           include_name = name_holder->get ();
20362           include_name_to_compare = include_name;
20363         }
20364       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20365         {
20366           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20367                                       include_name, (char *) NULL));
20368           include_name_to_compare = hold_compare.get ();
20369         }
20370     }
20371
20372   pst_filename = pst->filename;
20373   gdb::unique_xmalloc_ptr<char> copied_name;
20374   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20375     {
20376       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20377                                  pst_filename, (char *) NULL));
20378       pst_filename = copied_name.get ();
20379     }
20380
20381   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20382
20383   if (file_is_pst)
20384     return NULL;
20385   return include_name;
20386 }
20387
20388 /* State machine to track the state of the line number program.  */
20389
20390 class lnp_state_machine
20391 {
20392 public:
20393   /* Initialize a machine state for the start of a line number
20394      program.  */
20395   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20396
20397   file_entry *current_file ()
20398   {
20399     /* lh->file_names is 0-based, but the file name numbers in the
20400        statement program are 1-based.  */
20401     return m_line_header->file_name_at (m_file);
20402   }
20403
20404   /* Record the line in the state machine.  END_SEQUENCE is true if
20405      we're processing the end of a sequence.  */
20406   void record_line (bool end_sequence);
20407
20408   /* Check address and if invalid nop-out the rest of the lines in this
20409      sequence.  */
20410   void check_line_address (struct dwarf2_cu *cu,
20411                            const gdb_byte *line_ptr,
20412                            CORE_ADDR lowpc, CORE_ADDR address);
20413
20414   void handle_set_discriminator (unsigned int discriminator)
20415   {
20416     m_discriminator = discriminator;
20417     m_line_has_non_zero_discriminator |= discriminator != 0;
20418   }
20419
20420   /* Handle DW_LNE_set_address.  */
20421   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20422   {
20423     m_op_index = 0;
20424     address += baseaddr;
20425     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20426   }
20427
20428   /* Handle DW_LNS_advance_pc.  */
20429   void handle_advance_pc (CORE_ADDR adjust);
20430
20431   /* Handle a special opcode.  */
20432   void handle_special_opcode (unsigned char op_code);
20433
20434   /* Handle DW_LNS_advance_line.  */
20435   void handle_advance_line (int line_delta)
20436   {
20437     advance_line (line_delta);
20438   }
20439
20440   /* Handle DW_LNS_set_file.  */
20441   void handle_set_file (file_name_index file);
20442
20443   /* Handle DW_LNS_negate_stmt.  */
20444   void handle_negate_stmt ()
20445   {
20446     m_is_stmt = !m_is_stmt;
20447   }
20448
20449   /* Handle DW_LNS_const_add_pc.  */
20450   void handle_const_add_pc ();
20451
20452   /* Handle DW_LNS_fixed_advance_pc.  */
20453   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20454   {
20455     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20456     m_op_index = 0;
20457   }
20458
20459   /* Handle DW_LNS_copy.  */
20460   void handle_copy ()
20461   {
20462     record_line (false);
20463     m_discriminator = 0;
20464   }
20465
20466   /* Handle DW_LNE_end_sequence.  */
20467   void handle_end_sequence ()
20468   {
20469     m_record_line_callback = ::record_line;
20470   }
20471
20472 private:
20473   /* Advance the line by LINE_DELTA.  */
20474   void advance_line (int line_delta)
20475   {
20476     m_line += line_delta;
20477
20478     if (line_delta != 0)
20479       m_line_has_non_zero_discriminator = m_discriminator != 0;
20480   }
20481
20482   gdbarch *m_gdbarch;
20483
20484   /* True if we're recording lines.
20485      Otherwise we're building partial symtabs and are just interested in
20486      finding include files mentioned by the line number program.  */
20487   bool m_record_lines_p;
20488
20489   /* The line number header.  */
20490   line_header *m_line_header;
20491
20492   /* These are part of the standard DWARF line number state machine,
20493      and initialized according to the DWARF spec.  */
20494
20495   unsigned char m_op_index = 0;
20496   /* The line table index (1-based) of the current file.  */
20497   file_name_index m_file = (file_name_index) 1;
20498   unsigned int m_line = 1;
20499
20500   /* These are initialized in the constructor.  */
20501
20502   CORE_ADDR m_address;
20503   bool m_is_stmt;
20504   unsigned int m_discriminator;
20505
20506   /* Additional bits of state we need to track.  */
20507
20508   /* The last file that we called dwarf2_start_subfile for.
20509      This is only used for TLLs.  */
20510   unsigned int m_last_file = 0;
20511   /* The last file a line number was recorded for.  */
20512   struct subfile *m_last_subfile = NULL;
20513
20514   /* The function to call to record a line.  */
20515   record_line_ftype *m_record_line_callback = NULL;
20516
20517   /* The last line number that was recorded, used to coalesce
20518      consecutive entries for the same line.  This can happen, for
20519      example, when discriminators are present.  PR 17276.  */
20520   unsigned int m_last_line = 0;
20521   bool m_line_has_non_zero_discriminator = false;
20522 };
20523
20524 void
20525 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20526 {
20527   CORE_ADDR addr_adj = (((m_op_index + adjust)
20528                          / m_line_header->maximum_ops_per_instruction)
20529                         * m_line_header->minimum_instruction_length);
20530   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20531   m_op_index = ((m_op_index + adjust)
20532                 % m_line_header->maximum_ops_per_instruction);
20533 }
20534
20535 void
20536 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20537 {
20538   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20539   CORE_ADDR addr_adj = (((m_op_index
20540                           + (adj_opcode / m_line_header->line_range))
20541                          / m_line_header->maximum_ops_per_instruction)
20542                         * m_line_header->minimum_instruction_length);
20543   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20544   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20545                 % m_line_header->maximum_ops_per_instruction);
20546
20547   int line_delta = (m_line_header->line_base
20548                     + (adj_opcode % m_line_header->line_range));
20549   advance_line (line_delta);
20550   record_line (false);
20551   m_discriminator = 0;
20552 }
20553
20554 void
20555 lnp_state_machine::handle_set_file (file_name_index file)
20556 {
20557   m_file = file;
20558
20559   const file_entry *fe = current_file ();
20560   if (fe == NULL)
20561     dwarf2_debug_line_missing_file_complaint ();
20562   else if (m_record_lines_p)
20563     {
20564       const char *dir = fe->include_dir (m_line_header);
20565
20566       m_last_subfile = current_subfile;
20567       m_line_has_non_zero_discriminator = m_discriminator != 0;
20568       dwarf2_start_subfile (fe->name, dir);
20569     }
20570 }
20571
20572 void
20573 lnp_state_machine::handle_const_add_pc ()
20574 {
20575   CORE_ADDR adjust
20576     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20577
20578   CORE_ADDR addr_adj
20579     = (((m_op_index + adjust)
20580         / m_line_header->maximum_ops_per_instruction)
20581        * m_line_header->minimum_instruction_length);
20582
20583   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20584   m_op_index = ((m_op_index + adjust)
20585                 % m_line_header->maximum_ops_per_instruction);
20586 }
20587
20588 /* Ignore this record_line request.  */
20589
20590 static void
20591 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20592 {
20593   return;
20594 }
20595
20596 /* Return non-zero if we should add LINE to the line number table.
20597    LINE is the line to add, LAST_LINE is the last line that was added,
20598    LAST_SUBFILE is the subfile for LAST_LINE.
20599    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20600    had a non-zero discriminator.
20601
20602    We have to be careful in the presence of discriminators.
20603    E.g., for this line:
20604
20605      for (i = 0; i < 100000; i++);
20606
20607    clang can emit four line number entries for that one line,
20608    each with a different discriminator.
20609    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20610
20611    However, we want gdb to coalesce all four entries into one.
20612    Otherwise the user could stepi into the middle of the line and
20613    gdb would get confused about whether the pc really was in the
20614    middle of the line.
20615
20616    Things are further complicated by the fact that two consecutive
20617    line number entries for the same line is a heuristic used by gcc
20618    to denote the end of the prologue.  So we can't just discard duplicate
20619    entries, we have to be selective about it.  The heuristic we use is
20620    that we only collapse consecutive entries for the same line if at least
20621    one of those entries has a non-zero discriminator.  PR 17276.
20622
20623    Note: Addresses in the line number state machine can never go backwards
20624    within one sequence, thus this coalescing is ok.  */
20625
20626 static int
20627 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20628                      int line_has_non_zero_discriminator,
20629                      struct subfile *last_subfile)
20630 {
20631   if (current_subfile != last_subfile)
20632     return 1;
20633   if (line != last_line)
20634     return 1;
20635   /* Same line for the same file that we've seen already.
20636      As a last check, for pr 17276, only record the line if the line
20637      has never had a non-zero discriminator.  */
20638   if (!line_has_non_zero_discriminator)
20639     return 1;
20640   return 0;
20641 }
20642
20643 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20644    in the line table of subfile SUBFILE.  */
20645
20646 static void
20647 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20648                      unsigned int line, CORE_ADDR address,
20649                      record_line_ftype p_record_line)
20650 {
20651   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20652
20653   if (dwarf_line_debug)
20654     {
20655       fprintf_unfiltered (gdb_stdlog,
20656                           "Recording line %u, file %s, address %s\n",
20657                           line, lbasename (subfile->name),
20658                           paddress (gdbarch, address));
20659     }
20660
20661   (*p_record_line) (subfile, line, addr);
20662 }
20663
20664 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20665    Mark the end of a set of line number records.
20666    The arguments are the same as for dwarf_record_line_1.
20667    If SUBFILE is NULL the request is ignored.  */
20668
20669 static void
20670 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20671                    CORE_ADDR address, record_line_ftype p_record_line)
20672 {
20673   if (subfile == NULL)
20674     return;
20675
20676   if (dwarf_line_debug)
20677     {
20678       fprintf_unfiltered (gdb_stdlog,
20679                           "Finishing current line, file %s, address %s\n",
20680                           lbasename (subfile->name),
20681                           paddress (gdbarch, address));
20682     }
20683
20684   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20685 }
20686
20687 void
20688 lnp_state_machine::record_line (bool end_sequence)
20689 {
20690   if (dwarf_line_debug)
20691     {
20692       fprintf_unfiltered (gdb_stdlog,
20693                           "Processing actual line %u: file %u,"
20694                           " address %s, is_stmt %u, discrim %u\n",
20695                           m_line, to_underlying (m_file),
20696                           paddress (m_gdbarch, m_address),
20697                           m_is_stmt, m_discriminator);
20698     }
20699
20700   file_entry *fe = current_file ();
20701
20702   if (fe == NULL)
20703     dwarf2_debug_line_missing_file_complaint ();
20704   /* For now we ignore lines not starting on an instruction boundary.
20705      But not when processing end_sequence for compatibility with the
20706      previous version of the code.  */
20707   else if (m_op_index == 0 || end_sequence)
20708     {
20709       fe->included_p = 1;
20710       if (m_record_lines_p && m_is_stmt)
20711         {
20712           if (m_last_subfile != current_subfile || end_sequence)
20713             {
20714               dwarf_finish_line (m_gdbarch, m_last_subfile,
20715                                  m_address, m_record_line_callback);
20716             }
20717
20718           if (!end_sequence)
20719             {
20720               if (dwarf_record_line_p (m_line, m_last_line,
20721                                        m_line_has_non_zero_discriminator,
20722                                        m_last_subfile))
20723                 {
20724                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20725                                        m_line, m_address,
20726                                        m_record_line_callback);
20727                 }
20728               m_last_subfile = current_subfile;
20729               m_last_line = m_line;
20730             }
20731         }
20732     }
20733 }
20734
20735 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20736                                       bool record_lines_p)
20737 {
20738   m_gdbarch = arch;
20739   m_record_lines_p = record_lines_p;
20740   m_line_header = lh;
20741
20742   m_record_line_callback = ::record_line;
20743
20744   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20745      was a line entry for it so that the backend has a chance to adjust it
20746      and also record it in case it needs it.  This is currently used by MIPS
20747      code, cf. `mips_adjust_dwarf2_line'.  */
20748   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20749   m_is_stmt = lh->default_is_stmt;
20750   m_discriminator = 0;
20751 }
20752
20753 void
20754 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20755                                        const gdb_byte *line_ptr,
20756                                        CORE_ADDR lowpc, CORE_ADDR address)
20757 {
20758   /* If address < lowpc then it's not a usable value, it's outside the
20759      pc range of the CU.  However, we restrict the test to only address
20760      values of zero to preserve GDB's previous behaviour which is to
20761      handle the specific case of a function being GC'd by the linker.  */
20762
20763   if (address == 0 && address < lowpc)
20764     {
20765       /* This line table is for a function which has been
20766          GCd by the linker.  Ignore it.  PR gdb/12528 */
20767
20768       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20769       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20770
20771       complaint (&symfile_complaints,
20772                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20773                  line_offset, objfile_name (objfile));
20774       m_record_line_callback = noop_record_line;
20775       /* Note: record_line_callback is left as noop_record_line until
20776          we see DW_LNE_end_sequence.  */
20777     }
20778 }
20779
20780 /* Subroutine of dwarf_decode_lines to simplify it.
20781    Process the line number information in LH.
20782    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20783    program in order to set included_p for every referenced header.  */
20784
20785 static void
20786 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20787                       const int decode_for_pst_p, CORE_ADDR lowpc)
20788 {
20789   const gdb_byte *line_ptr, *extended_end;
20790   const gdb_byte *line_end;
20791   unsigned int bytes_read, extended_len;
20792   unsigned char op_code, extended_op;
20793   CORE_ADDR baseaddr;
20794   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20795   bfd *abfd = objfile->obfd;
20796   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20797   /* True if we're recording line info (as opposed to building partial
20798      symtabs and just interested in finding include files mentioned by
20799      the line number program).  */
20800   bool record_lines_p = !decode_for_pst_p;
20801
20802   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20803
20804   line_ptr = lh->statement_program_start;
20805   line_end = lh->statement_program_end;
20806
20807   /* Read the statement sequences until there's nothing left.  */
20808   while (line_ptr < line_end)
20809     {
20810       /* The DWARF line number program state machine.  Reset the state
20811          machine at the start of each sequence.  */
20812       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20813       bool end_sequence = false;
20814
20815       if (record_lines_p)
20816         {
20817           /* Start a subfile for the current file of the state
20818              machine.  */
20819           const file_entry *fe = state_machine.current_file ();
20820
20821           if (fe != NULL)
20822             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20823         }
20824
20825       /* Decode the table.  */
20826       while (line_ptr < line_end && !end_sequence)
20827         {
20828           op_code = read_1_byte (abfd, line_ptr);
20829           line_ptr += 1;
20830
20831           if (op_code >= lh->opcode_base)
20832             {
20833               /* Special opcode.  */
20834               state_machine.handle_special_opcode (op_code);
20835             }
20836           else switch (op_code)
20837             {
20838             case DW_LNS_extended_op:
20839               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20840                                                    &bytes_read);
20841               line_ptr += bytes_read;
20842               extended_end = line_ptr + extended_len;
20843               extended_op = read_1_byte (abfd, line_ptr);
20844               line_ptr += 1;
20845               switch (extended_op)
20846                 {
20847                 case DW_LNE_end_sequence:
20848                   state_machine.handle_end_sequence ();
20849                   end_sequence = true;
20850                   break;
20851                 case DW_LNE_set_address:
20852                   {
20853                     CORE_ADDR address
20854                       = read_address (abfd, line_ptr, cu, &bytes_read);
20855                     line_ptr += bytes_read;
20856
20857                     state_machine.check_line_address (cu, line_ptr,
20858                                                       lowpc, address);
20859                     state_machine.handle_set_address (baseaddr, address);
20860                   }
20861                   break;
20862                 case DW_LNE_define_file:
20863                   {
20864                     const char *cur_file;
20865                     unsigned int mod_time, length;
20866                     dir_index dindex;
20867
20868                     cur_file = read_direct_string (abfd, line_ptr,
20869                                                    &bytes_read);
20870                     line_ptr += bytes_read;
20871                     dindex = (dir_index)
20872                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20873                     line_ptr += bytes_read;
20874                     mod_time =
20875                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20876                     line_ptr += bytes_read;
20877                     length =
20878                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20879                     line_ptr += bytes_read;
20880                     lh->add_file_name (cur_file, dindex, mod_time, length);
20881                   }
20882                   break;
20883                 case DW_LNE_set_discriminator:
20884                   {
20885                     /* The discriminator is not interesting to the
20886                        debugger; just ignore it.  We still need to
20887                        check its value though:
20888                        if there are consecutive entries for the same
20889                        (non-prologue) line we want to coalesce them.
20890                        PR 17276.  */
20891                     unsigned int discr
20892                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20893                     line_ptr += bytes_read;
20894
20895                     state_machine.handle_set_discriminator (discr);
20896                   }
20897                   break;
20898                 default:
20899                   complaint (&symfile_complaints,
20900                              _("mangled .debug_line section"));
20901                   return;
20902                 }
20903               /* Make sure that we parsed the extended op correctly.  If e.g.
20904                  we expected a different address size than the producer used,
20905                  we may have read the wrong number of bytes.  */
20906               if (line_ptr != extended_end)
20907                 {
20908                   complaint (&symfile_complaints,
20909                              _("mangled .debug_line section"));
20910                   return;
20911                 }
20912               break;
20913             case DW_LNS_copy:
20914               state_machine.handle_copy ();
20915               break;
20916             case DW_LNS_advance_pc:
20917               {
20918                 CORE_ADDR adjust
20919                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20920                 line_ptr += bytes_read;
20921
20922                 state_machine.handle_advance_pc (adjust);
20923               }
20924               break;
20925             case DW_LNS_advance_line:
20926               {
20927                 int line_delta
20928                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20929                 line_ptr += bytes_read;
20930
20931                 state_machine.handle_advance_line (line_delta);
20932               }
20933               break;
20934             case DW_LNS_set_file:
20935               {
20936                 file_name_index file
20937                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20938                                                             &bytes_read);
20939                 line_ptr += bytes_read;
20940
20941                 state_machine.handle_set_file (file);
20942               }
20943               break;
20944             case DW_LNS_set_column:
20945               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20946               line_ptr += bytes_read;
20947               break;
20948             case DW_LNS_negate_stmt:
20949               state_machine.handle_negate_stmt ();
20950               break;
20951             case DW_LNS_set_basic_block:
20952               break;
20953             /* Add to the address register of the state machine the
20954                address increment value corresponding to special opcode
20955                255.  I.e., this value is scaled by the minimum
20956                instruction length since special opcode 255 would have
20957                scaled the increment.  */
20958             case DW_LNS_const_add_pc:
20959               state_machine.handle_const_add_pc ();
20960               break;
20961             case DW_LNS_fixed_advance_pc:
20962               {
20963                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20964                 line_ptr += 2;
20965
20966                 state_machine.handle_fixed_advance_pc (addr_adj);
20967               }
20968               break;
20969             default:
20970               {
20971                 /* Unknown standard opcode, ignore it.  */
20972                 int i;
20973
20974                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20975                   {
20976                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20977                     line_ptr += bytes_read;
20978                   }
20979               }
20980             }
20981         }
20982
20983       if (!end_sequence)
20984         dwarf2_debug_line_missing_end_sequence_complaint ();
20985
20986       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20987          in which case we still finish recording the last line).  */
20988       state_machine.record_line (true);
20989     }
20990 }
20991
20992 /* Decode the Line Number Program (LNP) for the given line_header
20993    structure and CU.  The actual information extracted and the type
20994    of structures created from the LNP depends on the value of PST.
20995
20996    1. If PST is NULL, then this procedure uses the data from the program
20997       to create all necessary symbol tables, and their linetables.
20998
20999    2. If PST is not NULL, this procedure reads the program to determine
21000       the list of files included by the unit represented by PST, and
21001       builds all the associated partial symbol tables.
21002
21003    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21004    It is used for relative paths in the line table.
21005    NOTE: When processing partial symtabs (pst != NULL),
21006    comp_dir == pst->dirname.
21007
21008    NOTE: It is important that psymtabs have the same file name (via strcmp)
21009    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21010    symtab we don't use it in the name of the psymtabs we create.
21011    E.g. expand_line_sal requires this when finding psymtabs to expand.
21012    A good testcase for this is mb-inline.exp.
21013
21014    LOWPC is the lowest address in CU (or 0 if not known).
21015
21016    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21017    for its PC<->lines mapping information.  Otherwise only the filename
21018    table is read in.  */
21019
21020 static void
21021 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21022                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21023                     CORE_ADDR lowpc, int decode_mapping)
21024 {
21025   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21026   const int decode_for_pst_p = (pst != NULL);
21027
21028   if (decode_mapping)
21029     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21030
21031   if (decode_for_pst_p)
21032     {
21033       int file_index;
21034
21035       /* Now that we're done scanning the Line Header Program, we can
21036          create the psymtab of each included file.  */
21037       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21038         if (lh->file_names[file_index].included_p == 1)
21039           {
21040             gdb::unique_xmalloc_ptr<char> name_holder;
21041             const char *include_name =
21042               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21043                                          &name_holder);
21044             if (include_name != NULL)
21045               dwarf2_create_include_psymtab (include_name, pst, objfile);
21046           }
21047     }
21048   else
21049     {
21050       /* Make sure a symtab is created for every file, even files
21051          which contain only variables (i.e. no code with associated
21052          line numbers).  */
21053       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21054       int i;
21055
21056       for (i = 0; i < lh->file_names.size (); i++)
21057         {
21058           file_entry &fe = lh->file_names[i];
21059
21060           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21061
21062           if (current_subfile->symtab == NULL)
21063             {
21064               current_subfile->symtab
21065                 = allocate_symtab (cust, current_subfile->name);
21066             }
21067           fe.symtab = current_subfile->symtab;
21068         }
21069     }
21070 }
21071
21072 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21073    DIRNAME the name of the source directory which contains FILENAME
21074    or NULL if not known.
21075    This routine tries to keep line numbers from identical absolute and
21076    relative file names in a common subfile.
21077
21078    Using the `list' example from the GDB testsuite, which resides in
21079    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21080    of /srcdir/list0.c yields the following debugging information for list0.c:
21081
21082    DW_AT_name:          /srcdir/list0.c
21083    DW_AT_comp_dir:      /compdir
21084    files.files[0].name: list0.h
21085    files.files[0].dir:  /srcdir
21086    files.files[1].name: list0.c
21087    files.files[1].dir:  /srcdir
21088
21089    The line number information for list0.c has to end up in a single
21090    subfile, so that `break /srcdir/list0.c:1' works as expected.
21091    start_subfile will ensure that this happens provided that we pass the
21092    concatenation of files.files[1].dir and files.files[1].name as the
21093    subfile's name.  */
21094
21095 static void
21096 dwarf2_start_subfile (const char *filename, const char *dirname)
21097 {
21098   char *copy = NULL;
21099
21100   /* In order not to lose the line information directory,
21101      we concatenate it to the filename when it makes sense.
21102      Note that the Dwarf3 standard says (speaking of filenames in line
21103      information): ``The directory index is ignored for file names
21104      that represent full path names''.  Thus ignoring dirname in the
21105      `else' branch below isn't an issue.  */
21106
21107   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21108     {
21109       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21110       filename = copy;
21111     }
21112
21113   start_subfile (filename);
21114
21115   if (copy != NULL)
21116     xfree (copy);
21117 }
21118
21119 /* Start a symtab for DWARF.
21120    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21121
21122 static struct compunit_symtab *
21123 dwarf2_start_symtab (struct dwarf2_cu *cu,
21124                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21125 {
21126   struct compunit_symtab *cust
21127     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21128                     low_pc, cu->language);
21129
21130   record_debugformat ("DWARF 2");
21131   record_producer (cu->producer);
21132
21133   /* We assume that we're processing GCC output.  */
21134   processing_gcc_compilation = 2;
21135
21136   cu->processing_has_namespace_info = 0;
21137
21138   return cust;
21139 }
21140
21141 static void
21142 var_decode_location (struct attribute *attr, struct symbol *sym,
21143                      struct dwarf2_cu *cu)
21144 {
21145   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21146   struct comp_unit_head *cu_header = &cu->header;
21147
21148   /* NOTE drow/2003-01-30: There used to be a comment and some special
21149      code here to turn a symbol with DW_AT_external and a
21150      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21151      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21152      with some versions of binutils) where shared libraries could have
21153      relocations against symbols in their debug information - the
21154      minimal symbol would have the right address, but the debug info
21155      would not.  It's no longer necessary, because we will explicitly
21156      apply relocations when we read in the debug information now.  */
21157
21158   /* A DW_AT_location attribute with no contents indicates that a
21159      variable has been optimized away.  */
21160   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21161     {
21162       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21163       return;
21164     }
21165
21166   /* Handle one degenerate form of location expression specially, to
21167      preserve GDB's previous behavior when section offsets are
21168      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21169      then mark this symbol as LOC_STATIC.  */
21170
21171   if (attr_form_is_block (attr)
21172       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21173            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21174           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21175               && (DW_BLOCK (attr)->size
21176                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21177     {
21178       unsigned int dummy;
21179
21180       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21181         SYMBOL_VALUE_ADDRESS (sym) =
21182           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21183       else
21184         SYMBOL_VALUE_ADDRESS (sym) =
21185           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21186       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21187       fixup_symbol_section (sym, objfile);
21188       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21189                                               SYMBOL_SECTION (sym));
21190       return;
21191     }
21192
21193   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21194      expression evaluator, and use LOC_COMPUTED only when necessary
21195      (i.e. when the value of a register or memory location is
21196      referenced, or a thread-local block, etc.).  Then again, it might
21197      not be worthwhile.  I'm assuming that it isn't unless performance
21198      or memory numbers show me otherwise.  */
21199
21200   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21201
21202   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21203     cu->has_loclist = 1;
21204 }
21205
21206 /* Given a pointer to a DWARF information entry, figure out if we need
21207    to make a symbol table entry for it, and if so, create a new entry
21208    and return a pointer to it.
21209    If TYPE is NULL, determine symbol type from the die, otherwise
21210    used the passed type.
21211    If SPACE is not NULL, use it to hold the new symbol.  If it is
21212    NULL, allocate a new symbol on the objfile's obstack.  */
21213
21214 static struct symbol *
21215 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21216             struct symbol *space)
21217 {
21218   struct dwarf2_per_objfile *dwarf2_per_objfile
21219     = cu->per_cu->dwarf2_per_objfile;
21220   struct objfile *objfile = dwarf2_per_objfile->objfile;
21221   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21222   struct symbol *sym = NULL;
21223   const char *name;
21224   struct attribute *attr = NULL;
21225   struct attribute *attr2 = NULL;
21226   CORE_ADDR baseaddr;
21227   struct pending **list_to_add = NULL;
21228
21229   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21230
21231   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21232
21233   name = dwarf2_name (die, cu);
21234   if (name)
21235     {
21236       const char *linkagename;
21237       int suppress_add = 0;
21238
21239       if (space)
21240         sym = space;
21241       else
21242         sym = allocate_symbol (objfile);
21243       OBJSTAT (objfile, n_syms++);
21244
21245       /* Cache this symbol's name and the name's demangled form (if any).  */
21246       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21247       linkagename = dwarf2_physname (name, die, cu);
21248       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21249
21250       /* Fortran does not have mangling standard and the mangling does differ
21251          between gfortran, iFort etc.  */
21252       if (cu->language == language_fortran
21253           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21254         symbol_set_demangled_name (&(sym->ginfo),
21255                                    dwarf2_full_name (name, die, cu),
21256                                    NULL);
21257
21258       /* Default assumptions.
21259          Use the passed type or decode it from the die.  */
21260       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21261       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21262       if (type != NULL)
21263         SYMBOL_TYPE (sym) = type;
21264       else
21265         SYMBOL_TYPE (sym) = die_type (die, cu);
21266       attr = dwarf2_attr (die,
21267                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21268                           cu);
21269       if (attr)
21270         {
21271           SYMBOL_LINE (sym) = DW_UNSND (attr);
21272         }
21273
21274       attr = dwarf2_attr (die,
21275                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21276                           cu);
21277       if (attr)
21278         {
21279           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21280           struct file_entry *fe;
21281
21282           if (cu->line_header != NULL)
21283             fe = cu->line_header->file_name_at (file_index);
21284           else
21285             fe = NULL;
21286
21287           if (fe == NULL)
21288             complaint (&symfile_complaints,
21289                        _("file index out of range"));
21290           else
21291             symbol_set_symtab (sym, fe->symtab);
21292         }
21293
21294       switch (die->tag)
21295         {
21296         case DW_TAG_label:
21297           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21298           if (attr)
21299             {
21300               CORE_ADDR addr;
21301
21302               addr = attr_value_as_address (attr);
21303               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21304               SYMBOL_VALUE_ADDRESS (sym) = addr;
21305             }
21306           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21307           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21308           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21309           add_symbol_to_list (sym, cu->list_in_scope);
21310           break;
21311         case DW_TAG_subprogram:
21312           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21313              finish_block.  */
21314           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21315           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21316           if ((attr2 && (DW_UNSND (attr2) != 0))
21317               || cu->language == language_ada)
21318             {
21319               /* Subprograms marked external are stored as a global symbol.
21320                  Ada subprograms, whether marked external or not, are always
21321                  stored as a global symbol, because we want to be able to
21322                  access them globally.  For instance, we want to be able
21323                  to break on a nested subprogram without having to
21324                  specify the context.  */
21325               list_to_add = &global_symbols;
21326             }
21327           else
21328             {
21329               list_to_add = cu->list_in_scope;
21330             }
21331           break;
21332         case DW_TAG_inlined_subroutine:
21333           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21334              finish_block.  */
21335           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21336           SYMBOL_INLINED (sym) = 1;
21337           list_to_add = cu->list_in_scope;
21338           break;
21339         case DW_TAG_template_value_param:
21340           suppress_add = 1;
21341           /* Fall through.  */
21342         case DW_TAG_constant:
21343         case DW_TAG_variable:
21344         case DW_TAG_member:
21345           /* Compilation with minimal debug info may result in
21346              variables with missing type entries.  Change the
21347              misleading `void' type to something sensible.  */
21348           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21349             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21350
21351           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21352           /* In the case of DW_TAG_member, we should only be called for
21353              static const members.  */
21354           if (die->tag == DW_TAG_member)
21355             {
21356               /* dwarf2_add_field uses die_is_declaration,
21357                  so we do the same.  */
21358               gdb_assert (die_is_declaration (die, cu));
21359               gdb_assert (attr);
21360             }
21361           if (attr)
21362             {
21363               dwarf2_const_value (attr, sym, cu);
21364               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21365               if (!suppress_add)
21366                 {
21367                   if (attr2 && (DW_UNSND (attr2) != 0))
21368                     list_to_add = &global_symbols;
21369                   else
21370                     list_to_add = cu->list_in_scope;
21371                 }
21372               break;
21373             }
21374           attr = dwarf2_attr (die, DW_AT_location, cu);
21375           if (attr)
21376             {
21377               var_decode_location (attr, sym, cu);
21378               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21379
21380               /* Fortran explicitly imports any global symbols to the local
21381                  scope by DW_TAG_common_block.  */
21382               if (cu->language == language_fortran && die->parent
21383                   && die->parent->tag == DW_TAG_common_block)
21384                 attr2 = NULL;
21385
21386               if (SYMBOL_CLASS (sym) == LOC_STATIC
21387                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21388                   && !dwarf2_per_objfile->has_section_at_zero)
21389                 {
21390                   /* When a static variable is eliminated by the linker,
21391                      the corresponding debug information is not stripped
21392                      out, but the variable address is set to null;
21393                      do not add such variables into symbol table.  */
21394                 }
21395               else if (attr2 && (DW_UNSND (attr2) != 0))
21396                 {
21397                   /* Workaround gfortran PR debug/40040 - it uses
21398                      DW_AT_location for variables in -fPIC libraries which may
21399                      get overriden by other libraries/executable and get
21400                      a different address.  Resolve it by the minimal symbol
21401                      which may come from inferior's executable using copy
21402                      relocation.  Make this workaround only for gfortran as for
21403                      other compilers GDB cannot guess the minimal symbol
21404                      Fortran mangling kind.  */
21405                   if (cu->language == language_fortran && die->parent
21406                       && die->parent->tag == DW_TAG_module
21407                       && cu->producer
21408                       && startswith (cu->producer, "GNU Fortran"))
21409                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21410
21411                   /* A variable with DW_AT_external is never static,
21412                      but it may be block-scoped.  */
21413                   list_to_add = (cu->list_in_scope == &file_symbols
21414                                  ? &global_symbols : cu->list_in_scope);
21415                 }
21416               else
21417                 list_to_add = cu->list_in_scope;
21418             }
21419           else
21420             {
21421               /* We do not know the address of this symbol.
21422                  If it is an external symbol and we have type information
21423                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21424                  The address of the variable will then be determined from
21425                  the minimal symbol table whenever the variable is
21426                  referenced.  */
21427               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21428
21429               /* Fortran explicitly imports any global symbols to the local
21430                  scope by DW_TAG_common_block.  */
21431               if (cu->language == language_fortran && die->parent
21432                   && die->parent->tag == DW_TAG_common_block)
21433                 {
21434                   /* SYMBOL_CLASS doesn't matter here because
21435                      read_common_block is going to reset it.  */
21436                   if (!suppress_add)
21437                     list_to_add = cu->list_in_scope;
21438                 }
21439               else if (attr2 && (DW_UNSND (attr2) != 0)
21440                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21441                 {
21442                   /* A variable with DW_AT_external is never static, but it
21443                      may be block-scoped.  */
21444                   list_to_add = (cu->list_in_scope == &file_symbols
21445                                  ? &global_symbols : cu->list_in_scope);
21446
21447                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21448                 }
21449               else if (!die_is_declaration (die, cu))
21450                 {
21451                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21452                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21453                   if (!suppress_add)
21454                     list_to_add = cu->list_in_scope;
21455                 }
21456             }
21457           break;
21458         case DW_TAG_formal_parameter:
21459           /* If we are inside a function, mark this as an argument.  If
21460              not, we might be looking at an argument to an inlined function
21461              when we do not have enough information to show inlined frames;
21462              pretend it's a local variable in that case so that the user can
21463              still see it.  */
21464           if (context_stack_depth > 0
21465               && context_stack[context_stack_depth - 1].name != NULL)
21466             SYMBOL_IS_ARGUMENT (sym) = 1;
21467           attr = dwarf2_attr (die, DW_AT_location, cu);
21468           if (attr)
21469             {
21470               var_decode_location (attr, sym, cu);
21471             }
21472           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21473           if (attr)
21474             {
21475               dwarf2_const_value (attr, sym, cu);
21476             }
21477
21478           list_to_add = cu->list_in_scope;
21479           break;
21480         case DW_TAG_unspecified_parameters:
21481           /* From varargs functions; gdb doesn't seem to have any
21482              interest in this information, so just ignore it for now.
21483              (FIXME?) */
21484           break;
21485         case DW_TAG_template_type_param:
21486           suppress_add = 1;
21487           /* Fall through.  */
21488         case DW_TAG_class_type:
21489         case DW_TAG_interface_type:
21490         case DW_TAG_structure_type:
21491         case DW_TAG_union_type:
21492         case DW_TAG_set_type:
21493         case DW_TAG_enumeration_type:
21494           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21495           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21496
21497           {
21498             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21499                really ever be static objects: otherwise, if you try
21500                to, say, break of a class's method and you're in a file
21501                which doesn't mention that class, it won't work unless
21502                the check for all static symbols in lookup_symbol_aux
21503                saves you.  See the OtherFileClass tests in
21504                gdb.c++/namespace.exp.  */
21505
21506             if (!suppress_add)
21507               {
21508                 list_to_add = (cu->list_in_scope == &file_symbols
21509                                && cu->language == language_cplus
21510                                ? &global_symbols : cu->list_in_scope);
21511
21512                 /* The semantics of C++ state that "struct foo {
21513                    ... }" also defines a typedef for "foo".  */
21514                 if (cu->language == language_cplus
21515                     || cu->language == language_ada
21516                     || cu->language == language_d
21517                     || cu->language == language_rust)
21518                   {
21519                     /* The symbol's name is already allocated along
21520                        with this objfile, so we don't need to
21521                        duplicate it for the type.  */
21522                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21523                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21524                   }
21525               }
21526           }
21527           break;
21528         case DW_TAG_typedef:
21529           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21530           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21531           list_to_add = cu->list_in_scope;
21532           break;
21533         case DW_TAG_base_type:
21534         case DW_TAG_subrange_type:
21535           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21536           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21537           list_to_add = cu->list_in_scope;
21538           break;
21539         case DW_TAG_enumerator:
21540           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21541           if (attr)
21542             {
21543               dwarf2_const_value (attr, sym, cu);
21544             }
21545           {
21546             /* NOTE: carlton/2003-11-10: See comment above in the
21547                DW_TAG_class_type, etc. block.  */
21548
21549             list_to_add = (cu->list_in_scope == &file_symbols
21550                            && cu->language == language_cplus
21551                            ? &global_symbols : cu->list_in_scope);
21552           }
21553           break;
21554         case DW_TAG_imported_declaration:
21555         case DW_TAG_namespace:
21556           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21557           list_to_add = &global_symbols;
21558           break;
21559         case DW_TAG_module:
21560           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21561           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21562           list_to_add = &global_symbols;
21563           break;
21564         case DW_TAG_common_block:
21565           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21566           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21567           add_symbol_to_list (sym, cu->list_in_scope);
21568           break;
21569         default:
21570           /* Not a tag we recognize.  Hopefully we aren't processing
21571              trash data, but since we must specifically ignore things
21572              we don't recognize, there is nothing else we should do at
21573              this point.  */
21574           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21575                      dwarf_tag_name (die->tag));
21576           break;
21577         }
21578
21579       if (suppress_add)
21580         {
21581           sym->hash_next = objfile->template_symbols;
21582           objfile->template_symbols = sym;
21583           list_to_add = NULL;
21584         }
21585
21586       if (list_to_add != NULL)
21587         add_symbol_to_list (sym, list_to_add);
21588
21589       /* For the benefit of old versions of GCC, check for anonymous
21590          namespaces based on the demangled name.  */
21591       if (!cu->processing_has_namespace_info
21592           && cu->language == language_cplus)
21593         cp_scan_for_anonymous_namespaces (sym, objfile);
21594     }
21595   return (sym);
21596 }
21597
21598 /* Given an attr with a DW_FORM_dataN value in host byte order,
21599    zero-extend it as appropriate for the symbol's type.  The DWARF
21600    standard (v4) is not entirely clear about the meaning of using
21601    DW_FORM_dataN for a constant with a signed type, where the type is
21602    wider than the data.  The conclusion of a discussion on the DWARF
21603    list was that this is unspecified.  We choose to always zero-extend
21604    because that is the interpretation long in use by GCC.  */
21605
21606 static gdb_byte *
21607 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21608                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21609 {
21610   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21611   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21612                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21613   LONGEST l = DW_UNSND (attr);
21614
21615   if (bits < sizeof (*value) * 8)
21616     {
21617       l &= ((LONGEST) 1 << bits) - 1;
21618       *value = l;
21619     }
21620   else if (bits == sizeof (*value) * 8)
21621     *value = l;
21622   else
21623     {
21624       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21625       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21626       return bytes;
21627     }
21628
21629   return NULL;
21630 }
21631
21632 /* Read a constant value from an attribute.  Either set *VALUE, or if
21633    the value does not fit in *VALUE, set *BYTES - either already
21634    allocated on the objfile obstack, or newly allocated on OBSTACK,
21635    or, set *BATON, if we translated the constant to a location
21636    expression.  */
21637
21638 static void
21639 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21640                          const char *name, struct obstack *obstack,
21641                          struct dwarf2_cu *cu,
21642                          LONGEST *value, const gdb_byte **bytes,
21643                          struct dwarf2_locexpr_baton **baton)
21644 {
21645   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21646   struct comp_unit_head *cu_header = &cu->header;
21647   struct dwarf_block *blk;
21648   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21649                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21650
21651   *value = 0;
21652   *bytes = NULL;
21653   *baton = NULL;
21654
21655   switch (attr->form)
21656     {
21657     case DW_FORM_addr:
21658     case DW_FORM_GNU_addr_index:
21659       {
21660         gdb_byte *data;
21661
21662         if (TYPE_LENGTH (type) != cu_header->addr_size)
21663           dwarf2_const_value_length_mismatch_complaint (name,
21664                                                         cu_header->addr_size,
21665                                                         TYPE_LENGTH (type));
21666         /* Symbols of this form are reasonably rare, so we just
21667            piggyback on the existing location code rather than writing
21668            a new implementation of symbol_computed_ops.  */
21669         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21670         (*baton)->per_cu = cu->per_cu;
21671         gdb_assert ((*baton)->per_cu);
21672
21673         (*baton)->size = 2 + cu_header->addr_size;
21674         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21675         (*baton)->data = data;
21676
21677         data[0] = DW_OP_addr;
21678         store_unsigned_integer (&data[1], cu_header->addr_size,
21679                                 byte_order, DW_ADDR (attr));
21680         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21681       }
21682       break;
21683     case DW_FORM_string:
21684     case DW_FORM_strp:
21685     case DW_FORM_GNU_str_index:
21686     case DW_FORM_GNU_strp_alt:
21687       /* DW_STRING is already allocated on the objfile obstack, point
21688          directly to it.  */
21689       *bytes = (const gdb_byte *) DW_STRING (attr);
21690       break;
21691     case DW_FORM_block1:
21692     case DW_FORM_block2:
21693     case DW_FORM_block4:
21694     case DW_FORM_block:
21695     case DW_FORM_exprloc:
21696     case DW_FORM_data16:
21697       blk = DW_BLOCK (attr);
21698       if (TYPE_LENGTH (type) != blk->size)
21699         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21700                                                       TYPE_LENGTH (type));
21701       *bytes = blk->data;
21702       break;
21703
21704       /* The DW_AT_const_value attributes are supposed to carry the
21705          symbol's value "represented as it would be on the target
21706          architecture."  By the time we get here, it's already been
21707          converted to host endianness, so we just need to sign- or
21708          zero-extend it as appropriate.  */
21709     case DW_FORM_data1:
21710       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21711       break;
21712     case DW_FORM_data2:
21713       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21714       break;
21715     case DW_FORM_data4:
21716       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21717       break;
21718     case DW_FORM_data8:
21719       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21720       break;
21721
21722     case DW_FORM_sdata:
21723     case DW_FORM_implicit_const:
21724       *value = DW_SND (attr);
21725       break;
21726
21727     case DW_FORM_udata:
21728       *value = DW_UNSND (attr);
21729       break;
21730
21731     default:
21732       complaint (&symfile_complaints,
21733                  _("unsupported const value attribute form: '%s'"),
21734                  dwarf_form_name (attr->form));
21735       *value = 0;
21736       break;
21737     }
21738 }
21739
21740
21741 /* Copy constant value from an attribute to a symbol.  */
21742
21743 static void
21744 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21745                     struct dwarf2_cu *cu)
21746 {
21747   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21748   LONGEST value;
21749   const gdb_byte *bytes;
21750   struct dwarf2_locexpr_baton *baton;
21751
21752   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21753                            SYMBOL_PRINT_NAME (sym),
21754                            &objfile->objfile_obstack, cu,
21755                            &value, &bytes, &baton);
21756
21757   if (baton != NULL)
21758     {
21759       SYMBOL_LOCATION_BATON (sym) = baton;
21760       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21761     }
21762   else if (bytes != NULL)
21763      {
21764       SYMBOL_VALUE_BYTES (sym) = bytes;
21765       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21766     }
21767   else
21768     {
21769       SYMBOL_VALUE (sym) = value;
21770       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21771     }
21772 }
21773
21774 /* Return the type of the die in question using its DW_AT_type attribute.  */
21775
21776 static struct type *
21777 die_type (struct die_info *die, struct dwarf2_cu *cu)
21778 {
21779   struct attribute *type_attr;
21780
21781   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21782   if (!type_attr)
21783     {
21784       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21785       /* A missing DW_AT_type represents a void type.  */
21786       return objfile_type (objfile)->builtin_void;
21787     }
21788
21789   return lookup_die_type (die, type_attr, cu);
21790 }
21791
21792 /* True iff CU's producer generates GNAT Ada auxiliary information
21793    that allows to find parallel types through that information instead
21794    of having to do expensive parallel lookups by type name.  */
21795
21796 static int
21797 need_gnat_info (struct dwarf2_cu *cu)
21798 {
21799   /* Assume that the Ada compiler was GNAT, which always produces
21800      the auxiliary information.  */
21801   return (cu->language == language_ada);
21802 }
21803
21804 /* Return the auxiliary type of the die in question using its
21805    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21806    attribute is not present.  */
21807
21808 static struct type *
21809 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21810 {
21811   struct attribute *type_attr;
21812
21813   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21814   if (!type_attr)
21815     return NULL;
21816
21817   return lookup_die_type (die, type_attr, cu);
21818 }
21819
21820 /* If DIE has a descriptive_type attribute, then set the TYPE's
21821    descriptive type accordingly.  */
21822
21823 static void
21824 set_descriptive_type (struct type *type, struct die_info *die,
21825                       struct dwarf2_cu *cu)
21826 {
21827   struct type *descriptive_type = die_descriptive_type (die, cu);
21828
21829   if (descriptive_type)
21830     {
21831       ALLOCATE_GNAT_AUX_TYPE (type);
21832       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21833     }
21834 }
21835
21836 /* Return the containing type of the die in question using its
21837    DW_AT_containing_type attribute.  */
21838
21839 static struct type *
21840 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21841 {
21842   struct attribute *type_attr;
21843   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21844
21845   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21846   if (!type_attr)
21847     error (_("Dwarf Error: Problem turning containing type into gdb type "
21848              "[in module %s]"), objfile_name (objfile));
21849
21850   return lookup_die_type (die, type_attr, cu);
21851 }
21852
21853 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21854
21855 static struct type *
21856 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21857 {
21858   struct dwarf2_per_objfile *dwarf2_per_objfile
21859     = cu->per_cu->dwarf2_per_objfile;
21860   struct objfile *objfile = dwarf2_per_objfile->objfile;
21861   char *message, *saved;
21862
21863   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21864                         objfile_name (objfile),
21865                         sect_offset_str (cu->header.sect_off),
21866                         sect_offset_str (die->sect_off));
21867   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21868                                   message, strlen (message));
21869   xfree (message);
21870
21871   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21872 }
21873
21874 /* Look up the type of DIE in CU using its type attribute ATTR.
21875    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21876    DW_AT_containing_type.
21877    If there is no type substitute an error marker.  */
21878
21879 static struct type *
21880 lookup_die_type (struct die_info *die, const struct attribute *attr,
21881                  struct dwarf2_cu *cu)
21882 {
21883   struct dwarf2_per_objfile *dwarf2_per_objfile
21884     = cu->per_cu->dwarf2_per_objfile;
21885   struct objfile *objfile = dwarf2_per_objfile->objfile;
21886   struct type *this_type;
21887
21888   gdb_assert (attr->name == DW_AT_type
21889               || attr->name == DW_AT_GNAT_descriptive_type
21890               || attr->name == DW_AT_containing_type);
21891
21892   /* First see if we have it cached.  */
21893
21894   if (attr->form == DW_FORM_GNU_ref_alt)
21895     {
21896       struct dwarf2_per_cu_data *per_cu;
21897       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21898
21899       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21900                                                  dwarf2_per_objfile);
21901       this_type = get_die_type_at_offset (sect_off, per_cu);
21902     }
21903   else if (attr_form_is_ref (attr))
21904     {
21905       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21906
21907       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21908     }
21909   else if (attr->form == DW_FORM_ref_sig8)
21910     {
21911       ULONGEST signature = DW_SIGNATURE (attr);
21912
21913       return get_signatured_type (die, signature, cu);
21914     }
21915   else
21916     {
21917       complaint (&symfile_complaints,
21918                  _("Dwarf Error: Bad type attribute %s in DIE"
21919                    " at %s [in module %s]"),
21920                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21921                  objfile_name (objfile));
21922       return build_error_marker_type (cu, die);
21923     }
21924
21925   /* If not cached we need to read it in.  */
21926
21927   if (this_type == NULL)
21928     {
21929       struct die_info *type_die = NULL;
21930       struct dwarf2_cu *type_cu = cu;
21931
21932       if (attr_form_is_ref (attr))
21933         type_die = follow_die_ref (die, attr, &type_cu);
21934       if (type_die == NULL)
21935         return build_error_marker_type (cu, die);
21936       /* If we find the type now, it's probably because the type came
21937          from an inter-CU reference and the type's CU got expanded before
21938          ours.  */
21939       this_type = read_type_die (type_die, type_cu);
21940     }
21941
21942   /* If we still don't have a type use an error marker.  */
21943
21944   if (this_type == NULL)
21945     return build_error_marker_type (cu, die);
21946
21947   return this_type;
21948 }
21949
21950 /* Return the type in DIE, CU.
21951    Returns NULL for invalid types.
21952
21953    This first does a lookup in die_type_hash,
21954    and only reads the die in if necessary.
21955
21956    NOTE: This can be called when reading in partial or full symbols.  */
21957
21958 static struct type *
21959 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21960 {
21961   struct type *this_type;
21962
21963   this_type = get_die_type (die, cu);
21964   if (this_type)
21965     return this_type;
21966
21967   return read_type_die_1 (die, cu);
21968 }
21969
21970 /* Read the type in DIE, CU.
21971    Returns NULL for invalid types.  */
21972
21973 static struct type *
21974 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21975 {
21976   struct type *this_type = NULL;
21977
21978   switch (die->tag)
21979     {
21980     case DW_TAG_class_type:
21981     case DW_TAG_interface_type:
21982     case DW_TAG_structure_type:
21983     case DW_TAG_union_type:
21984       this_type = read_structure_type (die, cu);
21985       break;
21986     case DW_TAG_enumeration_type:
21987       this_type = read_enumeration_type (die, cu);
21988       break;
21989     case DW_TAG_subprogram:
21990     case DW_TAG_subroutine_type:
21991     case DW_TAG_inlined_subroutine:
21992       this_type = read_subroutine_type (die, cu);
21993       break;
21994     case DW_TAG_array_type:
21995       this_type = read_array_type (die, cu);
21996       break;
21997     case DW_TAG_set_type:
21998       this_type = read_set_type (die, cu);
21999       break;
22000     case DW_TAG_pointer_type:
22001       this_type = read_tag_pointer_type (die, cu);
22002       break;
22003     case DW_TAG_ptr_to_member_type:
22004       this_type = read_tag_ptr_to_member_type (die, cu);
22005       break;
22006     case DW_TAG_reference_type:
22007       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22008       break;
22009     case DW_TAG_rvalue_reference_type:
22010       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22011       break;
22012     case DW_TAG_const_type:
22013       this_type = read_tag_const_type (die, cu);
22014       break;
22015     case DW_TAG_volatile_type:
22016       this_type = read_tag_volatile_type (die, cu);
22017       break;
22018     case DW_TAG_restrict_type:
22019       this_type = read_tag_restrict_type (die, cu);
22020       break;
22021     case DW_TAG_string_type:
22022       this_type = read_tag_string_type (die, cu);
22023       break;
22024     case DW_TAG_typedef:
22025       this_type = read_typedef (die, cu);
22026       break;
22027     case DW_TAG_subrange_type:
22028       this_type = read_subrange_type (die, cu);
22029       break;
22030     case DW_TAG_base_type:
22031       this_type = read_base_type (die, cu);
22032       break;
22033     case DW_TAG_unspecified_type:
22034       this_type = read_unspecified_type (die, cu);
22035       break;
22036     case DW_TAG_namespace:
22037       this_type = read_namespace_type (die, cu);
22038       break;
22039     case DW_TAG_module:
22040       this_type = read_module_type (die, cu);
22041       break;
22042     case DW_TAG_atomic_type:
22043       this_type = read_tag_atomic_type (die, cu);
22044       break;
22045     default:
22046       complaint (&symfile_complaints,
22047                  _("unexpected tag in read_type_die: '%s'"),
22048                  dwarf_tag_name (die->tag));
22049       break;
22050     }
22051
22052   return this_type;
22053 }
22054
22055 /* See if we can figure out if the class lives in a namespace.  We do
22056    this by looking for a member function; its demangled name will
22057    contain namespace info, if there is any.
22058    Return the computed name or NULL.
22059    Space for the result is allocated on the objfile's obstack.
22060    This is the full-die version of guess_partial_die_structure_name.
22061    In this case we know DIE has no useful parent.  */
22062
22063 static char *
22064 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22065 {
22066   struct die_info *spec_die;
22067   struct dwarf2_cu *spec_cu;
22068   struct die_info *child;
22069   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22070
22071   spec_cu = cu;
22072   spec_die = die_specification (die, &spec_cu);
22073   if (spec_die != NULL)
22074     {
22075       die = spec_die;
22076       cu = spec_cu;
22077     }
22078
22079   for (child = die->child;
22080        child != NULL;
22081        child = child->sibling)
22082     {
22083       if (child->tag == DW_TAG_subprogram)
22084         {
22085           const char *linkage_name = dw2_linkage_name (child, cu);
22086
22087           if (linkage_name != NULL)
22088             {
22089               char *actual_name
22090                 = language_class_name_from_physname (cu->language_defn,
22091                                                      linkage_name);
22092               char *name = NULL;
22093
22094               if (actual_name != NULL)
22095                 {
22096                   const char *die_name = dwarf2_name (die, cu);
22097
22098                   if (die_name != NULL
22099                       && strcmp (die_name, actual_name) != 0)
22100                     {
22101                       /* Strip off the class name from the full name.
22102                          We want the prefix.  */
22103                       int die_name_len = strlen (die_name);
22104                       int actual_name_len = strlen (actual_name);
22105
22106                       /* Test for '::' as a sanity check.  */
22107                       if (actual_name_len > die_name_len + 2
22108                           && actual_name[actual_name_len
22109                                          - die_name_len - 1] == ':')
22110                         name = (char *) obstack_copy0 (
22111                           &objfile->per_bfd->storage_obstack,
22112                           actual_name, actual_name_len - die_name_len - 2);
22113                     }
22114                 }
22115               xfree (actual_name);
22116               return name;
22117             }
22118         }
22119     }
22120
22121   return NULL;
22122 }
22123
22124 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22125    prefix part in such case.  See
22126    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22127
22128 static const char *
22129 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22130 {
22131   struct attribute *attr;
22132   const char *base;
22133
22134   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22135       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22136     return NULL;
22137
22138   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22139     return NULL;
22140
22141   attr = dw2_linkage_name_attr (die, cu);
22142   if (attr == NULL || DW_STRING (attr) == NULL)
22143     return NULL;
22144
22145   /* dwarf2_name had to be already called.  */
22146   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22147
22148   /* Strip the base name, keep any leading namespaces/classes.  */
22149   base = strrchr (DW_STRING (attr), ':');
22150   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22151     return "";
22152
22153   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22154   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22155                                  DW_STRING (attr),
22156                                  &base[-1] - DW_STRING (attr));
22157 }
22158
22159 /* Return the name of the namespace/class that DIE is defined within,
22160    or "" if we can't tell.  The caller should not xfree the result.
22161
22162    For example, if we're within the method foo() in the following
22163    code:
22164
22165    namespace N {
22166      class C {
22167        void foo () {
22168        }
22169      };
22170    }
22171
22172    then determine_prefix on foo's die will return "N::C".  */
22173
22174 static const char *
22175 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22176 {
22177   struct dwarf2_per_objfile *dwarf2_per_objfile
22178     = cu->per_cu->dwarf2_per_objfile;
22179   struct die_info *parent, *spec_die;
22180   struct dwarf2_cu *spec_cu;
22181   struct type *parent_type;
22182   const char *retval;
22183
22184   if (cu->language != language_cplus
22185       && cu->language != language_fortran && cu->language != language_d
22186       && cu->language != language_rust)
22187     return "";
22188
22189   retval = anonymous_struct_prefix (die, cu);
22190   if (retval)
22191     return retval;
22192
22193   /* We have to be careful in the presence of DW_AT_specification.
22194      For example, with GCC 3.4, given the code
22195
22196      namespace N {
22197        void foo() {
22198          // Definition of N::foo.
22199        }
22200      }
22201
22202      then we'll have a tree of DIEs like this:
22203
22204      1: DW_TAG_compile_unit
22205        2: DW_TAG_namespace        // N
22206          3: DW_TAG_subprogram     // declaration of N::foo
22207        4: DW_TAG_subprogram       // definition of N::foo
22208             DW_AT_specification   // refers to die #3
22209
22210      Thus, when processing die #4, we have to pretend that we're in
22211      the context of its DW_AT_specification, namely the contex of die
22212      #3.  */
22213   spec_cu = cu;
22214   spec_die = die_specification (die, &spec_cu);
22215   if (spec_die == NULL)
22216     parent = die->parent;
22217   else
22218     {
22219       parent = spec_die->parent;
22220       cu = spec_cu;
22221     }
22222
22223   if (parent == NULL)
22224     return "";
22225   else if (parent->building_fullname)
22226     {
22227       const char *name;
22228       const char *parent_name;
22229
22230       /* It has been seen on RealView 2.2 built binaries,
22231          DW_TAG_template_type_param types actually _defined_ as
22232          children of the parent class:
22233
22234          enum E {};
22235          template class <class Enum> Class{};
22236          Class<enum E> class_e;
22237
22238          1: DW_TAG_class_type (Class)
22239            2: DW_TAG_enumeration_type (E)
22240              3: DW_TAG_enumerator (enum1:0)
22241              3: DW_TAG_enumerator (enum2:1)
22242              ...
22243            2: DW_TAG_template_type_param
22244               DW_AT_type  DW_FORM_ref_udata (E)
22245
22246          Besides being broken debug info, it can put GDB into an
22247          infinite loop.  Consider:
22248
22249          When we're building the full name for Class<E>, we'll start
22250          at Class, and go look over its template type parameters,
22251          finding E.  We'll then try to build the full name of E, and
22252          reach here.  We're now trying to build the full name of E,
22253          and look over the parent DIE for containing scope.  In the
22254          broken case, if we followed the parent DIE of E, we'd again
22255          find Class, and once again go look at its template type
22256          arguments, etc., etc.  Simply don't consider such parent die
22257          as source-level parent of this die (it can't be, the language
22258          doesn't allow it), and break the loop here.  */
22259       name = dwarf2_name (die, cu);
22260       parent_name = dwarf2_name (parent, cu);
22261       complaint (&symfile_complaints,
22262                  _("template param type '%s' defined within parent '%s'"),
22263                  name ? name : "<unknown>",
22264                  parent_name ? parent_name : "<unknown>");
22265       return "";
22266     }
22267   else
22268     switch (parent->tag)
22269       {
22270       case DW_TAG_namespace:
22271         parent_type = read_type_die (parent, cu);
22272         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22273            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22274            Work around this problem here.  */
22275         if (cu->language == language_cplus
22276             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22277           return "";
22278         /* We give a name to even anonymous namespaces.  */
22279         return TYPE_TAG_NAME (parent_type);
22280       case DW_TAG_class_type:
22281       case DW_TAG_interface_type:
22282       case DW_TAG_structure_type:
22283       case DW_TAG_union_type:
22284       case DW_TAG_module:
22285         parent_type = read_type_die (parent, cu);
22286         if (TYPE_TAG_NAME (parent_type) != NULL)
22287           return TYPE_TAG_NAME (parent_type);
22288         else
22289           /* An anonymous structure is only allowed non-static data
22290              members; no typedefs, no member functions, et cetera.
22291              So it does not need a prefix.  */
22292           return "";
22293       case DW_TAG_compile_unit:
22294       case DW_TAG_partial_unit:
22295         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22296         if (cu->language == language_cplus
22297             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22298             && die->child != NULL
22299             && (die->tag == DW_TAG_class_type
22300                 || die->tag == DW_TAG_structure_type
22301                 || die->tag == DW_TAG_union_type))
22302           {
22303             char *name = guess_full_die_structure_name (die, cu);
22304             if (name != NULL)
22305               return name;
22306           }
22307         return "";
22308       case DW_TAG_enumeration_type:
22309         parent_type = read_type_die (parent, cu);
22310         if (TYPE_DECLARED_CLASS (parent_type))
22311           {
22312             if (TYPE_TAG_NAME (parent_type) != NULL)
22313               return TYPE_TAG_NAME (parent_type);
22314             return "";
22315           }
22316         /* Fall through.  */
22317       default:
22318         return determine_prefix (parent, cu);
22319       }
22320 }
22321
22322 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22323    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22324    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22325    an obconcat, otherwise allocate storage for the result.  The CU argument is
22326    used to determine the language and hence, the appropriate separator.  */
22327
22328 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22329
22330 static char *
22331 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22332                  int physname, struct dwarf2_cu *cu)
22333 {
22334   const char *lead = "";
22335   const char *sep;
22336
22337   if (suffix == NULL || suffix[0] == '\0'
22338       || prefix == NULL || prefix[0] == '\0')
22339     sep = "";
22340   else if (cu->language == language_d)
22341     {
22342       /* For D, the 'main' function could be defined in any module, but it
22343          should never be prefixed.  */
22344       if (strcmp (suffix, "D main") == 0)
22345         {
22346           prefix = "";
22347           sep = "";
22348         }
22349       else
22350         sep = ".";
22351     }
22352   else if (cu->language == language_fortran && physname)
22353     {
22354       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22355          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22356
22357       lead = "__";
22358       sep = "_MOD_";
22359     }
22360   else
22361     sep = "::";
22362
22363   if (prefix == NULL)
22364     prefix = "";
22365   if (suffix == NULL)
22366     suffix = "";
22367
22368   if (obs == NULL)
22369     {
22370       char *retval
22371         = ((char *)
22372            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22373
22374       strcpy (retval, lead);
22375       strcat (retval, prefix);
22376       strcat (retval, sep);
22377       strcat (retval, suffix);
22378       return retval;
22379     }
22380   else
22381     {
22382       /* We have an obstack.  */
22383       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22384     }
22385 }
22386
22387 /* Return sibling of die, NULL if no sibling.  */
22388
22389 static struct die_info *
22390 sibling_die (struct die_info *die)
22391 {
22392   return die->sibling;
22393 }
22394
22395 /* Get name of a die, return NULL if not found.  */
22396
22397 static const char *
22398 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22399                           struct obstack *obstack)
22400 {
22401   if (name && cu->language == language_cplus)
22402     {
22403       std::string canon_name = cp_canonicalize_string (name);
22404
22405       if (!canon_name.empty ())
22406         {
22407           if (canon_name != name)
22408             name = (const char *) obstack_copy0 (obstack,
22409                                                  canon_name.c_str (),
22410                                                  canon_name.length ());
22411         }
22412     }
22413
22414   return name;
22415 }
22416
22417 /* Get name of a die, return NULL if not found.
22418    Anonymous namespaces are converted to their magic string.  */
22419
22420 static const char *
22421 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22422 {
22423   struct attribute *attr;
22424   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22425
22426   attr = dwarf2_attr (die, DW_AT_name, cu);
22427   if ((!attr || !DW_STRING (attr))
22428       && die->tag != DW_TAG_namespace
22429       && die->tag != DW_TAG_class_type
22430       && die->tag != DW_TAG_interface_type
22431       && die->tag != DW_TAG_structure_type
22432       && die->tag != DW_TAG_union_type)
22433     return NULL;
22434
22435   switch (die->tag)
22436     {
22437     case DW_TAG_compile_unit:
22438     case DW_TAG_partial_unit:
22439       /* Compilation units have a DW_AT_name that is a filename, not
22440          a source language identifier.  */
22441     case DW_TAG_enumeration_type:
22442     case DW_TAG_enumerator:
22443       /* These tags always have simple identifiers already; no need
22444          to canonicalize them.  */
22445       return DW_STRING (attr);
22446
22447     case DW_TAG_namespace:
22448       if (attr != NULL && DW_STRING (attr) != NULL)
22449         return DW_STRING (attr);
22450       return CP_ANONYMOUS_NAMESPACE_STR;
22451
22452     case DW_TAG_class_type:
22453     case DW_TAG_interface_type:
22454     case DW_TAG_structure_type:
22455     case DW_TAG_union_type:
22456       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22457          structures or unions.  These were of the form "._%d" in GCC 4.1,
22458          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22459          and GCC 4.4.  We work around this problem by ignoring these.  */
22460       if (attr && DW_STRING (attr)
22461           && (startswith (DW_STRING (attr), "._")
22462               || startswith (DW_STRING (attr), "<anonymous")))
22463         return NULL;
22464
22465       /* GCC might emit a nameless typedef that has a linkage name.  See
22466          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22467       if (!attr || DW_STRING (attr) == NULL)
22468         {
22469           char *demangled = NULL;
22470
22471           attr = dw2_linkage_name_attr (die, cu);
22472           if (attr == NULL || DW_STRING (attr) == NULL)
22473             return NULL;
22474
22475           /* Avoid demangling DW_STRING (attr) the second time on a second
22476              call for the same DIE.  */
22477           if (!DW_STRING_IS_CANONICAL (attr))
22478             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22479
22480           if (demangled)
22481             {
22482               const char *base;
22483
22484               /* FIXME: we already did this for the partial symbol... */
22485               DW_STRING (attr)
22486                 = ((const char *)
22487                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22488                                   demangled, strlen (demangled)));
22489               DW_STRING_IS_CANONICAL (attr) = 1;
22490               xfree (demangled);
22491
22492               /* Strip any leading namespaces/classes, keep only the base name.
22493                  DW_AT_name for named DIEs does not contain the prefixes.  */
22494               base = strrchr (DW_STRING (attr), ':');
22495               if (base && base > DW_STRING (attr) && base[-1] == ':')
22496                 return &base[1];
22497               else
22498                 return DW_STRING (attr);
22499             }
22500         }
22501       break;
22502
22503     default:
22504       break;
22505     }
22506
22507   if (!DW_STRING_IS_CANONICAL (attr))
22508     {
22509       DW_STRING (attr)
22510         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22511                                     &objfile->per_bfd->storage_obstack);
22512       DW_STRING_IS_CANONICAL (attr) = 1;
22513     }
22514   return DW_STRING (attr);
22515 }
22516
22517 /* Return the die that this die in an extension of, or NULL if there
22518    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22519    containing the return value on output.  */
22520
22521 static struct die_info *
22522 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22523 {
22524   struct attribute *attr;
22525
22526   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22527   if (attr == NULL)
22528     return NULL;
22529
22530   return follow_die_ref (die, attr, ext_cu);
22531 }
22532
22533 /* Convert a DIE tag into its string name.  */
22534
22535 static const char *
22536 dwarf_tag_name (unsigned tag)
22537 {
22538   const char *name = get_DW_TAG_name (tag);
22539
22540   if (name == NULL)
22541     return "DW_TAG_<unknown>";
22542
22543   return name;
22544 }
22545
22546 /* Convert a DWARF attribute code into its string name.  */
22547
22548 static const char *
22549 dwarf_attr_name (unsigned attr)
22550 {
22551   const char *name;
22552
22553 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22554   if (attr == DW_AT_MIPS_fde)
22555     return "DW_AT_MIPS_fde";
22556 #else
22557   if (attr == DW_AT_HP_block_index)
22558     return "DW_AT_HP_block_index";
22559 #endif
22560
22561   name = get_DW_AT_name (attr);
22562
22563   if (name == NULL)
22564     return "DW_AT_<unknown>";
22565
22566   return name;
22567 }
22568
22569 /* Convert a DWARF value form code into its string name.  */
22570
22571 static const char *
22572 dwarf_form_name (unsigned form)
22573 {
22574   const char *name = get_DW_FORM_name (form);
22575
22576   if (name == NULL)
22577     return "DW_FORM_<unknown>";
22578
22579   return name;
22580 }
22581
22582 static const char *
22583 dwarf_bool_name (unsigned mybool)
22584 {
22585   if (mybool)
22586     return "TRUE";
22587   else
22588     return "FALSE";
22589 }
22590
22591 /* Convert a DWARF type code into its string name.  */
22592
22593 static const char *
22594 dwarf_type_encoding_name (unsigned enc)
22595 {
22596   const char *name = get_DW_ATE_name (enc);
22597
22598   if (name == NULL)
22599     return "DW_ATE_<unknown>";
22600
22601   return name;
22602 }
22603
22604 static void
22605 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22606 {
22607   unsigned int i;
22608
22609   print_spaces (indent, f);
22610   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22611                       dwarf_tag_name (die->tag), die->abbrev,
22612                       sect_offset_str (die->sect_off));
22613
22614   if (die->parent != NULL)
22615     {
22616       print_spaces (indent, f);
22617       fprintf_unfiltered (f, "  parent at offset: %s\n",
22618                           sect_offset_str (die->parent->sect_off));
22619     }
22620
22621   print_spaces (indent, f);
22622   fprintf_unfiltered (f, "  has children: %s\n",
22623            dwarf_bool_name (die->child != NULL));
22624
22625   print_spaces (indent, f);
22626   fprintf_unfiltered (f, "  attributes:\n");
22627
22628   for (i = 0; i < die->num_attrs; ++i)
22629     {
22630       print_spaces (indent, f);
22631       fprintf_unfiltered (f, "    %s (%s) ",
22632                dwarf_attr_name (die->attrs[i].name),
22633                dwarf_form_name (die->attrs[i].form));
22634
22635       switch (die->attrs[i].form)
22636         {
22637         case DW_FORM_addr:
22638         case DW_FORM_GNU_addr_index:
22639           fprintf_unfiltered (f, "address: ");
22640           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22641           break;
22642         case DW_FORM_block2:
22643         case DW_FORM_block4:
22644         case DW_FORM_block:
22645         case DW_FORM_block1:
22646           fprintf_unfiltered (f, "block: size %s",
22647                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22648           break;
22649         case DW_FORM_exprloc:
22650           fprintf_unfiltered (f, "expression: size %s",
22651                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22652           break;
22653         case DW_FORM_data16:
22654           fprintf_unfiltered (f, "constant of 16 bytes");
22655           break;
22656         case DW_FORM_ref_addr:
22657           fprintf_unfiltered (f, "ref address: ");
22658           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22659           break;
22660         case DW_FORM_GNU_ref_alt:
22661           fprintf_unfiltered (f, "alt ref address: ");
22662           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22663           break;
22664         case DW_FORM_ref1:
22665         case DW_FORM_ref2:
22666         case DW_FORM_ref4:
22667         case DW_FORM_ref8:
22668         case DW_FORM_ref_udata:
22669           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22670                               (long) (DW_UNSND (&die->attrs[i])));
22671           break;
22672         case DW_FORM_data1:
22673         case DW_FORM_data2:
22674         case DW_FORM_data4:
22675         case DW_FORM_data8:
22676         case DW_FORM_udata:
22677         case DW_FORM_sdata:
22678           fprintf_unfiltered (f, "constant: %s",
22679                               pulongest (DW_UNSND (&die->attrs[i])));
22680           break;
22681         case DW_FORM_sec_offset:
22682           fprintf_unfiltered (f, "section offset: %s",
22683                               pulongest (DW_UNSND (&die->attrs[i])));
22684           break;
22685         case DW_FORM_ref_sig8:
22686           fprintf_unfiltered (f, "signature: %s",
22687                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22688           break;
22689         case DW_FORM_string:
22690         case DW_FORM_strp:
22691         case DW_FORM_line_strp:
22692         case DW_FORM_GNU_str_index:
22693         case DW_FORM_GNU_strp_alt:
22694           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22695                    DW_STRING (&die->attrs[i])
22696                    ? DW_STRING (&die->attrs[i]) : "",
22697                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22698           break;
22699         case DW_FORM_flag:
22700           if (DW_UNSND (&die->attrs[i]))
22701             fprintf_unfiltered (f, "flag: TRUE");
22702           else
22703             fprintf_unfiltered (f, "flag: FALSE");
22704           break;
22705         case DW_FORM_flag_present:
22706           fprintf_unfiltered (f, "flag: TRUE");
22707           break;
22708         case DW_FORM_indirect:
22709           /* The reader will have reduced the indirect form to
22710              the "base form" so this form should not occur.  */
22711           fprintf_unfiltered (f, 
22712                               "unexpected attribute form: DW_FORM_indirect");
22713           break;
22714         case DW_FORM_implicit_const:
22715           fprintf_unfiltered (f, "constant: %s",
22716                               plongest (DW_SND (&die->attrs[i])));
22717           break;
22718         default:
22719           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22720                    die->attrs[i].form);
22721           break;
22722         }
22723       fprintf_unfiltered (f, "\n");
22724     }
22725 }
22726
22727 static void
22728 dump_die_for_error (struct die_info *die)
22729 {
22730   dump_die_shallow (gdb_stderr, 0, die);
22731 }
22732
22733 static void
22734 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22735 {
22736   int indent = level * 4;
22737
22738   gdb_assert (die != NULL);
22739
22740   if (level >= max_level)
22741     return;
22742
22743   dump_die_shallow (f, indent, die);
22744
22745   if (die->child != NULL)
22746     {
22747       print_spaces (indent, f);
22748       fprintf_unfiltered (f, "  Children:");
22749       if (level + 1 < max_level)
22750         {
22751           fprintf_unfiltered (f, "\n");
22752           dump_die_1 (f, level + 1, max_level, die->child);
22753         }
22754       else
22755         {
22756           fprintf_unfiltered (f,
22757                               " [not printed, max nesting level reached]\n");
22758         }
22759     }
22760
22761   if (die->sibling != NULL && level > 0)
22762     {
22763       dump_die_1 (f, level, max_level, die->sibling);
22764     }
22765 }
22766
22767 /* This is called from the pdie macro in gdbinit.in.
22768    It's not static so gcc will keep a copy callable from gdb.  */
22769
22770 void
22771 dump_die (struct die_info *die, int max_level)
22772 {
22773   dump_die_1 (gdb_stdlog, 0, max_level, die);
22774 }
22775
22776 static void
22777 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22778 {
22779   void **slot;
22780
22781   slot = htab_find_slot_with_hash (cu->die_hash, die,
22782                                    to_underlying (die->sect_off),
22783                                    INSERT);
22784
22785   *slot = die;
22786 }
22787
22788 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22789    required kind.  */
22790
22791 static sect_offset
22792 dwarf2_get_ref_die_offset (const struct attribute *attr)
22793 {
22794   if (attr_form_is_ref (attr))
22795     return (sect_offset) DW_UNSND (attr);
22796
22797   complaint (&symfile_complaints,
22798              _("unsupported die ref attribute form: '%s'"),
22799              dwarf_form_name (attr->form));
22800   return {};
22801 }
22802
22803 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22804  * the value held by the attribute is not constant.  */
22805
22806 static LONGEST
22807 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22808 {
22809   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22810     return DW_SND (attr);
22811   else if (attr->form == DW_FORM_udata
22812            || attr->form == DW_FORM_data1
22813            || attr->form == DW_FORM_data2
22814            || attr->form == DW_FORM_data4
22815            || attr->form == DW_FORM_data8)
22816     return DW_UNSND (attr);
22817   else
22818     {
22819       /* For DW_FORM_data16 see attr_form_is_constant.  */
22820       complaint (&symfile_complaints,
22821                  _("Attribute value is not a constant (%s)"),
22822                  dwarf_form_name (attr->form));
22823       return default_value;
22824     }
22825 }
22826
22827 /* Follow reference or signature attribute ATTR of SRC_DIE.
22828    On entry *REF_CU is the CU of SRC_DIE.
22829    On exit *REF_CU is the CU of the result.  */
22830
22831 static struct die_info *
22832 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22833                        struct dwarf2_cu **ref_cu)
22834 {
22835   struct die_info *die;
22836
22837   if (attr_form_is_ref (attr))
22838     die = follow_die_ref (src_die, attr, ref_cu);
22839   else if (attr->form == DW_FORM_ref_sig8)
22840     die = follow_die_sig (src_die, attr, ref_cu);
22841   else
22842     {
22843       dump_die_for_error (src_die);
22844       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22845              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22846     }
22847
22848   return die;
22849 }
22850
22851 /* Follow reference OFFSET.
22852    On entry *REF_CU is the CU of the source die referencing OFFSET.
22853    On exit *REF_CU is the CU of the result.
22854    Returns NULL if OFFSET is invalid.  */
22855
22856 static struct die_info *
22857 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22858                    struct dwarf2_cu **ref_cu)
22859 {
22860   struct die_info temp_die;
22861   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22862   struct dwarf2_per_objfile *dwarf2_per_objfile
22863     = cu->per_cu->dwarf2_per_objfile;
22864
22865   gdb_assert (cu->per_cu != NULL);
22866
22867   target_cu = cu;
22868
22869   if (cu->per_cu->is_debug_types)
22870     {
22871       /* .debug_types CUs cannot reference anything outside their CU.
22872          If they need to, they have to reference a signatured type via
22873          DW_FORM_ref_sig8.  */
22874       if (!offset_in_cu_p (&cu->header, sect_off))
22875         return NULL;
22876     }
22877   else if (offset_in_dwz != cu->per_cu->is_dwz
22878            || !offset_in_cu_p (&cu->header, sect_off))
22879     {
22880       struct dwarf2_per_cu_data *per_cu;
22881
22882       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22883                                                  dwarf2_per_objfile);
22884
22885       /* If necessary, add it to the queue and load its DIEs.  */
22886       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22887         load_full_comp_unit (per_cu, cu->language);
22888
22889       target_cu = per_cu->cu;
22890     }
22891   else if (cu->dies == NULL)
22892     {
22893       /* We're loading full DIEs during partial symbol reading.  */
22894       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22895       load_full_comp_unit (cu->per_cu, language_minimal);
22896     }
22897
22898   *ref_cu = target_cu;
22899   temp_die.sect_off = sect_off;
22900   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22901                                                   &temp_die,
22902                                                   to_underlying (sect_off));
22903 }
22904
22905 /* Follow reference attribute ATTR of SRC_DIE.
22906    On entry *REF_CU is the CU of SRC_DIE.
22907    On exit *REF_CU is the CU of the result.  */
22908
22909 static struct die_info *
22910 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22911                 struct dwarf2_cu **ref_cu)
22912 {
22913   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22914   struct dwarf2_cu *cu = *ref_cu;
22915   struct die_info *die;
22916
22917   die = follow_die_offset (sect_off,
22918                            (attr->form == DW_FORM_GNU_ref_alt
22919                             || cu->per_cu->is_dwz),
22920                            ref_cu);
22921   if (!die)
22922     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22923            "at %s [in module %s]"),
22924            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22925            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22926
22927   return die;
22928 }
22929
22930 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22931    Returned value is intended for DW_OP_call*.  Returned
22932    dwarf2_locexpr_baton->data has lifetime of
22933    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22934
22935 struct dwarf2_locexpr_baton
22936 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22937                                struct dwarf2_per_cu_data *per_cu,
22938                                CORE_ADDR (*get_frame_pc) (void *baton),
22939                                void *baton)
22940 {
22941   struct dwarf2_cu *cu;
22942   struct die_info *die;
22943   struct attribute *attr;
22944   struct dwarf2_locexpr_baton retval;
22945   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22946   struct objfile *objfile = dwarf2_per_objfile->objfile;
22947
22948   if (per_cu->cu == NULL)
22949     load_cu (per_cu);
22950   cu = per_cu->cu;
22951   if (cu == NULL)
22952     {
22953       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22954          Instead just throw an error, not much else we can do.  */
22955       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22956              sect_offset_str (sect_off), objfile_name (objfile));
22957     }
22958
22959   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22960   if (!die)
22961     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22962            sect_offset_str (sect_off), objfile_name (objfile));
22963
22964   attr = dwarf2_attr (die, DW_AT_location, cu);
22965   if (!attr)
22966     {
22967       /* DWARF: "If there is no such attribute, then there is no effect.".
22968          DATA is ignored if SIZE is 0.  */
22969
22970       retval.data = NULL;
22971       retval.size = 0;
22972     }
22973   else if (attr_form_is_section_offset (attr))
22974     {
22975       struct dwarf2_loclist_baton loclist_baton;
22976       CORE_ADDR pc = (*get_frame_pc) (baton);
22977       size_t size;
22978
22979       fill_in_loclist_baton (cu, &loclist_baton, attr);
22980
22981       retval.data = dwarf2_find_location_expression (&loclist_baton,
22982                                                      &size, pc);
22983       retval.size = size;
22984     }
22985   else
22986     {
22987       if (!attr_form_is_block (attr))
22988         error (_("Dwarf Error: DIE at %s referenced in module %s "
22989                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22990                sect_offset_str (sect_off), objfile_name (objfile));
22991
22992       retval.data = DW_BLOCK (attr)->data;
22993       retval.size = DW_BLOCK (attr)->size;
22994     }
22995   retval.per_cu = cu->per_cu;
22996
22997   age_cached_comp_units (dwarf2_per_objfile);
22998
22999   return retval;
23000 }
23001
23002 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23003    offset.  */
23004
23005 struct dwarf2_locexpr_baton
23006 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23007                              struct dwarf2_per_cu_data *per_cu,
23008                              CORE_ADDR (*get_frame_pc) (void *baton),
23009                              void *baton)
23010 {
23011   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23012
23013   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23014 }
23015
23016 /* Write a constant of a given type as target-ordered bytes into
23017    OBSTACK.  */
23018
23019 static const gdb_byte *
23020 write_constant_as_bytes (struct obstack *obstack,
23021                          enum bfd_endian byte_order,
23022                          struct type *type,
23023                          ULONGEST value,
23024                          LONGEST *len)
23025 {
23026   gdb_byte *result;
23027
23028   *len = TYPE_LENGTH (type);
23029   result = (gdb_byte *) obstack_alloc (obstack, *len);
23030   store_unsigned_integer (result, *len, byte_order, value);
23031
23032   return result;
23033 }
23034
23035 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23036    pointer to the constant bytes and set LEN to the length of the
23037    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23038    does not have a DW_AT_const_value, return NULL.  */
23039
23040 const gdb_byte *
23041 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23042                              struct dwarf2_per_cu_data *per_cu,
23043                              struct obstack *obstack,
23044                              LONGEST *len)
23045 {
23046   struct dwarf2_cu *cu;
23047   struct die_info *die;
23048   struct attribute *attr;
23049   const gdb_byte *result = NULL;
23050   struct type *type;
23051   LONGEST value;
23052   enum bfd_endian byte_order;
23053   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23054
23055   if (per_cu->cu == NULL)
23056     load_cu (per_cu);
23057   cu = per_cu->cu;
23058   if (cu == NULL)
23059     {
23060       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23061          Instead just throw an error, not much else we can do.  */
23062       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23063              sect_offset_str (sect_off), objfile_name (objfile));
23064     }
23065
23066   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23067   if (!die)
23068     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23069            sect_offset_str (sect_off), objfile_name (objfile));
23070
23071   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23072   if (attr == NULL)
23073     return NULL;
23074
23075   byte_order = (bfd_big_endian (objfile->obfd)
23076                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23077
23078   switch (attr->form)
23079     {
23080     case DW_FORM_addr:
23081     case DW_FORM_GNU_addr_index:
23082       {
23083         gdb_byte *tem;
23084
23085         *len = cu->header.addr_size;
23086         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23087         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23088         result = tem;
23089       }
23090       break;
23091     case DW_FORM_string:
23092     case DW_FORM_strp:
23093     case DW_FORM_GNU_str_index:
23094     case DW_FORM_GNU_strp_alt:
23095       /* DW_STRING is already allocated on the objfile obstack, point
23096          directly to it.  */
23097       result = (const gdb_byte *) DW_STRING (attr);
23098       *len = strlen (DW_STRING (attr));
23099       break;
23100     case DW_FORM_block1:
23101     case DW_FORM_block2:
23102     case DW_FORM_block4:
23103     case DW_FORM_block:
23104     case DW_FORM_exprloc:
23105     case DW_FORM_data16:
23106       result = DW_BLOCK (attr)->data;
23107       *len = DW_BLOCK (attr)->size;
23108       break;
23109
23110       /* The DW_AT_const_value attributes are supposed to carry the
23111          symbol's value "represented as it would be on the target
23112          architecture."  By the time we get here, it's already been
23113          converted to host endianness, so we just need to sign- or
23114          zero-extend it as appropriate.  */
23115     case DW_FORM_data1:
23116       type = die_type (die, cu);
23117       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23118       if (result == NULL)
23119         result = write_constant_as_bytes (obstack, byte_order,
23120                                           type, value, len);
23121       break;
23122     case DW_FORM_data2:
23123       type = die_type (die, cu);
23124       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23125       if (result == NULL)
23126         result = write_constant_as_bytes (obstack, byte_order,
23127                                           type, value, len);
23128       break;
23129     case DW_FORM_data4:
23130       type = die_type (die, cu);
23131       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23132       if (result == NULL)
23133         result = write_constant_as_bytes (obstack, byte_order,
23134                                           type, value, len);
23135       break;
23136     case DW_FORM_data8:
23137       type = die_type (die, cu);
23138       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23139       if (result == NULL)
23140         result = write_constant_as_bytes (obstack, byte_order,
23141                                           type, value, len);
23142       break;
23143
23144     case DW_FORM_sdata:
23145     case DW_FORM_implicit_const:
23146       type = die_type (die, cu);
23147       result = write_constant_as_bytes (obstack, byte_order,
23148                                         type, DW_SND (attr), len);
23149       break;
23150
23151     case DW_FORM_udata:
23152       type = die_type (die, cu);
23153       result = write_constant_as_bytes (obstack, byte_order,
23154                                         type, DW_UNSND (attr), len);
23155       break;
23156
23157     default:
23158       complaint (&symfile_complaints,
23159                  _("unsupported const value attribute form: '%s'"),
23160                  dwarf_form_name (attr->form));
23161       break;
23162     }
23163
23164   return result;
23165 }
23166
23167 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23168    valid type for this die is found.  */
23169
23170 struct type *
23171 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23172                                 struct dwarf2_per_cu_data *per_cu)
23173 {
23174   struct dwarf2_cu *cu;
23175   struct die_info *die;
23176
23177   if (per_cu->cu == NULL)
23178     load_cu (per_cu);
23179   cu = per_cu->cu;
23180   if (!cu)
23181     return NULL;
23182
23183   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23184   if (!die)
23185     return NULL;
23186
23187   return die_type (die, cu);
23188 }
23189
23190 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23191    PER_CU.  */
23192
23193 struct type *
23194 dwarf2_get_die_type (cu_offset die_offset,
23195                      struct dwarf2_per_cu_data *per_cu)
23196 {
23197   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23198   return get_die_type_at_offset (die_offset_sect, per_cu);
23199 }
23200
23201 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23202    On entry *REF_CU is the CU of SRC_DIE.
23203    On exit *REF_CU is the CU of the result.
23204    Returns NULL if the referenced DIE isn't found.  */
23205
23206 static struct die_info *
23207 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23208                   struct dwarf2_cu **ref_cu)
23209 {
23210   struct die_info temp_die;
23211   struct dwarf2_cu *sig_cu;
23212   struct die_info *die;
23213
23214   /* While it might be nice to assert sig_type->type == NULL here,
23215      we can get here for DW_AT_imported_declaration where we need
23216      the DIE not the type.  */
23217
23218   /* If necessary, add it to the queue and load its DIEs.  */
23219
23220   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23221     read_signatured_type (sig_type);
23222
23223   sig_cu = sig_type->per_cu.cu;
23224   gdb_assert (sig_cu != NULL);
23225   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23226   temp_die.sect_off = sig_type->type_offset_in_section;
23227   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23228                                                  to_underlying (temp_die.sect_off));
23229   if (die)
23230     {
23231       struct dwarf2_per_objfile *dwarf2_per_objfile
23232         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23233
23234       /* For .gdb_index version 7 keep track of included TUs.
23235          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23236       if (dwarf2_per_objfile->index_table != NULL
23237           && dwarf2_per_objfile->index_table->version <= 7)
23238         {
23239           VEC_safe_push (dwarf2_per_cu_ptr,
23240                          (*ref_cu)->per_cu->imported_symtabs,
23241                          sig_cu->per_cu);
23242         }
23243
23244       *ref_cu = sig_cu;
23245       return die;
23246     }
23247
23248   return NULL;
23249 }
23250
23251 /* Follow signatured type referenced by ATTR in SRC_DIE.
23252    On entry *REF_CU is the CU of SRC_DIE.
23253    On exit *REF_CU is the CU of the result.
23254    The result is the DIE of the type.
23255    If the referenced type cannot be found an error is thrown.  */
23256
23257 static struct die_info *
23258 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23259                 struct dwarf2_cu **ref_cu)
23260 {
23261   ULONGEST signature = DW_SIGNATURE (attr);
23262   struct signatured_type *sig_type;
23263   struct die_info *die;
23264
23265   gdb_assert (attr->form == DW_FORM_ref_sig8);
23266
23267   sig_type = lookup_signatured_type (*ref_cu, signature);
23268   /* sig_type will be NULL if the signatured type is missing from
23269      the debug info.  */
23270   if (sig_type == NULL)
23271     {
23272       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23273                " from DIE at %s [in module %s]"),
23274              hex_string (signature), sect_offset_str (src_die->sect_off),
23275              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23276     }
23277
23278   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23279   if (die == NULL)
23280     {
23281       dump_die_for_error (src_die);
23282       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23283                " from DIE at %s [in module %s]"),
23284              hex_string (signature), sect_offset_str (src_die->sect_off),
23285              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23286     }
23287
23288   return die;
23289 }
23290
23291 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23292    reading in and processing the type unit if necessary.  */
23293
23294 static struct type *
23295 get_signatured_type (struct die_info *die, ULONGEST signature,
23296                      struct dwarf2_cu *cu)
23297 {
23298   struct dwarf2_per_objfile *dwarf2_per_objfile
23299     = cu->per_cu->dwarf2_per_objfile;
23300   struct signatured_type *sig_type;
23301   struct dwarf2_cu *type_cu;
23302   struct die_info *type_die;
23303   struct type *type;
23304
23305   sig_type = lookup_signatured_type (cu, signature);
23306   /* sig_type will be NULL if the signatured type is missing from
23307      the debug info.  */
23308   if (sig_type == NULL)
23309     {
23310       complaint (&symfile_complaints,
23311                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23312                    " from DIE at %s [in module %s]"),
23313                  hex_string (signature), sect_offset_str (die->sect_off),
23314                  objfile_name (dwarf2_per_objfile->objfile));
23315       return build_error_marker_type (cu, die);
23316     }
23317
23318   /* If we already know the type we're done.  */
23319   if (sig_type->type != NULL)
23320     return sig_type->type;
23321
23322   type_cu = cu;
23323   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23324   if (type_die != NULL)
23325     {
23326       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23327          is created.  This is important, for example, because for c++ classes
23328          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23329       type = read_type_die (type_die, type_cu);
23330       if (type == NULL)
23331         {
23332           complaint (&symfile_complaints,
23333                      _("Dwarf Error: Cannot build signatured type %s"
23334                        " referenced from DIE at %s [in module %s]"),
23335                      hex_string (signature), sect_offset_str (die->sect_off),
23336                      objfile_name (dwarf2_per_objfile->objfile));
23337           type = build_error_marker_type (cu, die);
23338         }
23339     }
23340   else
23341     {
23342       complaint (&symfile_complaints,
23343                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23344                    " from DIE at %s [in module %s]"),
23345                  hex_string (signature), sect_offset_str (die->sect_off),
23346                  objfile_name (dwarf2_per_objfile->objfile));
23347       type = build_error_marker_type (cu, die);
23348     }
23349   sig_type->type = type;
23350
23351   return type;
23352 }
23353
23354 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23355    reading in and processing the type unit if necessary.  */
23356
23357 static struct type *
23358 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23359                           struct dwarf2_cu *cu) /* ARI: editCase function */
23360 {
23361   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23362   if (attr_form_is_ref (attr))
23363     {
23364       struct dwarf2_cu *type_cu = cu;
23365       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23366
23367       return read_type_die (type_die, type_cu);
23368     }
23369   else if (attr->form == DW_FORM_ref_sig8)
23370     {
23371       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23372     }
23373   else
23374     {
23375       struct dwarf2_per_objfile *dwarf2_per_objfile
23376         = cu->per_cu->dwarf2_per_objfile;
23377
23378       complaint (&symfile_complaints,
23379                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23380                    " at %s [in module %s]"),
23381                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23382                  objfile_name (dwarf2_per_objfile->objfile));
23383       return build_error_marker_type (cu, die);
23384     }
23385 }
23386
23387 /* Load the DIEs associated with type unit PER_CU into memory.  */
23388
23389 static void
23390 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23391 {
23392   struct signatured_type *sig_type;
23393
23394   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23395   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23396
23397   /* We have the per_cu, but we need the signatured_type.
23398      Fortunately this is an easy translation.  */
23399   gdb_assert (per_cu->is_debug_types);
23400   sig_type = (struct signatured_type *) per_cu;
23401
23402   gdb_assert (per_cu->cu == NULL);
23403
23404   read_signatured_type (sig_type);
23405
23406   gdb_assert (per_cu->cu != NULL);
23407 }
23408
23409 /* die_reader_func for read_signatured_type.
23410    This is identical to load_full_comp_unit_reader,
23411    but is kept separate for now.  */
23412
23413 static void
23414 read_signatured_type_reader (const struct die_reader_specs *reader,
23415                              const gdb_byte *info_ptr,
23416                              struct die_info *comp_unit_die,
23417                              int has_children,
23418                              void *data)
23419 {
23420   struct dwarf2_cu *cu = reader->cu;
23421
23422   gdb_assert (cu->die_hash == NULL);
23423   cu->die_hash =
23424     htab_create_alloc_ex (cu->header.length / 12,
23425                           die_hash,
23426                           die_eq,
23427                           NULL,
23428                           &cu->comp_unit_obstack,
23429                           hashtab_obstack_allocate,
23430                           dummy_obstack_deallocate);
23431
23432   if (has_children)
23433     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23434                                                   &info_ptr, comp_unit_die);
23435   cu->dies = comp_unit_die;
23436   /* comp_unit_die is not stored in die_hash, no need.  */
23437
23438   /* We try not to read any attributes in this function, because not
23439      all CUs needed for references have been loaded yet, and symbol
23440      table processing isn't initialized.  But we have to set the CU language,
23441      or we won't be able to build types correctly.
23442      Similarly, if we do not read the producer, we can not apply
23443      producer-specific interpretation.  */
23444   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23445 }
23446
23447 /* Read in a signatured type and build its CU and DIEs.
23448    If the type is a stub for the real type in a DWO file,
23449    read in the real type from the DWO file as well.  */
23450
23451 static void
23452 read_signatured_type (struct signatured_type *sig_type)
23453 {
23454   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23455
23456   gdb_assert (per_cu->is_debug_types);
23457   gdb_assert (per_cu->cu == NULL);
23458
23459   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23460                            read_signatured_type_reader, NULL);
23461   sig_type->per_cu.tu_read = 1;
23462 }
23463
23464 /* Decode simple location descriptions.
23465    Given a pointer to a dwarf block that defines a location, compute
23466    the location and return the value.
23467
23468    NOTE drow/2003-11-18: This function is called in two situations
23469    now: for the address of static or global variables (partial symbols
23470    only) and for offsets into structures which are expected to be
23471    (more or less) constant.  The partial symbol case should go away,
23472    and only the constant case should remain.  That will let this
23473    function complain more accurately.  A few special modes are allowed
23474    without complaint for global variables (for instance, global
23475    register values and thread-local values).
23476
23477    A location description containing no operations indicates that the
23478    object is optimized out.  The return value is 0 for that case.
23479    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23480    callers will only want a very basic result and this can become a
23481    complaint.
23482
23483    Note that stack[0] is unused except as a default error return.  */
23484
23485 static CORE_ADDR
23486 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23487 {
23488   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23489   size_t i;
23490   size_t size = blk->size;
23491   const gdb_byte *data = blk->data;
23492   CORE_ADDR stack[64];
23493   int stacki;
23494   unsigned int bytes_read, unsnd;
23495   gdb_byte op;
23496
23497   i = 0;
23498   stacki = 0;
23499   stack[stacki] = 0;
23500   stack[++stacki] = 0;
23501
23502   while (i < size)
23503     {
23504       op = data[i++];
23505       switch (op)
23506         {
23507         case DW_OP_lit0:
23508         case DW_OP_lit1:
23509         case DW_OP_lit2:
23510         case DW_OP_lit3:
23511         case DW_OP_lit4:
23512         case DW_OP_lit5:
23513         case DW_OP_lit6:
23514         case DW_OP_lit7:
23515         case DW_OP_lit8:
23516         case DW_OP_lit9:
23517         case DW_OP_lit10:
23518         case DW_OP_lit11:
23519         case DW_OP_lit12:
23520         case DW_OP_lit13:
23521         case DW_OP_lit14:
23522         case DW_OP_lit15:
23523         case DW_OP_lit16:
23524         case DW_OP_lit17:
23525         case DW_OP_lit18:
23526         case DW_OP_lit19:
23527         case DW_OP_lit20:
23528         case DW_OP_lit21:
23529         case DW_OP_lit22:
23530         case DW_OP_lit23:
23531         case DW_OP_lit24:
23532         case DW_OP_lit25:
23533         case DW_OP_lit26:
23534         case DW_OP_lit27:
23535         case DW_OP_lit28:
23536         case DW_OP_lit29:
23537         case DW_OP_lit30:
23538         case DW_OP_lit31:
23539           stack[++stacki] = op - DW_OP_lit0;
23540           break;
23541
23542         case DW_OP_reg0:
23543         case DW_OP_reg1:
23544         case DW_OP_reg2:
23545         case DW_OP_reg3:
23546         case DW_OP_reg4:
23547         case DW_OP_reg5:
23548         case DW_OP_reg6:
23549         case DW_OP_reg7:
23550         case DW_OP_reg8:
23551         case DW_OP_reg9:
23552         case DW_OP_reg10:
23553         case DW_OP_reg11:
23554         case DW_OP_reg12:
23555         case DW_OP_reg13:
23556         case DW_OP_reg14:
23557         case DW_OP_reg15:
23558         case DW_OP_reg16:
23559         case DW_OP_reg17:
23560         case DW_OP_reg18:
23561         case DW_OP_reg19:
23562         case DW_OP_reg20:
23563         case DW_OP_reg21:
23564         case DW_OP_reg22:
23565         case DW_OP_reg23:
23566         case DW_OP_reg24:
23567         case DW_OP_reg25:
23568         case DW_OP_reg26:
23569         case DW_OP_reg27:
23570         case DW_OP_reg28:
23571         case DW_OP_reg29:
23572         case DW_OP_reg30:
23573         case DW_OP_reg31:
23574           stack[++stacki] = op - DW_OP_reg0;
23575           if (i < size)
23576             dwarf2_complex_location_expr_complaint ();
23577           break;
23578
23579         case DW_OP_regx:
23580           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23581           i += bytes_read;
23582           stack[++stacki] = unsnd;
23583           if (i < size)
23584             dwarf2_complex_location_expr_complaint ();
23585           break;
23586
23587         case DW_OP_addr:
23588           stack[++stacki] = read_address (objfile->obfd, &data[i],
23589                                           cu, &bytes_read);
23590           i += bytes_read;
23591           break;
23592
23593         case DW_OP_const1u:
23594           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23595           i += 1;
23596           break;
23597
23598         case DW_OP_const1s:
23599           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23600           i += 1;
23601           break;
23602
23603         case DW_OP_const2u:
23604           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23605           i += 2;
23606           break;
23607
23608         case DW_OP_const2s:
23609           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23610           i += 2;
23611           break;
23612
23613         case DW_OP_const4u:
23614           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23615           i += 4;
23616           break;
23617
23618         case DW_OP_const4s:
23619           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23620           i += 4;
23621           break;
23622
23623         case DW_OP_const8u:
23624           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23625           i += 8;
23626           break;
23627
23628         case DW_OP_constu:
23629           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23630                                                   &bytes_read);
23631           i += bytes_read;
23632           break;
23633
23634         case DW_OP_consts:
23635           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23636           i += bytes_read;
23637           break;
23638
23639         case DW_OP_dup:
23640           stack[stacki + 1] = stack[stacki];
23641           stacki++;
23642           break;
23643
23644         case DW_OP_plus:
23645           stack[stacki - 1] += stack[stacki];
23646           stacki--;
23647           break;
23648
23649         case DW_OP_plus_uconst:
23650           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23651                                                  &bytes_read);
23652           i += bytes_read;
23653           break;
23654
23655         case DW_OP_minus:
23656           stack[stacki - 1] -= stack[stacki];
23657           stacki--;
23658           break;
23659
23660         case DW_OP_deref:
23661           /* If we're not the last op, then we definitely can't encode
23662              this using GDB's address_class enum.  This is valid for partial
23663              global symbols, although the variable's address will be bogus
23664              in the psymtab.  */
23665           if (i < size)
23666             dwarf2_complex_location_expr_complaint ();
23667           break;
23668
23669         case DW_OP_GNU_push_tls_address:
23670         case DW_OP_form_tls_address:
23671           /* The top of the stack has the offset from the beginning
23672              of the thread control block at which the variable is located.  */
23673           /* Nothing should follow this operator, so the top of stack would
23674              be returned.  */
23675           /* This is valid for partial global symbols, but the variable's
23676              address will be bogus in the psymtab.  Make it always at least
23677              non-zero to not look as a variable garbage collected by linker
23678              which have DW_OP_addr 0.  */
23679           if (i < size)
23680             dwarf2_complex_location_expr_complaint ();
23681           stack[stacki]++;
23682           break;
23683
23684         case DW_OP_GNU_uninit:
23685           break;
23686
23687         case DW_OP_GNU_addr_index:
23688         case DW_OP_GNU_const_index:
23689           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23690                                                          &bytes_read);
23691           i += bytes_read;
23692           break;
23693
23694         default:
23695           {
23696             const char *name = get_DW_OP_name (op);
23697
23698             if (name)
23699               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23700                          name);
23701             else
23702               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23703                          op);
23704           }
23705
23706           return (stack[stacki]);
23707         }
23708
23709       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23710          outside of the allocated space.  Also enforce minimum>0.  */
23711       if (stacki >= ARRAY_SIZE (stack) - 1)
23712         {
23713           complaint (&symfile_complaints,
23714                      _("location description stack overflow"));
23715           return 0;
23716         }
23717
23718       if (stacki <= 0)
23719         {
23720           complaint (&symfile_complaints,
23721                      _("location description stack underflow"));
23722           return 0;
23723         }
23724     }
23725   return (stack[stacki]);
23726 }
23727
23728 /* memory allocation interface */
23729
23730 static struct dwarf_block *
23731 dwarf_alloc_block (struct dwarf2_cu *cu)
23732 {
23733   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23734 }
23735
23736 static struct die_info *
23737 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23738 {
23739   struct die_info *die;
23740   size_t size = sizeof (struct die_info);
23741
23742   if (num_attrs > 1)
23743     size += (num_attrs - 1) * sizeof (struct attribute);
23744
23745   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23746   memset (die, 0, sizeof (struct die_info));
23747   return (die);
23748 }
23749
23750 \f
23751 /* Macro support.  */
23752
23753 /* Return file name relative to the compilation directory of file number I in
23754    *LH's file name table.  The result is allocated using xmalloc; the caller is
23755    responsible for freeing it.  */
23756
23757 static char *
23758 file_file_name (int file, struct line_header *lh)
23759 {
23760   /* Is the file number a valid index into the line header's file name
23761      table?  Remember that file numbers start with one, not zero.  */
23762   if (1 <= file && file <= lh->file_names.size ())
23763     {
23764       const file_entry &fe = lh->file_names[file - 1];
23765
23766       if (!IS_ABSOLUTE_PATH (fe.name))
23767         {
23768           const char *dir = fe.include_dir (lh);
23769           if (dir != NULL)
23770             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23771         }
23772       return xstrdup (fe.name);
23773     }
23774   else
23775     {
23776       /* The compiler produced a bogus file number.  We can at least
23777          record the macro definitions made in the file, even if we
23778          won't be able to find the file by name.  */
23779       char fake_name[80];
23780
23781       xsnprintf (fake_name, sizeof (fake_name),
23782                  "<bad macro file number %d>", file);
23783
23784       complaint (&symfile_complaints,
23785                  _("bad file number in macro information (%d)"),
23786                  file);
23787
23788       return xstrdup (fake_name);
23789     }
23790 }
23791
23792 /* Return the full name of file number I in *LH's file name table.
23793    Use COMP_DIR as the name of the current directory of the
23794    compilation.  The result is allocated using xmalloc; the caller is
23795    responsible for freeing it.  */
23796 static char *
23797 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23798 {
23799   /* Is the file number a valid index into the line header's file name
23800      table?  Remember that file numbers start with one, not zero.  */
23801   if (1 <= file && file <= lh->file_names.size ())
23802     {
23803       char *relative = file_file_name (file, lh);
23804
23805       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23806         return relative;
23807       return reconcat (relative, comp_dir, SLASH_STRING,
23808                        relative, (char *) NULL);
23809     }
23810   else
23811     return file_file_name (file, lh);
23812 }
23813
23814
23815 static struct macro_source_file *
23816 macro_start_file (int file, int line,
23817                   struct macro_source_file *current_file,
23818                   struct line_header *lh)
23819 {
23820   /* File name relative to the compilation directory of this source file.  */
23821   char *file_name = file_file_name (file, lh);
23822
23823   if (! current_file)
23824     {
23825       /* Note: We don't create a macro table for this compilation unit
23826          at all until we actually get a filename.  */
23827       struct macro_table *macro_table = get_macro_table ();
23828
23829       /* If we have no current file, then this must be the start_file
23830          directive for the compilation unit's main source file.  */
23831       current_file = macro_set_main (macro_table, file_name);
23832       macro_define_special (macro_table);
23833     }
23834   else
23835     current_file = macro_include (current_file, line, file_name);
23836
23837   xfree (file_name);
23838
23839   return current_file;
23840 }
23841
23842 static const char *
23843 consume_improper_spaces (const char *p, const char *body)
23844 {
23845   if (*p == ' ')
23846     {
23847       complaint (&symfile_complaints,
23848                  _("macro definition contains spaces "
23849                    "in formal argument list:\n`%s'"),
23850                  body);
23851
23852       while (*p == ' ')
23853         p++;
23854     }
23855
23856   return p;
23857 }
23858
23859
23860 static void
23861 parse_macro_definition (struct macro_source_file *file, int line,
23862                         const char *body)
23863 {
23864   const char *p;
23865
23866   /* The body string takes one of two forms.  For object-like macro
23867      definitions, it should be:
23868
23869         <macro name> " " <definition>
23870
23871      For function-like macro definitions, it should be:
23872
23873         <macro name> "() " <definition>
23874      or
23875         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23876
23877      Spaces may appear only where explicitly indicated, and in the
23878      <definition>.
23879
23880      The Dwarf 2 spec says that an object-like macro's name is always
23881      followed by a space, but versions of GCC around March 2002 omit
23882      the space when the macro's definition is the empty string.
23883
23884      The Dwarf 2 spec says that there should be no spaces between the
23885      formal arguments in a function-like macro's formal argument list,
23886      but versions of GCC around March 2002 include spaces after the
23887      commas.  */
23888
23889
23890   /* Find the extent of the macro name.  The macro name is terminated
23891      by either a space or null character (for an object-like macro) or
23892      an opening paren (for a function-like macro).  */
23893   for (p = body; *p; p++)
23894     if (*p == ' ' || *p == '(')
23895       break;
23896
23897   if (*p == ' ' || *p == '\0')
23898     {
23899       /* It's an object-like macro.  */
23900       int name_len = p - body;
23901       char *name = savestring (body, name_len);
23902       const char *replacement;
23903
23904       if (*p == ' ')
23905         replacement = body + name_len + 1;
23906       else
23907         {
23908           dwarf2_macro_malformed_definition_complaint (body);
23909           replacement = body + name_len;
23910         }
23911
23912       macro_define_object (file, line, name, replacement);
23913
23914       xfree (name);
23915     }
23916   else if (*p == '(')
23917     {
23918       /* It's a function-like macro.  */
23919       char *name = savestring (body, p - body);
23920       int argc = 0;
23921       int argv_size = 1;
23922       char **argv = XNEWVEC (char *, argv_size);
23923
23924       p++;
23925
23926       p = consume_improper_spaces (p, body);
23927
23928       /* Parse the formal argument list.  */
23929       while (*p && *p != ')')
23930         {
23931           /* Find the extent of the current argument name.  */
23932           const char *arg_start = p;
23933
23934           while (*p && *p != ',' && *p != ')' && *p != ' ')
23935             p++;
23936
23937           if (! *p || p == arg_start)
23938             dwarf2_macro_malformed_definition_complaint (body);
23939           else
23940             {
23941               /* Make sure argv has room for the new argument.  */
23942               if (argc >= argv_size)
23943                 {
23944                   argv_size *= 2;
23945                   argv = XRESIZEVEC (char *, argv, argv_size);
23946                 }
23947
23948               argv[argc++] = savestring (arg_start, p - arg_start);
23949             }
23950
23951           p = consume_improper_spaces (p, body);
23952
23953           /* Consume the comma, if present.  */
23954           if (*p == ',')
23955             {
23956               p++;
23957
23958               p = consume_improper_spaces (p, body);
23959             }
23960         }
23961
23962       if (*p == ')')
23963         {
23964           p++;
23965
23966           if (*p == ' ')
23967             /* Perfectly formed definition, no complaints.  */
23968             macro_define_function (file, line, name,
23969                                    argc, (const char **) argv,
23970                                    p + 1);
23971           else if (*p == '\0')
23972             {
23973               /* Complain, but do define it.  */
23974               dwarf2_macro_malformed_definition_complaint (body);
23975               macro_define_function (file, line, name,
23976                                      argc, (const char **) argv,
23977                                      p);
23978             }
23979           else
23980             /* Just complain.  */
23981             dwarf2_macro_malformed_definition_complaint (body);
23982         }
23983       else
23984         /* Just complain.  */
23985         dwarf2_macro_malformed_definition_complaint (body);
23986
23987       xfree (name);
23988       {
23989         int i;
23990
23991         for (i = 0; i < argc; i++)
23992           xfree (argv[i]);
23993       }
23994       xfree (argv);
23995     }
23996   else
23997     dwarf2_macro_malformed_definition_complaint (body);
23998 }
23999
24000 /* Skip some bytes from BYTES according to the form given in FORM.
24001    Returns the new pointer.  */
24002
24003 static const gdb_byte *
24004 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24005                  enum dwarf_form form,
24006                  unsigned int offset_size,
24007                  struct dwarf2_section_info *section)
24008 {
24009   unsigned int bytes_read;
24010
24011   switch (form)
24012     {
24013     case DW_FORM_data1:
24014     case DW_FORM_flag:
24015       ++bytes;
24016       break;
24017
24018     case DW_FORM_data2:
24019       bytes += 2;
24020       break;
24021
24022     case DW_FORM_data4:
24023       bytes += 4;
24024       break;
24025
24026     case DW_FORM_data8:
24027       bytes += 8;
24028       break;
24029
24030     case DW_FORM_data16:
24031       bytes += 16;
24032       break;
24033
24034     case DW_FORM_string:
24035       read_direct_string (abfd, bytes, &bytes_read);
24036       bytes += bytes_read;
24037       break;
24038
24039     case DW_FORM_sec_offset:
24040     case DW_FORM_strp:
24041     case DW_FORM_GNU_strp_alt:
24042       bytes += offset_size;
24043       break;
24044
24045     case DW_FORM_block:
24046       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24047       bytes += bytes_read;
24048       break;
24049
24050     case DW_FORM_block1:
24051       bytes += 1 + read_1_byte (abfd, bytes);
24052       break;
24053     case DW_FORM_block2:
24054       bytes += 2 + read_2_bytes (abfd, bytes);
24055       break;
24056     case DW_FORM_block4:
24057       bytes += 4 + read_4_bytes (abfd, bytes);
24058       break;
24059
24060     case DW_FORM_sdata:
24061     case DW_FORM_udata:
24062     case DW_FORM_GNU_addr_index:
24063     case DW_FORM_GNU_str_index:
24064       bytes = gdb_skip_leb128 (bytes, buffer_end);
24065       if (bytes == NULL)
24066         {
24067           dwarf2_section_buffer_overflow_complaint (section);
24068           return NULL;
24069         }
24070       break;
24071
24072     case DW_FORM_implicit_const:
24073       break;
24074
24075     default:
24076       {
24077         complaint (&symfile_complaints,
24078                    _("invalid form 0x%x in `%s'"),
24079                    form, get_section_name (section));
24080         return NULL;
24081       }
24082     }
24083
24084   return bytes;
24085 }
24086
24087 /* A helper for dwarf_decode_macros that handles skipping an unknown
24088    opcode.  Returns an updated pointer to the macro data buffer; or,
24089    on error, issues a complaint and returns NULL.  */
24090
24091 static const gdb_byte *
24092 skip_unknown_opcode (unsigned int opcode,
24093                      const gdb_byte **opcode_definitions,
24094                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24095                      bfd *abfd,
24096                      unsigned int offset_size,
24097                      struct dwarf2_section_info *section)
24098 {
24099   unsigned int bytes_read, i;
24100   unsigned long arg;
24101   const gdb_byte *defn;
24102
24103   if (opcode_definitions[opcode] == NULL)
24104     {
24105       complaint (&symfile_complaints,
24106                  _("unrecognized DW_MACFINO opcode 0x%x"),
24107                  opcode);
24108       return NULL;
24109     }
24110
24111   defn = opcode_definitions[opcode];
24112   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24113   defn += bytes_read;
24114
24115   for (i = 0; i < arg; ++i)
24116     {
24117       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24118                                  (enum dwarf_form) defn[i], offset_size,
24119                                  section);
24120       if (mac_ptr == NULL)
24121         {
24122           /* skip_form_bytes already issued the complaint.  */
24123           return NULL;
24124         }
24125     }
24126
24127   return mac_ptr;
24128 }
24129
24130 /* A helper function which parses the header of a macro section.
24131    If the macro section is the extended (for now called "GNU") type,
24132    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24133    the header, or issues a complaint and returns NULL on error.  */
24134
24135 static const gdb_byte *
24136 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24137                           bfd *abfd,
24138                           const gdb_byte *mac_ptr,
24139                           unsigned int *offset_size,
24140                           int section_is_gnu)
24141 {
24142   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24143
24144   if (section_is_gnu)
24145     {
24146       unsigned int version, flags;
24147
24148       version = read_2_bytes (abfd, mac_ptr);
24149       if (version != 4 && version != 5)
24150         {
24151           complaint (&symfile_complaints,
24152                      _("unrecognized version `%d' in .debug_macro section"),
24153                      version);
24154           return NULL;
24155         }
24156       mac_ptr += 2;
24157
24158       flags = read_1_byte (abfd, mac_ptr);
24159       ++mac_ptr;
24160       *offset_size = (flags & 1) ? 8 : 4;
24161
24162       if ((flags & 2) != 0)
24163         /* We don't need the line table offset.  */
24164         mac_ptr += *offset_size;
24165
24166       /* Vendor opcode descriptions.  */
24167       if ((flags & 4) != 0)
24168         {
24169           unsigned int i, count;
24170
24171           count = read_1_byte (abfd, mac_ptr);
24172           ++mac_ptr;
24173           for (i = 0; i < count; ++i)
24174             {
24175               unsigned int opcode, bytes_read;
24176               unsigned long arg;
24177
24178               opcode = read_1_byte (abfd, mac_ptr);
24179               ++mac_ptr;
24180               opcode_definitions[opcode] = mac_ptr;
24181               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24182               mac_ptr += bytes_read;
24183               mac_ptr += arg;
24184             }
24185         }
24186     }
24187
24188   return mac_ptr;
24189 }
24190
24191 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24192    including DW_MACRO_import.  */
24193
24194 static void
24195 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24196                           bfd *abfd,
24197                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24198                           struct macro_source_file *current_file,
24199                           struct line_header *lh,
24200                           struct dwarf2_section_info *section,
24201                           int section_is_gnu, int section_is_dwz,
24202                           unsigned int offset_size,
24203                           htab_t include_hash)
24204 {
24205   struct objfile *objfile = dwarf2_per_objfile->objfile;
24206   enum dwarf_macro_record_type macinfo_type;
24207   int at_commandline;
24208   const gdb_byte *opcode_definitions[256];
24209
24210   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24211                                       &offset_size, section_is_gnu);
24212   if (mac_ptr == NULL)
24213     {
24214       /* We already issued a complaint.  */
24215       return;
24216     }
24217
24218   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24219      GDB is still reading the definitions from command line.  First
24220      DW_MACINFO_start_file will need to be ignored as it was already executed
24221      to create CURRENT_FILE for the main source holding also the command line
24222      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24223      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24224
24225   at_commandline = 1;
24226
24227   do
24228     {
24229       /* Do we at least have room for a macinfo type byte?  */
24230       if (mac_ptr >= mac_end)
24231         {
24232           dwarf2_section_buffer_overflow_complaint (section);
24233           break;
24234         }
24235
24236       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24237       mac_ptr++;
24238
24239       /* Note that we rely on the fact that the corresponding GNU and
24240          DWARF constants are the same.  */
24241       DIAGNOSTIC_PUSH
24242       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24243       switch (macinfo_type)
24244         {
24245           /* A zero macinfo type indicates the end of the macro
24246              information.  */
24247         case 0:
24248           break;
24249
24250         case DW_MACRO_define:
24251         case DW_MACRO_undef:
24252         case DW_MACRO_define_strp:
24253         case DW_MACRO_undef_strp:
24254         case DW_MACRO_define_sup:
24255         case DW_MACRO_undef_sup:
24256           {
24257             unsigned int bytes_read;
24258             int line;
24259             const char *body;
24260             int is_define;
24261
24262             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24263             mac_ptr += bytes_read;
24264
24265             if (macinfo_type == DW_MACRO_define
24266                 || macinfo_type == DW_MACRO_undef)
24267               {
24268                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24269                 mac_ptr += bytes_read;
24270               }
24271             else
24272               {
24273                 LONGEST str_offset;
24274
24275                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24276                 mac_ptr += offset_size;
24277
24278                 if (macinfo_type == DW_MACRO_define_sup
24279                     || macinfo_type == DW_MACRO_undef_sup
24280                     || section_is_dwz)
24281                   {
24282                     struct dwz_file *dwz
24283                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24284
24285                     body = read_indirect_string_from_dwz (objfile,
24286                                                           dwz, str_offset);
24287                   }
24288                 else
24289                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24290                                                          abfd, str_offset);
24291               }
24292
24293             is_define = (macinfo_type == DW_MACRO_define
24294                          || macinfo_type == DW_MACRO_define_strp
24295                          || macinfo_type == DW_MACRO_define_sup);
24296             if (! current_file)
24297               {
24298                 /* DWARF violation as no main source is present.  */
24299                 complaint (&symfile_complaints,
24300                            _("debug info with no main source gives macro %s "
24301                              "on line %d: %s"),
24302                            is_define ? _("definition") : _("undefinition"),
24303                            line, body);
24304                 break;
24305               }
24306             if ((line == 0 && !at_commandline)
24307                 || (line != 0 && at_commandline))
24308               complaint (&symfile_complaints,
24309                          _("debug info gives %s macro %s with %s line %d: %s"),
24310                          at_commandline ? _("command-line") : _("in-file"),
24311                          is_define ? _("definition") : _("undefinition"),
24312                          line == 0 ? _("zero") : _("non-zero"), line, body);
24313
24314             if (is_define)
24315               parse_macro_definition (current_file, line, body);
24316             else
24317               {
24318                 gdb_assert (macinfo_type == DW_MACRO_undef
24319                             || macinfo_type == DW_MACRO_undef_strp
24320                             || macinfo_type == DW_MACRO_undef_sup);
24321                 macro_undef (current_file, line, body);
24322               }
24323           }
24324           break;
24325
24326         case DW_MACRO_start_file:
24327           {
24328             unsigned int bytes_read;
24329             int line, file;
24330
24331             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24332             mac_ptr += bytes_read;
24333             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24334             mac_ptr += bytes_read;
24335
24336             if ((line == 0 && !at_commandline)
24337                 || (line != 0 && at_commandline))
24338               complaint (&symfile_complaints,
24339                          _("debug info gives source %d included "
24340                            "from %s at %s line %d"),
24341                          file, at_commandline ? _("command-line") : _("file"),
24342                          line == 0 ? _("zero") : _("non-zero"), line);
24343
24344             if (at_commandline)
24345               {
24346                 /* This DW_MACRO_start_file was executed in the
24347                    pass one.  */
24348                 at_commandline = 0;
24349               }
24350             else
24351               current_file = macro_start_file (file, line, current_file, lh);
24352           }
24353           break;
24354
24355         case DW_MACRO_end_file:
24356           if (! current_file)
24357             complaint (&symfile_complaints,
24358                        _("macro debug info has an unmatched "
24359                          "`close_file' directive"));
24360           else
24361             {
24362               current_file = current_file->included_by;
24363               if (! current_file)
24364                 {
24365                   enum dwarf_macro_record_type next_type;
24366
24367                   /* GCC circa March 2002 doesn't produce the zero
24368                      type byte marking the end of the compilation
24369                      unit.  Complain if it's not there, but exit no
24370                      matter what.  */
24371
24372                   /* Do we at least have room for a macinfo type byte?  */
24373                   if (mac_ptr >= mac_end)
24374                     {
24375                       dwarf2_section_buffer_overflow_complaint (section);
24376                       return;
24377                     }
24378
24379                   /* We don't increment mac_ptr here, so this is just
24380                      a look-ahead.  */
24381                   next_type
24382                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24383                                                                   mac_ptr);
24384                   if (next_type != 0)
24385                     complaint (&symfile_complaints,
24386                                _("no terminating 0-type entry for "
24387                                  "macros in `.debug_macinfo' section"));
24388
24389                   return;
24390                 }
24391             }
24392           break;
24393
24394         case DW_MACRO_import:
24395         case DW_MACRO_import_sup:
24396           {
24397             LONGEST offset;
24398             void **slot;
24399             bfd *include_bfd = abfd;
24400             struct dwarf2_section_info *include_section = section;
24401             const gdb_byte *include_mac_end = mac_end;
24402             int is_dwz = section_is_dwz;
24403             const gdb_byte *new_mac_ptr;
24404
24405             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24406             mac_ptr += offset_size;
24407
24408             if (macinfo_type == DW_MACRO_import_sup)
24409               {
24410                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24411
24412                 dwarf2_read_section (objfile, &dwz->macro);
24413
24414                 include_section = &dwz->macro;
24415                 include_bfd = get_section_bfd_owner (include_section);
24416                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24417                 is_dwz = 1;
24418               }
24419
24420             new_mac_ptr = include_section->buffer + offset;
24421             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24422
24423             if (*slot != NULL)
24424               {
24425                 /* This has actually happened; see
24426                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24427                 complaint (&symfile_complaints,
24428                            _("recursive DW_MACRO_import in "
24429                              ".debug_macro section"));
24430               }
24431             else
24432               {
24433                 *slot = (void *) new_mac_ptr;
24434
24435                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24436                                           include_bfd, new_mac_ptr,
24437                                           include_mac_end, current_file, lh,
24438                                           section, section_is_gnu, is_dwz,
24439                                           offset_size, include_hash);
24440
24441                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24442               }
24443           }
24444           break;
24445
24446         case DW_MACINFO_vendor_ext:
24447           if (!section_is_gnu)
24448             {
24449               unsigned int bytes_read;
24450
24451               /* This reads the constant, but since we don't recognize
24452                  any vendor extensions, we ignore it.  */
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               /* We don't recognize any vendor extensions.  */
24459               break;
24460             }
24461           /* FALLTHROUGH */
24462
24463         default:
24464           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24465                                          mac_ptr, mac_end, abfd, offset_size,
24466                                          section);
24467           if (mac_ptr == NULL)
24468             return;
24469           break;
24470         }
24471       DIAGNOSTIC_POP
24472     } while (macinfo_type != 0);
24473 }
24474
24475 static void
24476 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24477                      int section_is_gnu)
24478 {
24479   struct dwarf2_per_objfile *dwarf2_per_objfile
24480     = cu->per_cu->dwarf2_per_objfile;
24481   struct objfile *objfile = dwarf2_per_objfile->objfile;
24482   struct line_header *lh = cu->line_header;
24483   bfd *abfd;
24484   const gdb_byte *mac_ptr, *mac_end;
24485   struct macro_source_file *current_file = 0;
24486   enum dwarf_macro_record_type macinfo_type;
24487   unsigned int offset_size = cu->header.offset_size;
24488   const gdb_byte *opcode_definitions[256];
24489   void **slot;
24490   struct dwarf2_section_info *section;
24491   const char *section_name;
24492
24493   if (cu->dwo_unit != NULL)
24494     {
24495       if (section_is_gnu)
24496         {
24497           section = &cu->dwo_unit->dwo_file->sections.macro;
24498           section_name = ".debug_macro.dwo";
24499         }
24500       else
24501         {
24502           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24503           section_name = ".debug_macinfo.dwo";
24504         }
24505     }
24506   else
24507     {
24508       if (section_is_gnu)
24509         {
24510           section = &dwarf2_per_objfile->macro;
24511           section_name = ".debug_macro";
24512         }
24513       else
24514         {
24515           section = &dwarf2_per_objfile->macinfo;
24516           section_name = ".debug_macinfo";
24517         }
24518     }
24519
24520   dwarf2_read_section (objfile, section);
24521   if (section->buffer == NULL)
24522     {
24523       complaint (&symfile_complaints, _("missing %s section"), section_name);
24524       return;
24525     }
24526   abfd = get_section_bfd_owner (section);
24527
24528   /* First pass: Find the name of the base filename.
24529      This filename is needed in order to process all macros whose definition
24530      (or undefinition) comes from the command line.  These macros are defined
24531      before the first DW_MACINFO_start_file entry, and yet still need to be
24532      associated to the base file.
24533
24534      To determine the base file name, we scan the macro definitions until we
24535      reach the first DW_MACINFO_start_file entry.  We then initialize
24536      CURRENT_FILE accordingly so that any macro definition found before the
24537      first DW_MACINFO_start_file can still be associated to the base file.  */
24538
24539   mac_ptr = section->buffer + offset;
24540   mac_end = section->buffer + section->size;
24541
24542   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24543                                       &offset_size, section_is_gnu);
24544   if (mac_ptr == NULL)
24545     {
24546       /* We already issued a complaint.  */
24547       return;
24548     }
24549
24550   do
24551     {
24552       /* Do we at least have room for a macinfo type byte?  */
24553       if (mac_ptr >= mac_end)
24554         {
24555           /* Complaint is printed during the second pass as GDB will probably
24556              stop the first pass earlier upon finding
24557              DW_MACINFO_start_file.  */
24558           break;
24559         }
24560
24561       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24562       mac_ptr++;
24563
24564       /* Note that we rely on the fact that the corresponding GNU and
24565          DWARF constants are the same.  */
24566       DIAGNOSTIC_PUSH
24567       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24568       switch (macinfo_type)
24569         {
24570           /* A zero macinfo type indicates the end of the macro
24571              information.  */
24572         case 0:
24573           break;
24574
24575         case DW_MACRO_define:
24576         case DW_MACRO_undef:
24577           /* Only skip the data by MAC_PTR.  */
24578           {
24579             unsigned int bytes_read;
24580
24581             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24582             mac_ptr += bytes_read;
24583             read_direct_string (abfd, mac_ptr, &bytes_read);
24584             mac_ptr += bytes_read;
24585           }
24586           break;
24587
24588         case DW_MACRO_start_file:
24589           {
24590             unsigned int bytes_read;
24591             int line, file;
24592
24593             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24594             mac_ptr += bytes_read;
24595             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24596             mac_ptr += bytes_read;
24597
24598             current_file = macro_start_file (file, line, current_file, lh);
24599           }
24600           break;
24601
24602         case DW_MACRO_end_file:
24603           /* No data to skip by MAC_PTR.  */
24604           break;
24605
24606         case DW_MACRO_define_strp:
24607         case DW_MACRO_undef_strp:
24608         case DW_MACRO_define_sup:
24609         case DW_MACRO_undef_sup:
24610           {
24611             unsigned int bytes_read;
24612
24613             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24614             mac_ptr += bytes_read;
24615             mac_ptr += offset_size;
24616           }
24617           break;
24618
24619         case DW_MACRO_import:
24620         case DW_MACRO_import_sup:
24621           /* Note that, according to the spec, a transparent include
24622              chain cannot call DW_MACRO_start_file.  So, we can just
24623              skip this opcode.  */
24624           mac_ptr += offset_size;
24625           break;
24626
24627         case DW_MACINFO_vendor_ext:
24628           /* Only skip the data by MAC_PTR.  */
24629           if (!section_is_gnu)
24630             {
24631               unsigned int bytes_read;
24632
24633               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24634               mac_ptr += bytes_read;
24635               read_direct_string (abfd, mac_ptr, &bytes_read);
24636               mac_ptr += bytes_read;
24637             }
24638           /* FALLTHROUGH */
24639
24640         default:
24641           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24642                                          mac_ptr, mac_end, abfd, offset_size,
24643                                          section);
24644           if (mac_ptr == NULL)
24645             return;
24646           break;
24647         }
24648       DIAGNOSTIC_POP
24649     } while (macinfo_type != 0 && current_file == NULL);
24650
24651   /* Second pass: Process all entries.
24652
24653      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24654      command-line macro definitions/undefinitions.  This flag is unset when we
24655      reach the first DW_MACINFO_start_file entry.  */
24656
24657   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24658                                            htab_eq_pointer,
24659                                            NULL, xcalloc, xfree));
24660   mac_ptr = section->buffer + offset;
24661   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24662   *slot = (void *) mac_ptr;
24663   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24664                             abfd, mac_ptr, mac_end,
24665                             current_file, lh, section,
24666                             section_is_gnu, 0, offset_size,
24667                             include_hash.get ());
24668 }
24669
24670 /* Check if the attribute's form is a DW_FORM_block*
24671    if so return true else false.  */
24672
24673 static int
24674 attr_form_is_block (const struct attribute *attr)
24675 {
24676   return (attr == NULL ? 0 :
24677       attr->form == DW_FORM_block1
24678       || attr->form == DW_FORM_block2
24679       || attr->form == DW_FORM_block4
24680       || attr->form == DW_FORM_block
24681       || attr->form == DW_FORM_exprloc);
24682 }
24683
24684 /* Return non-zero if ATTR's value is a section offset --- classes
24685    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24686    You may use DW_UNSND (attr) to retrieve such offsets.
24687
24688    Section 7.5.4, "Attribute Encodings", explains that no attribute
24689    may have a value that belongs to more than one of these classes; it
24690    would be ambiguous if we did, because we use the same forms for all
24691    of them.  */
24692
24693 static int
24694 attr_form_is_section_offset (const struct attribute *attr)
24695 {
24696   return (attr->form == DW_FORM_data4
24697           || attr->form == DW_FORM_data8
24698           || attr->form == DW_FORM_sec_offset);
24699 }
24700
24701 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24702    zero otherwise.  When this function returns true, you can apply
24703    dwarf2_get_attr_constant_value to it.
24704
24705    However, note that for some attributes you must check
24706    attr_form_is_section_offset before using this test.  DW_FORM_data4
24707    and DW_FORM_data8 are members of both the constant class, and of
24708    the classes that contain offsets into other debug sections
24709    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24710    that, if an attribute's can be either a constant or one of the
24711    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24712    taken as section offsets, not constants.
24713
24714    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24715    cannot handle that.  */
24716
24717 static int
24718 attr_form_is_constant (const struct attribute *attr)
24719 {
24720   switch (attr->form)
24721     {
24722     case DW_FORM_sdata:
24723     case DW_FORM_udata:
24724     case DW_FORM_data1:
24725     case DW_FORM_data2:
24726     case DW_FORM_data4:
24727     case DW_FORM_data8:
24728     case DW_FORM_implicit_const:
24729       return 1;
24730     default:
24731       return 0;
24732     }
24733 }
24734
24735
24736 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24737    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24738
24739 static int
24740 attr_form_is_ref (const struct attribute *attr)
24741 {
24742   switch (attr->form)
24743     {
24744     case DW_FORM_ref_addr:
24745     case DW_FORM_ref1:
24746     case DW_FORM_ref2:
24747     case DW_FORM_ref4:
24748     case DW_FORM_ref8:
24749     case DW_FORM_ref_udata:
24750     case DW_FORM_GNU_ref_alt:
24751       return 1;
24752     default:
24753       return 0;
24754     }
24755 }
24756
24757 /* Return the .debug_loc section to use for CU.
24758    For DWO files use .debug_loc.dwo.  */
24759
24760 static struct dwarf2_section_info *
24761 cu_debug_loc_section (struct dwarf2_cu *cu)
24762 {
24763   struct dwarf2_per_objfile *dwarf2_per_objfile
24764     = cu->per_cu->dwarf2_per_objfile;
24765
24766   if (cu->dwo_unit)
24767     {
24768       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24769       
24770       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24771     }
24772   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24773                                   : &dwarf2_per_objfile->loc);
24774 }
24775
24776 /* A helper function that fills in a dwarf2_loclist_baton.  */
24777
24778 static void
24779 fill_in_loclist_baton (struct dwarf2_cu *cu,
24780                        struct dwarf2_loclist_baton *baton,
24781                        const struct attribute *attr)
24782 {
24783   struct dwarf2_per_objfile *dwarf2_per_objfile
24784     = cu->per_cu->dwarf2_per_objfile;
24785   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24786
24787   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24788
24789   baton->per_cu = cu->per_cu;
24790   gdb_assert (baton->per_cu);
24791   /* We don't know how long the location list is, but make sure we
24792      don't run off the edge of the section.  */
24793   baton->size = section->size - DW_UNSND (attr);
24794   baton->data = section->buffer + DW_UNSND (attr);
24795   baton->base_address = cu->base_address;
24796   baton->from_dwo = cu->dwo_unit != NULL;
24797 }
24798
24799 static void
24800 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24801                              struct dwarf2_cu *cu, int is_block)
24802 {
24803   struct dwarf2_per_objfile *dwarf2_per_objfile
24804     = cu->per_cu->dwarf2_per_objfile;
24805   struct objfile *objfile = dwarf2_per_objfile->objfile;
24806   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24807
24808   if (attr_form_is_section_offset (attr)
24809       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24810          the section.  If so, fall through to the complaint in the
24811          other branch.  */
24812       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24813     {
24814       struct dwarf2_loclist_baton *baton;
24815
24816       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24817
24818       fill_in_loclist_baton (cu, baton, attr);
24819
24820       if (cu->base_known == 0)
24821         complaint (&symfile_complaints,
24822                    _("Location list used without "
24823                      "specifying the CU base address."));
24824
24825       SYMBOL_ACLASS_INDEX (sym) = (is_block
24826                                    ? dwarf2_loclist_block_index
24827                                    : dwarf2_loclist_index);
24828       SYMBOL_LOCATION_BATON (sym) = baton;
24829     }
24830   else
24831     {
24832       struct dwarf2_locexpr_baton *baton;
24833
24834       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24835       baton->per_cu = cu->per_cu;
24836       gdb_assert (baton->per_cu);
24837
24838       if (attr_form_is_block (attr))
24839         {
24840           /* Note that we're just copying the block's data pointer
24841              here, not the actual data.  We're still pointing into the
24842              info_buffer for SYM's objfile; right now we never release
24843              that buffer, but when we do clean up properly this may
24844              need to change.  */
24845           baton->size = DW_BLOCK (attr)->size;
24846           baton->data = DW_BLOCK (attr)->data;
24847         }
24848       else
24849         {
24850           dwarf2_invalid_attrib_class_complaint ("location description",
24851                                                  SYMBOL_NATURAL_NAME (sym));
24852           baton->size = 0;
24853         }
24854
24855       SYMBOL_ACLASS_INDEX (sym) = (is_block
24856                                    ? dwarf2_locexpr_block_index
24857                                    : dwarf2_locexpr_index);
24858       SYMBOL_LOCATION_BATON (sym) = baton;
24859     }
24860 }
24861
24862 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24863    came from a separate debuginfo file, then the master objfile is
24864    returned.  */
24865
24866 struct objfile *
24867 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24868 {
24869   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24870
24871   /* Return the master objfile, so that we can report and look up the
24872      correct file containing this variable.  */
24873   if (objfile->separate_debug_objfile_backlink)
24874     objfile = objfile->separate_debug_objfile_backlink;
24875
24876   return objfile;
24877 }
24878
24879 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24880    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24881    CU_HEADERP first.  */
24882
24883 static const struct comp_unit_head *
24884 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24885                        struct dwarf2_per_cu_data *per_cu)
24886 {
24887   const gdb_byte *info_ptr;
24888
24889   if (per_cu->cu)
24890     return &per_cu->cu->header;
24891
24892   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24893
24894   memset (cu_headerp, 0, sizeof (*cu_headerp));
24895   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24896                        rcuh_kind::COMPILE);
24897
24898   return cu_headerp;
24899 }
24900
24901 /* Return the address size given in the compilation unit header for CU.  */
24902
24903 int
24904 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24905 {
24906   struct comp_unit_head cu_header_local;
24907   const struct comp_unit_head *cu_headerp;
24908
24909   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24910
24911   return cu_headerp->addr_size;
24912 }
24913
24914 /* Return the offset size given in the compilation unit header for CU.  */
24915
24916 int
24917 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24918 {
24919   struct comp_unit_head cu_header_local;
24920   const struct comp_unit_head *cu_headerp;
24921
24922   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24923
24924   return cu_headerp->offset_size;
24925 }
24926
24927 /* See its dwarf2loc.h declaration.  */
24928
24929 int
24930 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24931 {
24932   struct comp_unit_head cu_header_local;
24933   const struct comp_unit_head *cu_headerp;
24934
24935   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24936
24937   if (cu_headerp->version == 2)
24938     return cu_headerp->addr_size;
24939   else
24940     return cu_headerp->offset_size;
24941 }
24942
24943 /* Return the text offset of the CU.  The returned offset comes from
24944    this CU's objfile.  If this objfile came from a separate debuginfo
24945    file, then the offset may be different from the corresponding
24946    offset in the parent objfile.  */
24947
24948 CORE_ADDR
24949 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24950 {
24951   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24952
24953   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24954 }
24955
24956 /* Return DWARF version number of PER_CU.  */
24957
24958 short
24959 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24960 {
24961   return per_cu->dwarf_version;
24962 }
24963
24964 /* Locate the .debug_info compilation unit from CU's objfile which contains
24965    the DIE at OFFSET.  Raises an error on failure.  */
24966
24967 static struct dwarf2_per_cu_data *
24968 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24969                                   unsigned int offset_in_dwz,
24970                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24971 {
24972   struct dwarf2_per_cu_data *this_cu;
24973   int low, high;
24974   const sect_offset *cu_off;
24975
24976   low = 0;
24977   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24978   while (high > low)
24979     {
24980       struct dwarf2_per_cu_data *mid_cu;
24981       int mid = low + (high - low) / 2;
24982
24983       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24984       cu_off = &mid_cu->sect_off;
24985       if (mid_cu->is_dwz > offset_in_dwz
24986           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24987         high = mid;
24988       else
24989         low = mid + 1;
24990     }
24991   gdb_assert (low == high);
24992   this_cu = dwarf2_per_objfile->all_comp_units[low];
24993   cu_off = &this_cu->sect_off;
24994   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24995     {
24996       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24997         error (_("Dwarf Error: could not find partial DIE containing "
24998                "offset %s [in module %s]"),
24999                sect_offset_str (sect_off),
25000                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25001
25002       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25003                   <= sect_off);
25004       return dwarf2_per_objfile->all_comp_units[low-1];
25005     }
25006   else
25007     {
25008       this_cu = dwarf2_per_objfile->all_comp_units[low];
25009       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25010           && sect_off >= this_cu->sect_off + this_cu->length)
25011         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25012       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25013       return this_cu;
25014     }
25015 }
25016
25017 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25018
25019 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25020   : per_cu (per_cu_),
25021     mark (0),
25022     has_loclist (0),
25023     checked_producer (0),
25024     producer_is_gxx_lt_4_6 (0),
25025     producer_is_gcc_lt_4_3 (0),
25026     producer_is_icc_lt_14 (0),
25027     processing_has_namespace_info (0)
25028 {
25029   per_cu->cu = this;
25030 }
25031
25032 /* Destroy a dwarf2_cu.  */
25033
25034 dwarf2_cu::~dwarf2_cu ()
25035 {
25036   per_cu->cu = NULL;
25037 }
25038
25039 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25040
25041 static void
25042 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25043                        enum language pretend_language)
25044 {
25045   struct attribute *attr;
25046
25047   /* Set the language we're debugging.  */
25048   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25049   if (attr)
25050     set_cu_language (DW_UNSND (attr), cu);
25051   else
25052     {
25053       cu->language = pretend_language;
25054       cu->language_defn = language_def (cu->language);
25055     }
25056
25057   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25058 }
25059
25060 /* Increase the age counter on each cached compilation unit, and free
25061    any that are too old.  */
25062
25063 static void
25064 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25065 {
25066   struct dwarf2_per_cu_data *per_cu, **last_chain;
25067
25068   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25069   per_cu = dwarf2_per_objfile->read_in_chain;
25070   while (per_cu != NULL)
25071     {
25072       per_cu->cu->last_used ++;
25073       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25074         dwarf2_mark (per_cu->cu);
25075       per_cu = per_cu->cu->read_in_chain;
25076     }
25077
25078   per_cu = dwarf2_per_objfile->read_in_chain;
25079   last_chain = &dwarf2_per_objfile->read_in_chain;
25080   while (per_cu != NULL)
25081     {
25082       struct dwarf2_per_cu_data *next_cu;
25083
25084       next_cu = per_cu->cu->read_in_chain;
25085
25086       if (!per_cu->cu->mark)
25087         {
25088           delete per_cu->cu;
25089           *last_chain = next_cu;
25090         }
25091       else
25092         last_chain = &per_cu->cu->read_in_chain;
25093
25094       per_cu = next_cu;
25095     }
25096 }
25097
25098 /* Remove a single compilation unit from the cache.  */
25099
25100 static void
25101 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25102 {
25103   struct dwarf2_per_cu_data *per_cu, **last_chain;
25104   struct dwarf2_per_objfile *dwarf2_per_objfile
25105     = target_per_cu->dwarf2_per_objfile;
25106
25107   per_cu = dwarf2_per_objfile->read_in_chain;
25108   last_chain = &dwarf2_per_objfile->read_in_chain;
25109   while (per_cu != NULL)
25110     {
25111       struct dwarf2_per_cu_data *next_cu;
25112
25113       next_cu = per_cu->cu->read_in_chain;
25114
25115       if (per_cu == target_per_cu)
25116         {
25117           delete per_cu->cu;
25118           per_cu->cu = NULL;
25119           *last_chain = next_cu;
25120           break;
25121         }
25122       else
25123         last_chain = &per_cu->cu->read_in_chain;
25124
25125       per_cu = next_cu;
25126     }
25127 }
25128
25129 /* Release all extra memory associated with OBJFILE.  */
25130
25131 void
25132 dwarf2_free_objfile (struct objfile *objfile)
25133 {
25134   struct dwarf2_per_objfile *dwarf2_per_objfile
25135     = get_dwarf2_per_objfile (objfile);
25136
25137   delete dwarf2_per_objfile;
25138 }
25139
25140 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25141    We store these in a hash table separate from the DIEs, and preserve them
25142    when the DIEs are flushed out of cache.
25143
25144    The CU "per_cu" pointer is needed because offset alone is not enough to
25145    uniquely identify the type.  A file may have multiple .debug_types sections,
25146    or the type may come from a DWO file.  Furthermore, while it's more logical
25147    to use per_cu->section+offset, with Fission the section with the data is in
25148    the DWO file but we don't know that section at the point we need it.
25149    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25150    because we can enter the lookup routine, get_die_type_at_offset, from
25151    outside this file, and thus won't necessarily have PER_CU->cu.
25152    Fortunately, PER_CU is stable for the life of the objfile.  */
25153
25154 struct dwarf2_per_cu_offset_and_type
25155 {
25156   const struct dwarf2_per_cu_data *per_cu;
25157   sect_offset sect_off;
25158   struct type *type;
25159 };
25160
25161 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25162
25163 static hashval_t
25164 per_cu_offset_and_type_hash (const void *item)
25165 {
25166   const struct dwarf2_per_cu_offset_and_type *ofs
25167     = (const struct dwarf2_per_cu_offset_and_type *) item;
25168
25169   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25170 }
25171
25172 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25173
25174 static int
25175 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25176 {
25177   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25178     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25179   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25180     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25181
25182   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25183           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25184 }
25185
25186 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25187    table if necessary.  For convenience, return TYPE.
25188
25189    The DIEs reading must have careful ordering to:
25190     * Not cause infite loops trying to read in DIEs as a prerequisite for
25191       reading current DIE.
25192     * Not trying to dereference contents of still incompletely read in types
25193       while reading in other DIEs.
25194     * Enable referencing still incompletely read in types just by a pointer to
25195       the type without accessing its fields.
25196
25197    Therefore caller should follow these rules:
25198      * Try to fetch any prerequisite types we may need to build this DIE type
25199        before building the type and calling set_die_type.
25200      * After building type call set_die_type for current DIE as soon as
25201        possible before fetching more types to complete the current type.
25202      * Make the type as complete as possible before fetching more types.  */
25203
25204 static struct type *
25205 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25206 {
25207   struct dwarf2_per_objfile *dwarf2_per_objfile
25208     = cu->per_cu->dwarf2_per_objfile;
25209   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25210   struct objfile *objfile = dwarf2_per_objfile->objfile;
25211   struct attribute *attr;
25212   struct dynamic_prop prop;
25213
25214   /* For Ada types, make sure that the gnat-specific data is always
25215      initialized (if not already set).  There are a few types where
25216      we should not be doing so, because the type-specific area is
25217      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25218      where the type-specific area is used to store the floatformat).
25219      But this is not a problem, because the gnat-specific information
25220      is actually not needed for these types.  */
25221   if (need_gnat_info (cu)
25222       && TYPE_CODE (type) != TYPE_CODE_FUNC
25223       && TYPE_CODE (type) != TYPE_CODE_FLT
25224       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25225       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25226       && TYPE_CODE (type) != TYPE_CODE_METHOD
25227       && !HAVE_GNAT_AUX_INFO (type))
25228     INIT_GNAT_SPECIFIC (type);
25229
25230   /* Read DW_AT_allocated and set in type.  */
25231   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25232   if (attr_form_is_block (attr))
25233     {
25234       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25235         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25236     }
25237   else if (attr != NULL)
25238     {
25239       complaint (&symfile_complaints,
25240                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25241                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25242                  sect_offset_str (die->sect_off));
25243     }
25244
25245   /* Read DW_AT_associated and set in type.  */
25246   attr = dwarf2_attr (die, DW_AT_associated, cu);
25247   if (attr_form_is_block (attr))
25248     {
25249       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25250         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25251     }
25252   else if (attr != NULL)
25253     {
25254       complaint (&symfile_complaints,
25255                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25256                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25257                  sect_offset_str (die->sect_off));
25258     }
25259
25260   /* Read DW_AT_data_location and set in type.  */
25261   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25262   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25263     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25264
25265   if (dwarf2_per_objfile->die_type_hash == NULL)
25266     {
25267       dwarf2_per_objfile->die_type_hash =
25268         htab_create_alloc_ex (127,
25269                               per_cu_offset_and_type_hash,
25270                               per_cu_offset_and_type_eq,
25271                               NULL,
25272                               &objfile->objfile_obstack,
25273                               hashtab_obstack_allocate,
25274                               dummy_obstack_deallocate);
25275     }
25276
25277   ofs.per_cu = cu->per_cu;
25278   ofs.sect_off = die->sect_off;
25279   ofs.type = type;
25280   slot = (struct dwarf2_per_cu_offset_and_type **)
25281     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25282   if (*slot)
25283     complaint (&symfile_complaints,
25284                _("A problem internal to GDB: DIE %s has type already set"),
25285                sect_offset_str (die->sect_off));
25286   *slot = XOBNEW (&objfile->objfile_obstack,
25287                   struct dwarf2_per_cu_offset_and_type);
25288   **slot = ofs;
25289   return type;
25290 }
25291
25292 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25293    or return NULL if the die does not have a saved type.  */
25294
25295 static struct type *
25296 get_die_type_at_offset (sect_offset sect_off,
25297                         struct dwarf2_per_cu_data *per_cu)
25298 {
25299   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25300   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25301
25302   if (dwarf2_per_objfile->die_type_hash == NULL)
25303     return NULL;
25304
25305   ofs.per_cu = per_cu;
25306   ofs.sect_off = sect_off;
25307   slot = ((struct dwarf2_per_cu_offset_and_type *)
25308           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25309   if (slot)
25310     return slot->type;
25311   else
25312     return NULL;
25313 }
25314
25315 /* Look up the type for DIE in CU in die_type_hash,
25316    or return NULL if DIE does not have a saved type.  */
25317
25318 static struct type *
25319 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25320 {
25321   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25322 }
25323
25324 /* Add a dependence relationship from CU to REF_PER_CU.  */
25325
25326 static void
25327 dwarf2_add_dependence (struct dwarf2_cu *cu,
25328                        struct dwarf2_per_cu_data *ref_per_cu)
25329 {
25330   void **slot;
25331
25332   if (cu->dependencies == NULL)
25333     cu->dependencies
25334       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25335                               NULL, &cu->comp_unit_obstack,
25336                               hashtab_obstack_allocate,
25337                               dummy_obstack_deallocate);
25338
25339   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25340   if (*slot == NULL)
25341     *slot = ref_per_cu;
25342 }
25343
25344 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25345    Set the mark field in every compilation unit in the
25346    cache that we must keep because we are keeping CU.  */
25347
25348 static int
25349 dwarf2_mark_helper (void **slot, void *data)
25350 {
25351   struct dwarf2_per_cu_data *per_cu;
25352
25353   per_cu = (struct dwarf2_per_cu_data *) *slot;
25354
25355   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25356      reading of the chain.  As such dependencies remain valid it is not much
25357      useful to track and undo them during QUIT cleanups.  */
25358   if (per_cu->cu == NULL)
25359     return 1;
25360
25361   if (per_cu->cu->mark)
25362     return 1;
25363   per_cu->cu->mark = 1;
25364
25365   if (per_cu->cu->dependencies != NULL)
25366     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25367
25368   return 1;
25369 }
25370
25371 /* Set the mark field in CU and in every other compilation unit in the
25372    cache that we must keep because we are keeping CU.  */
25373
25374 static void
25375 dwarf2_mark (struct dwarf2_cu *cu)
25376 {
25377   if (cu->mark)
25378     return;
25379   cu->mark = 1;
25380   if (cu->dependencies != NULL)
25381     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25382 }
25383
25384 static void
25385 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25386 {
25387   while (per_cu)
25388     {
25389       per_cu->cu->mark = 0;
25390       per_cu = per_cu->cu->read_in_chain;
25391     }
25392 }
25393
25394 /* Trivial hash function for partial_die_info: the hash value of a DIE
25395    is its offset in .debug_info for this objfile.  */
25396
25397 static hashval_t
25398 partial_die_hash (const void *item)
25399 {
25400   const struct partial_die_info *part_die
25401     = (const struct partial_die_info *) item;
25402
25403   return to_underlying (part_die->sect_off);
25404 }
25405
25406 /* Trivial comparison function for partial_die_info structures: two DIEs
25407    are equal if they have the same offset.  */
25408
25409 static int
25410 partial_die_eq (const void *item_lhs, const void *item_rhs)
25411 {
25412   const struct partial_die_info *part_die_lhs
25413     = (const struct partial_die_info *) item_lhs;
25414   const struct partial_die_info *part_die_rhs
25415     = (const struct partial_die_info *) item_rhs;
25416
25417   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25418 }
25419
25420 static struct cmd_list_element *set_dwarf_cmdlist;
25421 static struct cmd_list_element *show_dwarf_cmdlist;
25422
25423 static void
25424 set_dwarf_cmd (const char *args, int from_tty)
25425 {
25426   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25427              gdb_stdout);
25428 }
25429
25430 static void
25431 show_dwarf_cmd (const char *args, int from_tty)
25432 {
25433   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25434 }
25435
25436 int dwarf_always_disassemble;
25437
25438 static void
25439 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25440                                struct cmd_list_element *c, const char *value)
25441 {
25442   fprintf_filtered (file,
25443                     _("Whether to always disassemble "
25444                       "DWARF expressions is %s.\n"),
25445                     value);
25446 }
25447
25448 static void
25449 show_check_physname (struct ui_file *file, int from_tty,
25450                      struct cmd_list_element *c, const char *value)
25451 {
25452   fprintf_filtered (file,
25453                     _("Whether to check \"physname\" is %s.\n"),
25454                     value);
25455 }
25456
25457 void
25458 _initialize_dwarf2_read (void)
25459 {
25460
25461   dwarf2_objfile_data_key = register_objfile_data ();
25462
25463   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25464 Set DWARF specific variables.\n\
25465 Configure DWARF variables such as the cache size"),
25466                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25467                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25468
25469   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25470 Show DWARF specific variables\n\
25471 Show DWARF variables such as the cache size"),
25472                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25473                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25474
25475   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25476                             &dwarf_max_cache_age, _("\
25477 Set the upper bound on the age of cached DWARF compilation units."), _("\
25478 Show the upper bound on the age of cached DWARF compilation units."), _("\
25479 A higher limit means that cached compilation units will be stored\n\
25480 in memory longer, and more total memory will be used.  Zero disables\n\
25481 caching, which can slow down startup."),
25482                             NULL,
25483                             show_dwarf_max_cache_age,
25484                             &set_dwarf_cmdlist,
25485                             &show_dwarf_cmdlist);
25486
25487   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25488                            &dwarf_always_disassemble, _("\
25489 Set whether `info address' always disassembles DWARF expressions."), _("\
25490 Show whether `info address' always disassembles DWARF expressions."), _("\
25491 When enabled, DWARF expressions are always printed in an assembly-like\n\
25492 syntax.  When disabled, expressions will be printed in a more\n\
25493 conversational style, when possible."),
25494                            NULL,
25495                            show_dwarf_always_disassemble,
25496                            &set_dwarf_cmdlist,
25497                            &show_dwarf_cmdlist);
25498
25499   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25500 Set debugging of the DWARF reader."), _("\
25501 Show debugging of the DWARF reader."), _("\
25502 When enabled (non-zero), debugging messages are printed during DWARF\n\
25503 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25504 information.  A value greater than 1 provides more verbose information."),
25505                             NULL,
25506                             NULL,
25507                             &setdebuglist, &showdebuglist);
25508
25509   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25510 Set debugging of the DWARF DIE reader."), _("\
25511 Show debugging of the DWARF DIE reader."), _("\
25512 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25513 The value is the maximum depth to print."),
25514                              NULL,
25515                              NULL,
25516                              &setdebuglist, &showdebuglist);
25517
25518   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25519 Set debugging of the dwarf line reader."), _("\
25520 Show debugging of the dwarf line reader."), _("\
25521 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25522 A value of 1 (one) provides basic information.\n\
25523 A value greater than 1 provides more verbose information."),
25524                              NULL,
25525                              NULL,
25526                              &setdebuglist, &showdebuglist);
25527
25528   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25529 Set cross-checking of \"physname\" code against demangler."), _("\
25530 Show cross-checking of \"physname\" code against demangler."), _("\
25531 When enabled, GDB's internal \"physname\" code is checked against\n\
25532 the demangler."),
25533                            NULL, show_check_physname,
25534                            &setdebuglist, &showdebuglist);
25535
25536   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25537                            no_class, &use_deprecated_index_sections, _("\
25538 Set whether to use deprecated gdb_index sections."), _("\
25539 Show whether to use deprecated gdb_index sections."), _("\
25540 When enabled, deprecated .gdb_index sections are used anyway.\n\
25541 Normally they are ignored either because of a missing feature or\n\
25542 performance issue.\n\
25543 Warning: This option must be enabled before gdb reads the file."),
25544                            NULL,
25545                            NULL,
25546                            &setlist, &showlist);
25547
25548   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25549                                                         &dwarf2_locexpr_funcs);
25550   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25551                                                         &dwarf2_loclist_funcs);
25552
25553   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25554                                         &dwarf2_block_frame_base_locexpr_funcs);
25555   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25556                                         &dwarf2_block_frame_base_loclist_funcs);
25557
25558 #if GDB_SELF_TEST
25559   selftests::register_test ("dw2_expand_symtabs_matching",
25560                             selftests::dw2_expand_symtabs_matching::run_test);
25561 #endif
25562 }