set varsize-limit: New GDB setting for maximum dynamic object size
[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 free_cached_comp_units (void *);
1825
1826 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1827
1828 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1829
1830 static struct type *set_die_type (struct die_info *, struct type *,
1831                                   struct dwarf2_cu *);
1832
1833 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1834
1835 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1836
1837 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1838                                  enum language);
1839
1840 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1841                                     enum language);
1842
1843 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1844                                     enum language);
1845
1846 static void dwarf2_add_dependence (struct dwarf2_cu *,
1847                                    struct dwarf2_per_cu_data *);
1848
1849 static void dwarf2_mark (struct dwarf2_cu *);
1850
1851 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1852
1853 static struct type *get_die_type_at_offset (sect_offset,
1854                                             struct dwarf2_per_cu_data *);
1855
1856 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1857
1858 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1859                              enum language pretend_language);
1860
1861 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1862
1863 /* Class, the destructor of which frees all allocated queue entries.  This
1864    will only have work to do if an error was thrown while processing the
1865    dwarf.  If no error was thrown then the queue entries should have all
1866    been processed, and freed, as we went along.  */
1867
1868 class dwarf2_queue_guard
1869 {
1870 public:
1871   dwarf2_queue_guard () = default;
1872
1873   /* Free any entries remaining on the queue.  There should only be
1874      entries left if we hit an error while processing the dwarf.  */
1875   ~dwarf2_queue_guard ()
1876   {
1877     struct dwarf2_queue_item *item, *last;
1878
1879     item = dwarf2_queue;
1880     while (item)
1881       {
1882         /* Anything still marked queued is likely to be in an
1883            inconsistent state, so discard it.  */
1884         if (item->per_cu->queued)
1885           {
1886             if (item->per_cu->cu != NULL)
1887               free_one_cached_comp_unit (item->per_cu);
1888             item->per_cu->queued = 0;
1889           }
1890
1891         last = item;
1892         item = item->next;
1893         xfree (last);
1894       }
1895
1896     dwarf2_queue = dwarf2_queue_tail = NULL;
1897   }
1898 };
1899
1900 /* The return type of find_file_and_directory.  Note, the enclosed
1901    string pointers are only valid while this object is valid.  */
1902
1903 struct file_and_directory
1904 {
1905   /* The filename.  This is never NULL.  */
1906   const char *name;
1907
1908   /* The compilation directory.  NULL if not known.  If we needed to
1909      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1910      points directly to the DW_AT_comp_dir string attribute owned by
1911      the obstack that owns the DIE.  */
1912   const char *comp_dir;
1913
1914   /* If we needed to build a new string for comp_dir, this is what
1915      owns the storage.  */
1916   std::string comp_dir_storage;
1917 };
1918
1919 static file_and_directory find_file_and_directory (struct die_info *die,
1920                                                    struct dwarf2_cu *cu);
1921
1922 static char *file_full_name (int file, struct line_header *lh,
1923                              const char *comp_dir);
1924
1925 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1926 enum class rcuh_kind { COMPILE, TYPE };
1927
1928 static const gdb_byte *read_and_check_comp_unit_head
1929   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1930    struct comp_unit_head *header,
1931    struct dwarf2_section_info *section,
1932    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1933    rcuh_kind section_kind);
1934
1935 static void init_cutu_and_read_dies
1936   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1937    int use_existing_cu, int keep,
1938    die_reader_func_ftype *die_reader_func, void *data);
1939
1940 static void init_cutu_and_read_dies_simple
1941   (struct dwarf2_per_cu_data *this_cu,
1942    die_reader_func_ftype *die_reader_func, void *data);
1943
1944 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1945
1946 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1947
1948 static struct dwo_unit *lookup_dwo_unit_in_dwp
1949   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1950    struct dwp_file *dwp_file, const char *comp_dir,
1951    ULONGEST signature, int is_debug_types);
1952
1953 static struct dwp_file *get_dwp_file
1954   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1955
1956 static struct dwo_unit *lookup_dwo_comp_unit
1957   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1958
1959 static struct dwo_unit *lookup_dwo_type_unit
1960   (struct signatured_type *, const char *, const char *);
1961
1962 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1963
1964 static void free_dwo_file_cleanup (void *);
1965
1966 struct free_dwo_file_cleanup_data
1967 {
1968   struct dwo_file *dwo_file;
1969   struct dwarf2_per_objfile *dwarf2_per_objfile;
1970 };
1971
1972 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1973
1974 static void check_producer (struct dwarf2_cu *cu);
1975
1976 static void free_line_header_voidp (void *arg);
1977 \f
1978 /* Various complaints about symbol reading that don't abort the process.  */
1979
1980 static void
1981 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1982 {
1983   complaint (&symfile_complaints,
1984              _("statement list doesn't fit in .debug_line section"));
1985 }
1986
1987 static void
1988 dwarf2_debug_line_missing_file_complaint (void)
1989 {
1990   complaint (&symfile_complaints,
1991              _(".debug_line section has line data without a file"));
1992 }
1993
1994 static void
1995 dwarf2_debug_line_missing_end_sequence_complaint (void)
1996 {
1997   complaint (&symfile_complaints,
1998              _(".debug_line section has line "
1999                "program sequence without an end"));
2000 }
2001
2002 static void
2003 dwarf2_complex_location_expr_complaint (void)
2004 {
2005   complaint (&symfile_complaints, _("location expression too complex"));
2006 }
2007
2008 static void
2009 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2010                                               int arg3)
2011 {
2012   complaint (&symfile_complaints,
2013              _("const value length mismatch for '%s', got %d, expected %d"),
2014              arg1, arg2, arg3);
2015 }
2016
2017 static void
2018 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2019 {
2020   complaint (&symfile_complaints,
2021              _("debug info runs off end of %s section"
2022                " [in module %s]"),
2023              get_section_name (section),
2024              get_section_file_name (section));
2025 }
2026
2027 static void
2028 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2029 {
2030   complaint (&symfile_complaints,
2031              _("macro debug info contains a "
2032                "malformed macro definition:\n`%s'"),
2033              arg1);
2034 }
2035
2036 static void
2037 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2038 {
2039   complaint (&symfile_complaints,
2040              _("invalid attribute class or form for '%s' in '%s'"),
2041              arg1, arg2);
2042 }
2043
2044 /* Hash function for line_header_hash.  */
2045
2046 static hashval_t
2047 line_header_hash (const struct line_header *ofs)
2048 {
2049   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2050 }
2051
2052 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2053
2054 static hashval_t
2055 line_header_hash_voidp (const void *item)
2056 {
2057   const struct line_header *ofs = (const struct line_header *) item;
2058
2059   return line_header_hash (ofs);
2060 }
2061
2062 /* Equality function for line_header_hash.  */
2063
2064 static int
2065 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2066 {
2067   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2068   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2069
2070   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2071           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2072 }
2073
2074 \f
2075
2076 /* Read the given attribute value as an address, taking the attribute's
2077    form into account.  */
2078
2079 static CORE_ADDR
2080 attr_value_as_address (struct attribute *attr)
2081 {
2082   CORE_ADDR addr;
2083
2084   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2085     {
2086       /* Aside from a few clearly defined exceptions, attributes that
2087          contain an address must always be in DW_FORM_addr form.
2088          Unfortunately, some compilers happen to be violating this
2089          requirement by encoding addresses using other forms, such
2090          as DW_FORM_data4 for example.  For those broken compilers,
2091          we try to do our best, without any guarantee of success,
2092          to interpret the address correctly.  It would also be nice
2093          to generate a complaint, but that would require us to maintain
2094          a list of legitimate cases where a non-address form is allowed,
2095          as well as update callers to pass in at least the CU's DWARF
2096          version.  This is more overhead than what we're willing to
2097          expand for a pretty rare case.  */
2098       addr = DW_UNSND (attr);
2099     }
2100   else
2101     addr = DW_ADDR (attr);
2102
2103   return addr;
2104 }
2105
2106 /* See declaration.  */
2107
2108 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2109                                         const dwarf2_debug_sections *names)
2110   : objfile (objfile_)
2111 {
2112   if (names == NULL)
2113     names = &dwarf2_elf_names;
2114
2115   bfd *obfd = objfile->obfd;
2116
2117   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2118     locate_sections (obfd, sec, *names);
2119 }
2120
2121 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2122
2123 dwarf2_per_objfile::~dwarf2_per_objfile ()
2124 {
2125   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2126   free_cached_comp_units ();
2127
2128   if (quick_file_names_table)
2129     htab_delete (quick_file_names_table);
2130
2131   if (line_header_hash)
2132     htab_delete (line_header_hash);
2133
2134   for (int ix = 0; ix < n_comp_units; ++ix)
2135    VEC_free (dwarf2_per_cu_ptr, all_comp_units[ix]->imported_symtabs);
2136
2137   for (int ix = 0; ix < n_type_units; ++ix)
2138     VEC_free (dwarf2_per_cu_ptr,
2139               all_type_units[ix]->per_cu.imported_symtabs);
2140   xfree (all_type_units);
2141
2142   VEC_free (dwarf2_section_info_def, types);
2143
2144   if (dwo_files != NULL)
2145     free_dwo_files (dwo_files, objfile);
2146   if (dwp_file != NULL)
2147     gdb_bfd_unref (dwp_file->dbfd);
2148
2149   if (dwz_file != NULL && dwz_file->dwz_bfd)
2150     gdb_bfd_unref (dwz_file->dwz_bfd);
2151
2152   if (index_table != NULL)
2153     index_table->~mapped_index ();
2154
2155   /* Everything else should be on the objfile obstack.  */
2156 }
2157
2158 /* See declaration.  */
2159
2160 void
2161 dwarf2_per_objfile::free_cached_comp_units ()
2162 {
2163   dwarf2_per_cu_data *per_cu = read_in_chain;
2164   dwarf2_per_cu_data **last_chain = &read_in_chain;
2165   while (per_cu != NULL)
2166     {
2167       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2168
2169       delete per_cu->cu;
2170       *last_chain = next_cu;
2171       per_cu = next_cu;
2172     }
2173 }
2174
2175 /* Try to locate the sections we need for DWARF 2 debugging
2176    information and return true if we have enough to do something.
2177    NAMES points to the dwarf2 section names, or is NULL if the standard
2178    ELF names are used.  */
2179
2180 int
2181 dwarf2_has_info (struct objfile *objfile,
2182                  const struct dwarf2_debug_sections *names)
2183 {
2184   if (objfile->flags & OBJF_READNEVER)
2185     return 0;
2186
2187   struct dwarf2_per_objfile *dwarf2_per_objfile
2188     = get_dwarf2_per_objfile (objfile);
2189
2190   if (dwarf2_per_objfile == NULL)
2191     {
2192       /* Initialize per-objfile state.  */
2193       dwarf2_per_objfile
2194         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2195                                                                      names);
2196       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2197     }
2198   return (!dwarf2_per_objfile->info.is_virtual
2199           && dwarf2_per_objfile->info.s.section != NULL
2200           && !dwarf2_per_objfile->abbrev.is_virtual
2201           && dwarf2_per_objfile->abbrev.s.section != NULL);
2202 }
2203
2204 /* Return the containing section of virtual section SECTION.  */
2205
2206 static struct dwarf2_section_info *
2207 get_containing_section (const struct dwarf2_section_info *section)
2208 {
2209   gdb_assert (section->is_virtual);
2210   return section->s.containing_section;
2211 }
2212
2213 /* Return the bfd owner of SECTION.  */
2214
2215 static struct bfd *
2216 get_section_bfd_owner (const struct dwarf2_section_info *section)
2217 {
2218   if (section->is_virtual)
2219     {
2220       section = get_containing_section (section);
2221       gdb_assert (!section->is_virtual);
2222     }
2223   return section->s.section->owner;
2224 }
2225
2226 /* Return the bfd section of SECTION.
2227    Returns NULL if the section is not present.  */
2228
2229 static asection *
2230 get_section_bfd_section (const struct dwarf2_section_info *section)
2231 {
2232   if (section->is_virtual)
2233     {
2234       section = get_containing_section (section);
2235       gdb_assert (!section->is_virtual);
2236     }
2237   return section->s.section;
2238 }
2239
2240 /* Return the name of SECTION.  */
2241
2242 static const char *
2243 get_section_name (const struct dwarf2_section_info *section)
2244 {
2245   asection *sectp = get_section_bfd_section (section);
2246
2247   gdb_assert (sectp != NULL);
2248   return bfd_section_name (get_section_bfd_owner (section), sectp);
2249 }
2250
2251 /* Return the name of the file SECTION is in.  */
2252
2253 static const char *
2254 get_section_file_name (const struct dwarf2_section_info *section)
2255 {
2256   bfd *abfd = get_section_bfd_owner (section);
2257
2258   return bfd_get_filename (abfd);
2259 }
2260
2261 /* Return the id of SECTION.
2262    Returns 0 if SECTION doesn't exist.  */
2263
2264 static int
2265 get_section_id (const struct dwarf2_section_info *section)
2266 {
2267   asection *sectp = get_section_bfd_section (section);
2268
2269   if (sectp == NULL)
2270     return 0;
2271   return sectp->id;
2272 }
2273
2274 /* Return the flags of SECTION.
2275    SECTION (or containing section if this is a virtual section) must exist.  */
2276
2277 static int
2278 get_section_flags (const struct dwarf2_section_info *section)
2279 {
2280   asection *sectp = get_section_bfd_section (section);
2281
2282   gdb_assert (sectp != NULL);
2283   return bfd_get_section_flags (sectp->owner, sectp);
2284 }
2285
2286 /* When loading sections, we look either for uncompressed section or for
2287    compressed section names.  */
2288
2289 static int
2290 section_is_p (const char *section_name,
2291               const struct dwarf2_section_names *names)
2292 {
2293   if (names->normal != NULL
2294       && strcmp (section_name, names->normal) == 0)
2295     return 1;
2296   if (names->compressed != NULL
2297       && strcmp (section_name, names->compressed) == 0)
2298     return 1;
2299   return 0;
2300 }
2301
2302 /* See declaration.  */
2303
2304 void
2305 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2306                                      const dwarf2_debug_sections &names)
2307 {
2308   flagword aflag = bfd_get_section_flags (abfd, sectp);
2309
2310   if ((aflag & SEC_HAS_CONTENTS) == 0)
2311     {
2312     }
2313   else if (section_is_p (sectp->name, &names.info))
2314     {
2315       this->info.s.section = sectp;
2316       this->info.size = bfd_get_section_size (sectp);
2317     }
2318   else if (section_is_p (sectp->name, &names.abbrev))
2319     {
2320       this->abbrev.s.section = sectp;
2321       this->abbrev.size = bfd_get_section_size (sectp);
2322     }
2323   else if (section_is_p (sectp->name, &names.line))
2324     {
2325       this->line.s.section = sectp;
2326       this->line.size = bfd_get_section_size (sectp);
2327     }
2328   else if (section_is_p (sectp->name, &names.loc))
2329     {
2330       this->loc.s.section = sectp;
2331       this->loc.size = bfd_get_section_size (sectp);
2332     }
2333   else if (section_is_p (sectp->name, &names.loclists))
2334     {
2335       this->loclists.s.section = sectp;
2336       this->loclists.size = bfd_get_section_size (sectp);
2337     }
2338   else if (section_is_p (sectp->name, &names.macinfo))
2339     {
2340       this->macinfo.s.section = sectp;
2341       this->macinfo.size = bfd_get_section_size (sectp);
2342     }
2343   else if (section_is_p (sectp->name, &names.macro))
2344     {
2345       this->macro.s.section = sectp;
2346       this->macro.size = bfd_get_section_size (sectp);
2347     }
2348   else if (section_is_p (sectp->name, &names.str))
2349     {
2350       this->str.s.section = sectp;
2351       this->str.size = bfd_get_section_size (sectp);
2352     }
2353   else if (section_is_p (sectp->name, &names.line_str))
2354     {
2355       this->line_str.s.section = sectp;
2356       this->line_str.size = bfd_get_section_size (sectp);
2357     }
2358   else if (section_is_p (sectp->name, &names.addr))
2359     {
2360       this->addr.s.section = sectp;
2361       this->addr.size = bfd_get_section_size (sectp);
2362     }
2363   else if (section_is_p (sectp->name, &names.frame))
2364     {
2365       this->frame.s.section = sectp;
2366       this->frame.size = bfd_get_section_size (sectp);
2367     }
2368   else if (section_is_p (sectp->name, &names.eh_frame))
2369     {
2370       this->eh_frame.s.section = sectp;
2371       this->eh_frame.size = bfd_get_section_size (sectp);
2372     }
2373   else if (section_is_p (sectp->name, &names.ranges))
2374     {
2375       this->ranges.s.section = sectp;
2376       this->ranges.size = bfd_get_section_size (sectp);
2377     }
2378   else if (section_is_p (sectp->name, &names.rnglists))
2379     {
2380       this->rnglists.s.section = sectp;
2381       this->rnglists.size = bfd_get_section_size (sectp);
2382     }
2383   else if (section_is_p (sectp->name, &names.types))
2384     {
2385       struct dwarf2_section_info type_section;
2386
2387       memset (&type_section, 0, sizeof (type_section));
2388       type_section.s.section = sectp;
2389       type_section.size = bfd_get_section_size (sectp);
2390
2391       VEC_safe_push (dwarf2_section_info_def, this->types,
2392                      &type_section);
2393     }
2394   else if (section_is_p (sectp->name, &names.gdb_index))
2395     {
2396       this->gdb_index.s.section = sectp;
2397       this->gdb_index.size = bfd_get_section_size (sectp);
2398     }
2399   else if (section_is_p (sectp->name, &names.debug_names))
2400     {
2401       this->debug_names.s.section = sectp;
2402       this->debug_names.size = bfd_get_section_size (sectp);
2403     }
2404   else if (section_is_p (sectp->name, &names.debug_aranges))
2405     {
2406       this->debug_aranges.s.section = sectp;
2407       this->debug_aranges.size = bfd_get_section_size (sectp);
2408     }
2409
2410   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2411       && bfd_section_vma (abfd, sectp) == 0)
2412     this->has_section_at_zero = true;
2413 }
2414
2415 /* A helper function that decides whether a section is empty,
2416    or not present.  */
2417
2418 static int
2419 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2420 {
2421   if (section->is_virtual)
2422     return section->size == 0;
2423   return section->s.section == NULL || section->size == 0;
2424 }
2425
2426 /* See dwarf2read.h.  */
2427
2428 void
2429 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2430 {
2431   asection *sectp;
2432   bfd *abfd;
2433   gdb_byte *buf, *retbuf;
2434
2435   if (info->readin)
2436     return;
2437   info->buffer = NULL;
2438   info->readin = 1;
2439
2440   if (dwarf2_section_empty_p (info))
2441     return;
2442
2443   sectp = get_section_bfd_section (info);
2444
2445   /* If this is a virtual section we need to read in the real one first.  */
2446   if (info->is_virtual)
2447     {
2448       struct dwarf2_section_info *containing_section =
2449         get_containing_section (info);
2450
2451       gdb_assert (sectp != NULL);
2452       if ((sectp->flags & SEC_RELOC) != 0)
2453         {
2454           error (_("Dwarf Error: DWP format V2 with relocations is not"
2455                    " supported in section %s [in module %s]"),
2456                  get_section_name (info), get_section_file_name (info));
2457         }
2458       dwarf2_read_section (objfile, containing_section);
2459       /* Other code should have already caught virtual sections that don't
2460          fit.  */
2461       gdb_assert (info->virtual_offset + info->size
2462                   <= containing_section->size);
2463       /* If the real section is empty or there was a problem reading the
2464          section we shouldn't get here.  */
2465       gdb_assert (containing_section->buffer != NULL);
2466       info->buffer = containing_section->buffer + info->virtual_offset;
2467       return;
2468     }
2469
2470   /* If the section has relocations, we must read it ourselves.
2471      Otherwise we attach it to the BFD.  */
2472   if ((sectp->flags & SEC_RELOC) == 0)
2473     {
2474       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2475       return;
2476     }
2477
2478   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2479   info->buffer = buf;
2480
2481   /* When debugging .o files, we may need to apply relocations; see
2482      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2483      We never compress sections in .o files, so we only need to
2484      try this when the section is not compressed.  */
2485   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2486   if (retbuf != NULL)
2487     {
2488       info->buffer = retbuf;
2489       return;
2490     }
2491
2492   abfd = get_section_bfd_owner (info);
2493   gdb_assert (abfd != NULL);
2494
2495   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2496       || bfd_bread (buf, info->size, abfd) != info->size)
2497     {
2498       error (_("Dwarf Error: Can't read DWARF data"
2499                " in section %s [in module %s]"),
2500              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2501     }
2502 }
2503
2504 /* A helper function that returns the size of a section in a safe way.
2505    If you are positive that the section has been read before using the
2506    size, then it is safe to refer to the dwarf2_section_info object's
2507    "size" field directly.  In other cases, you must call this
2508    function, because for compressed sections the size field is not set
2509    correctly until the section has been read.  */
2510
2511 static bfd_size_type
2512 dwarf2_section_size (struct objfile *objfile,
2513                      struct dwarf2_section_info *info)
2514 {
2515   if (!info->readin)
2516     dwarf2_read_section (objfile, info);
2517   return info->size;
2518 }
2519
2520 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2521    SECTION_NAME.  */
2522
2523 void
2524 dwarf2_get_section_info (struct objfile *objfile,
2525                          enum dwarf2_section_enum sect,
2526                          asection **sectp, const gdb_byte **bufp,
2527                          bfd_size_type *sizep)
2528 {
2529   struct dwarf2_per_objfile *data
2530     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2531                                                   dwarf2_objfile_data_key);
2532   struct dwarf2_section_info *info;
2533
2534   /* We may see an objfile without any DWARF, in which case we just
2535      return nothing.  */
2536   if (data == NULL)
2537     {
2538       *sectp = NULL;
2539       *bufp = NULL;
2540       *sizep = 0;
2541       return;
2542     }
2543   switch (sect)
2544     {
2545     case DWARF2_DEBUG_FRAME:
2546       info = &data->frame;
2547       break;
2548     case DWARF2_EH_FRAME:
2549       info = &data->eh_frame;
2550       break;
2551     default:
2552       gdb_assert_not_reached ("unexpected section");
2553     }
2554
2555   dwarf2_read_section (objfile, info);
2556
2557   *sectp = get_section_bfd_section (info);
2558   *bufp = info->buffer;
2559   *sizep = info->size;
2560 }
2561
2562 /* A helper function to find the sections for a .dwz file.  */
2563
2564 static void
2565 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2566 {
2567   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2568
2569   /* Note that we only support the standard ELF names, because .dwz
2570      is ELF-only (at the time of writing).  */
2571   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2572     {
2573       dwz_file->abbrev.s.section = sectp;
2574       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2575     }
2576   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2577     {
2578       dwz_file->info.s.section = sectp;
2579       dwz_file->info.size = bfd_get_section_size (sectp);
2580     }
2581   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2582     {
2583       dwz_file->str.s.section = sectp;
2584       dwz_file->str.size = bfd_get_section_size (sectp);
2585     }
2586   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2587     {
2588       dwz_file->line.s.section = sectp;
2589       dwz_file->line.size = bfd_get_section_size (sectp);
2590     }
2591   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2592     {
2593       dwz_file->macro.s.section = sectp;
2594       dwz_file->macro.size = bfd_get_section_size (sectp);
2595     }
2596   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2597     {
2598       dwz_file->gdb_index.s.section = sectp;
2599       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2600     }
2601   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2602     {
2603       dwz_file->debug_names.s.section = sectp;
2604       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2605     }
2606 }
2607
2608 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2609    there is no .gnu_debugaltlink section in the file.  Error if there
2610    is such a section but the file cannot be found.  */
2611
2612 static struct dwz_file *
2613 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2614 {
2615   const char *filename;
2616   struct dwz_file *result;
2617   bfd_size_type buildid_len_arg;
2618   size_t buildid_len;
2619   bfd_byte *buildid;
2620
2621   if (dwarf2_per_objfile->dwz_file != NULL)
2622     return dwarf2_per_objfile->dwz_file;
2623
2624   bfd_set_error (bfd_error_no_error);
2625   gdb::unique_xmalloc_ptr<char> data
2626     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2627                                   &buildid_len_arg, &buildid));
2628   if (data == NULL)
2629     {
2630       if (bfd_get_error () == bfd_error_no_error)
2631         return NULL;
2632       error (_("could not read '.gnu_debugaltlink' section: %s"),
2633              bfd_errmsg (bfd_get_error ()));
2634     }
2635
2636   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2637
2638   buildid_len = (size_t) buildid_len_arg;
2639
2640   filename = data.get ();
2641
2642   std::string abs_storage;
2643   if (!IS_ABSOLUTE_PATH (filename))
2644     {
2645       gdb::unique_xmalloc_ptr<char> abs
2646         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2647
2648       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2649       filename = abs_storage.c_str ();
2650     }
2651
2652   /* First try the file name given in the section.  If that doesn't
2653      work, try to use the build-id instead.  */
2654   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2655   if (dwz_bfd != NULL)
2656     {
2657       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2658         dwz_bfd.release ();
2659     }
2660
2661   if (dwz_bfd == NULL)
2662     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2663
2664   if (dwz_bfd == NULL)
2665     error (_("could not find '.gnu_debugaltlink' file for %s"),
2666            objfile_name (dwarf2_per_objfile->objfile));
2667
2668   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2669                            struct dwz_file);
2670   result->dwz_bfd = dwz_bfd.release ();
2671
2672   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2673
2674   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2675   dwarf2_per_objfile->dwz_file = result;
2676   return result;
2677 }
2678 \f
2679 /* DWARF quick_symbols_functions support.  */
2680
2681 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2682    unique line tables, so we maintain a separate table of all .debug_line
2683    derived entries to support the sharing.
2684    All the quick functions need is the list of file names.  We discard the
2685    line_header when we're done and don't need to record it here.  */
2686 struct quick_file_names
2687 {
2688   /* The data used to construct the hash key.  */
2689   struct stmt_list_hash hash;
2690
2691   /* The number of entries in file_names, real_names.  */
2692   unsigned int num_file_names;
2693
2694   /* The file names from the line table, after being run through
2695      file_full_name.  */
2696   const char **file_names;
2697
2698   /* The file names from the line table after being run through
2699      gdb_realpath.  These are computed lazily.  */
2700   const char **real_names;
2701 };
2702
2703 /* When using the index (and thus not using psymtabs), each CU has an
2704    object of this type.  This is used to hold information needed by
2705    the various "quick" methods.  */
2706 struct dwarf2_per_cu_quick_data
2707 {
2708   /* The file table.  This can be NULL if there was no file table
2709      or it's currently not read in.
2710      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2711   struct quick_file_names *file_names;
2712
2713   /* The corresponding symbol table.  This is NULL if symbols for this
2714      CU have not yet been read.  */
2715   struct compunit_symtab *compunit_symtab;
2716
2717   /* A temporary mark bit used when iterating over all CUs in
2718      expand_symtabs_matching.  */
2719   unsigned int mark : 1;
2720
2721   /* True if we've tried to read the file table and found there isn't one.
2722      There will be no point in trying to read it again next time.  */
2723   unsigned int no_file_data : 1;
2724 };
2725
2726 /* Utility hash function for a stmt_list_hash.  */
2727
2728 static hashval_t
2729 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2730 {
2731   hashval_t v = 0;
2732
2733   if (stmt_list_hash->dwo_unit != NULL)
2734     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2735   v += to_underlying (stmt_list_hash->line_sect_off);
2736   return v;
2737 }
2738
2739 /* Utility equality function for a stmt_list_hash.  */
2740
2741 static int
2742 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2743                     const struct stmt_list_hash *rhs)
2744 {
2745   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2746     return 0;
2747   if (lhs->dwo_unit != NULL
2748       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2749     return 0;
2750
2751   return lhs->line_sect_off == rhs->line_sect_off;
2752 }
2753
2754 /* Hash function for a quick_file_names.  */
2755
2756 static hashval_t
2757 hash_file_name_entry (const void *e)
2758 {
2759   const struct quick_file_names *file_data
2760     = (const struct quick_file_names *) e;
2761
2762   return hash_stmt_list_entry (&file_data->hash);
2763 }
2764
2765 /* Equality function for a quick_file_names.  */
2766
2767 static int
2768 eq_file_name_entry (const void *a, const void *b)
2769 {
2770   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2771   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2772
2773   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2774 }
2775
2776 /* Delete function for a quick_file_names.  */
2777
2778 static void
2779 delete_file_name_entry (void *e)
2780 {
2781   struct quick_file_names *file_data = (struct quick_file_names *) e;
2782   int i;
2783
2784   for (i = 0; i < file_data->num_file_names; ++i)
2785     {
2786       xfree ((void*) file_data->file_names[i]);
2787       if (file_data->real_names)
2788         xfree ((void*) file_data->real_names[i]);
2789     }
2790
2791   /* The space for the struct itself lives on objfile_obstack,
2792      so we don't free it here.  */
2793 }
2794
2795 /* Create a quick_file_names hash table.  */
2796
2797 static htab_t
2798 create_quick_file_names_table (unsigned int nr_initial_entries)
2799 {
2800   return htab_create_alloc (nr_initial_entries,
2801                             hash_file_name_entry, eq_file_name_entry,
2802                             delete_file_name_entry, xcalloc, xfree);
2803 }
2804
2805 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2806    have to be created afterwards.  You should call age_cached_comp_units after
2807    processing PER_CU->CU.  dw2_setup must have been already called.  */
2808
2809 static void
2810 load_cu (struct dwarf2_per_cu_data *per_cu)
2811 {
2812   if (per_cu->is_debug_types)
2813     load_full_type_unit (per_cu);
2814   else
2815     load_full_comp_unit (per_cu, language_minimal);
2816
2817   if (per_cu->cu == NULL)
2818     return;  /* Dummy CU.  */
2819
2820   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2821 }
2822
2823 /* Read in the symbols for PER_CU.  */
2824
2825 static void
2826 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2827 {
2828   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2829
2830   /* Skip type_unit_groups, reading the type units they contain
2831      is handled elsewhere.  */
2832   if (IS_TYPE_UNIT_GROUP (per_cu))
2833     return;
2834
2835   /* The destructor of dwarf2_queue_guard frees any entries left on
2836      the queue.  After this point we're guaranteed to leave this function
2837      with the dwarf queue empty.  */
2838   dwarf2_queue_guard q_guard;
2839
2840   if (dwarf2_per_objfile->using_index
2841       ? per_cu->v.quick->compunit_symtab == NULL
2842       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2843     {
2844       queue_comp_unit (per_cu, language_minimal);
2845       load_cu (per_cu);
2846
2847       /* If we just loaded a CU from a DWO, and we're working with an index
2848          that may badly handle TUs, load all the TUs in that DWO as well.
2849          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2850       if (!per_cu->is_debug_types
2851           && per_cu->cu != NULL
2852           && per_cu->cu->dwo_unit != NULL
2853           && dwarf2_per_objfile->index_table != NULL
2854           && dwarf2_per_objfile->index_table->version <= 7
2855           /* DWP files aren't supported yet.  */
2856           && get_dwp_file (dwarf2_per_objfile) == NULL)
2857         queue_and_load_all_dwo_tus (per_cu);
2858     }
2859
2860   process_queue (dwarf2_per_objfile);
2861
2862   /* Age the cache, releasing compilation units that have not
2863      been used recently.  */
2864   age_cached_comp_units (dwarf2_per_objfile);
2865 }
2866
2867 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2868    the objfile from which this CU came.  Returns the resulting symbol
2869    table.  */
2870
2871 static struct compunit_symtab *
2872 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2873 {
2874   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2875
2876   gdb_assert (dwarf2_per_objfile->using_index);
2877   if (!per_cu->v.quick->compunit_symtab)
2878     {
2879       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
2880                                               dwarf2_per_objfile);
2881       scoped_restore decrementer = increment_reading_symtab ();
2882       dw2_do_instantiate_symtab (per_cu);
2883       process_cu_includes (dwarf2_per_objfile);
2884       do_cleanups (back_to);
2885     }
2886
2887   return per_cu->v.quick->compunit_symtab;
2888 }
2889
2890 /* Return the CU/TU given its index.
2891
2892    This is intended for loops like:
2893
2894    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2895                     + dwarf2_per_objfile->n_type_units); ++i)
2896      {
2897        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2898
2899        ...;
2900      }
2901 */
2902
2903 static struct dwarf2_per_cu_data *
2904 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
2905               int index)
2906 {
2907   if (index >= dwarf2_per_objfile->n_comp_units)
2908     {
2909       index -= dwarf2_per_objfile->n_comp_units;
2910       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2911       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2912     }
2913
2914   return dwarf2_per_objfile->all_comp_units[index];
2915 }
2916
2917 /* Return the CU given its index.
2918    This differs from dw2_get_cutu in that it's for when you know INDEX
2919    refers to a CU.  */
2920
2921 static struct dwarf2_per_cu_data *
2922 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
2923 {
2924   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2925
2926   return dwarf2_per_objfile->all_comp_units[index];
2927 }
2928
2929 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2930    objfile_obstack, and constructed with the specified field
2931    values.  */
2932
2933 static dwarf2_per_cu_data *
2934 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2935                           struct dwarf2_section_info *section,
2936                           int is_dwz,
2937                           sect_offset sect_off, ULONGEST length)
2938 {
2939   struct objfile *objfile = dwarf2_per_objfile->objfile;
2940   dwarf2_per_cu_data *the_cu
2941     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2942                      struct dwarf2_per_cu_data);
2943   the_cu->sect_off = sect_off;
2944   the_cu->length = length;
2945   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2946   the_cu->section = section;
2947   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2948                                    struct dwarf2_per_cu_quick_data);
2949   the_cu->is_dwz = is_dwz;
2950   return the_cu;
2951 }
2952
2953 /* A helper for create_cus_from_index that handles a given list of
2954    CUs.  */
2955
2956 static void
2957 create_cus_from_index_list (struct objfile *objfile,
2958                             const gdb_byte *cu_list, offset_type n_elements,
2959                             struct dwarf2_section_info *section,
2960                             int is_dwz,
2961                             int base_offset)
2962 {
2963   offset_type i;
2964   struct dwarf2_per_objfile *dwarf2_per_objfile
2965     = get_dwarf2_per_objfile (objfile);
2966
2967   for (i = 0; i < n_elements; i += 2)
2968     {
2969       gdb_static_assert (sizeof (ULONGEST) >= 8);
2970
2971       sect_offset sect_off
2972         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2973       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2974       cu_list += 2 * 8;
2975
2976       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
2977         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2978                                      sect_off, length);
2979     }
2980 }
2981
2982 /* Read the CU list from the mapped index, and use it to create all
2983    the CU objects for this objfile.  */
2984
2985 static void
2986 create_cus_from_index (struct objfile *objfile,
2987                        const gdb_byte *cu_list, offset_type cu_list_elements,
2988                        const gdb_byte *dwz_list, offset_type dwz_elements)
2989 {
2990   struct dwz_file *dwz;
2991   struct dwarf2_per_objfile *dwarf2_per_objfile
2992     = get_dwarf2_per_objfile (objfile);
2993
2994   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
2995   dwarf2_per_objfile->all_comp_units =
2996     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
2997                dwarf2_per_objfile->n_comp_units);
2998
2999   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3000                               &dwarf2_per_objfile->info, 0, 0);
3001
3002   if (dwz_elements == 0)
3003     return;
3004
3005   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3006   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3007                               cu_list_elements / 2);
3008 }
3009
3010 /* Create the signatured type hash table from the index.  */
3011
3012 static void
3013 create_signatured_type_table_from_index (struct objfile *objfile,
3014                                          struct dwarf2_section_info *section,
3015                                          const gdb_byte *bytes,
3016                                          offset_type elements)
3017 {
3018   offset_type i;
3019   htab_t sig_types_hash;
3020   struct dwarf2_per_objfile *dwarf2_per_objfile
3021     = get_dwarf2_per_objfile (objfile);
3022
3023   dwarf2_per_objfile->n_type_units
3024     = dwarf2_per_objfile->n_allocated_type_units
3025     = elements / 3;
3026   dwarf2_per_objfile->all_type_units =
3027     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3028
3029   sig_types_hash = allocate_signatured_type_table (objfile);
3030
3031   for (i = 0; i < elements; i += 3)
3032     {
3033       struct signatured_type *sig_type;
3034       ULONGEST signature;
3035       void **slot;
3036       cu_offset type_offset_in_tu;
3037
3038       gdb_static_assert (sizeof (ULONGEST) >= 8);
3039       sect_offset sect_off
3040         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3041       type_offset_in_tu
3042         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3043                                                 BFD_ENDIAN_LITTLE);
3044       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3045       bytes += 3 * 8;
3046
3047       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3048                                  struct signatured_type);
3049       sig_type->signature = signature;
3050       sig_type->type_offset_in_tu = type_offset_in_tu;
3051       sig_type->per_cu.is_debug_types = 1;
3052       sig_type->per_cu.section = section;
3053       sig_type->per_cu.sect_off = sect_off;
3054       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3055       sig_type->per_cu.v.quick
3056         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3057                           struct dwarf2_per_cu_quick_data);
3058
3059       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3060       *slot = sig_type;
3061
3062       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3063     }
3064
3065   dwarf2_per_objfile->signatured_types = sig_types_hash;
3066 }
3067
3068 /* Create the signatured type hash table from .debug_names.  */
3069
3070 static void
3071 create_signatured_type_table_from_debug_names
3072   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3073    const mapped_debug_names &map,
3074    struct dwarf2_section_info *section,
3075    struct dwarf2_section_info *abbrev_section)
3076 {
3077   struct objfile *objfile = dwarf2_per_objfile->objfile;
3078
3079   dwarf2_read_section (objfile, section);
3080   dwarf2_read_section (objfile, abbrev_section);
3081
3082   dwarf2_per_objfile->n_type_units
3083     = dwarf2_per_objfile->n_allocated_type_units
3084     = map.tu_count;
3085   dwarf2_per_objfile->all_type_units
3086     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3087
3088   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3089
3090   for (uint32_t i = 0; i < map.tu_count; ++i)
3091     {
3092       struct signatured_type *sig_type;
3093       ULONGEST signature;
3094       void **slot;
3095       cu_offset type_offset_in_tu;
3096
3097       sect_offset sect_off
3098         = (sect_offset) (extract_unsigned_integer
3099                          (map.tu_table_reordered + i * map.offset_size,
3100                           map.offset_size,
3101                           map.dwarf5_byte_order));
3102
3103       comp_unit_head cu_header;
3104       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3105                                      abbrev_section,
3106                                      section->buffer + to_underlying (sect_off),
3107                                      rcuh_kind::TYPE);
3108
3109       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3110                                  struct signatured_type);
3111       sig_type->signature = cu_header.signature;
3112       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3113       sig_type->per_cu.is_debug_types = 1;
3114       sig_type->per_cu.section = section;
3115       sig_type->per_cu.sect_off = sect_off;
3116       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3117       sig_type->per_cu.v.quick
3118         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3119                           struct dwarf2_per_cu_quick_data);
3120
3121       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3122       *slot = sig_type;
3123
3124       dwarf2_per_objfile->all_type_units[i] = sig_type;
3125     }
3126
3127   dwarf2_per_objfile->signatured_types = sig_types_hash;
3128 }
3129
3130 /* Read the address map data from the mapped index, and use it to
3131    populate the objfile's psymtabs_addrmap.  */
3132
3133 static void
3134 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3135                            struct mapped_index *index)
3136 {
3137   struct objfile *objfile = dwarf2_per_objfile->objfile;
3138   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3139   const gdb_byte *iter, *end;
3140   struct addrmap *mutable_map;
3141   CORE_ADDR baseaddr;
3142
3143   auto_obstack temp_obstack;
3144
3145   mutable_map = addrmap_create_mutable (&temp_obstack);
3146
3147   iter = index->address_table.data ();
3148   end = iter + index->address_table.size ();
3149
3150   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3151
3152   while (iter < end)
3153     {
3154       ULONGEST hi, lo, cu_index;
3155       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3156       iter += 8;
3157       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3158       iter += 8;
3159       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3160       iter += 4;
3161
3162       if (lo > hi)
3163         {
3164           complaint (&symfile_complaints,
3165                      _(".gdb_index address table has invalid range (%s - %s)"),
3166                      hex_string (lo), hex_string (hi));
3167           continue;
3168         }
3169
3170       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3171         {
3172           complaint (&symfile_complaints,
3173                      _(".gdb_index address table has invalid CU number %u"),
3174                      (unsigned) cu_index);
3175           continue;
3176         }
3177
3178       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3179       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3180       addrmap_set_empty (mutable_map, lo, hi - 1,
3181                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3182     }
3183
3184   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3185                                                     &objfile->objfile_obstack);
3186 }
3187
3188 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3189    populate the objfile's psymtabs_addrmap.  */
3190
3191 static void
3192 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3193                              struct dwarf2_section_info *section)
3194 {
3195   struct objfile *objfile = dwarf2_per_objfile->objfile;
3196   bfd *abfd = objfile->obfd;
3197   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3198   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3199                                        SECT_OFF_TEXT (objfile));
3200
3201   auto_obstack temp_obstack;
3202   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3203
3204   std::unordered_map<sect_offset,
3205                      dwarf2_per_cu_data *,
3206                      gdb::hash_enum<sect_offset>>
3207     debug_info_offset_to_per_cu;
3208   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3209     {
3210       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3211       const auto insertpair
3212         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3213       if (!insertpair.second)
3214         {
3215           warning (_("Section .debug_aranges in %s has duplicate "
3216                      "debug_info_offset %s, ignoring .debug_aranges."),
3217                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3218           return;
3219         }
3220     }
3221
3222   dwarf2_read_section (objfile, section);
3223
3224   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3225
3226   const gdb_byte *addr = section->buffer;
3227
3228   while (addr < section->buffer + section->size)
3229     {
3230       const gdb_byte *const entry_addr = addr;
3231       unsigned int bytes_read;
3232
3233       const LONGEST entry_length = read_initial_length (abfd, addr,
3234                                                         &bytes_read);
3235       addr += bytes_read;
3236
3237       const gdb_byte *const entry_end = addr + entry_length;
3238       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3239       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3240       if (addr + entry_length > section->buffer + section->size)
3241         {
3242           warning (_("Section .debug_aranges in %s entry at offset %zu "
3243                      "length %s exceeds section length %s, "
3244                      "ignoring .debug_aranges."),
3245                    objfile_name (objfile), entry_addr - section->buffer,
3246                    plongest (bytes_read + entry_length),
3247                    pulongest (section->size));
3248           return;
3249         }
3250
3251       /* The version number.  */
3252       const uint16_t version = read_2_bytes (abfd, addr);
3253       addr += 2;
3254       if (version != 2)
3255         {
3256           warning (_("Section .debug_aranges in %s entry at offset %zu "
3257                      "has unsupported version %d, ignoring .debug_aranges."),
3258                    objfile_name (objfile), entry_addr - section->buffer,
3259                    version);
3260           return;
3261         }
3262
3263       const uint64_t debug_info_offset
3264         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3265       addr += offset_size;
3266       const auto per_cu_it
3267         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3268       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3269         {
3270           warning (_("Section .debug_aranges in %s entry at offset %zu "
3271                      "debug_info_offset %s does not exists, "
3272                      "ignoring .debug_aranges."),
3273                    objfile_name (objfile), entry_addr - section->buffer,
3274                    pulongest (debug_info_offset));
3275           return;
3276         }
3277       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3278
3279       const uint8_t address_size = *addr++;
3280       if (address_size < 1 || address_size > 8)
3281         {
3282           warning (_("Section .debug_aranges in %s entry at offset %zu "
3283                      "address_size %u is invalid, ignoring .debug_aranges."),
3284                    objfile_name (objfile), entry_addr - section->buffer,
3285                    address_size);
3286           return;
3287         }
3288
3289       const uint8_t segment_selector_size = *addr++;
3290       if (segment_selector_size != 0)
3291         {
3292           warning (_("Section .debug_aranges in %s entry at offset %zu "
3293                      "segment_selector_size %u is not supported, "
3294                      "ignoring .debug_aranges."),
3295                    objfile_name (objfile), entry_addr - section->buffer,
3296                    segment_selector_size);
3297           return;
3298         }
3299
3300       /* Must pad to an alignment boundary that is twice the address
3301          size.  It is undocumented by the DWARF standard but GCC does
3302          use it.  */
3303       for (size_t padding = ((-(addr - section->buffer))
3304                              & (2 * address_size - 1));
3305            padding > 0; padding--)
3306         if (*addr++ != 0)
3307           {
3308             warning (_("Section .debug_aranges in %s entry at offset %zu "
3309                        "padding is not zero, ignoring .debug_aranges."),
3310                      objfile_name (objfile), entry_addr - section->buffer);
3311             return;
3312           }
3313
3314       for (;;)
3315         {
3316           if (addr + 2 * address_size > entry_end)
3317             {
3318               warning (_("Section .debug_aranges in %s entry at offset %zu "
3319                          "address list is not properly terminated, "
3320                          "ignoring .debug_aranges."),
3321                        objfile_name (objfile), entry_addr - section->buffer);
3322               return;
3323             }
3324           ULONGEST start = extract_unsigned_integer (addr, address_size,
3325                                                      dwarf5_byte_order);
3326           addr += address_size;
3327           ULONGEST length = extract_unsigned_integer (addr, address_size,
3328                                                       dwarf5_byte_order);
3329           addr += address_size;
3330           if (start == 0 && length == 0)
3331             break;
3332           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3333             {
3334               /* Symbol was eliminated due to a COMDAT group.  */
3335               continue;
3336             }
3337           ULONGEST end = start + length;
3338           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3339           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3340           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3341         }
3342     }
3343
3344   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3345                                                     &objfile->objfile_obstack);
3346 }
3347
3348 /* Find a slot in the mapped index INDEX for the object named NAME.
3349    If NAME is found, set *VEC_OUT to point to the CU vector in the
3350    constant pool and return true.  If NAME cannot be found, return
3351    false.  */
3352
3353 static bool
3354 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3355                           offset_type **vec_out)
3356 {
3357   offset_type hash;
3358   offset_type slot, step;
3359   int (*cmp) (const char *, const char *);
3360
3361   gdb::unique_xmalloc_ptr<char> without_params;
3362   if (current_language->la_language == language_cplus
3363       || current_language->la_language == language_fortran
3364       || current_language->la_language == language_d)
3365     {
3366       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3367          not contain any.  */
3368
3369       if (strchr (name, '(') != NULL)
3370         {
3371           without_params = cp_remove_params (name);
3372
3373           if (without_params != NULL)
3374             name = without_params.get ();
3375         }
3376     }
3377
3378   /* Index version 4 did not support case insensitive searches.  But the
3379      indices for case insensitive languages are built in lowercase, therefore
3380      simulate our NAME being searched is also lowercased.  */
3381   hash = mapped_index_string_hash ((index->version == 4
3382                                     && case_sensitivity == case_sensitive_off
3383                                     ? 5 : index->version),
3384                                    name);
3385
3386   slot = hash & (index->symbol_table.size () - 1);
3387   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3388   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3389
3390   for (;;)
3391     {
3392       const char *str;
3393
3394       const auto &bucket = index->symbol_table[slot];
3395       if (bucket.name == 0 && bucket.vec == 0)
3396         return false;
3397
3398       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3399       if (!cmp (name, str))
3400         {
3401           *vec_out = (offset_type *) (index->constant_pool
3402                                       + MAYBE_SWAP (bucket.vec));
3403           return true;
3404         }
3405
3406       slot = (slot + step) & (index->symbol_table.size () - 1);
3407     }
3408 }
3409
3410 /* A helper function that reads the .gdb_index from SECTION and fills
3411    in MAP.  FILENAME is the name of the file containing the section;
3412    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3413    ok to use deprecated sections.
3414
3415    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3416    out parameters that are filled in with information about the CU and
3417    TU lists in the section.
3418
3419    Returns 1 if all went well, 0 otherwise.  */
3420
3421 static int
3422 read_index_from_section (struct objfile *objfile,
3423                          const char *filename,
3424                          int deprecated_ok,
3425                          struct dwarf2_section_info *section,
3426                          struct mapped_index *map,
3427                          const gdb_byte **cu_list,
3428                          offset_type *cu_list_elements,
3429                          const gdb_byte **types_list,
3430                          offset_type *types_list_elements)
3431 {
3432   const gdb_byte *addr;
3433   offset_type version;
3434   offset_type *metadata;
3435   int i;
3436
3437   if (dwarf2_section_empty_p (section))
3438     return 0;
3439
3440   /* Older elfutils strip versions could keep the section in the main
3441      executable while splitting it for the separate debug info file.  */
3442   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3443     return 0;
3444
3445   dwarf2_read_section (objfile, section);
3446
3447   addr = section->buffer;
3448   /* Version check.  */
3449   version = MAYBE_SWAP (*(offset_type *) addr);
3450   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3451      causes the index to behave very poorly for certain requests.  Version 3
3452      contained incomplete addrmap.  So, it seems better to just ignore such
3453      indices.  */
3454   if (version < 4)
3455     {
3456       static int warning_printed = 0;
3457       if (!warning_printed)
3458         {
3459           warning (_("Skipping obsolete .gdb_index section in %s."),
3460                    filename);
3461           warning_printed = 1;
3462         }
3463       return 0;
3464     }
3465   /* Index version 4 uses a different hash function than index version
3466      5 and later.
3467
3468      Versions earlier than 6 did not emit psymbols for inlined
3469      functions.  Using these files will cause GDB not to be able to
3470      set breakpoints on inlined functions by name, so we ignore these
3471      indices unless the user has done
3472      "set use-deprecated-index-sections on".  */
3473   if (version < 6 && !deprecated_ok)
3474     {
3475       static int warning_printed = 0;
3476       if (!warning_printed)
3477         {
3478           warning (_("\
3479 Skipping deprecated .gdb_index section in %s.\n\
3480 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3481 to use the section anyway."),
3482                    filename);
3483           warning_printed = 1;
3484         }
3485       return 0;
3486     }
3487   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3488      of the TU (for symbols coming from TUs),
3489      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3490      Plus gold-generated indices can have duplicate entries for global symbols,
3491      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3492      These are just performance bugs, and we can't distinguish gdb-generated
3493      indices from gold-generated ones, so issue no warning here.  */
3494
3495   /* Indexes with higher version than the one supported by GDB may be no
3496      longer backward compatible.  */
3497   if (version > 8)
3498     return 0;
3499
3500   map->version = version;
3501   map->total_size = section->size;
3502
3503   metadata = (offset_type *) (addr + sizeof (offset_type));
3504
3505   i = 0;
3506   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3507   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3508                        / 8);
3509   ++i;
3510
3511   *types_list = addr + MAYBE_SWAP (metadata[i]);
3512   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3513                            - MAYBE_SWAP (metadata[i]))
3514                           / 8);
3515   ++i;
3516
3517   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3518   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3519   map->address_table
3520     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3521   ++i;
3522
3523   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3524   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3525   map->symbol_table
3526     = gdb::array_view<mapped_index::symbol_table_slot>
3527        ((mapped_index::symbol_table_slot *) symbol_table,
3528         (mapped_index::symbol_table_slot *) symbol_table_end);
3529
3530   ++i;
3531   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3532
3533   return 1;
3534 }
3535
3536 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3537    elements of all the CUs and return 1.  Otherwise, return 0.  */
3538
3539 static int
3540 dwarf2_read_index (struct objfile *objfile)
3541 {
3542   struct mapped_index local_map, *map;
3543   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3544   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3545   struct dwz_file *dwz;
3546   struct dwarf2_per_objfile *dwarf2_per_objfile
3547     = get_dwarf2_per_objfile (objfile);
3548
3549   if (!read_index_from_section (objfile, objfile_name (objfile),
3550                                 use_deprecated_index_sections,
3551                                 &dwarf2_per_objfile->gdb_index, &local_map,
3552                                 &cu_list, &cu_list_elements,
3553                                 &types_list, &types_list_elements))
3554     return 0;
3555
3556   /* Don't use the index if it's empty.  */
3557   if (local_map.symbol_table.empty ())
3558     return 0;
3559
3560   /* If there is a .dwz file, read it so we can get its CU list as
3561      well.  */
3562   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3563   if (dwz != NULL)
3564     {
3565       struct mapped_index dwz_map;
3566       const gdb_byte *dwz_types_ignore;
3567       offset_type dwz_types_elements_ignore;
3568
3569       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3570                                     1,
3571                                     &dwz->gdb_index, &dwz_map,
3572                                     &dwz_list, &dwz_list_elements,
3573                                     &dwz_types_ignore,
3574                                     &dwz_types_elements_ignore))
3575         {
3576           warning (_("could not read '.gdb_index' section from %s; skipping"),
3577                    bfd_get_filename (dwz->dwz_bfd));
3578           return 0;
3579         }
3580     }
3581
3582   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3583                          dwz_list_elements);
3584
3585   if (types_list_elements)
3586     {
3587       struct dwarf2_section_info *section;
3588
3589       /* We can only handle a single .debug_types when we have an
3590          index.  */
3591       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3592         return 0;
3593
3594       section = VEC_index (dwarf2_section_info_def,
3595                            dwarf2_per_objfile->types, 0);
3596
3597       create_signatured_type_table_from_index (objfile, section, types_list,
3598                                                types_list_elements);
3599     }
3600
3601   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3602
3603   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3604   map = new (map) mapped_index ();
3605   *map = local_map;
3606
3607   dwarf2_per_objfile->index_table = map;
3608   dwarf2_per_objfile->using_index = 1;
3609   dwarf2_per_objfile->quick_file_names_table =
3610     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3611
3612   return 1;
3613 }
3614
3615 /* die_reader_func for dw2_get_file_names.  */
3616
3617 static void
3618 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3619                            const gdb_byte *info_ptr,
3620                            struct die_info *comp_unit_die,
3621                            int has_children,
3622                            void *data)
3623 {
3624   struct dwarf2_cu *cu = reader->cu;
3625   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3626   struct dwarf2_per_objfile *dwarf2_per_objfile
3627     = cu->per_cu->dwarf2_per_objfile;
3628   struct objfile *objfile = dwarf2_per_objfile->objfile;
3629   struct dwarf2_per_cu_data *lh_cu;
3630   struct attribute *attr;
3631   int i;
3632   void **slot;
3633   struct quick_file_names *qfn;
3634
3635   gdb_assert (! this_cu->is_debug_types);
3636
3637   /* Our callers never want to match partial units -- instead they
3638      will match the enclosing full CU.  */
3639   if (comp_unit_die->tag == DW_TAG_partial_unit)
3640     {
3641       this_cu->v.quick->no_file_data = 1;
3642       return;
3643     }
3644
3645   lh_cu = this_cu;
3646   slot = NULL;
3647
3648   line_header_up lh;
3649   sect_offset line_offset {};
3650
3651   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3652   if (attr)
3653     {
3654       struct quick_file_names find_entry;
3655
3656       line_offset = (sect_offset) DW_UNSND (attr);
3657
3658       /* We may have already read in this line header (TU line header sharing).
3659          If we have we're done.  */
3660       find_entry.hash.dwo_unit = cu->dwo_unit;
3661       find_entry.hash.line_sect_off = line_offset;
3662       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3663                              &find_entry, INSERT);
3664       if (*slot != NULL)
3665         {
3666           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3667           return;
3668         }
3669
3670       lh = dwarf_decode_line_header (line_offset, cu);
3671     }
3672   if (lh == NULL)
3673     {
3674       lh_cu->v.quick->no_file_data = 1;
3675       return;
3676     }
3677
3678   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3679   qfn->hash.dwo_unit = cu->dwo_unit;
3680   qfn->hash.line_sect_off = line_offset;
3681   gdb_assert (slot != NULL);
3682   *slot = qfn;
3683
3684   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3685
3686   qfn->num_file_names = lh->file_names.size ();
3687   qfn->file_names =
3688     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3689   for (i = 0; i < lh->file_names.size (); ++i)
3690     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3691   qfn->real_names = NULL;
3692
3693   lh_cu->v.quick->file_names = qfn;
3694 }
3695
3696 /* A helper for the "quick" functions which attempts to read the line
3697    table for THIS_CU.  */
3698
3699 static struct quick_file_names *
3700 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3701 {
3702   /* This should never be called for TUs.  */
3703   gdb_assert (! this_cu->is_debug_types);
3704   /* Nor type unit groups.  */
3705   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3706
3707   if (this_cu->v.quick->file_names != NULL)
3708     return this_cu->v.quick->file_names;
3709   /* If we know there is no line data, no point in looking again.  */
3710   if (this_cu->v.quick->no_file_data)
3711     return NULL;
3712
3713   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3714
3715   if (this_cu->v.quick->no_file_data)
3716     return NULL;
3717   return this_cu->v.quick->file_names;
3718 }
3719
3720 /* A helper for the "quick" functions which computes and caches the
3721    real path for a given file name from the line table.  */
3722
3723 static const char *
3724 dw2_get_real_path (struct objfile *objfile,
3725                    struct quick_file_names *qfn, int index)
3726 {
3727   if (qfn->real_names == NULL)
3728     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3729                                       qfn->num_file_names, const char *);
3730
3731   if (qfn->real_names[index] == NULL)
3732     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3733
3734   return qfn->real_names[index];
3735 }
3736
3737 static struct symtab *
3738 dw2_find_last_source_symtab (struct objfile *objfile)
3739 {
3740   struct dwarf2_per_objfile *dwarf2_per_objfile
3741     = get_dwarf2_per_objfile (objfile);
3742   int index = dwarf2_per_objfile->n_comp_units - 1;
3743   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
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   int i;
3814   const char *name_basename = lbasename (name);
3815   struct dwarf2_per_objfile *dwarf2_per_objfile
3816     = get_dwarf2_per_objfile (objfile);
3817
3818   /* The rule is CUs specify all the files, including those used by
3819      any TU, so there's no need to scan TUs here.  */
3820
3821   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3822     {
3823       int j;
3824       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
3825       struct quick_file_names *file_data;
3826
3827       /* We only need to look at symtabs not already expanded.  */
3828       if (per_cu->v.quick->compunit_symtab)
3829         continue;
3830
3831       file_data = dw2_get_file_names (per_cu);
3832       if (file_data == NULL)
3833         continue;
3834
3835       for (j = 0; j < file_data->num_file_names; ++j)
3836         {
3837           const char *this_name = file_data->file_names[j];
3838           const char *this_real_name;
3839
3840           if (compare_filenames_for_search (this_name, name))
3841             {
3842               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3843                                         callback))
3844                 return true;
3845               continue;
3846             }
3847
3848           /* Before we invoke realpath, which can get expensive when many
3849              files are involved, do a quick comparison of the basenames.  */
3850           if (! basenames_may_differ
3851               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3852             continue;
3853
3854           this_real_name = dw2_get_real_path (objfile, file_data, j);
3855           if (compare_filenames_for_search (this_real_name, name))
3856             {
3857               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3858                                         callback))
3859                 return true;
3860               continue;
3861             }
3862
3863           if (real_path != NULL)
3864             {
3865               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3866               gdb_assert (IS_ABSOLUTE_PATH (name));
3867               if (this_real_name != NULL
3868                   && FILENAME_CMP (real_path, this_real_name) == 0)
3869                 {
3870                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3871                                             callback))
3872                     return true;
3873                   continue;
3874                 }
3875             }
3876         }
3877     }
3878
3879   return false;
3880 }
3881
3882 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3883
3884 struct dw2_symtab_iterator
3885 {
3886   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3887   struct dwarf2_per_objfile *dwarf2_per_objfile;
3888   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3889   int want_specific_block;
3890   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3891      Unused if !WANT_SPECIFIC_BLOCK.  */
3892   int block_index;
3893   /* The kind of symbol we're looking for.  */
3894   domain_enum domain;
3895   /* The list of CUs from the index entry of the symbol,
3896      or NULL if not found.  */
3897   offset_type *vec;
3898   /* The next element in VEC to look at.  */
3899   int next;
3900   /* The number of elements in VEC, or zero if there is no match.  */
3901   int length;
3902   /* Have we seen a global version of the symbol?
3903      If so we can ignore all further global instances.
3904      This is to work around gold/15646, inefficient gold-generated
3905      indices.  */
3906   int global_seen;
3907 };
3908
3909 /* Initialize the index symtab iterator ITER.
3910    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3911    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3912
3913 static void
3914 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3915                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3916                       int want_specific_block,
3917                       int block_index,
3918                       domain_enum domain,
3919                       const char *name)
3920 {
3921   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3922   iter->want_specific_block = want_specific_block;
3923   iter->block_index = block_index;
3924   iter->domain = domain;
3925   iter->next = 0;
3926   iter->global_seen = 0;
3927
3928   mapped_index *index = dwarf2_per_objfile->index_table;
3929
3930   /* index is NULL if OBJF_READNOW.  */
3931   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3932     iter->length = MAYBE_SWAP (*iter->vec);
3933   else
3934     {
3935       iter->vec = NULL;
3936       iter->length = 0;
3937     }
3938 }
3939
3940 /* Return the next matching CU or NULL if there are no more.  */
3941
3942 static struct dwarf2_per_cu_data *
3943 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3944 {
3945   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3946
3947   for ( ; iter->next < iter->length; ++iter->next)
3948     {
3949       offset_type cu_index_and_attrs =
3950         MAYBE_SWAP (iter->vec[iter->next + 1]);
3951       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3952       struct dwarf2_per_cu_data *per_cu;
3953       int want_static = iter->block_index != GLOBAL_BLOCK;
3954       /* This value is only valid for index versions >= 7.  */
3955       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3956       gdb_index_symbol_kind symbol_kind =
3957         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3958       /* Only check the symbol attributes if they're present.
3959          Indices prior to version 7 don't record them,
3960          and indices >= 7 may elide them for certain symbols
3961          (gold does this).  */
3962       int attrs_valid =
3963         (dwarf2_per_objfile->index_table->version >= 7
3964          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3965
3966       /* Don't crash on bad data.  */
3967       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3968                        + dwarf2_per_objfile->n_type_units))
3969         {
3970           complaint (&symfile_complaints,
3971                      _(".gdb_index entry has bad CU index"
3972                        " [in module %s]"),
3973                      objfile_name (dwarf2_per_objfile->objfile));
3974           continue;
3975         }
3976
3977       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
3978
3979       /* Skip if already read in.  */
3980       if (per_cu->v.quick->compunit_symtab)
3981         continue;
3982
3983       /* Check static vs global.  */
3984       if (attrs_valid)
3985         {
3986           if (iter->want_specific_block
3987               && want_static != is_static)
3988             continue;
3989           /* Work around gold/15646.  */
3990           if (!is_static && iter->global_seen)
3991             continue;
3992           if (!is_static)
3993             iter->global_seen = 1;
3994         }
3995
3996       /* Only check the symbol's kind if it has one.  */
3997       if (attrs_valid)
3998         {
3999           switch (iter->domain)
4000             {
4001             case VAR_DOMAIN:
4002               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4003                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4004                   /* Some types are also in VAR_DOMAIN.  */
4005                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4006                 continue;
4007               break;
4008             case STRUCT_DOMAIN:
4009               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4010                 continue;
4011               break;
4012             case LABEL_DOMAIN:
4013               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4014                 continue;
4015               break;
4016             default:
4017               break;
4018             }
4019         }
4020
4021       ++iter->next;
4022       return per_cu;
4023     }
4024
4025   return NULL;
4026 }
4027
4028 static struct compunit_symtab *
4029 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4030                    const char *name, domain_enum domain)
4031 {
4032   struct compunit_symtab *stab_best = NULL;
4033   struct dwarf2_per_objfile *dwarf2_per_objfile
4034     = get_dwarf2_per_objfile (objfile);
4035
4036   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4037
4038   struct dw2_symtab_iterator iter;
4039   struct dwarf2_per_cu_data *per_cu;
4040
4041   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4042
4043   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4044     {
4045       struct symbol *sym, *with_opaque = NULL;
4046       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4047       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4048       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4049
4050       sym = block_find_symbol (block, name, domain,
4051                                block_find_non_opaque_type_preferred,
4052                                &with_opaque);
4053
4054       /* Some caution must be observed with overloaded functions
4055          and methods, since the index will not contain any overload
4056          information (but NAME might contain it).  */
4057
4058       if (sym != NULL
4059           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4060         return stab;
4061       if (with_opaque != NULL
4062           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4063         stab_best = stab;
4064
4065       /* Keep looking through other CUs.  */
4066     }
4067
4068   return stab_best;
4069 }
4070
4071 static void
4072 dw2_print_stats (struct objfile *objfile)
4073 {
4074   struct dwarf2_per_objfile *dwarf2_per_objfile
4075     = get_dwarf2_per_objfile (objfile);
4076   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4077   int count = 0;
4078
4079   for (int i = 0; i < total; ++i)
4080     {
4081       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4082
4083       if (!per_cu->v.quick->compunit_symtab)
4084         ++count;
4085     }
4086   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4087   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4088 }
4089
4090 /* This dumps minimal information about the index.
4091    It is called via "mt print objfiles".
4092    One use is to verify .gdb_index has been loaded by the
4093    gdb.dwarf2/gdb-index.exp testcase.  */
4094
4095 static void
4096 dw2_dump (struct objfile *objfile)
4097 {
4098   struct dwarf2_per_objfile *dwarf2_per_objfile
4099     = get_dwarf2_per_objfile (objfile);
4100
4101   gdb_assert (dwarf2_per_objfile->using_index);
4102   printf_filtered (".gdb_index:");
4103   if (dwarf2_per_objfile->index_table != NULL)
4104     {
4105       printf_filtered (" version %d\n",
4106                        dwarf2_per_objfile->index_table->version);
4107     }
4108   else
4109     printf_filtered (" faked for \"readnow\"\n");
4110   printf_filtered ("\n");
4111 }
4112
4113 static void
4114 dw2_relocate (struct objfile *objfile,
4115               const struct section_offsets *new_offsets,
4116               const struct section_offsets *delta)
4117 {
4118   /* There's nothing to relocate here.  */
4119 }
4120
4121 static void
4122 dw2_expand_symtabs_for_function (struct objfile *objfile,
4123                                  const char *func_name)
4124 {
4125   struct dwarf2_per_objfile *dwarf2_per_objfile
4126     = get_dwarf2_per_objfile (objfile);
4127
4128   struct dw2_symtab_iterator iter;
4129   struct dwarf2_per_cu_data *per_cu;
4130
4131   /* Note: It doesn't matter what we pass for block_index here.  */
4132   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4133                         func_name);
4134
4135   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4136     dw2_instantiate_symtab (per_cu);
4137
4138 }
4139
4140 static void
4141 dw2_expand_all_symtabs (struct objfile *objfile)
4142 {
4143   struct dwarf2_per_objfile *dwarf2_per_objfile
4144     = get_dwarf2_per_objfile (objfile);
4145   int total_units = (dwarf2_per_objfile->n_comp_units
4146                      + dwarf2_per_objfile->n_type_units);
4147
4148   for (int i = 0; i < total_units; ++i)
4149     {
4150       struct dwarf2_per_cu_data *per_cu
4151         = dw2_get_cutu (dwarf2_per_objfile, i);
4152
4153       dw2_instantiate_symtab (per_cu);
4154     }
4155 }
4156
4157 static void
4158 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4159                                   const char *fullname)
4160 {
4161   struct dwarf2_per_objfile *dwarf2_per_objfile
4162     = get_dwarf2_per_objfile (objfile);
4163
4164   /* We don't need to consider type units here.
4165      This is only called for examining code, e.g. expand_line_sal.
4166      There can be an order of magnitude (or more) more type units
4167      than comp units, and we avoid them if we can.  */
4168
4169   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4170     {
4171       int j;
4172       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4173       struct quick_file_names *file_data;
4174
4175       /* We only need to look at symtabs not already expanded.  */
4176       if (per_cu->v.quick->compunit_symtab)
4177         continue;
4178
4179       file_data = dw2_get_file_names (per_cu);
4180       if (file_data == NULL)
4181         continue;
4182
4183       for (j = 0; j < file_data->num_file_names; ++j)
4184         {
4185           const char *this_fullname = file_data->file_names[j];
4186
4187           if (filename_cmp (this_fullname, fullname) == 0)
4188             {
4189               dw2_instantiate_symtab (per_cu);
4190               break;
4191             }
4192         }
4193     }
4194 }
4195
4196 static void
4197 dw2_map_matching_symbols (struct objfile *objfile,
4198                           const char * name, domain_enum domain,
4199                           int global,
4200                           int (*callback) (struct block *,
4201                                            struct symbol *, void *),
4202                           void *data, symbol_name_match_type match,
4203                           symbol_compare_ftype *ordered_compare)
4204 {
4205   /* Currently unimplemented; used for Ada.  The function can be called if the
4206      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4207      does not look for non-Ada symbols this function should just return.  */
4208 }
4209
4210 /* Symbol name matcher for .gdb_index names.
4211
4212    Symbol names in .gdb_index have a few particularities:
4213
4214    - There's no indication of which is the language of each symbol.
4215
4216      Since each language has its own symbol name matching algorithm,
4217      and we don't know which language is the right one, we must match
4218      each symbol against all languages.  This would be a potential
4219      performance problem if it were not mitigated by the
4220      mapped_index::name_components lookup table, which significantly
4221      reduces the number of times we need to call into this matcher,
4222      making it a non-issue.
4223
4224    - Symbol names in the index have no overload (parameter)
4225      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4226      appear as "foo" in the index, for example.
4227
4228      This means that the lookup names passed to the symbol name
4229      matcher functions must have no parameter information either
4230      because (e.g.) symbol search name "foo" does not match
4231      lookup-name "foo(int)" [while swapping search name for lookup
4232      name would match].
4233 */
4234 class gdb_index_symbol_name_matcher
4235 {
4236 public:
4237   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4238   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4239
4240   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4241      Returns true if any matcher matches.  */
4242   bool matches (const char *symbol_name);
4243
4244 private:
4245   /* A reference to the lookup name we're matching against.  */
4246   const lookup_name_info &m_lookup_name;
4247
4248   /* A vector holding all the different symbol name matchers, for all
4249      languages.  */
4250   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4251 };
4252
4253 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4254   (const lookup_name_info &lookup_name)
4255     : m_lookup_name (lookup_name)
4256 {
4257   /* Prepare the vector of comparison functions upfront, to avoid
4258      doing the same work for each symbol.  Care is taken to avoid
4259      matching with the same matcher more than once if/when multiple
4260      languages use the same matcher function.  */
4261   auto &matchers = m_symbol_name_matcher_funcs;
4262   matchers.reserve (nr_languages);
4263
4264   matchers.push_back (default_symbol_name_matcher);
4265
4266   for (int i = 0; i < nr_languages; i++)
4267     {
4268       const language_defn *lang = language_def ((enum language) i);
4269       symbol_name_matcher_ftype *name_matcher
4270         = get_symbol_name_matcher (lang, m_lookup_name);
4271
4272       /* Don't insert the same comparison routine more than once.
4273          Note that we do this linear walk instead of a seemingly
4274          cheaper sorted insert, or use a std::set or something like
4275          that, because relative order of function addresses is not
4276          stable.  This is not a problem in practice because the number
4277          of supported languages is low, and the cost here is tiny
4278          compared to the number of searches we'll do afterwards using
4279          this object.  */
4280       if (name_matcher != default_symbol_name_matcher
4281           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4282               == matchers.end ()))
4283         matchers.push_back (name_matcher);
4284     }
4285 }
4286
4287 bool
4288 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4289 {
4290   for (auto matches_name : m_symbol_name_matcher_funcs)
4291     if (matches_name (symbol_name, m_lookup_name, NULL))
4292       return true;
4293
4294   return false;
4295 }
4296
4297 /* Starting from a search name, return the string that finds the upper
4298    bound of all strings that start with SEARCH_NAME in a sorted name
4299    list.  Returns the empty string to indicate that the upper bound is
4300    the end of the list.  */
4301
4302 static std::string
4303 make_sort_after_prefix_name (const char *search_name)
4304 {
4305   /* When looking to complete "func", we find the upper bound of all
4306      symbols that start with "func" by looking for where we'd insert
4307      the closest string that would follow "func" in lexicographical
4308      order.  Usually, that's "func"-with-last-character-incremented,
4309      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4310      will be UTF-8 multi-byte sequences, but we can't be certain.
4311      Especially mind the 0xff character, which is a valid character in
4312      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4313      rule out compilers allowing it in identifiers.  Note that
4314      conveniently, strcmp/strcasecmp are specified to compare
4315      characters interpreted as unsigned char.  So what we do is treat
4316      the whole string as a base 256 number composed of a sequence of
4317      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4318      to 0, and carries 1 to the following more-significant position.
4319      If the very first character in SEARCH_NAME ends up incremented
4320      and carries/overflows, then the upper bound is the end of the
4321      list.  The string after the empty string is also the empty
4322      string.
4323
4324      Some examples of this operation:
4325
4326        SEARCH_NAME  => "+1" RESULT
4327
4328        "abc"              => "abd"
4329        "ab\xff"           => "ac"
4330        "\xff" "a" "\xff"  => "\xff" "b"
4331        "\xff"             => ""
4332        "\xff\xff"         => ""
4333        ""                 => ""
4334
4335      Then, with these symbols for example:
4336
4337       func
4338       func1
4339       fund
4340
4341      completing "func" looks for symbols between "func" and
4342      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4343      which finds "func" and "func1", but not "fund".
4344
4345      And with:
4346
4347       funcÿ     (Latin1 'ÿ' [0xff])
4348       funcÿ1
4349       fund
4350
4351      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4352      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4353
4354      And with:
4355
4356       ÿÿ        (Latin1 'ÿ' [0xff])
4357       ÿÿ1
4358
4359      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4360      the end of the list.
4361   */
4362   std::string after = search_name;
4363   while (!after.empty () && (unsigned char) after.back () == 0xff)
4364     after.pop_back ();
4365   if (!after.empty ())
4366     after.back () = (unsigned char) after.back () + 1;
4367   return after;
4368 }
4369
4370 /* See declaration.  */
4371
4372 std::pair<std::vector<name_component>::const_iterator,
4373           std::vector<name_component>::const_iterator>
4374 mapped_index_base::find_name_components_bounds
4375   (const lookup_name_info &lookup_name_without_params) const
4376 {
4377   auto *name_cmp
4378     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4379
4380   const char *cplus
4381     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4382
4383   /* Comparison function object for lower_bound that matches against a
4384      given symbol name.  */
4385   auto lookup_compare_lower = [&] (const name_component &elem,
4386                                    const char *name)
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 (elem_name, name) < 0;
4391     };
4392
4393   /* Comparison function object for upper_bound that matches against a
4394      given symbol name.  */
4395   auto lookup_compare_upper = [&] (const char *name,
4396                                    const name_component &elem)
4397     {
4398       const char *elem_qualified = this->symbol_name_at (elem.idx);
4399       const char *elem_name = elem_qualified + elem.name_offset;
4400       return name_cmp (name, elem_name) < 0;
4401     };
4402
4403   auto begin = this->name_components.begin ();
4404   auto end = this->name_components.end ();
4405
4406   /* Find the lower bound.  */
4407   auto lower = [&] ()
4408     {
4409       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4410         return begin;
4411       else
4412         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4413     } ();
4414
4415   /* Find the upper bound.  */
4416   auto upper = [&] ()
4417     {
4418       if (lookup_name_without_params.completion_mode ())
4419         {
4420           /* In completion mode, we want UPPER to point past all
4421              symbols names that have the same prefix.  I.e., with
4422              these symbols, and completing "func":
4423
4424               function        << lower bound
4425               function1
4426               other_function  << upper bound
4427
4428              We find the upper bound by looking for the insertion
4429              point of "func"-with-last-character-incremented,
4430              i.e. "fund".  */
4431           std::string after = make_sort_after_prefix_name (cplus);
4432           if (after.empty ())
4433             return end;
4434           return std::lower_bound (lower, end, after.c_str (),
4435                                    lookup_compare_lower);
4436         }
4437       else
4438         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4439     } ();
4440
4441   return {lower, upper};
4442 }
4443
4444 /* See declaration.  */
4445
4446 void
4447 mapped_index_base::build_name_components ()
4448 {
4449   if (!this->name_components.empty ())
4450     return;
4451
4452   this->name_components_casing = case_sensitivity;
4453   auto *name_cmp
4454     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4455
4456   /* The code below only knows how to break apart components of C++
4457      symbol names (and other languages that use '::' as
4458      namespace/module separator).  If we add support for wild matching
4459      to some language that uses some other operator (E.g., Ada, Go and
4460      D use '.'), then we'll need to try splitting the symbol name
4461      according to that language too.  Note that Ada does support wild
4462      matching, but doesn't currently support .gdb_index.  */
4463   auto count = this->symbol_name_count ();
4464   for (offset_type idx = 0; idx < count; idx++)
4465     {
4466       if (this->symbol_name_slot_invalid (idx))
4467         continue;
4468
4469       const char *name = this->symbol_name_at (idx);
4470
4471       /* Add each name component to the name component table.  */
4472       unsigned int previous_len = 0;
4473       for (unsigned int current_len = cp_find_first_component (name);
4474            name[current_len] != '\0';
4475            current_len += cp_find_first_component (name + current_len))
4476         {
4477           gdb_assert (name[current_len] == ':');
4478           this->name_components.push_back ({previous_len, idx});
4479           /* Skip the '::'.  */
4480           current_len += 2;
4481           previous_len = current_len;
4482         }
4483       this->name_components.push_back ({previous_len, idx});
4484     }
4485
4486   /* Sort name_components elements by name.  */
4487   auto name_comp_compare = [&] (const name_component &left,
4488                                 const name_component &right)
4489     {
4490       const char *left_qualified = this->symbol_name_at (left.idx);
4491       const char *right_qualified = this->symbol_name_at (right.idx);
4492
4493       const char *left_name = left_qualified + left.name_offset;
4494       const char *right_name = right_qualified + right.name_offset;
4495
4496       return name_cmp (left_name, right_name) < 0;
4497     };
4498
4499   std::sort (this->name_components.begin (),
4500              this->name_components.end (),
4501              name_comp_compare);
4502 }
4503
4504 /* Helper for dw2_expand_symtabs_matching that works with a
4505    mapped_index_base instead of the containing objfile.  This is split
4506    to a separate function in order to be able to unit test the
4507    name_components matching using a mock mapped_index_base.  For each
4508    symbol name that matches, calls MATCH_CALLBACK, passing it the
4509    symbol's index in the mapped_index_base symbol table.  */
4510
4511 static void
4512 dw2_expand_symtabs_matching_symbol
4513   (mapped_index_base &index,
4514    const lookup_name_info &lookup_name_in,
4515    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4516    enum search_domain kind,
4517    gdb::function_view<void (offset_type)> match_callback)
4518 {
4519   lookup_name_info lookup_name_without_params
4520     = lookup_name_in.make_ignore_params ();
4521   gdb_index_symbol_name_matcher lookup_name_matcher
4522     (lookup_name_without_params);
4523
4524   /* Build the symbol name component sorted vector, if we haven't
4525      yet.  */
4526   index.build_name_components ();
4527
4528   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4529
4530   /* Now for each symbol name in range, check to see if we have a name
4531      match, and if so, call the MATCH_CALLBACK callback.  */
4532
4533   /* The same symbol may appear more than once in the range though.
4534      E.g., if we're looking for symbols that complete "w", and we have
4535      a symbol named "w1::w2", we'll find the two name components for
4536      that same symbol in the range.  To be sure we only call the
4537      callback once per symbol, we first collect the symbol name
4538      indexes that matched in a temporary vector and ignore
4539      duplicates.  */
4540   std::vector<offset_type> matches;
4541   matches.reserve (std::distance (bounds.first, bounds.second));
4542
4543   for (; bounds.first != bounds.second; ++bounds.first)
4544     {
4545       const char *qualified = index.symbol_name_at (bounds.first->idx);
4546
4547       if (!lookup_name_matcher.matches (qualified)
4548           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4549         continue;
4550
4551       matches.push_back (bounds.first->idx);
4552     }
4553
4554   std::sort (matches.begin (), matches.end ());
4555
4556   /* Finally call the callback, once per match.  */
4557   ULONGEST prev = -1;
4558   for (offset_type idx : matches)
4559     {
4560       if (prev != idx)
4561         {
4562           match_callback (idx);
4563           prev = idx;
4564         }
4565     }
4566
4567   /* Above we use a type wider than idx's for 'prev', since 0 and
4568      (offset_type)-1 are both possible values.  */
4569   static_assert (sizeof (prev) > sizeof (offset_type), "");
4570 }
4571
4572 #if GDB_SELF_TEST
4573
4574 namespace selftests { namespace dw2_expand_symtabs_matching {
4575
4576 /* A mock .gdb_index/.debug_names-like name index table, enough to
4577    exercise dw2_expand_symtabs_matching_symbol, which works with the
4578    mapped_index_base interface.  Builds an index from the symbol list
4579    passed as parameter to the constructor.  */
4580 class mock_mapped_index : public mapped_index_base
4581 {
4582 public:
4583   mock_mapped_index (gdb::array_view<const char *> symbols)
4584     : m_symbol_table (symbols)
4585   {}
4586
4587   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4588
4589   /* Return the number of names in the symbol table.  */
4590   virtual size_t symbol_name_count () const
4591   {
4592     return m_symbol_table.size ();
4593   }
4594
4595   /* Get the name of the symbol at IDX in the symbol table.  */
4596   virtual const char *symbol_name_at (offset_type idx) const
4597   {
4598     return m_symbol_table[idx];
4599   }
4600
4601 private:
4602   gdb::array_view<const char *> m_symbol_table;
4603 };
4604
4605 /* Convenience function that converts a NULL pointer to a "<null>"
4606    string, to pass to print routines.  */
4607
4608 static const char *
4609 string_or_null (const char *str)
4610 {
4611   return str != NULL ? str : "<null>";
4612 }
4613
4614 /* Check if a lookup_name_info built from
4615    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4616    index.  EXPECTED_LIST is the list of expected matches, in expected
4617    matching order.  If no match expected, then an empty list is
4618    specified.  Returns true on success.  On failure prints a warning
4619    indicating the file:line that failed, and returns false.  */
4620
4621 static bool
4622 check_match (const char *file, int line,
4623              mock_mapped_index &mock_index,
4624              const char *name, symbol_name_match_type match_type,
4625              bool completion_mode,
4626              std::initializer_list<const char *> expected_list)
4627 {
4628   lookup_name_info lookup_name (name, match_type, completion_mode);
4629
4630   bool matched = true;
4631
4632   auto mismatch = [&] (const char *expected_str,
4633                        const char *got)
4634   {
4635     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4636                "expected=\"%s\", got=\"%s\"\n"),
4637              file, line,
4638              (match_type == symbol_name_match_type::FULL
4639               ? "FULL" : "WILD"),
4640              name, string_or_null (expected_str), string_or_null (got));
4641     matched = false;
4642   };
4643
4644   auto expected_it = expected_list.begin ();
4645   auto expected_end = expected_list.end ();
4646
4647   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4648                                       NULL, ALL_DOMAIN,
4649                                       [&] (offset_type idx)
4650   {
4651     const char *matched_name = mock_index.symbol_name_at (idx);
4652     const char *expected_str
4653       = expected_it == expected_end ? NULL : *expected_it++;
4654
4655     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4656       mismatch (expected_str, matched_name);
4657   });
4658
4659   const char *expected_str
4660   = expected_it == expected_end ? NULL : *expected_it++;
4661   if (expected_str != NULL)
4662     mismatch (expected_str, NULL);
4663
4664   return matched;
4665 }
4666
4667 /* The symbols added to the mock mapped_index for testing (in
4668    canonical form).  */
4669 static const char *test_symbols[] = {
4670   "function",
4671   "std::bar",
4672   "std::zfunction",
4673   "std::zfunction2",
4674   "w1::w2",
4675   "ns::foo<char*>",
4676   "ns::foo<int>",
4677   "ns::foo<long>",
4678   "ns2::tmpl<int>::foo2",
4679   "(anonymous namespace)::A::B::C",
4680
4681   /* These are used to check that the increment-last-char in the
4682      matching algorithm for completion doesn't match "t1_fund" when
4683      completing "t1_func".  */
4684   "t1_func",
4685   "t1_func1",
4686   "t1_fund",
4687   "t1_fund1",
4688
4689   /* A UTF-8 name with multi-byte sequences to make sure that
4690      cp-name-parser understands this as a single identifier ("função"
4691      is "function" in PT).  */
4692   u8"u8função",
4693
4694   /* \377 (0xff) is Latin1 'ÿ'.  */
4695   "yfunc\377",
4696
4697   /* \377 (0xff) is Latin1 'ÿ'.  */
4698   "\377",
4699   "\377\377123",
4700
4701   /* A name with all sorts of complications.  Starts with "z" to make
4702      it easier for the completion tests below.  */
4703 #define Z_SYM_NAME \
4704   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4705     "::tuple<(anonymous namespace)::ui*, " \
4706     "std::default_delete<(anonymous namespace)::ui>, void>"
4707
4708   Z_SYM_NAME
4709 };
4710
4711 /* Returns true if the mapped_index_base::find_name_component_bounds
4712    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4713    in completion mode.  */
4714
4715 static bool
4716 check_find_bounds_finds (mapped_index_base &index,
4717                          const char *search_name,
4718                          gdb::array_view<const char *> expected_syms)
4719 {
4720   lookup_name_info lookup_name (search_name,
4721                                 symbol_name_match_type::FULL, true);
4722
4723   auto bounds = index.find_name_components_bounds (lookup_name);
4724
4725   size_t distance = std::distance (bounds.first, bounds.second);
4726   if (distance != expected_syms.size ())
4727     return false;
4728
4729   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4730     {
4731       auto nc_elem = bounds.first + exp_elem;
4732       const char *qualified = index.symbol_name_at (nc_elem->idx);
4733       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4734         return false;
4735     }
4736
4737   return true;
4738 }
4739
4740 /* Test the lower-level mapped_index::find_name_component_bounds
4741    method.  */
4742
4743 static void
4744 test_mapped_index_find_name_component_bounds ()
4745 {
4746   mock_mapped_index mock_index (test_symbols);
4747
4748   mock_index.build_name_components ();
4749
4750   /* Test the lower-level mapped_index::find_name_component_bounds
4751      method in completion mode.  */
4752   {
4753     static const char *expected_syms[] = {
4754       "t1_func",
4755       "t1_func1",
4756     };
4757
4758     SELF_CHECK (check_find_bounds_finds (mock_index,
4759                                          "t1_func", expected_syms));
4760   }
4761
4762   /* Check that the increment-last-char in the name matching algorithm
4763      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4764   {
4765     static const char *expected_syms1[] = {
4766       "\377",
4767       "\377\377123",
4768     };
4769     SELF_CHECK (check_find_bounds_finds (mock_index,
4770                                          "\377", expected_syms1));
4771
4772     static const char *expected_syms2[] = {
4773       "\377\377123",
4774     };
4775     SELF_CHECK (check_find_bounds_finds (mock_index,
4776                                          "\377\377", expected_syms2));
4777   }
4778 }
4779
4780 /* Test dw2_expand_symtabs_matching_symbol.  */
4781
4782 static void
4783 test_dw2_expand_symtabs_matching_symbol ()
4784 {
4785   mock_mapped_index mock_index (test_symbols);
4786
4787   /* We let all tests run until the end even if some fails, for debug
4788      convenience.  */
4789   bool any_mismatch = false;
4790
4791   /* Create the expected symbols list (an initializer_list).  Needed
4792      because lists have commas, and we need to pass them to CHECK,
4793      which is a macro.  */
4794 #define EXPECT(...) { __VA_ARGS__ }
4795
4796   /* Wrapper for check_match that passes down the current
4797      __FILE__/__LINE__.  */
4798 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4799   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4800                                 mock_index,                             \
4801                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4802                                 EXPECTED_LIST)
4803
4804   /* Identity checks.  */
4805   for (const char *sym : test_symbols)
4806     {
4807       /* Should be able to match all existing symbols.  */
4808       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4809                    EXPECT (sym));
4810
4811       /* Should be able to match all existing symbols with
4812          parameters.  */
4813       std::string with_params = std::string (sym) + "(int)";
4814       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4815                    EXPECT (sym));
4816
4817       /* Should be able to match all existing symbols with
4818          parameters and qualifiers.  */
4819       with_params = std::string (sym) + " ( int ) const";
4820       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4821                    EXPECT (sym));
4822
4823       /* This should really find sym, but cp-name-parser.y doesn't
4824          know about lvalue/rvalue qualifiers yet.  */
4825       with_params = std::string (sym) + " ( int ) &&";
4826       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4827                    {});
4828     }
4829
4830   /* Check that the name matching algorithm for completion doesn't get
4831      confused with Latin1 'ÿ' / 0xff.  */
4832   {
4833     static const char str[] = "\377";
4834     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4835                  EXPECT ("\377", "\377\377123"));
4836   }
4837
4838   /* Check that the increment-last-char in the matching algorithm for
4839      completion doesn't match "t1_fund" when completing "t1_func".  */
4840   {
4841     static const char str[] = "t1_func";
4842     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4843                  EXPECT ("t1_func", "t1_func1"));
4844   }
4845
4846   /* Check that completion mode works at each prefix of the expected
4847      symbol name.  */
4848   {
4849     static const char str[] = "function(int)";
4850     size_t len = strlen (str);
4851     std::string lookup;
4852
4853     for (size_t i = 1; i < len; i++)
4854       {
4855         lookup.assign (str, i);
4856         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4857                      EXPECT ("function"));
4858       }
4859   }
4860
4861   /* While "w" is a prefix of both components, the match function
4862      should still only be called once.  */
4863   {
4864     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4865                  EXPECT ("w1::w2"));
4866     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4867                  EXPECT ("w1::w2"));
4868   }
4869
4870   /* Same, with a "complicated" symbol.  */
4871   {
4872     static const char str[] = Z_SYM_NAME;
4873     size_t len = strlen (str);
4874     std::string lookup;
4875
4876     for (size_t i = 1; i < len; i++)
4877       {
4878         lookup.assign (str, i);
4879         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4880                      EXPECT (Z_SYM_NAME));
4881       }
4882   }
4883
4884   /* In FULL mode, an incomplete symbol doesn't match.  */
4885   {
4886     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4887                  {});
4888   }
4889
4890   /* A complete symbol with parameters matches any overload, since the
4891      index has no overload info.  */
4892   {
4893     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4894                  EXPECT ("std::zfunction", "std::zfunction2"));
4895     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4896                  EXPECT ("std::zfunction", "std::zfunction2"));
4897     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4898                  EXPECT ("std::zfunction", "std::zfunction2"));
4899   }
4900
4901   /* Check that whitespace is ignored appropriately.  A symbol with a
4902      template argument list. */
4903   {
4904     static const char expected[] = "ns::foo<int>";
4905     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4906                  EXPECT (expected));
4907     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4908                  EXPECT (expected));
4909   }
4910
4911   /* Check that whitespace is ignored appropriately.  A symbol with a
4912      template argument list that includes a pointer.  */
4913   {
4914     static const char expected[] = "ns::foo<char*>";
4915     /* Try both completion and non-completion modes.  */
4916     static const bool completion_mode[2] = {false, true};
4917     for (size_t i = 0; i < 2; i++)
4918       {
4919         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4920                      completion_mode[i], EXPECT (expected));
4921         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4922                      completion_mode[i], EXPECT (expected));
4923
4924         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4925                      completion_mode[i], EXPECT (expected));
4926         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4927                      completion_mode[i], EXPECT (expected));
4928       }
4929   }
4930
4931   {
4932     /* Check method qualifiers are ignored.  */
4933     static const char expected[] = "ns::foo<char*>";
4934     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4935                  symbol_name_match_type::FULL, true, EXPECT (expected));
4936     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4937                  symbol_name_match_type::FULL, true, EXPECT (expected));
4938     CHECK_MATCH ("foo < char * >  ( int ) const",
4939                  symbol_name_match_type::WILD, true, EXPECT (expected));
4940     CHECK_MATCH ("foo < char * >  ( int ) &&",
4941                  symbol_name_match_type::WILD, true, EXPECT (expected));
4942   }
4943
4944   /* Test lookup names that don't match anything.  */
4945   {
4946     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4947                  {});
4948
4949     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4950                  {});
4951   }
4952
4953   /* Some wild matching tests, exercising "(anonymous namespace)",
4954      which should not be confused with a parameter list.  */
4955   {
4956     static const char *syms[] = {
4957       "A::B::C",
4958       "B::C",
4959       "C",
4960       "A :: B :: C ( int )",
4961       "B :: C ( int )",
4962       "C ( int )",
4963     };
4964
4965     for (const char *s : syms)
4966       {
4967         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4968                      EXPECT ("(anonymous namespace)::A::B::C"));
4969       }
4970   }
4971
4972   {
4973     static const char expected[] = "ns2::tmpl<int>::foo2";
4974     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4975                  EXPECT (expected));
4976     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4977                  EXPECT (expected));
4978   }
4979
4980   SELF_CHECK (!any_mismatch);
4981
4982 #undef EXPECT
4983 #undef CHECK_MATCH
4984 }
4985
4986 static void
4987 run_test ()
4988 {
4989   test_mapped_index_find_name_component_bounds ();
4990   test_dw2_expand_symtabs_matching_symbol ();
4991 }
4992
4993 }} // namespace selftests::dw2_expand_symtabs_matching
4994
4995 #endif /* GDB_SELF_TEST */
4996
4997 /* If FILE_MATCHER is NULL or if PER_CU has
4998    dwarf2_per_cu_quick_data::MARK set (see
4999    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5000    EXPANSION_NOTIFY on it.  */
5001
5002 static void
5003 dw2_expand_symtabs_matching_one
5004   (struct dwarf2_per_cu_data *per_cu,
5005    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5006    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5007 {
5008   if (file_matcher == NULL || per_cu->v.quick->mark)
5009     {
5010       bool symtab_was_null
5011         = (per_cu->v.quick->compunit_symtab == NULL);
5012
5013       dw2_instantiate_symtab (per_cu);
5014
5015       if (expansion_notify != NULL
5016           && symtab_was_null
5017           && per_cu->v.quick->compunit_symtab != NULL)
5018         expansion_notify (per_cu->v.quick->compunit_symtab);
5019     }
5020 }
5021
5022 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5023    matched, to expand corresponding CUs that were marked.  IDX is the
5024    index of the symbol name that matched.  */
5025
5026 static void
5027 dw2_expand_marked_cus
5028   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5029    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5030    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5031    search_domain kind)
5032 {
5033   offset_type *vec, vec_len, vec_idx;
5034   bool global_seen = false;
5035   mapped_index &index = *dwarf2_per_objfile->index_table;
5036
5037   vec = (offset_type *) (index.constant_pool
5038                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5039   vec_len = MAYBE_SWAP (vec[0]);
5040   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5041     {
5042       struct dwarf2_per_cu_data *per_cu;
5043       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5044       /* This value is only valid for index versions >= 7.  */
5045       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5046       gdb_index_symbol_kind symbol_kind =
5047         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5048       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5049       /* Only check the symbol attributes if they're present.
5050          Indices prior to version 7 don't record them,
5051          and indices >= 7 may elide them for certain symbols
5052          (gold does this).  */
5053       int attrs_valid =
5054         (index.version >= 7
5055          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5056
5057       /* Work around gold/15646.  */
5058       if (attrs_valid)
5059         {
5060           if (!is_static && global_seen)
5061             continue;
5062           if (!is_static)
5063             global_seen = true;
5064         }
5065
5066       /* Only check the symbol's kind if it has one.  */
5067       if (attrs_valid)
5068         {
5069           switch (kind)
5070             {
5071             case VARIABLES_DOMAIN:
5072               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5073                 continue;
5074               break;
5075             case FUNCTIONS_DOMAIN:
5076               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5077                 continue;
5078               break;
5079             case TYPES_DOMAIN:
5080               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5081                 continue;
5082               break;
5083             default:
5084               break;
5085             }
5086         }
5087
5088       /* Don't crash on bad data.  */
5089       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5090                        + dwarf2_per_objfile->n_type_units))
5091         {
5092           complaint (&symfile_complaints,
5093                      _(".gdb_index entry has bad CU index"
5094                        " [in module %s]"),
5095                        objfile_name (dwarf2_per_objfile->objfile));
5096           continue;
5097         }
5098
5099       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5100       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5101                                        expansion_notify);
5102     }
5103 }
5104
5105 /* If FILE_MATCHER is non-NULL, set all the
5106    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5107    that match FILE_MATCHER.  */
5108
5109 static void
5110 dw_expand_symtabs_matching_file_matcher
5111   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5112    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5113 {
5114   if (file_matcher == NULL)
5115     return;
5116
5117   objfile *const objfile = dwarf2_per_objfile->objfile;
5118
5119   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5120                                             htab_eq_pointer,
5121                                             NULL, xcalloc, xfree));
5122   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5123                                                 htab_eq_pointer,
5124                                                 NULL, xcalloc, xfree));
5125
5126   /* The rule is CUs specify all the files, including those used by
5127      any TU, so there's no need to scan TUs here.  */
5128
5129   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5130     {
5131       int j;
5132       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5133       struct quick_file_names *file_data;
5134       void **slot;
5135
5136       QUIT;
5137
5138       per_cu->v.quick->mark = 0;
5139
5140       /* We only need to look at symtabs not already expanded.  */
5141       if (per_cu->v.quick->compunit_symtab)
5142         continue;
5143
5144       file_data = dw2_get_file_names (per_cu);
5145       if (file_data == NULL)
5146         continue;
5147
5148       if (htab_find (visited_not_found.get (), file_data) != NULL)
5149         continue;
5150       else if (htab_find (visited_found.get (), file_data) != NULL)
5151         {
5152           per_cu->v.quick->mark = 1;
5153           continue;
5154         }
5155
5156       for (j = 0; j < file_data->num_file_names; ++j)
5157         {
5158           const char *this_real_name;
5159
5160           if (file_matcher (file_data->file_names[j], false))
5161             {
5162               per_cu->v.quick->mark = 1;
5163               break;
5164             }
5165
5166           /* Before we invoke realpath, which can get expensive when many
5167              files are involved, do a quick comparison of the basenames.  */
5168           if (!basenames_may_differ
5169               && !file_matcher (lbasename (file_data->file_names[j]),
5170                                 true))
5171             continue;
5172
5173           this_real_name = dw2_get_real_path (objfile, file_data, j);
5174           if (file_matcher (this_real_name, false))
5175             {
5176               per_cu->v.quick->mark = 1;
5177               break;
5178             }
5179         }
5180
5181       slot = htab_find_slot (per_cu->v.quick->mark
5182                              ? visited_found.get ()
5183                              : visited_not_found.get (),
5184                              file_data, INSERT);
5185       *slot = file_data;
5186     }
5187 }
5188
5189 static void
5190 dw2_expand_symtabs_matching
5191   (struct objfile *objfile,
5192    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5193    const lookup_name_info &lookup_name,
5194    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5195    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5196    enum search_domain kind)
5197 {
5198   struct dwarf2_per_objfile *dwarf2_per_objfile
5199     = get_dwarf2_per_objfile (objfile);
5200
5201   /* index_table is NULL if OBJF_READNOW.  */
5202   if (!dwarf2_per_objfile->index_table)
5203     return;
5204
5205   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5206
5207   mapped_index &index = *dwarf2_per_objfile->index_table;
5208
5209   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5210                                       symbol_matcher,
5211                                       kind, [&] (offset_type idx)
5212     {
5213       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5214                              expansion_notify, kind);
5215     });
5216 }
5217
5218 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5219    symtab.  */
5220
5221 static struct compunit_symtab *
5222 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5223                                           CORE_ADDR pc)
5224 {
5225   int i;
5226
5227   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5228       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5229     return cust;
5230
5231   if (cust->includes == NULL)
5232     return NULL;
5233
5234   for (i = 0; cust->includes[i]; ++i)
5235     {
5236       struct compunit_symtab *s = cust->includes[i];
5237
5238       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5239       if (s != NULL)
5240         return s;
5241     }
5242
5243   return NULL;
5244 }
5245
5246 static struct compunit_symtab *
5247 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5248                                   struct bound_minimal_symbol msymbol,
5249                                   CORE_ADDR pc,
5250                                   struct obj_section *section,
5251                                   int warn_if_readin)
5252 {
5253   struct dwarf2_per_cu_data *data;
5254   struct compunit_symtab *result;
5255
5256   if (!objfile->psymtabs_addrmap)
5257     return NULL;
5258
5259   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5260                                                      pc);
5261   if (!data)
5262     return NULL;
5263
5264   if (warn_if_readin && data->v.quick->compunit_symtab)
5265     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5266              paddress (get_objfile_arch (objfile), pc));
5267
5268   result
5269     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5270                                                 pc);
5271   gdb_assert (result != NULL);
5272   return result;
5273 }
5274
5275 static void
5276 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5277                           void *data, int need_fullname)
5278 {
5279   struct dwarf2_per_objfile *dwarf2_per_objfile
5280     = get_dwarf2_per_objfile (objfile);
5281
5282   if (!dwarf2_per_objfile->filenames_cache)
5283     {
5284       dwarf2_per_objfile->filenames_cache.emplace ();
5285
5286       htab_up visited (htab_create_alloc (10,
5287                                           htab_hash_pointer, htab_eq_pointer,
5288                                           NULL, xcalloc, xfree));
5289
5290       /* The rule is CUs specify all the files, including those used
5291          by any TU, so there's no need to scan TUs here.  We can
5292          ignore file names coming from already-expanded CUs.  */
5293
5294       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5295         {
5296           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5297
5298           if (per_cu->v.quick->compunit_symtab)
5299             {
5300               void **slot = htab_find_slot (visited.get (),
5301                                             per_cu->v.quick->file_names,
5302                                             INSERT);
5303
5304               *slot = per_cu->v.quick->file_names;
5305             }
5306         }
5307
5308       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5309         {
5310           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5311           struct quick_file_names *file_data;
5312           void **slot;
5313
5314           /* We only need to look at symtabs not already expanded.  */
5315           if (per_cu->v.quick->compunit_symtab)
5316             continue;
5317
5318           file_data = dw2_get_file_names (per_cu);
5319           if (file_data == NULL)
5320             continue;
5321
5322           slot = htab_find_slot (visited.get (), file_data, INSERT);
5323           if (*slot)
5324             {
5325               /* Already visited.  */
5326               continue;
5327             }
5328           *slot = file_data;
5329
5330           for (int j = 0; j < file_data->num_file_names; ++j)
5331             {
5332               const char *filename = file_data->file_names[j];
5333               dwarf2_per_objfile->filenames_cache->seen (filename);
5334             }
5335         }
5336     }
5337
5338   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5339     {
5340       gdb::unique_xmalloc_ptr<char> this_real_name;
5341
5342       if (need_fullname)
5343         this_real_name = gdb_realpath (filename);
5344       (*fun) (filename, this_real_name.get (), data);
5345     });
5346 }
5347
5348 static int
5349 dw2_has_symbols (struct objfile *objfile)
5350 {
5351   return 1;
5352 }
5353
5354 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5355 {
5356   dw2_has_symbols,
5357   dw2_find_last_source_symtab,
5358   dw2_forget_cached_source_info,
5359   dw2_map_symtabs_matching_filename,
5360   dw2_lookup_symbol,
5361   dw2_print_stats,
5362   dw2_dump,
5363   dw2_relocate,
5364   dw2_expand_symtabs_for_function,
5365   dw2_expand_all_symtabs,
5366   dw2_expand_symtabs_with_fullname,
5367   dw2_map_matching_symbols,
5368   dw2_expand_symtabs_matching,
5369   dw2_find_pc_sect_compunit_symtab,
5370   NULL,
5371   dw2_map_symbol_filenames
5372 };
5373
5374 /* DWARF-5 debug_names reader.  */
5375
5376 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5377 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5378
5379 /* A helper function that reads the .debug_names section in SECTION
5380    and fills in MAP.  FILENAME is the name of the file containing the
5381    section; it is used for error reporting.
5382
5383    Returns true if all went well, false otherwise.  */
5384
5385 static bool
5386 read_debug_names_from_section (struct objfile *objfile,
5387                                const char *filename,
5388                                struct dwarf2_section_info *section,
5389                                mapped_debug_names &map)
5390 {
5391   if (dwarf2_section_empty_p (section))
5392     return false;
5393
5394   /* Older elfutils strip versions could keep the section in the main
5395      executable while splitting it for the separate debug info file.  */
5396   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5397     return false;
5398
5399   dwarf2_read_section (objfile, section);
5400
5401   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5402
5403   const gdb_byte *addr = section->buffer;
5404
5405   bfd *const abfd = get_section_bfd_owner (section);
5406
5407   unsigned int bytes_read;
5408   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5409   addr += bytes_read;
5410
5411   map.dwarf5_is_dwarf64 = bytes_read != 4;
5412   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5413   if (bytes_read + length != section->size)
5414     {
5415       /* There may be multiple per-CU indices.  */
5416       warning (_("Section .debug_names in %s length %s does not match "
5417                  "section length %s, ignoring .debug_names."),
5418                filename, plongest (bytes_read + length),
5419                pulongest (section->size));
5420       return false;
5421     }
5422
5423   /* The version number.  */
5424   uint16_t version = read_2_bytes (abfd, addr);
5425   addr += 2;
5426   if (version != 5)
5427     {
5428       warning (_("Section .debug_names in %s has unsupported version %d, "
5429                  "ignoring .debug_names."),
5430                filename, version);
5431       return false;
5432     }
5433
5434   /* Padding.  */
5435   uint16_t padding = read_2_bytes (abfd, addr);
5436   addr += 2;
5437   if (padding != 0)
5438     {
5439       warning (_("Section .debug_names in %s has unsupported padding %d, "
5440                  "ignoring .debug_names."),
5441                filename, padding);
5442       return false;
5443     }
5444
5445   /* comp_unit_count - The number of CUs in the CU list.  */
5446   map.cu_count = read_4_bytes (abfd, addr);
5447   addr += 4;
5448
5449   /* local_type_unit_count - The number of TUs in the local TU
5450      list.  */
5451   map.tu_count = read_4_bytes (abfd, addr);
5452   addr += 4;
5453
5454   /* foreign_type_unit_count - The number of TUs in the foreign TU
5455      list.  */
5456   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5457   addr += 4;
5458   if (foreign_tu_count != 0)
5459     {
5460       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5461                  "ignoring .debug_names."),
5462                filename, static_cast<unsigned long> (foreign_tu_count));
5463       return false;
5464     }
5465
5466   /* bucket_count - The number of hash buckets in the hash lookup
5467      table.  */
5468   map.bucket_count = read_4_bytes (abfd, addr);
5469   addr += 4;
5470
5471   /* name_count - The number of unique names in the index.  */
5472   map.name_count = read_4_bytes (abfd, addr);
5473   addr += 4;
5474
5475   /* abbrev_table_size - The size in bytes of the abbreviations
5476      table.  */
5477   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5478   addr += 4;
5479
5480   /* augmentation_string_size - The size in bytes of the augmentation
5481      string.  This value is rounded up to a multiple of 4.  */
5482   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5483   addr += 4;
5484   map.augmentation_is_gdb = ((augmentation_string_size
5485                               == sizeof (dwarf5_augmentation))
5486                              && memcmp (addr, dwarf5_augmentation,
5487                                         sizeof (dwarf5_augmentation)) == 0);
5488   augmentation_string_size += (-augmentation_string_size) & 3;
5489   addr += augmentation_string_size;
5490
5491   /* List of CUs */
5492   map.cu_table_reordered = addr;
5493   addr += map.cu_count * map.offset_size;
5494
5495   /* List of Local TUs */
5496   map.tu_table_reordered = addr;
5497   addr += map.tu_count * map.offset_size;
5498
5499   /* Hash Lookup Table */
5500   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5501   addr += map.bucket_count * 4;
5502   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5503   addr += map.name_count * 4;
5504
5505   /* Name Table */
5506   map.name_table_string_offs_reordered = addr;
5507   addr += map.name_count * map.offset_size;
5508   map.name_table_entry_offs_reordered = addr;
5509   addr += map.name_count * map.offset_size;
5510
5511   const gdb_byte *abbrev_table_start = addr;
5512   for (;;)
5513     {
5514       unsigned int bytes_read;
5515       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5516       addr += bytes_read;
5517       if (index_num == 0)
5518         break;
5519
5520       const auto insertpair
5521         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5522       if (!insertpair.second)
5523         {
5524           warning (_("Section .debug_names in %s has duplicate index %s, "
5525                      "ignoring .debug_names."),
5526                    filename, pulongest (index_num));
5527           return false;
5528         }
5529       mapped_debug_names::index_val &indexval = insertpair.first->second;
5530       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5531       addr += bytes_read;
5532
5533       for (;;)
5534         {
5535           mapped_debug_names::index_val::attr attr;
5536           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5537           addr += bytes_read;
5538           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5539           addr += bytes_read;
5540           if (attr.form == DW_FORM_implicit_const)
5541             {
5542               attr.implicit_const = read_signed_leb128 (abfd, addr,
5543                                                         &bytes_read);
5544               addr += bytes_read;
5545             }
5546           if (attr.dw_idx == 0 && attr.form == 0)
5547             break;
5548           indexval.attr_vec.push_back (std::move (attr));
5549         }
5550     }
5551   if (addr != abbrev_table_start + abbrev_table_size)
5552     {
5553       warning (_("Section .debug_names in %s has abbreviation_table "
5554                  "of size %zu vs. written as %u, ignoring .debug_names."),
5555                filename, addr - abbrev_table_start, abbrev_table_size);
5556       return false;
5557     }
5558   map.entry_pool = addr;
5559
5560   return true;
5561 }
5562
5563 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5564    list.  */
5565
5566 static void
5567 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5568                                   const mapped_debug_names &map,
5569                                   dwarf2_section_info &section,
5570                                   bool is_dwz, int base_offset)
5571 {
5572   sect_offset sect_off_prev;
5573   for (uint32_t i = 0; i <= map.cu_count; ++i)
5574     {
5575       sect_offset sect_off_next;
5576       if (i < map.cu_count)
5577         {
5578           sect_off_next
5579             = (sect_offset) (extract_unsigned_integer
5580                              (map.cu_table_reordered + i * map.offset_size,
5581                               map.offset_size,
5582                               map.dwarf5_byte_order));
5583         }
5584       else
5585         sect_off_next = (sect_offset) section.size;
5586       if (i >= 1)
5587         {
5588           const ULONGEST length = sect_off_next - sect_off_prev;
5589           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5590             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5591                                          sect_off_prev, length);
5592         }
5593       sect_off_prev = sect_off_next;
5594     }
5595 }
5596
5597 /* Read the CU list from the mapped index, and use it to create all
5598    the CU objects for this dwarf2_per_objfile.  */
5599
5600 static void
5601 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5602                              const mapped_debug_names &map,
5603                              const mapped_debug_names &dwz_map)
5604 {
5605   struct objfile *objfile = dwarf2_per_objfile->objfile;
5606
5607   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5608   dwarf2_per_objfile->all_comp_units
5609     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5610                  dwarf2_per_objfile->n_comp_units);
5611
5612   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5613                                     dwarf2_per_objfile->info,
5614                                     false /* is_dwz */,
5615                                     0 /* base_offset */);
5616
5617   if (dwz_map.cu_count == 0)
5618     return;
5619
5620   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5621   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5622                                     true /* is_dwz */,
5623                                     map.cu_count /* base_offset */);
5624 }
5625
5626 /* Read .debug_names.  If everything went ok, initialize the "quick"
5627    elements of all the CUs and return true.  Otherwise, return false.  */
5628
5629 static bool
5630 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5631 {
5632   mapped_debug_names local_map (dwarf2_per_objfile);
5633   mapped_debug_names dwz_map (dwarf2_per_objfile);
5634   struct objfile *objfile = dwarf2_per_objfile->objfile;
5635
5636   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5637                                       &dwarf2_per_objfile->debug_names,
5638                                       local_map))
5639     return false;
5640
5641   /* Don't use the index if it's empty.  */
5642   if (local_map.name_count == 0)
5643     return false;
5644
5645   /* If there is a .dwz file, read it so we can get its CU list as
5646      well.  */
5647   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5648   if (dwz != NULL)
5649     {
5650       if (!read_debug_names_from_section (objfile,
5651                                           bfd_get_filename (dwz->dwz_bfd),
5652                                           &dwz->debug_names, dwz_map))
5653         {
5654           warning (_("could not read '.debug_names' section from %s; skipping"),
5655                    bfd_get_filename (dwz->dwz_bfd));
5656           return false;
5657         }
5658     }
5659
5660   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5661
5662   if (local_map.tu_count != 0)
5663     {
5664       /* We can only handle a single .debug_types when we have an
5665          index.  */
5666       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5667         return false;
5668
5669       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5670                                                 dwarf2_per_objfile->types, 0);
5671
5672       create_signatured_type_table_from_debug_names
5673         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5674     }
5675
5676   create_addrmap_from_aranges (dwarf2_per_objfile,
5677                                &dwarf2_per_objfile->debug_aranges);
5678
5679   dwarf2_per_objfile->debug_names_table.reset
5680     (new mapped_debug_names (dwarf2_per_objfile));
5681   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5682   dwarf2_per_objfile->using_index = 1;
5683   dwarf2_per_objfile->quick_file_names_table =
5684     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5685
5686   return true;
5687 }
5688
5689 /* Type used to manage iterating over all CUs looking for a symbol for
5690    .debug_names.  */
5691
5692 class dw2_debug_names_iterator
5693 {
5694 public:
5695   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5696      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5697   dw2_debug_names_iterator (const mapped_debug_names &map,
5698                             bool want_specific_block,
5699                             block_enum block_index, domain_enum domain,
5700                             const char *name)
5701     : m_map (map), m_want_specific_block (want_specific_block),
5702       m_block_index (block_index), m_domain (domain),
5703       m_addr (find_vec_in_debug_names (map, name))
5704   {}
5705
5706   dw2_debug_names_iterator (const mapped_debug_names &map,
5707                             search_domain search, uint32_t namei)
5708     : m_map (map),
5709       m_search (search),
5710       m_addr (find_vec_in_debug_names (map, namei))
5711   {}
5712
5713   /* Return the next matching CU or NULL if there are no more.  */
5714   dwarf2_per_cu_data *next ();
5715
5716 private:
5717   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5718                                                   const char *name);
5719   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5720                                                   uint32_t namei);
5721
5722   /* The internalized form of .debug_names.  */
5723   const mapped_debug_names &m_map;
5724
5725   /* If true, only look for symbols that match BLOCK_INDEX.  */
5726   const bool m_want_specific_block = false;
5727
5728   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5729      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5730      value.  */
5731   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5732
5733   /* The kind of symbol we're looking for.  */
5734   const domain_enum m_domain = UNDEF_DOMAIN;
5735   const search_domain m_search = ALL_DOMAIN;
5736
5737   /* The list of CUs from the index entry of the symbol, or NULL if
5738      not found.  */
5739   const gdb_byte *m_addr;
5740 };
5741
5742 const char *
5743 mapped_debug_names::namei_to_name (uint32_t namei) const
5744 {
5745   const ULONGEST namei_string_offs
5746     = extract_unsigned_integer ((name_table_string_offs_reordered
5747                                  + namei * offset_size),
5748                                 offset_size,
5749                                 dwarf5_byte_order);
5750   return read_indirect_string_at_offset
5751     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5752 }
5753
5754 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5755    found, return pointer to its pool data.  If NAME cannot be found,
5756    return NULL.  */
5757
5758 const gdb_byte *
5759 dw2_debug_names_iterator::find_vec_in_debug_names
5760   (const mapped_debug_names &map, const char *name)
5761 {
5762   int (*cmp) (const char *, const char *);
5763
5764   if (current_language->la_language == language_cplus
5765       || current_language->la_language == language_fortran
5766       || current_language->la_language == language_d)
5767     {
5768       /* NAME is already canonical.  Drop any qualifiers as
5769          .debug_names does not contain any.  */
5770
5771       if (strchr (name, '(') != NULL)
5772         {
5773           gdb::unique_xmalloc_ptr<char> without_params
5774             = cp_remove_params (name);
5775
5776           if (without_params != NULL)
5777             {
5778               name = without_params.get();
5779             }
5780         }
5781     }
5782
5783   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5784
5785   const uint32_t full_hash = dwarf5_djb_hash (name);
5786   uint32_t namei
5787     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5788                                 (map.bucket_table_reordered
5789                                  + (full_hash % map.bucket_count)), 4,
5790                                 map.dwarf5_byte_order);
5791   if (namei == 0)
5792     return NULL;
5793   --namei;
5794   if (namei >= map.name_count)
5795     {
5796       complaint (&symfile_complaints,
5797                  _("Wrong .debug_names with name index %u but name_count=%u "
5798                    "[in module %s]"),
5799                  namei, map.name_count,
5800                  objfile_name (map.dwarf2_per_objfile->objfile));
5801       return NULL;
5802     }
5803
5804   for (;;)
5805     {
5806       const uint32_t namei_full_hash
5807         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5808                                     (map.hash_table_reordered + namei), 4,
5809                                     map.dwarf5_byte_order);
5810       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5811         return NULL;
5812
5813       if (full_hash == namei_full_hash)
5814         {
5815           const char *const namei_string = map.namei_to_name (namei);
5816
5817 #if 0 /* An expensive sanity check.  */
5818           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5819             {
5820               complaint (&symfile_complaints,
5821                          _("Wrong .debug_names hash for string at index %u "
5822                            "[in module %s]"),
5823                          namei, objfile_name (dwarf2_per_objfile->objfile));
5824               return NULL;
5825             }
5826 #endif
5827
5828           if (cmp (namei_string, name) == 0)
5829             {
5830               const ULONGEST namei_entry_offs
5831                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5832                                              + namei * map.offset_size),
5833                                             map.offset_size, map.dwarf5_byte_order);
5834               return map.entry_pool + namei_entry_offs;
5835             }
5836         }
5837
5838       ++namei;
5839       if (namei >= map.name_count)
5840         return NULL;
5841     }
5842 }
5843
5844 const gdb_byte *
5845 dw2_debug_names_iterator::find_vec_in_debug_names
5846   (const mapped_debug_names &map, uint32_t namei)
5847 {
5848   if (namei >= map.name_count)
5849     {
5850       complaint (&symfile_complaints,
5851                  _("Wrong .debug_names with name index %u but name_count=%u "
5852                    "[in module %s]"),
5853                  namei, map.name_count,
5854                  objfile_name (map.dwarf2_per_objfile->objfile));
5855       return NULL;
5856     }
5857
5858   const ULONGEST namei_entry_offs
5859     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5860                                  + namei * map.offset_size),
5861                                 map.offset_size, map.dwarf5_byte_order);
5862   return map.entry_pool + namei_entry_offs;
5863 }
5864
5865 /* See dw2_debug_names_iterator.  */
5866
5867 dwarf2_per_cu_data *
5868 dw2_debug_names_iterator::next ()
5869 {
5870   if (m_addr == NULL)
5871     return NULL;
5872
5873   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5874   struct objfile *objfile = dwarf2_per_objfile->objfile;
5875   bfd *const abfd = objfile->obfd;
5876
5877  again:
5878
5879   unsigned int bytes_read;
5880   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5881   m_addr += bytes_read;
5882   if (abbrev == 0)
5883     return NULL;
5884
5885   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5886   if (indexval_it == m_map.abbrev_map.cend ())
5887     {
5888       complaint (&symfile_complaints,
5889                  _("Wrong .debug_names undefined abbrev code %s "
5890                    "[in module %s]"),
5891                  pulongest (abbrev), objfile_name (objfile));
5892       return NULL;
5893     }
5894   const mapped_debug_names::index_val &indexval = indexval_it->second;
5895   bool have_is_static = false;
5896   bool is_static;
5897   dwarf2_per_cu_data *per_cu = NULL;
5898   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5899     {
5900       ULONGEST ull;
5901       switch (attr.form)
5902         {
5903         case DW_FORM_implicit_const:
5904           ull = attr.implicit_const;
5905           break;
5906         case DW_FORM_flag_present:
5907           ull = 1;
5908           break;
5909         case DW_FORM_udata:
5910           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5911           m_addr += bytes_read;
5912           break;
5913         default:
5914           complaint (&symfile_complaints,
5915                      _("Unsupported .debug_names form %s [in module %s]"),
5916                      dwarf_form_name (attr.form),
5917                      objfile_name (objfile));
5918           return NULL;
5919         }
5920       switch (attr.dw_idx)
5921         {
5922         case DW_IDX_compile_unit:
5923           /* Don't crash on bad data.  */
5924           if (ull >= dwarf2_per_objfile->n_comp_units)
5925             {
5926               complaint (&symfile_complaints,
5927                          _(".debug_names entry has bad CU index %s"
5928                            " [in module %s]"),
5929                          pulongest (ull),
5930                          objfile_name (dwarf2_per_objfile->objfile));
5931               continue;
5932             }
5933           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
5934           break;
5935         case DW_IDX_type_unit:
5936           /* Don't crash on bad data.  */
5937           if (ull >= dwarf2_per_objfile->n_type_units)
5938             {
5939               complaint (&symfile_complaints,
5940                          _(".debug_names entry has bad TU index %s"
5941                            " [in module %s]"),
5942                          pulongest (ull),
5943                          objfile_name (dwarf2_per_objfile->objfile));
5944               continue;
5945             }
5946           per_cu = dw2_get_cutu (dwarf2_per_objfile,
5947                                  dwarf2_per_objfile->n_comp_units + ull);
5948           break;
5949         case DW_IDX_GNU_internal:
5950           if (!m_map.augmentation_is_gdb)
5951             break;
5952           have_is_static = true;
5953           is_static = true;
5954           break;
5955         case DW_IDX_GNU_external:
5956           if (!m_map.augmentation_is_gdb)
5957             break;
5958           have_is_static = true;
5959           is_static = false;
5960           break;
5961         }
5962     }
5963
5964   /* Skip if already read in.  */
5965   if (per_cu->v.quick->compunit_symtab)
5966     goto again;
5967
5968   /* Check static vs global.  */
5969   if (have_is_static)
5970     {
5971       const bool want_static = m_block_index != GLOBAL_BLOCK;
5972       if (m_want_specific_block && want_static != is_static)
5973         goto again;
5974     }
5975
5976   /* Match dw2_symtab_iter_next, symbol_kind
5977      and debug_names::psymbol_tag.  */
5978   switch (m_domain)
5979     {
5980     case VAR_DOMAIN:
5981       switch (indexval.dwarf_tag)
5982         {
5983         case DW_TAG_variable:
5984         case DW_TAG_subprogram:
5985         /* Some types are also in VAR_DOMAIN.  */
5986         case DW_TAG_typedef:
5987         case DW_TAG_structure_type:
5988           break;
5989         default:
5990           goto again;
5991         }
5992       break;
5993     case STRUCT_DOMAIN:
5994       switch (indexval.dwarf_tag)
5995         {
5996         case DW_TAG_typedef:
5997         case DW_TAG_structure_type:
5998           break;
5999         default:
6000           goto again;
6001         }
6002       break;
6003     case LABEL_DOMAIN:
6004       switch (indexval.dwarf_tag)
6005         {
6006         case 0:
6007         case DW_TAG_variable:
6008           break;
6009         default:
6010           goto again;
6011         }
6012       break;
6013     default:
6014       break;
6015     }
6016
6017   /* Match dw2_expand_symtabs_matching, symbol_kind and
6018      debug_names::psymbol_tag.  */
6019   switch (m_search)
6020     {
6021     case VARIABLES_DOMAIN:
6022       switch (indexval.dwarf_tag)
6023         {
6024         case DW_TAG_variable:
6025           break;
6026         default:
6027           goto again;
6028         }
6029       break;
6030     case FUNCTIONS_DOMAIN:
6031       switch (indexval.dwarf_tag)
6032         {
6033         case DW_TAG_subprogram:
6034           break;
6035         default:
6036           goto again;
6037         }
6038       break;
6039     case TYPES_DOMAIN:
6040       switch (indexval.dwarf_tag)
6041         {
6042         case DW_TAG_typedef:
6043         case DW_TAG_structure_type:
6044           break;
6045         default:
6046           goto again;
6047         }
6048       break;
6049     default:
6050       break;
6051     }
6052
6053   return per_cu;
6054 }
6055
6056 static struct compunit_symtab *
6057 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6058                                const char *name, domain_enum domain)
6059 {
6060   const block_enum block_index = static_cast<block_enum> (block_index_int);
6061   struct dwarf2_per_objfile *dwarf2_per_objfile
6062     = get_dwarf2_per_objfile (objfile);
6063
6064   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6065   if (!mapp)
6066     {
6067       /* index is NULL if OBJF_READNOW.  */
6068       return NULL;
6069     }
6070   const auto &map = *mapp;
6071
6072   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6073                                  block_index, domain, name);
6074
6075   struct compunit_symtab *stab_best = NULL;
6076   struct dwarf2_per_cu_data *per_cu;
6077   while ((per_cu = iter.next ()) != NULL)
6078     {
6079       struct symbol *sym, *with_opaque = NULL;
6080       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6081       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6082       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6083
6084       sym = block_find_symbol (block, name, domain,
6085                                block_find_non_opaque_type_preferred,
6086                                &with_opaque);
6087
6088       /* Some caution must be observed with overloaded functions and
6089          methods, since the index will not contain any overload
6090          information (but NAME might contain it).  */
6091
6092       if (sym != NULL
6093           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6094         return stab;
6095       if (with_opaque != NULL
6096           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6097         stab_best = stab;
6098
6099       /* Keep looking through other CUs.  */
6100     }
6101
6102   return stab_best;
6103 }
6104
6105 /* This dumps minimal information about .debug_names.  It is called
6106    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6107    uses this to verify that .debug_names has been loaded.  */
6108
6109 static void
6110 dw2_debug_names_dump (struct objfile *objfile)
6111 {
6112   struct dwarf2_per_objfile *dwarf2_per_objfile
6113     = get_dwarf2_per_objfile (objfile);
6114
6115   gdb_assert (dwarf2_per_objfile->using_index);
6116   printf_filtered (".debug_names:");
6117   if (dwarf2_per_objfile->debug_names_table)
6118     printf_filtered (" exists\n");
6119   else
6120     printf_filtered (" faked for \"readnow\"\n");
6121   printf_filtered ("\n");
6122 }
6123
6124 static void
6125 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6126                                              const char *func_name)
6127 {
6128   struct dwarf2_per_objfile *dwarf2_per_objfile
6129     = get_dwarf2_per_objfile (objfile);
6130
6131   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6132   if (dwarf2_per_objfile->debug_names_table)
6133     {
6134       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6135
6136       /* Note: It doesn't matter what we pass for block_index here.  */
6137       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6138                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6139
6140       struct dwarf2_per_cu_data *per_cu;
6141       while ((per_cu = iter.next ()) != NULL)
6142         dw2_instantiate_symtab (per_cu);
6143     }
6144 }
6145
6146 static void
6147 dw2_debug_names_expand_symtabs_matching
6148   (struct objfile *objfile,
6149    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6150    const lookup_name_info &lookup_name,
6151    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6152    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6153    enum search_domain kind)
6154 {
6155   struct dwarf2_per_objfile *dwarf2_per_objfile
6156     = get_dwarf2_per_objfile (objfile);
6157
6158   /* debug_names_table is NULL if OBJF_READNOW.  */
6159   if (!dwarf2_per_objfile->debug_names_table)
6160     return;
6161
6162   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6163
6164   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6165
6166   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6167                                       symbol_matcher,
6168                                       kind, [&] (offset_type namei)
6169     {
6170       /* The name was matched, now expand corresponding CUs that were
6171          marked.  */
6172       dw2_debug_names_iterator iter (map, kind, namei);
6173
6174       struct dwarf2_per_cu_data *per_cu;
6175       while ((per_cu = iter.next ()) != NULL)
6176         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6177                                          expansion_notify);
6178     });
6179 }
6180
6181 const struct quick_symbol_functions dwarf2_debug_names_functions =
6182 {
6183   dw2_has_symbols,
6184   dw2_find_last_source_symtab,
6185   dw2_forget_cached_source_info,
6186   dw2_map_symtabs_matching_filename,
6187   dw2_debug_names_lookup_symbol,
6188   dw2_print_stats,
6189   dw2_debug_names_dump,
6190   dw2_relocate,
6191   dw2_debug_names_expand_symtabs_for_function,
6192   dw2_expand_all_symtabs,
6193   dw2_expand_symtabs_with_fullname,
6194   dw2_map_matching_symbols,
6195   dw2_debug_names_expand_symtabs_matching,
6196   dw2_find_pc_sect_compunit_symtab,
6197   NULL,
6198   dw2_map_symbol_filenames
6199 };
6200
6201 /* See symfile.h.  */
6202
6203 bool
6204 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6205 {
6206   struct dwarf2_per_objfile *dwarf2_per_objfile
6207     = get_dwarf2_per_objfile (objfile);
6208
6209   /* If we're about to read full symbols, don't bother with the
6210      indices.  In this case we also don't care if some other debug
6211      format is making psymtabs, because they are all about to be
6212      expanded anyway.  */
6213   if ((objfile->flags & OBJF_READNOW))
6214     {
6215       int i;
6216
6217       dwarf2_per_objfile->using_index = 1;
6218       create_all_comp_units (dwarf2_per_objfile);
6219       create_all_type_units (dwarf2_per_objfile);
6220       dwarf2_per_objfile->quick_file_names_table =
6221         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6222
6223       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6224                        + dwarf2_per_objfile->n_type_units); ++i)
6225         {
6226           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6227
6228           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6229                                             struct dwarf2_per_cu_quick_data);
6230         }
6231
6232       /* Return 1 so that gdb sees the "quick" functions.  However,
6233          these functions will be no-ops because we will have expanded
6234          all symtabs.  */
6235       *index_kind = dw_index_kind::GDB_INDEX;
6236       return true;
6237     }
6238
6239   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6240     {
6241       *index_kind = dw_index_kind::DEBUG_NAMES;
6242       return true;
6243     }
6244
6245   if (dwarf2_read_index (objfile))
6246     {
6247       *index_kind = dw_index_kind::GDB_INDEX;
6248       return true;
6249     }
6250
6251   return false;
6252 }
6253
6254 \f
6255
6256 /* Build a partial symbol table.  */
6257
6258 void
6259 dwarf2_build_psymtabs (struct objfile *objfile)
6260 {
6261   struct dwarf2_per_objfile *dwarf2_per_objfile
6262     = get_dwarf2_per_objfile (objfile);
6263
6264   if (objfile->global_psymbols.capacity () == 0
6265       && objfile->static_psymbols.capacity () == 0)
6266     init_psymbol_list (objfile, 1024);
6267
6268   TRY
6269     {
6270       /* This isn't really ideal: all the data we allocate on the
6271          objfile's obstack is still uselessly kept around.  However,
6272          freeing it seems unsafe.  */
6273       psymtab_discarder psymtabs (objfile);
6274       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6275       psymtabs.keep ();
6276     }
6277   CATCH (except, RETURN_MASK_ERROR)
6278     {
6279       exception_print (gdb_stderr, except);
6280     }
6281   END_CATCH
6282 }
6283
6284 /* Return the total length of the CU described by HEADER.  */
6285
6286 static unsigned int
6287 get_cu_length (const struct comp_unit_head *header)
6288 {
6289   return header->initial_length_size + header->length;
6290 }
6291
6292 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6293
6294 static inline bool
6295 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6296 {
6297   sect_offset bottom = cu_header->sect_off;
6298   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6299
6300   return sect_off >= bottom && sect_off < top;
6301 }
6302
6303 /* Find the base address of the compilation unit for range lists and
6304    location lists.  It will normally be specified by DW_AT_low_pc.
6305    In DWARF-3 draft 4, the base address could be overridden by
6306    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6307    compilation units with discontinuous ranges.  */
6308
6309 static void
6310 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6311 {
6312   struct attribute *attr;
6313
6314   cu->base_known = 0;
6315   cu->base_address = 0;
6316
6317   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6318   if (attr)
6319     {
6320       cu->base_address = attr_value_as_address (attr);
6321       cu->base_known = 1;
6322     }
6323   else
6324     {
6325       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6326       if (attr)
6327         {
6328           cu->base_address = attr_value_as_address (attr);
6329           cu->base_known = 1;
6330         }
6331     }
6332 }
6333
6334 /* Read in the comp unit header information from the debug_info at info_ptr.
6335    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6336    NOTE: This leaves members offset, first_die_offset to be filled in
6337    by the caller.  */
6338
6339 static const gdb_byte *
6340 read_comp_unit_head (struct comp_unit_head *cu_header,
6341                      const gdb_byte *info_ptr,
6342                      struct dwarf2_section_info *section,
6343                      rcuh_kind section_kind)
6344 {
6345   int signed_addr;
6346   unsigned int bytes_read;
6347   const char *filename = get_section_file_name (section);
6348   bfd *abfd = get_section_bfd_owner (section);
6349
6350   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6351   cu_header->initial_length_size = bytes_read;
6352   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6353   info_ptr += bytes_read;
6354   cu_header->version = read_2_bytes (abfd, info_ptr);
6355   info_ptr += 2;
6356   if (cu_header->version < 5)
6357     switch (section_kind)
6358       {
6359       case rcuh_kind::COMPILE:
6360         cu_header->unit_type = DW_UT_compile;
6361         break;
6362       case rcuh_kind::TYPE:
6363         cu_header->unit_type = DW_UT_type;
6364         break;
6365       default:
6366         internal_error (__FILE__, __LINE__,
6367                         _("read_comp_unit_head: invalid section_kind"));
6368       }
6369   else
6370     {
6371       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6372                                                  (read_1_byte (abfd, info_ptr));
6373       info_ptr += 1;
6374       switch (cu_header->unit_type)
6375         {
6376         case DW_UT_compile:
6377           if (section_kind != rcuh_kind::COMPILE)
6378             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6379                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6380                    filename);
6381           break;
6382         case DW_UT_type:
6383           section_kind = rcuh_kind::TYPE;
6384           break;
6385         default:
6386           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6387                  "(is %d, should be %d or %d) [in module %s]"),
6388                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6389         }
6390
6391       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6392       info_ptr += 1;
6393     }
6394   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6395                                                           cu_header,
6396                                                           &bytes_read);
6397   info_ptr += bytes_read;
6398   if (cu_header->version < 5)
6399     {
6400       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6401       info_ptr += 1;
6402     }
6403   signed_addr = bfd_get_sign_extend_vma (abfd);
6404   if (signed_addr < 0)
6405     internal_error (__FILE__, __LINE__,
6406                     _("read_comp_unit_head: dwarf from non elf file"));
6407   cu_header->signed_addr_p = signed_addr;
6408
6409   if (section_kind == rcuh_kind::TYPE)
6410     {
6411       LONGEST type_offset;
6412
6413       cu_header->signature = read_8_bytes (abfd, info_ptr);
6414       info_ptr += 8;
6415
6416       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6417       info_ptr += bytes_read;
6418       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6419       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6420         error (_("Dwarf Error: Too big type_offset in compilation unit "
6421                "header (is %s) [in module %s]"), plongest (type_offset),
6422                filename);
6423     }
6424
6425   return info_ptr;
6426 }
6427
6428 /* Helper function that returns the proper abbrev section for
6429    THIS_CU.  */
6430
6431 static struct dwarf2_section_info *
6432 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6433 {
6434   struct dwarf2_section_info *abbrev;
6435   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6436
6437   if (this_cu->is_dwz)
6438     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6439   else
6440     abbrev = &dwarf2_per_objfile->abbrev;
6441
6442   return abbrev;
6443 }
6444
6445 /* Subroutine of read_and_check_comp_unit_head and
6446    read_and_check_type_unit_head to simplify them.
6447    Perform various error checking on the header.  */
6448
6449 static void
6450 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6451                             struct comp_unit_head *header,
6452                             struct dwarf2_section_info *section,
6453                             struct dwarf2_section_info *abbrev_section)
6454 {
6455   const char *filename = get_section_file_name (section);
6456
6457   if (header->version < 2 || header->version > 5)
6458     error (_("Dwarf Error: wrong version in compilation unit header "
6459            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6460            filename);
6461
6462   if (to_underlying (header->abbrev_sect_off)
6463       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6464     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6465            "(offset %s + 6) [in module %s]"),
6466            sect_offset_str (header->abbrev_sect_off),
6467            sect_offset_str (header->sect_off),
6468            filename);
6469
6470   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6471      avoid potential 32-bit overflow.  */
6472   if (((ULONGEST) header->sect_off + get_cu_length (header))
6473       > section->size)
6474     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6475            "(offset %s + 0) [in module %s]"),
6476            header->length, sect_offset_str (header->sect_off),
6477            filename);
6478 }
6479
6480 /* Read in a CU/TU header and perform some basic error checking.
6481    The contents of the header are stored in HEADER.
6482    The result is a pointer to the start of the first DIE.  */
6483
6484 static const gdb_byte *
6485 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6486                                struct comp_unit_head *header,
6487                                struct dwarf2_section_info *section,
6488                                struct dwarf2_section_info *abbrev_section,
6489                                const gdb_byte *info_ptr,
6490                                rcuh_kind section_kind)
6491 {
6492   const gdb_byte *beg_of_comp_unit = info_ptr;
6493
6494   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6495
6496   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6497
6498   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6499
6500   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6501                               abbrev_section);
6502
6503   return info_ptr;
6504 }
6505
6506 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6507
6508 static sect_offset
6509 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6510                     struct dwarf2_section_info *section,
6511                     sect_offset sect_off)
6512 {
6513   bfd *abfd = get_section_bfd_owner (section);
6514   const gdb_byte *info_ptr;
6515   unsigned int initial_length_size, offset_size;
6516   uint16_t version;
6517
6518   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6519   info_ptr = section->buffer + to_underlying (sect_off);
6520   read_initial_length (abfd, info_ptr, &initial_length_size);
6521   offset_size = initial_length_size == 4 ? 4 : 8;
6522   info_ptr += initial_length_size;
6523
6524   version = read_2_bytes (abfd, info_ptr);
6525   info_ptr += 2;
6526   if (version >= 5)
6527     {
6528       /* Skip unit type and address size.  */
6529       info_ptr += 2;
6530     }
6531
6532   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6533 }
6534
6535 /* Allocate a new partial symtab for file named NAME and mark this new
6536    partial symtab as being an include of PST.  */
6537
6538 static void
6539 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6540                                struct objfile *objfile)
6541 {
6542   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6543
6544   if (!IS_ABSOLUTE_PATH (subpst->filename))
6545     {
6546       /* It shares objfile->objfile_obstack.  */
6547       subpst->dirname = pst->dirname;
6548     }
6549
6550   subpst->textlow = 0;
6551   subpst->texthigh = 0;
6552
6553   subpst->dependencies
6554     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6555   subpst->dependencies[0] = pst;
6556   subpst->number_of_dependencies = 1;
6557
6558   subpst->globals_offset = 0;
6559   subpst->n_global_syms = 0;
6560   subpst->statics_offset = 0;
6561   subpst->n_static_syms = 0;
6562   subpst->compunit_symtab = NULL;
6563   subpst->read_symtab = pst->read_symtab;
6564   subpst->readin = 0;
6565
6566   /* No private part is necessary for include psymtabs.  This property
6567      can be used to differentiate between such include psymtabs and
6568      the regular ones.  */
6569   subpst->read_symtab_private = NULL;
6570 }
6571
6572 /* Read the Line Number Program data and extract the list of files
6573    included by the source file represented by PST.  Build an include
6574    partial symtab for each of these included files.  */
6575
6576 static void
6577 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6578                                struct die_info *die,
6579                                struct partial_symtab *pst)
6580 {
6581   line_header_up lh;
6582   struct attribute *attr;
6583
6584   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6585   if (attr)
6586     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6587   if (lh == NULL)
6588     return;  /* No linetable, so no includes.  */
6589
6590   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6591   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6592 }
6593
6594 static hashval_t
6595 hash_signatured_type (const void *item)
6596 {
6597   const struct signatured_type *sig_type
6598     = (const struct signatured_type *) item;
6599
6600   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6601   return sig_type->signature;
6602 }
6603
6604 static int
6605 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6606 {
6607   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6608   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6609
6610   return lhs->signature == rhs->signature;
6611 }
6612
6613 /* Allocate a hash table for signatured types.  */
6614
6615 static htab_t
6616 allocate_signatured_type_table (struct objfile *objfile)
6617 {
6618   return htab_create_alloc_ex (41,
6619                                hash_signatured_type,
6620                                eq_signatured_type,
6621                                NULL,
6622                                &objfile->objfile_obstack,
6623                                hashtab_obstack_allocate,
6624                                dummy_obstack_deallocate);
6625 }
6626
6627 /* A helper function to add a signatured type CU to a table.  */
6628
6629 static int
6630 add_signatured_type_cu_to_table (void **slot, void *datum)
6631 {
6632   struct signatured_type *sigt = (struct signatured_type *) *slot;
6633   struct signatured_type ***datap = (struct signatured_type ***) datum;
6634
6635   **datap = sigt;
6636   ++*datap;
6637
6638   return 1;
6639 }
6640
6641 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6642    and fill them into TYPES_HTAB.  It will process only type units,
6643    therefore DW_UT_type.  */
6644
6645 static void
6646 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6647                               struct dwo_file *dwo_file,
6648                               dwarf2_section_info *section, htab_t &types_htab,
6649                               rcuh_kind section_kind)
6650 {
6651   struct objfile *objfile = dwarf2_per_objfile->objfile;
6652   struct dwarf2_section_info *abbrev_section;
6653   bfd *abfd;
6654   const gdb_byte *info_ptr, *end_ptr;
6655
6656   abbrev_section = (dwo_file != NULL
6657                     ? &dwo_file->sections.abbrev
6658                     : &dwarf2_per_objfile->abbrev);
6659
6660   if (dwarf_read_debug)
6661     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6662                         get_section_name (section),
6663                         get_section_file_name (abbrev_section));
6664
6665   dwarf2_read_section (objfile, section);
6666   info_ptr = section->buffer;
6667
6668   if (info_ptr == NULL)
6669     return;
6670
6671   /* We can't set abfd until now because the section may be empty or
6672      not present, in which case the bfd is unknown.  */
6673   abfd = get_section_bfd_owner (section);
6674
6675   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6676      because we don't need to read any dies: the signature is in the
6677      header.  */
6678
6679   end_ptr = info_ptr + section->size;
6680   while (info_ptr < end_ptr)
6681     {
6682       struct signatured_type *sig_type;
6683       struct dwo_unit *dwo_tu;
6684       void **slot;
6685       const gdb_byte *ptr = info_ptr;
6686       struct comp_unit_head header;
6687       unsigned int length;
6688
6689       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6690
6691       /* Initialize it due to a false compiler warning.  */
6692       header.signature = -1;
6693       header.type_cu_offset_in_tu = (cu_offset) -1;
6694
6695       /* We need to read the type's signature in order to build the hash
6696          table, but we don't need anything else just yet.  */
6697
6698       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6699                                            abbrev_section, ptr, section_kind);
6700
6701       length = get_cu_length (&header);
6702
6703       /* Skip dummy type units.  */
6704       if (ptr >= info_ptr + length
6705           || peek_abbrev_code (abfd, ptr) == 0
6706           || header.unit_type != DW_UT_type)
6707         {
6708           info_ptr += length;
6709           continue;
6710         }
6711
6712       if (types_htab == NULL)
6713         {
6714           if (dwo_file)
6715             types_htab = allocate_dwo_unit_table (objfile);
6716           else
6717             types_htab = allocate_signatured_type_table (objfile);
6718         }
6719
6720       if (dwo_file)
6721         {
6722           sig_type = NULL;
6723           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6724                                    struct dwo_unit);
6725           dwo_tu->dwo_file = dwo_file;
6726           dwo_tu->signature = header.signature;
6727           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6728           dwo_tu->section = section;
6729           dwo_tu->sect_off = sect_off;
6730           dwo_tu->length = length;
6731         }
6732       else
6733         {
6734           /* N.B.: type_offset is not usable if this type uses a DWO file.
6735              The real type_offset is in the DWO file.  */
6736           dwo_tu = NULL;
6737           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6738                                      struct signatured_type);
6739           sig_type->signature = header.signature;
6740           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6741           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6742           sig_type->per_cu.is_debug_types = 1;
6743           sig_type->per_cu.section = section;
6744           sig_type->per_cu.sect_off = sect_off;
6745           sig_type->per_cu.length = length;
6746         }
6747
6748       slot = htab_find_slot (types_htab,
6749                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6750                              INSERT);
6751       gdb_assert (slot != NULL);
6752       if (*slot != NULL)
6753         {
6754           sect_offset dup_sect_off;
6755
6756           if (dwo_file)
6757             {
6758               const struct dwo_unit *dup_tu
6759                 = (const struct dwo_unit *) *slot;
6760
6761               dup_sect_off = dup_tu->sect_off;
6762             }
6763           else
6764             {
6765               const struct signatured_type *dup_tu
6766                 = (const struct signatured_type *) *slot;
6767
6768               dup_sect_off = dup_tu->per_cu.sect_off;
6769             }
6770
6771           complaint (&symfile_complaints,
6772                      _("debug type entry at offset %s is duplicate to"
6773                        " the entry at offset %s, signature %s"),
6774                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6775                      hex_string (header.signature));
6776         }
6777       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6778
6779       if (dwarf_read_debug > 1)
6780         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6781                             sect_offset_str (sect_off),
6782                             hex_string (header.signature));
6783
6784       info_ptr += length;
6785     }
6786 }
6787
6788 /* Create the hash table of all entries in the .debug_types
6789    (or .debug_types.dwo) section(s).
6790    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6791    otherwise it is NULL.
6792
6793    The result is a pointer to the hash table or NULL if there are no types.
6794
6795    Note: This function processes DWO files only, not DWP files.  */
6796
6797 static void
6798 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6799                                struct dwo_file *dwo_file,
6800                                VEC (dwarf2_section_info_def) *types,
6801                                htab_t &types_htab)
6802 {
6803   int ix;
6804   struct dwarf2_section_info *section;
6805
6806   if (VEC_empty (dwarf2_section_info_def, types))
6807     return;
6808
6809   for (ix = 0;
6810        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6811        ++ix)
6812     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6813                                   types_htab, rcuh_kind::TYPE);
6814 }
6815
6816 /* Create the hash table of all entries in the .debug_types section,
6817    and initialize all_type_units.
6818    The result is zero if there is an error (e.g. missing .debug_types section),
6819    otherwise non-zero.  */
6820
6821 static int
6822 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6823 {
6824   htab_t types_htab = NULL;
6825   struct signatured_type **iter;
6826
6827   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6828                                 &dwarf2_per_objfile->info, types_htab,
6829                                 rcuh_kind::COMPILE);
6830   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6831                                  dwarf2_per_objfile->types, types_htab);
6832   if (types_htab == NULL)
6833     {
6834       dwarf2_per_objfile->signatured_types = NULL;
6835       return 0;
6836     }
6837
6838   dwarf2_per_objfile->signatured_types = types_htab;
6839
6840   dwarf2_per_objfile->n_type_units
6841     = dwarf2_per_objfile->n_allocated_type_units
6842     = htab_elements (types_htab);
6843   dwarf2_per_objfile->all_type_units =
6844     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
6845   iter = &dwarf2_per_objfile->all_type_units[0];
6846   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
6847   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
6848               == dwarf2_per_objfile->n_type_units);
6849
6850   return 1;
6851 }
6852
6853 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6854    If SLOT is non-NULL, it is the entry to use in the hash table.
6855    Otherwise we find one.  */
6856
6857 static struct signatured_type *
6858 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6859                void **slot)
6860 {
6861   struct objfile *objfile = dwarf2_per_objfile->objfile;
6862   int n_type_units = dwarf2_per_objfile->n_type_units;
6863   struct signatured_type *sig_type;
6864
6865   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
6866   ++n_type_units;
6867   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
6868     {
6869       if (dwarf2_per_objfile->n_allocated_type_units == 0)
6870         dwarf2_per_objfile->n_allocated_type_units = 1;
6871       dwarf2_per_objfile->n_allocated_type_units *= 2;
6872       dwarf2_per_objfile->all_type_units
6873         = XRESIZEVEC (struct signatured_type *,
6874                       dwarf2_per_objfile->all_type_units,
6875                       dwarf2_per_objfile->n_allocated_type_units);
6876       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6877     }
6878   dwarf2_per_objfile->n_type_units = n_type_units;
6879
6880   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6881                              struct signatured_type);
6882   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
6883   sig_type->signature = sig;
6884   sig_type->per_cu.is_debug_types = 1;
6885   if (dwarf2_per_objfile->using_index)
6886     {
6887       sig_type->per_cu.v.quick =
6888         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6889                         struct dwarf2_per_cu_quick_data);
6890     }
6891
6892   if (slot == NULL)
6893     {
6894       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6895                              sig_type, INSERT);
6896     }
6897   gdb_assert (*slot == NULL);
6898   *slot = sig_type;
6899   /* The rest of sig_type must be filled in by the caller.  */
6900   return sig_type;
6901 }
6902
6903 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6904    Fill in SIG_ENTRY with DWO_ENTRY.  */
6905
6906 static void
6907 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6908                                   struct signatured_type *sig_entry,
6909                                   struct dwo_unit *dwo_entry)
6910 {
6911   /* Make sure we're not clobbering something we don't expect to.  */
6912   gdb_assert (! sig_entry->per_cu.queued);
6913   gdb_assert (sig_entry->per_cu.cu == NULL);
6914   if (dwarf2_per_objfile->using_index)
6915     {
6916       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6917       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6918     }
6919   else
6920       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6921   gdb_assert (sig_entry->signature == dwo_entry->signature);
6922   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6923   gdb_assert (sig_entry->type_unit_group == NULL);
6924   gdb_assert (sig_entry->dwo_unit == NULL);
6925
6926   sig_entry->per_cu.section = dwo_entry->section;
6927   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6928   sig_entry->per_cu.length = dwo_entry->length;
6929   sig_entry->per_cu.reading_dwo_directly = 1;
6930   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6931   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6932   sig_entry->dwo_unit = dwo_entry;
6933 }
6934
6935 /* Subroutine of lookup_signatured_type.
6936    If we haven't read the TU yet, create the signatured_type data structure
6937    for a TU to be read in directly from a DWO file, bypassing the stub.
6938    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6939    using .gdb_index, then when reading a CU we want to stay in the DWO file
6940    containing that CU.  Otherwise we could end up reading several other DWO
6941    files (due to comdat folding) to process the transitive closure of all the
6942    mentioned TUs, and that can be slow.  The current DWO file will have every
6943    type signature that it needs.
6944    We only do this for .gdb_index because in the psymtab case we already have
6945    to read all the DWOs to build the type unit groups.  */
6946
6947 static struct signatured_type *
6948 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6949 {
6950   struct dwarf2_per_objfile *dwarf2_per_objfile
6951     = cu->per_cu->dwarf2_per_objfile;
6952   struct objfile *objfile = dwarf2_per_objfile->objfile;
6953   struct dwo_file *dwo_file;
6954   struct dwo_unit find_dwo_entry, *dwo_entry;
6955   struct signatured_type find_sig_entry, *sig_entry;
6956   void **slot;
6957
6958   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6959
6960   /* If TU skeletons have been removed then we may not have read in any
6961      TUs yet.  */
6962   if (dwarf2_per_objfile->signatured_types == NULL)
6963     {
6964       dwarf2_per_objfile->signatured_types
6965         = allocate_signatured_type_table (objfile);
6966     }
6967
6968   /* We only ever need to read in one copy of a signatured type.
6969      Use the global signatured_types array to do our own comdat-folding
6970      of types.  If this is the first time we're reading this TU, and
6971      the TU has an entry in .gdb_index, replace the recorded data from
6972      .gdb_index with this TU.  */
6973
6974   find_sig_entry.signature = sig;
6975   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6976                          &find_sig_entry, INSERT);
6977   sig_entry = (struct signatured_type *) *slot;
6978
6979   /* We can get here with the TU already read, *or* in the process of being
6980      read.  Don't reassign the global entry to point to this DWO if that's
6981      the case.  Also note that if the TU is already being read, it may not
6982      have come from a DWO, the program may be a mix of Fission-compiled
6983      code and non-Fission-compiled code.  */
6984
6985   /* Have we already tried to read this TU?
6986      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6987      needn't exist in the global table yet).  */
6988   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6989     return sig_entry;
6990
6991   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6992      dwo_unit of the TU itself.  */
6993   dwo_file = cu->dwo_unit->dwo_file;
6994
6995   /* Ok, this is the first time we're reading this TU.  */
6996   if (dwo_file->tus == NULL)
6997     return NULL;
6998   find_dwo_entry.signature = sig;
6999   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7000   if (dwo_entry == NULL)
7001     return NULL;
7002
7003   /* If the global table doesn't have an entry for this TU, add one.  */
7004   if (sig_entry == NULL)
7005     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7006
7007   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7008   sig_entry->per_cu.tu_read = 1;
7009   return sig_entry;
7010 }
7011
7012 /* Subroutine of lookup_signatured_type.
7013    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7014    then try the DWP file.  If the TU stub (skeleton) has been removed then
7015    it won't be in .gdb_index.  */
7016
7017 static struct signatured_type *
7018 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7019 {
7020   struct dwarf2_per_objfile *dwarf2_per_objfile
7021     = cu->per_cu->dwarf2_per_objfile;
7022   struct objfile *objfile = dwarf2_per_objfile->objfile;
7023   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7024   struct dwo_unit *dwo_entry;
7025   struct signatured_type find_sig_entry, *sig_entry;
7026   void **slot;
7027
7028   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7029   gdb_assert (dwp_file != NULL);
7030
7031   /* If TU skeletons have been removed then we may not have read in any
7032      TUs yet.  */
7033   if (dwarf2_per_objfile->signatured_types == NULL)
7034     {
7035       dwarf2_per_objfile->signatured_types
7036         = allocate_signatured_type_table (objfile);
7037     }
7038
7039   find_sig_entry.signature = sig;
7040   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7041                          &find_sig_entry, INSERT);
7042   sig_entry = (struct signatured_type *) *slot;
7043
7044   /* Have we already tried to read this TU?
7045      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7046      needn't exist in the global table yet).  */
7047   if (sig_entry != NULL)
7048     return sig_entry;
7049
7050   if (dwp_file->tus == NULL)
7051     return NULL;
7052   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7053                                       sig, 1 /* is_debug_types */);
7054   if (dwo_entry == NULL)
7055     return NULL;
7056
7057   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7058   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7059
7060   return sig_entry;
7061 }
7062
7063 /* Lookup a signature based type for DW_FORM_ref_sig8.
7064    Returns NULL if signature SIG is not present in the table.
7065    It is up to the caller to complain about this.  */
7066
7067 static struct signatured_type *
7068 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7069 {
7070   struct dwarf2_per_objfile *dwarf2_per_objfile
7071     = cu->per_cu->dwarf2_per_objfile;
7072
7073   if (cu->dwo_unit
7074       && dwarf2_per_objfile->using_index)
7075     {
7076       /* We're in a DWO/DWP file, and we're using .gdb_index.
7077          These cases require special processing.  */
7078       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7079         return lookup_dwo_signatured_type (cu, sig);
7080       else
7081         return lookup_dwp_signatured_type (cu, sig);
7082     }
7083   else
7084     {
7085       struct signatured_type find_entry, *entry;
7086
7087       if (dwarf2_per_objfile->signatured_types == NULL)
7088         return NULL;
7089       find_entry.signature = sig;
7090       entry = ((struct signatured_type *)
7091                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7092       return entry;
7093     }
7094 }
7095 \f
7096 /* Low level DIE reading support.  */
7097
7098 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7099
7100 static void
7101 init_cu_die_reader (struct die_reader_specs *reader,
7102                     struct dwarf2_cu *cu,
7103                     struct dwarf2_section_info *section,
7104                     struct dwo_file *dwo_file,
7105                     struct abbrev_table *abbrev_table)
7106 {
7107   gdb_assert (section->readin && section->buffer != NULL);
7108   reader->abfd = get_section_bfd_owner (section);
7109   reader->cu = cu;
7110   reader->dwo_file = dwo_file;
7111   reader->die_section = section;
7112   reader->buffer = section->buffer;
7113   reader->buffer_end = section->buffer + section->size;
7114   reader->comp_dir = NULL;
7115   reader->abbrev_table = abbrev_table;
7116 }
7117
7118 /* Subroutine of init_cutu_and_read_dies to simplify it.
7119    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7120    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7121    already.
7122
7123    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7124    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7125    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7126    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7127    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7128    STUB_COMP_DIR may be non-NULL.
7129    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7130    are filled in with the info of the DIE from the DWO file.
7131    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7132    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7133    kept around for at least as long as *RESULT_READER.
7134
7135    The result is non-zero if a valid (non-dummy) DIE was found.  */
7136
7137 static int
7138 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7139                         struct dwo_unit *dwo_unit,
7140                         struct die_info *stub_comp_unit_die,
7141                         const char *stub_comp_dir,
7142                         struct die_reader_specs *result_reader,
7143                         const gdb_byte **result_info_ptr,
7144                         struct die_info **result_comp_unit_die,
7145                         int *result_has_children,
7146                         abbrev_table_up *result_dwo_abbrev_table)
7147 {
7148   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7149   struct objfile *objfile = dwarf2_per_objfile->objfile;
7150   struct dwarf2_cu *cu = this_cu->cu;
7151   bfd *abfd;
7152   const gdb_byte *begin_info_ptr, *info_ptr;
7153   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7154   int i,num_extra_attrs;
7155   struct dwarf2_section_info *dwo_abbrev_section;
7156   struct attribute *attr;
7157   struct die_info *comp_unit_die;
7158
7159   /* At most one of these may be provided.  */
7160   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7161
7162   /* These attributes aren't processed until later:
7163      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7164      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7165      referenced later.  However, these attributes are found in the stub
7166      which we won't have later.  In order to not impose this complication
7167      on the rest of the code, we read them here and copy them to the
7168      DWO CU/TU die.  */
7169
7170   stmt_list = NULL;
7171   low_pc = NULL;
7172   high_pc = NULL;
7173   ranges = NULL;
7174   comp_dir = NULL;
7175
7176   if (stub_comp_unit_die != NULL)
7177     {
7178       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7179          DWO file.  */
7180       if (! this_cu->is_debug_types)
7181         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7182       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7183       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7184       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7185       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7186
7187       /* There should be a DW_AT_addr_base attribute here (if needed).
7188          We need the value before we can process DW_FORM_GNU_addr_index.  */
7189       cu->addr_base = 0;
7190       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7191       if (attr)
7192         cu->addr_base = DW_UNSND (attr);
7193
7194       /* There should be a DW_AT_ranges_base attribute here (if needed).
7195          We need the value before we can process DW_AT_ranges.  */
7196       cu->ranges_base = 0;
7197       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7198       if (attr)
7199         cu->ranges_base = DW_UNSND (attr);
7200     }
7201   else if (stub_comp_dir != NULL)
7202     {
7203       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7204       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7205       comp_dir->name = DW_AT_comp_dir;
7206       comp_dir->form = DW_FORM_string;
7207       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7208       DW_STRING (comp_dir) = stub_comp_dir;
7209     }
7210
7211   /* Set up for reading the DWO CU/TU.  */
7212   cu->dwo_unit = dwo_unit;
7213   dwarf2_section_info *section = dwo_unit->section;
7214   dwarf2_read_section (objfile, section);
7215   abfd = get_section_bfd_owner (section);
7216   begin_info_ptr = info_ptr = (section->buffer
7217                                + to_underlying (dwo_unit->sect_off));
7218   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7219
7220   if (this_cu->is_debug_types)
7221     {
7222       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7223
7224       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7225                                                 &cu->header, section,
7226                                                 dwo_abbrev_section,
7227                                                 info_ptr, rcuh_kind::TYPE);
7228       /* This is not an assert because it can be caused by bad debug info.  */
7229       if (sig_type->signature != cu->header.signature)
7230         {
7231           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7232                    " TU at offset %s [in module %s]"),
7233                  hex_string (sig_type->signature),
7234                  hex_string (cu->header.signature),
7235                  sect_offset_str (dwo_unit->sect_off),
7236                  bfd_get_filename (abfd));
7237         }
7238       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7239       /* For DWOs coming from DWP files, we don't know the CU length
7240          nor the type's offset in the TU until now.  */
7241       dwo_unit->length = get_cu_length (&cu->header);
7242       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7243
7244       /* Establish the type offset that can be used to lookup the type.
7245          For DWO files, we don't know it until now.  */
7246       sig_type->type_offset_in_section
7247         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7248     }
7249   else
7250     {
7251       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7252                                                 &cu->header, section,
7253                                                 dwo_abbrev_section,
7254                                                 info_ptr, rcuh_kind::COMPILE);
7255       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7256       /* For DWOs coming from DWP files, we don't know the CU length
7257          until now.  */
7258       dwo_unit->length = get_cu_length (&cu->header);
7259     }
7260
7261   *result_dwo_abbrev_table
7262     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7263                                cu->header.abbrev_sect_off);
7264   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7265                       result_dwo_abbrev_table->get ());
7266
7267   /* Read in the die, but leave space to copy over the attributes
7268      from the stub.  This has the benefit of simplifying the rest of
7269      the code - all the work to maintain the illusion of a single
7270      DW_TAG_{compile,type}_unit DIE is done here.  */
7271   num_extra_attrs = ((stmt_list != NULL)
7272                      + (low_pc != NULL)
7273                      + (high_pc != NULL)
7274                      + (ranges != NULL)
7275                      + (comp_dir != NULL));
7276   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7277                               result_has_children, num_extra_attrs);
7278
7279   /* Copy over the attributes from the stub to the DIE we just read in.  */
7280   comp_unit_die = *result_comp_unit_die;
7281   i = comp_unit_die->num_attrs;
7282   if (stmt_list != NULL)
7283     comp_unit_die->attrs[i++] = *stmt_list;
7284   if (low_pc != NULL)
7285     comp_unit_die->attrs[i++] = *low_pc;
7286   if (high_pc != NULL)
7287     comp_unit_die->attrs[i++] = *high_pc;
7288   if (ranges != NULL)
7289     comp_unit_die->attrs[i++] = *ranges;
7290   if (comp_dir != NULL)
7291     comp_unit_die->attrs[i++] = *comp_dir;
7292   comp_unit_die->num_attrs += num_extra_attrs;
7293
7294   if (dwarf_die_debug)
7295     {
7296       fprintf_unfiltered (gdb_stdlog,
7297                           "Read die from %s@0x%x of %s:\n",
7298                           get_section_name (section),
7299                           (unsigned) (begin_info_ptr - section->buffer),
7300                           bfd_get_filename (abfd));
7301       dump_die (comp_unit_die, dwarf_die_debug);
7302     }
7303
7304   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7305      TUs by skipping the stub and going directly to the entry in the DWO file.
7306      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7307      to get it via circuitous means.  Blech.  */
7308   if (comp_dir != NULL)
7309     result_reader->comp_dir = DW_STRING (comp_dir);
7310
7311   /* Skip dummy compilation units.  */
7312   if (info_ptr >= begin_info_ptr + dwo_unit->length
7313       || peek_abbrev_code (abfd, info_ptr) == 0)
7314     return 0;
7315
7316   *result_info_ptr = info_ptr;
7317   return 1;
7318 }
7319
7320 /* Subroutine of init_cutu_and_read_dies to simplify it.
7321    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7322    Returns NULL if the specified DWO unit cannot be found.  */
7323
7324 static struct dwo_unit *
7325 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7326                  struct die_info *comp_unit_die)
7327 {
7328   struct dwarf2_cu *cu = this_cu->cu;
7329   ULONGEST signature;
7330   struct dwo_unit *dwo_unit;
7331   const char *comp_dir, *dwo_name;
7332
7333   gdb_assert (cu != NULL);
7334
7335   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7336   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7337   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7338
7339   if (this_cu->is_debug_types)
7340     {
7341       struct signatured_type *sig_type;
7342
7343       /* Since this_cu is the first member of struct signatured_type,
7344          we can go from a pointer to one to a pointer to the other.  */
7345       sig_type = (struct signatured_type *) this_cu;
7346       signature = sig_type->signature;
7347       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7348     }
7349   else
7350     {
7351       struct attribute *attr;
7352
7353       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7354       if (! attr)
7355         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7356                  " [in module %s]"),
7357                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7358       signature = DW_UNSND (attr);
7359       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7360                                        signature);
7361     }
7362
7363   return dwo_unit;
7364 }
7365
7366 /* Subroutine of init_cutu_and_read_dies to simplify it.
7367    See it for a description of the parameters.
7368    Read a TU directly from a DWO file, bypassing the stub.  */
7369
7370 static void
7371 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7372                            int use_existing_cu, int keep,
7373                            die_reader_func_ftype *die_reader_func,
7374                            void *data)
7375 {
7376   std::unique_ptr<dwarf2_cu> new_cu;
7377   struct signatured_type *sig_type;
7378   struct die_reader_specs reader;
7379   const gdb_byte *info_ptr;
7380   struct die_info *comp_unit_die;
7381   int has_children;
7382   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7383
7384   /* Verify we can do the following downcast, and that we have the
7385      data we need.  */
7386   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7387   sig_type = (struct signatured_type *) this_cu;
7388   gdb_assert (sig_type->dwo_unit != NULL);
7389
7390   if (use_existing_cu && this_cu->cu != NULL)
7391     {
7392       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7393       /* There's no need to do the rereading_dwo_cu handling that
7394          init_cutu_and_read_dies does since we don't read the stub.  */
7395     }
7396   else
7397     {
7398       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7399       gdb_assert (this_cu->cu == NULL);
7400       new_cu.reset (new dwarf2_cu (this_cu));
7401     }
7402
7403   /* A future optimization, if needed, would be to use an existing
7404      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7405      could share abbrev tables.  */
7406
7407   /* The abbreviation table used by READER, this must live at least as long as
7408      READER.  */
7409   abbrev_table_up dwo_abbrev_table;
7410
7411   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7412                               NULL /* stub_comp_unit_die */,
7413                               sig_type->dwo_unit->dwo_file->comp_dir,
7414                               &reader, &info_ptr,
7415                               &comp_unit_die, &has_children,
7416                               &dwo_abbrev_table) == 0)
7417     {
7418       /* Dummy die.  */
7419       return;
7420     }
7421
7422   /* All the "real" work is done here.  */
7423   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7424
7425   /* This duplicates the code in init_cutu_and_read_dies,
7426      but the alternative is making the latter more complex.
7427      This function is only for the special case of using DWO files directly:
7428      no point in overly complicating the general case just to handle this.  */
7429   if (new_cu != NULL && keep)
7430     {
7431       /* Link this CU into read_in_chain.  */
7432       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7433       dwarf2_per_objfile->read_in_chain = this_cu;
7434       /* The chain owns it now.  */
7435       new_cu.release ();
7436     }
7437 }
7438
7439 /* Initialize a CU (or TU) and read its DIEs.
7440    If the CU defers to a DWO file, read the DWO file as well.
7441
7442    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7443    Otherwise the table specified in the comp unit header is read in and used.
7444    This is an optimization for when we already have the abbrev table.
7445
7446    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7447    Otherwise, a new CU is allocated with xmalloc.
7448
7449    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7450    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7451
7452    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7453    linker) then DIE_READER_FUNC will not get called.  */
7454
7455 static void
7456 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7457                          struct abbrev_table *abbrev_table,
7458                          int use_existing_cu, int keep,
7459                          die_reader_func_ftype *die_reader_func,
7460                          void *data)
7461 {
7462   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7463   struct objfile *objfile = dwarf2_per_objfile->objfile;
7464   struct dwarf2_section_info *section = this_cu->section;
7465   bfd *abfd = get_section_bfd_owner (section);
7466   struct dwarf2_cu *cu;
7467   const gdb_byte *begin_info_ptr, *info_ptr;
7468   struct die_reader_specs reader;
7469   struct die_info *comp_unit_die;
7470   int has_children;
7471   struct attribute *attr;
7472   struct signatured_type *sig_type = NULL;
7473   struct dwarf2_section_info *abbrev_section;
7474   /* Non-zero if CU currently points to a DWO file and we need to
7475      reread it.  When this happens we need to reread the skeleton die
7476      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7477   int rereading_dwo_cu = 0;
7478
7479   if (dwarf_die_debug)
7480     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7481                         this_cu->is_debug_types ? "type" : "comp",
7482                         sect_offset_str (this_cu->sect_off));
7483
7484   if (use_existing_cu)
7485     gdb_assert (keep);
7486
7487   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7488      file (instead of going through the stub), short-circuit all of this.  */
7489   if (this_cu->reading_dwo_directly)
7490     {
7491       /* Narrow down the scope of possibilities to have to understand.  */
7492       gdb_assert (this_cu->is_debug_types);
7493       gdb_assert (abbrev_table == NULL);
7494       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7495                                  die_reader_func, data);
7496       return;
7497     }
7498
7499   /* This is cheap if the section is already read in.  */
7500   dwarf2_read_section (objfile, section);
7501
7502   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7503
7504   abbrev_section = get_abbrev_section_for_cu (this_cu);
7505
7506   std::unique_ptr<dwarf2_cu> new_cu;
7507   if (use_existing_cu && this_cu->cu != NULL)
7508     {
7509       cu = this_cu->cu;
7510       /* If this CU is from a DWO file we need to start over, we need to
7511          refetch the attributes from the skeleton CU.
7512          This could be optimized by retrieving those attributes from when we
7513          were here the first time: the previous comp_unit_die was stored in
7514          comp_unit_obstack.  But there's no data yet that we need this
7515          optimization.  */
7516       if (cu->dwo_unit != NULL)
7517         rereading_dwo_cu = 1;
7518     }
7519   else
7520     {
7521       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7522       gdb_assert (this_cu->cu == NULL);
7523       new_cu.reset (new dwarf2_cu (this_cu));
7524       cu = new_cu.get ();
7525     }
7526
7527   /* Get the header.  */
7528   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7529     {
7530       /* We already have the header, there's no need to read it in again.  */
7531       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7532     }
7533   else
7534     {
7535       if (this_cu->is_debug_types)
7536         {
7537           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7538                                                     &cu->header, section,
7539                                                     abbrev_section, info_ptr,
7540                                                     rcuh_kind::TYPE);
7541
7542           /* Since per_cu is the first member of struct signatured_type,
7543              we can go from a pointer to one to a pointer to the other.  */
7544           sig_type = (struct signatured_type *) this_cu;
7545           gdb_assert (sig_type->signature == cu->header.signature);
7546           gdb_assert (sig_type->type_offset_in_tu
7547                       == cu->header.type_cu_offset_in_tu);
7548           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7549
7550           /* LENGTH has not been set yet for type units if we're
7551              using .gdb_index.  */
7552           this_cu->length = get_cu_length (&cu->header);
7553
7554           /* Establish the type offset that can be used to lookup the type.  */
7555           sig_type->type_offset_in_section =
7556             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7557
7558           this_cu->dwarf_version = cu->header.version;
7559         }
7560       else
7561         {
7562           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7563                                                     &cu->header, section,
7564                                                     abbrev_section,
7565                                                     info_ptr,
7566                                                     rcuh_kind::COMPILE);
7567
7568           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7569           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7570           this_cu->dwarf_version = cu->header.version;
7571         }
7572     }
7573
7574   /* Skip dummy compilation units.  */
7575   if (info_ptr >= begin_info_ptr + this_cu->length
7576       || peek_abbrev_code (abfd, info_ptr) == 0)
7577     return;
7578
7579   /* If we don't have them yet, read the abbrevs for this compilation unit.
7580      And if we need to read them now, make sure they're freed when we're
7581      done (own the table through ABBREV_TABLE_HOLDER).  */
7582   abbrev_table_up abbrev_table_holder;
7583   if (abbrev_table != NULL)
7584     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7585   else
7586     {
7587       abbrev_table_holder
7588         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7589                                    cu->header.abbrev_sect_off);
7590       abbrev_table = abbrev_table_holder.get ();
7591     }
7592
7593   /* Read the top level CU/TU die.  */
7594   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7595   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7596
7597   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7598      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7599      table from the DWO file and pass the ownership over to us.  It will be
7600      referenced from READER, so we must make sure to free it after we're done
7601      with READER.
7602
7603      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7604      DWO CU, that this test will fail (the attribute will not be present).  */
7605   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7606   abbrev_table_up dwo_abbrev_table;
7607   if (attr)
7608     {
7609       struct dwo_unit *dwo_unit;
7610       struct die_info *dwo_comp_unit_die;
7611
7612       if (has_children)
7613         {
7614           complaint (&symfile_complaints,
7615                      _("compilation unit with DW_AT_GNU_dwo_name"
7616                        " has children (offset %s) [in module %s]"),
7617                      sect_offset_str (this_cu->sect_off),
7618                      bfd_get_filename (abfd));
7619         }
7620       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7621       if (dwo_unit != NULL)
7622         {
7623           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7624                                       comp_unit_die, NULL,
7625                                       &reader, &info_ptr,
7626                                       &dwo_comp_unit_die, &has_children,
7627                                       &dwo_abbrev_table) == 0)
7628             {
7629               /* Dummy die.  */
7630               return;
7631             }
7632           comp_unit_die = dwo_comp_unit_die;
7633         }
7634       else
7635         {
7636           /* Yikes, we couldn't find the rest of the DIE, we only have
7637              the stub.  A complaint has already been logged.  There's
7638              not much more we can do except pass on the stub DIE to
7639              die_reader_func.  We don't want to throw an error on bad
7640              debug info.  */
7641         }
7642     }
7643
7644   /* All of the above is setup for this call.  Yikes.  */
7645   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7646
7647   /* Done, clean up.  */
7648   if (new_cu != NULL && keep)
7649     {
7650       /* Link this CU into read_in_chain.  */
7651       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7652       dwarf2_per_objfile->read_in_chain = this_cu;
7653       /* The chain owns it now.  */
7654       new_cu.release ();
7655     }
7656 }
7657
7658 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7659    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7660    to have already done the lookup to find the DWO file).
7661
7662    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7663    THIS_CU->is_debug_types, but nothing else.
7664
7665    We fill in THIS_CU->length.
7666
7667    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7668    linker) then DIE_READER_FUNC will not get called.
7669
7670    THIS_CU->cu is always freed when done.
7671    This is done in order to not leave THIS_CU->cu in a state where we have
7672    to care whether it refers to the "main" CU or the DWO CU.  */
7673
7674 static void
7675 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7676                                    struct dwo_file *dwo_file,
7677                                    die_reader_func_ftype *die_reader_func,
7678                                    void *data)
7679 {
7680   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7681   struct objfile *objfile = dwarf2_per_objfile->objfile;
7682   struct dwarf2_section_info *section = this_cu->section;
7683   bfd *abfd = get_section_bfd_owner (section);
7684   struct dwarf2_section_info *abbrev_section;
7685   const gdb_byte *begin_info_ptr, *info_ptr;
7686   struct die_reader_specs reader;
7687   struct die_info *comp_unit_die;
7688   int has_children;
7689
7690   if (dwarf_die_debug)
7691     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7692                         this_cu->is_debug_types ? "type" : "comp",
7693                         sect_offset_str (this_cu->sect_off));
7694
7695   gdb_assert (this_cu->cu == NULL);
7696
7697   abbrev_section = (dwo_file != NULL
7698                     ? &dwo_file->sections.abbrev
7699                     : get_abbrev_section_for_cu (this_cu));
7700
7701   /* This is cheap if the section is already read in.  */
7702   dwarf2_read_section (objfile, section);
7703
7704   struct dwarf2_cu cu (this_cu);
7705
7706   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7707   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7708                                             &cu.header, section,
7709                                             abbrev_section, info_ptr,
7710                                             (this_cu->is_debug_types
7711                                              ? rcuh_kind::TYPE
7712                                              : rcuh_kind::COMPILE));
7713
7714   this_cu->length = get_cu_length (&cu.header);
7715
7716   /* Skip dummy compilation units.  */
7717   if (info_ptr >= begin_info_ptr + this_cu->length
7718       || peek_abbrev_code (abfd, info_ptr) == 0)
7719     return;
7720
7721   abbrev_table_up abbrev_table
7722     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7723                                cu.header.abbrev_sect_off);
7724
7725   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7726   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7727
7728   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7729 }
7730
7731 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7732    does not lookup the specified DWO file.
7733    This cannot be used to read DWO files.
7734
7735    THIS_CU->cu is always freed when done.
7736    This is done in order to not leave THIS_CU->cu in a state where we have
7737    to care whether it refers to the "main" CU or the DWO CU.
7738    We can revisit this if the data shows there's a performance issue.  */
7739
7740 static void
7741 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7742                                 die_reader_func_ftype *die_reader_func,
7743                                 void *data)
7744 {
7745   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7746 }
7747 \f
7748 /* Type Unit Groups.
7749
7750    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7751    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7752    so that all types coming from the same compilation (.o file) are grouped
7753    together.  A future step could be to put the types in the same symtab as
7754    the CU the types ultimately came from.  */
7755
7756 static hashval_t
7757 hash_type_unit_group (const void *item)
7758 {
7759   const struct type_unit_group *tu_group
7760     = (const struct type_unit_group *) item;
7761
7762   return hash_stmt_list_entry (&tu_group->hash);
7763 }
7764
7765 static int
7766 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7767 {
7768   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7769   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7770
7771   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7772 }
7773
7774 /* Allocate a hash table for type unit groups.  */
7775
7776 static htab_t
7777 allocate_type_unit_groups_table (struct objfile *objfile)
7778 {
7779   return htab_create_alloc_ex (3,
7780                                hash_type_unit_group,
7781                                eq_type_unit_group,
7782                                NULL,
7783                                &objfile->objfile_obstack,
7784                                hashtab_obstack_allocate,
7785                                dummy_obstack_deallocate);
7786 }
7787
7788 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7789    partial symtabs.  We combine several TUs per psymtab to not let the size
7790    of any one psymtab grow too big.  */
7791 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7792 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7793
7794 /* Helper routine for get_type_unit_group.
7795    Create the type_unit_group object used to hold one or more TUs.  */
7796
7797 static struct type_unit_group *
7798 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7799 {
7800   struct dwarf2_per_objfile *dwarf2_per_objfile
7801     = cu->per_cu->dwarf2_per_objfile;
7802   struct objfile *objfile = dwarf2_per_objfile->objfile;
7803   struct dwarf2_per_cu_data *per_cu;
7804   struct type_unit_group *tu_group;
7805
7806   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7807                              struct type_unit_group);
7808   per_cu = &tu_group->per_cu;
7809   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7810
7811   if (dwarf2_per_objfile->using_index)
7812     {
7813       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7814                                         struct dwarf2_per_cu_quick_data);
7815     }
7816   else
7817     {
7818       unsigned int line_offset = to_underlying (line_offset_struct);
7819       struct partial_symtab *pst;
7820       char *name;
7821
7822       /* Give the symtab a useful name for debug purposes.  */
7823       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7824         name = xstrprintf ("<type_units_%d>",
7825                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7826       else
7827         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
7828
7829       pst = create_partial_symtab (per_cu, name);
7830       pst->anonymous = 1;
7831
7832       xfree (name);
7833     }
7834
7835   tu_group->hash.dwo_unit = cu->dwo_unit;
7836   tu_group->hash.line_sect_off = line_offset_struct;
7837
7838   return tu_group;
7839 }
7840
7841 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7842    STMT_LIST is a DW_AT_stmt_list attribute.  */
7843
7844 static struct type_unit_group *
7845 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7846 {
7847   struct dwarf2_per_objfile *dwarf2_per_objfile
7848     = cu->per_cu->dwarf2_per_objfile;
7849   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7850   struct type_unit_group *tu_group;
7851   void **slot;
7852   unsigned int line_offset;
7853   struct type_unit_group type_unit_group_for_lookup;
7854
7855   if (dwarf2_per_objfile->type_unit_groups == NULL)
7856     {
7857       dwarf2_per_objfile->type_unit_groups =
7858         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7859     }
7860
7861   /* Do we need to create a new group, or can we use an existing one?  */
7862
7863   if (stmt_list)
7864     {
7865       line_offset = DW_UNSND (stmt_list);
7866       ++tu_stats->nr_symtab_sharers;
7867     }
7868   else
7869     {
7870       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7871          We can do various things here like create one group per TU or
7872          spread them over multiple groups to split up the expansion work.
7873          To avoid worst case scenarios (too many groups or too large groups)
7874          we, umm, group them in bunches.  */
7875       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7876                      | (tu_stats->nr_stmt_less_type_units
7877                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7878       ++tu_stats->nr_stmt_less_type_units;
7879     }
7880
7881   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7882   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7883   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7884                          &type_unit_group_for_lookup, INSERT);
7885   if (*slot != NULL)
7886     {
7887       tu_group = (struct type_unit_group *) *slot;
7888       gdb_assert (tu_group != NULL);
7889     }
7890   else
7891     {
7892       sect_offset line_offset_struct = (sect_offset) line_offset;
7893       tu_group = create_type_unit_group (cu, line_offset_struct);
7894       *slot = tu_group;
7895       ++tu_stats->nr_symtabs;
7896     }
7897
7898   return tu_group;
7899 }
7900 \f
7901 /* Partial symbol tables.  */
7902
7903 /* Create a psymtab named NAME and assign it to PER_CU.
7904
7905    The caller must fill in the following details:
7906    dirname, textlow, texthigh.  */
7907
7908 static struct partial_symtab *
7909 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7910 {
7911   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7912   struct partial_symtab *pst;
7913
7914   pst = start_psymtab_common (objfile, name, 0,
7915                               objfile->global_psymbols,
7916                               objfile->static_psymbols);
7917
7918   pst->psymtabs_addrmap_supported = 1;
7919
7920   /* This is the glue that links PST into GDB's symbol API.  */
7921   pst->read_symtab_private = per_cu;
7922   pst->read_symtab = dwarf2_read_symtab;
7923   per_cu->v.psymtab = pst;
7924
7925   return pst;
7926 }
7927
7928 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7929    type.  */
7930
7931 struct process_psymtab_comp_unit_data
7932 {
7933   /* True if we are reading a DW_TAG_partial_unit.  */
7934
7935   int want_partial_unit;
7936
7937   /* The "pretend" language that is used if the CU doesn't declare a
7938      language.  */
7939
7940   enum language pretend_language;
7941 };
7942
7943 /* die_reader_func for process_psymtab_comp_unit.  */
7944
7945 static void
7946 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7947                                   const gdb_byte *info_ptr,
7948                                   struct die_info *comp_unit_die,
7949                                   int has_children,
7950                                   void *data)
7951 {
7952   struct dwarf2_cu *cu = reader->cu;
7953   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7954   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7955   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7956   CORE_ADDR baseaddr;
7957   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7958   struct partial_symtab *pst;
7959   enum pc_bounds_kind cu_bounds_kind;
7960   const char *filename;
7961   struct process_psymtab_comp_unit_data *info
7962     = (struct process_psymtab_comp_unit_data *) data;
7963
7964   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7965     return;
7966
7967   gdb_assert (! per_cu->is_debug_types);
7968
7969   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7970
7971   cu->list_in_scope = &file_symbols;
7972
7973   /* Allocate a new partial symbol table structure.  */
7974   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7975   if (filename == NULL)
7976     filename = "";
7977
7978   pst = create_partial_symtab (per_cu, filename);
7979
7980   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7981   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7982
7983   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7984
7985   dwarf2_find_base_address (comp_unit_die, cu);
7986
7987   /* Possibly set the default values of LOWPC and HIGHPC from
7988      `DW_AT_ranges'.  */
7989   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7990                                          &best_highpc, cu, pst);
7991   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7992     /* Store the contiguous range if it is not empty; it can be empty for
7993        CUs with no code.  */
7994     addrmap_set_empty (objfile->psymtabs_addrmap,
7995                        gdbarch_adjust_dwarf2_addr (gdbarch,
7996                                                    best_lowpc + baseaddr),
7997                        gdbarch_adjust_dwarf2_addr (gdbarch,
7998                                                    best_highpc + baseaddr) - 1,
7999                        pst);
8000
8001   /* Check if comp unit has_children.
8002      If so, read the rest of the partial symbols from this comp unit.
8003      If not, there's no more debug_info for this comp unit.  */
8004   if (has_children)
8005     {
8006       struct partial_die_info *first_die;
8007       CORE_ADDR lowpc, highpc;
8008
8009       lowpc = ((CORE_ADDR) -1);
8010       highpc = ((CORE_ADDR) 0);
8011
8012       first_die = load_partial_dies (reader, info_ptr, 1);
8013
8014       scan_partial_symbols (first_die, &lowpc, &highpc,
8015                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8016
8017       /* If we didn't find a lowpc, set it to highpc to avoid
8018          complaints from `maint check'.  */
8019       if (lowpc == ((CORE_ADDR) -1))
8020         lowpc = highpc;
8021
8022       /* If the compilation unit didn't have an explicit address range,
8023          then use the information extracted from its child dies.  */
8024       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8025         {
8026           best_lowpc = lowpc;
8027           best_highpc = highpc;
8028         }
8029     }
8030   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8031   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8032
8033   end_psymtab_common (objfile, pst);
8034
8035   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8036     {
8037       int i;
8038       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8039       struct dwarf2_per_cu_data *iter;
8040
8041       /* Fill in 'dependencies' here; we fill in 'users' in a
8042          post-pass.  */
8043       pst->number_of_dependencies = len;
8044       pst->dependencies =
8045         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8046       for (i = 0;
8047            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8048                         i, iter);
8049            ++i)
8050         pst->dependencies[i] = iter->v.psymtab;
8051
8052       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8053     }
8054
8055   /* Get the list of files included in the current compilation unit,
8056      and build a psymtab for each of them.  */
8057   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8058
8059   if (dwarf_read_debug)
8060     {
8061       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8062
8063       fprintf_unfiltered (gdb_stdlog,
8064                           "Psymtab for %s unit @%s: %s - %s"
8065                           ", %d global, %d static syms\n",
8066                           per_cu->is_debug_types ? "type" : "comp",
8067                           sect_offset_str (per_cu->sect_off),
8068                           paddress (gdbarch, pst->textlow),
8069                           paddress (gdbarch, pst->texthigh),
8070                           pst->n_global_syms, pst->n_static_syms);
8071     }
8072 }
8073
8074 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8075    Process compilation unit THIS_CU for a psymtab.  */
8076
8077 static void
8078 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8079                            int want_partial_unit,
8080                            enum language pretend_language)
8081 {
8082   /* If this compilation unit was already read in, free the
8083      cached copy in order to read it in again.  This is
8084      necessary because we skipped some symbols when we first
8085      read in the compilation unit (see load_partial_dies).
8086      This problem could be avoided, but the benefit is unclear.  */
8087   if (this_cu->cu != NULL)
8088     free_one_cached_comp_unit (this_cu);
8089
8090   if (this_cu->is_debug_types)
8091     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8092                              NULL);
8093   else
8094     {
8095       process_psymtab_comp_unit_data info;
8096       info.want_partial_unit = want_partial_unit;
8097       info.pretend_language = pretend_language;
8098       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8099                                process_psymtab_comp_unit_reader, &info);
8100     }
8101
8102   /* Age out any secondary CUs.  */
8103   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8104 }
8105
8106 /* Reader function for build_type_psymtabs.  */
8107
8108 static void
8109 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8110                             const gdb_byte *info_ptr,
8111                             struct die_info *type_unit_die,
8112                             int has_children,
8113                             void *data)
8114 {
8115   struct dwarf2_per_objfile *dwarf2_per_objfile
8116     = reader->cu->per_cu->dwarf2_per_objfile;
8117   struct objfile *objfile = dwarf2_per_objfile->objfile;
8118   struct dwarf2_cu *cu = reader->cu;
8119   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8120   struct signatured_type *sig_type;
8121   struct type_unit_group *tu_group;
8122   struct attribute *attr;
8123   struct partial_die_info *first_die;
8124   CORE_ADDR lowpc, highpc;
8125   struct partial_symtab *pst;
8126
8127   gdb_assert (data == NULL);
8128   gdb_assert (per_cu->is_debug_types);
8129   sig_type = (struct signatured_type *) per_cu;
8130
8131   if (! has_children)
8132     return;
8133
8134   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8135   tu_group = get_type_unit_group (cu, attr);
8136
8137   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8138
8139   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8140   cu->list_in_scope = &file_symbols;
8141   pst = create_partial_symtab (per_cu, "");
8142   pst->anonymous = 1;
8143
8144   first_die = load_partial_dies (reader, info_ptr, 1);
8145
8146   lowpc = (CORE_ADDR) -1;
8147   highpc = (CORE_ADDR) 0;
8148   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8149
8150   end_psymtab_common (objfile, pst);
8151 }
8152
8153 /* Struct used to sort TUs by their abbreviation table offset.  */
8154
8155 struct tu_abbrev_offset
8156 {
8157   struct signatured_type *sig_type;
8158   sect_offset abbrev_offset;
8159 };
8160
8161 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8162
8163 static bool
8164 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8165                           const struct tu_abbrev_offset &b)
8166 {
8167   return a.abbrev_offset < b.abbrev_offset;
8168 }
8169
8170 /* Efficiently read all the type units.
8171    This does the bulk of the work for build_type_psymtabs.
8172
8173    The efficiency is because we sort TUs by the abbrev table they use and
8174    only read each abbrev table once.  In one program there are 200K TUs
8175    sharing 8K abbrev tables.
8176
8177    The main purpose of this function is to support building the
8178    dwarf2_per_objfile->type_unit_groups table.
8179    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8180    can collapse the search space by grouping them by stmt_list.
8181    The savings can be significant, in the same program from above the 200K TUs
8182    share 8K stmt_list tables.
8183
8184    FUNC is expected to call get_type_unit_group, which will create the
8185    struct type_unit_group if necessary and add it to
8186    dwarf2_per_objfile->type_unit_groups.  */
8187
8188 static void
8189 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8190 {
8191   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8192   abbrev_table_up abbrev_table;
8193   sect_offset abbrev_offset;
8194   int i;
8195
8196   /* It's up to the caller to not call us multiple times.  */
8197   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8198
8199   if (dwarf2_per_objfile->n_type_units == 0)
8200     return;
8201
8202   /* TUs typically share abbrev tables, and there can be way more TUs than
8203      abbrev tables.  Sort by abbrev table to reduce the number of times we
8204      read each abbrev table in.
8205      Alternatives are to punt or to maintain a cache of abbrev tables.
8206      This is simpler and efficient enough for now.
8207
8208      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8209      symtab to use).  Typically TUs with the same abbrev offset have the same
8210      stmt_list value too so in practice this should work well.
8211
8212      The basic algorithm here is:
8213
8214       sort TUs by abbrev table
8215       for each TU with same abbrev table:
8216         read abbrev table if first user
8217         read TU top level DIE
8218           [IWBN if DWO skeletons had DW_AT_stmt_list]
8219         call FUNC  */
8220
8221   if (dwarf_read_debug)
8222     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8223
8224   /* Sort in a separate table to maintain the order of all_type_units
8225      for .gdb_index: TU indices directly index all_type_units.  */
8226   std::vector<struct tu_abbrev_offset> sorted_by_abbrev
8227     (dwarf2_per_objfile->n_type_units);
8228   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8229     {
8230       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8231
8232       sorted_by_abbrev[i].sig_type = sig_type;
8233       sorted_by_abbrev[i].abbrev_offset =
8234         read_abbrev_offset (dwarf2_per_objfile,
8235                             sig_type->per_cu.section,
8236                             sig_type->per_cu.sect_off);
8237     }
8238   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8239              sort_tu_by_abbrev_offset);
8240
8241   abbrev_offset = (sect_offset) ~(unsigned) 0;
8242
8243   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8244     {
8245       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8246
8247       /* Switch to the next abbrev table if necessary.  */
8248       if (abbrev_table == NULL
8249           || tu->abbrev_offset != abbrev_offset)
8250         {
8251           abbrev_offset = tu->abbrev_offset;
8252           abbrev_table =
8253             abbrev_table_read_table (dwarf2_per_objfile,
8254                                      &dwarf2_per_objfile->abbrev,
8255                                      abbrev_offset);
8256           ++tu_stats->nr_uniq_abbrev_tables;
8257         }
8258
8259       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table.get (),
8260                                0, 0, build_type_psymtabs_reader, NULL);
8261     }
8262 }
8263
8264 /* Print collected type unit statistics.  */
8265
8266 static void
8267 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8268 {
8269   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8270
8271   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8272   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8273                       dwarf2_per_objfile->n_type_units);
8274   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8275                       tu_stats->nr_uniq_abbrev_tables);
8276   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8277                       tu_stats->nr_symtabs);
8278   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8279                       tu_stats->nr_symtab_sharers);
8280   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8281                       tu_stats->nr_stmt_less_type_units);
8282   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8283                       tu_stats->nr_all_type_units_reallocs);
8284 }
8285
8286 /* Traversal function for build_type_psymtabs.  */
8287
8288 static int
8289 build_type_psymtab_dependencies (void **slot, void *info)
8290 {
8291   struct dwarf2_per_objfile *dwarf2_per_objfile
8292     = (struct dwarf2_per_objfile *) info;
8293   struct objfile *objfile = dwarf2_per_objfile->objfile;
8294   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8295   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8296   struct partial_symtab *pst = per_cu->v.psymtab;
8297   int len = VEC_length (sig_type_ptr, tu_group->tus);
8298   struct signatured_type *iter;
8299   int i;
8300
8301   gdb_assert (len > 0);
8302   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8303
8304   pst->number_of_dependencies = len;
8305   pst->dependencies =
8306     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8307   for (i = 0;
8308        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8309        ++i)
8310     {
8311       gdb_assert (iter->per_cu.is_debug_types);
8312       pst->dependencies[i] = iter->per_cu.v.psymtab;
8313       iter->type_unit_group = tu_group;
8314     }
8315
8316   VEC_free (sig_type_ptr, tu_group->tus);
8317
8318   return 1;
8319 }
8320
8321 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8322    Build partial symbol tables for the .debug_types comp-units.  */
8323
8324 static void
8325 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8326 {
8327   if (! create_all_type_units (dwarf2_per_objfile))
8328     return;
8329
8330   build_type_psymtabs_1 (dwarf2_per_objfile);
8331 }
8332
8333 /* Traversal function for process_skeletonless_type_unit.
8334    Read a TU in a DWO file and build partial symbols for it.  */
8335
8336 static int
8337 process_skeletonless_type_unit (void **slot, void *info)
8338 {
8339   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8340   struct dwarf2_per_objfile *dwarf2_per_objfile
8341     = (struct dwarf2_per_objfile *) info;
8342   struct signatured_type find_entry, *entry;
8343
8344   /* If this TU doesn't exist in the global table, add it and read it in.  */
8345
8346   if (dwarf2_per_objfile->signatured_types == NULL)
8347     {
8348       dwarf2_per_objfile->signatured_types
8349         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8350     }
8351
8352   find_entry.signature = dwo_unit->signature;
8353   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8354                          INSERT);
8355   /* If we've already seen this type there's nothing to do.  What's happening
8356      is we're doing our own version of comdat-folding here.  */
8357   if (*slot != NULL)
8358     return 1;
8359
8360   /* This does the job that create_all_type_units would have done for
8361      this TU.  */
8362   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8363   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8364   *slot = entry;
8365
8366   /* This does the job that build_type_psymtabs_1 would have done.  */
8367   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8368                            build_type_psymtabs_reader, NULL);
8369
8370   return 1;
8371 }
8372
8373 /* Traversal function for process_skeletonless_type_units.  */
8374
8375 static int
8376 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8377 {
8378   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8379
8380   if (dwo_file->tus != NULL)
8381     {
8382       htab_traverse_noresize (dwo_file->tus,
8383                               process_skeletonless_type_unit, info);
8384     }
8385
8386   return 1;
8387 }
8388
8389 /* Scan all TUs of DWO files, verifying we've processed them.
8390    This is needed in case a TU was emitted without its skeleton.
8391    Note: This can't be done until we know what all the DWO files are.  */
8392
8393 static void
8394 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8395 {
8396   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8397   if (get_dwp_file (dwarf2_per_objfile) == NULL
8398       && dwarf2_per_objfile->dwo_files != NULL)
8399     {
8400       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8401                               process_dwo_file_for_skeletonless_type_units,
8402                               dwarf2_per_objfile);
8403     }
8404 }
8405
8406 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8407
8408 static void
8409 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8410 {
8411   int i;
8412
8413   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8414     {
8415       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8416       struct partial_symtab *pst = per_cu->v.psymtab;
8417       int j;
8418
8419       if (pst == NULL)
8420         continue;
8421
8422       for (j = 0; j < pst->number_of_dependencies; ++j)
8423         {
8424           /* Set the 'user' field only if it is not already set.  */
8425           if (pst->dependencies[j]->user == NULL)
8426             pst->dependencies[j]->user = pst;
8427         }
8428     }
8429 }
8430
8431 /* Build the partial symbol table by doing a quick pass through the
8432    .debug_info and .debug_abbrev sections.  */
8433
8434 static void
8435 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8436 {
8437   struct cleanup *back_to;
8438   int i;
8439   struct objfile *objfile = dwarf2_per_objfile->objfile;
8440
8441   if (dwarf_read_debug)
8442     {
8443       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8444                           objfile_name (objfile));
8445     }
8446
8447   dwarf2_per_objfile->reading_partial_symbols = 1;
8448
8449   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8450
8451   /* Any cached compilation units will be linked by the per-objfile
8452      read_in_chain.  Make sure to free them when we're done.  */
8453   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8454
8455   build_type_psymtabs (dwarf2_per_objfile);
8456
8457   create_all_comp_units (dwarf2_per_objfile);
8458
8459   /* Create a temporary address map on a temporary obstack.  We later
8460      copy this to the final obstack.  */
8461   auto_obstack temp_obstack;
8462
8463   scoped_restore save_psymtabs_addrmap
8464     = make_scoped_restore (&objfile->psymtabs_addrmap,
8465                            addrmap_create_mutable (&temp_obstack));
8466
8467   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8468     {
8469       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8470
8471       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8472     }
8473
8474   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8475   process_skeletonless_type_units (dwarf2_per_objfile);
8476
8477   /* Now that all TUs have been processed we can fill in the dependencies.  */
8478   if (dwarf2_per_objfile->type_unit_groups != NULL)
8479     {
8480       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8481                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8482     }
8483
8484   if (dwarf_read_debug)
8485     print_tu_stats (dwarf2_per_objfile);
8486
8487   set_partial_user (dwarf2_per_objfile);
8488
8489   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8490                                                     &objfile->objfile_obstack);
8491   /* At this point we want to keep the address map.  */
8492   save_psymtabs_addrmap.release ();
8493
8494   do_cleanups (back_to);
8495
8496   if (dwarf_read_debug)
8497     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8498                         objfile_name (objfile));
8499 }
8500
8501 /* die_reader_func for load_partial_comp_unit.  */
8502
8503 static void
8504 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8505                                const gdb_byte *info_ptr,
8506                                struct die_info *comp_unit_die,
8507                                int has_children,
8508                                void *data)
8509 {
8510   struct dwarf2_cu *cu = reader->cu;
8511
8512   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8513
8514   /* Check if comp unit has_children.
8515      If so, read the rest of the partial symbols from this comp unit.
8516      If not, there's no more debug_info for this comp unit.  */
8517   if (has_children)
8518     load_partial_dies (reader, info_ptr, 0);
8519 }
8520
8521 /* Load the partial DIEs for a secondary CU into memory.
8522    This is also used when rereading a primary CU with load_all_dies.  */
8523
8524 static void
8525 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8526 {
8527   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8528                            load_partial_comp_unit_reader, NULL);
8529 }
8530
8531 static void
8532 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8533                               struct dwarf2_section_info *section,
8534                               struct dwarf2_section_info *abbrev_section,
8535                               unsigned int is_dwz,
8536                               int *n_allocated,
8537                               int *n_comp_units,
8538                               struct dwarf2_per_cu_data ***all_comp_units)
8539 {
8540   const gdb_byte *info_ptr;
8541   struct objfile *objfile = dwarf2_per_objfile->objfile;
8542
8543   if (dwarf_read_debug)
8544     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8545                         get_section_name (section),
8546                         get_section_file_name (section));
8547
8548   dwarf2_read_section (objfile, section);
8549
8550   info_ptr = section->buffer;
8551
8552   while (info_ptr < section->buffer + section->size)
8553     {
8554       struct dwarf2_per_cu_data *this_cu;
8555
8556       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8557
8558       comp_unit_head cu_header;
8559       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8560                                      abbrev_section, info_ptr,
8561                                      rcuh_kind::COMPILE);
8562
8563       /* Save the compilation unit for later lookup.  */
8564       if (cu_header.unit_type != DW_UT_type)
8565         {
8566           this_cu = XOBNEW (&objfile->objfile_obstack,
8567                             struct dwarf2_per_cu_data);
8568           memset (this_cu, 0, sizeof (*this_cu));
8569         }
8570       else
8571         {
8572           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8573                                   struct signatured_type);
8574           memset (sig_type, 0, sizeof (*sig_type));
8575           sig_type->signature = cu_header.signature;
8576           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8577           this_cu = &sig_type->per_cu;
8578         }
8579       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8580       this_cu->sect_off = sect_off;
8581       this_cu->length = cu_header.length + cu_header.initial_length_size;
8582       this_cu->is_dwz = is_dwz;
8583       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8584       this_cu->section = section;
8585
8586       if (*n_comp_units == *n_allocated)
8587         {
8588           *n_allocated *= 2;
8589           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8590                                         *all_comp_units, *n_allocated);
8591         }
8592       (*all_comp_units)[*n_comp_units] = this_cu;
8593       ++*n_comp_units;
8594
8595       info_ptr = info_ptr + this_cu->length;
8596     }
8597 }
8598
8599 /* Create a list of all compilation units in OBJFILE.
8600    This is only done for -readnow and building partial symtabs.  */
8601
8602 static void
8603 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8604 {
8605   int n_allocated;
8606   int n_comp_units;
8607   struct dwarf2_per_cu_data **all_comp_units;
8608   struct dwz_file *dwz;
8609   struct objfile *objfile = dwarf2_per_objfile->objfile;
8610
8611   n_comp_units = 0;
8612   n_allocated = 10;
8613   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
8614
8615   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8616                                 &dwarf2_per_objfile->abbrev, 0,
8617                                 &n_allocated, &n_comp_units, &all_comp_units);
8618
8619   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8620   if (dwz != NULL)
8621     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8622                                   1, &n_allocated, &n_comp_units,
8623                                   &all_comp_units);
8624
8625   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
8626                                                   struct dwarf2_per_cu_data *,
8627                                                   n_comp_units);
8628   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
8629           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
8630   xfree (all_comp_units);
8631   dwarf2_per_objfile->n_comp_units = n_comp_units;
8632 }
8633
8634 /* Process all loaded DIEs for compilation unit CU, starting at
8635    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8636    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8637    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8638    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8639
8640 static void
8641 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8642                       CORE_ADDR *highpc, int set_addrmap,
8643                       struct dwarf2_cu *cu)
8644 {
8645   struct partial_die_info *pdi;
8646
8647   /* Now, march along the PDI's, descending into ones which have
8648      interesting children but skipping the children of the other ones,
8649      until we reach the end of the compilation unit.  */
8650
8651   pdi = first_die;
8652
8653   while (pdi != NULL)
8654     {
8655       pdi->fixup (cu);
8656
8657       /* Anonymous namespaces or modules have no name but have interesting
8658          children, so we need to look at them.  Ditto for anonymous
8659          enums.  */
8660
8661       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8662           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8663           || pdi->tag == DW_TAG_imported_unit
8664           || pdi->tag == DW_TAG_inlined_subroutine)
8665         {
8666           switch (pdi->tag)
8667             {
8668             case DW_TAG_subprogram:
8669             case DW_TAG_inlined_subroutine:
8670               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8671               break;
8672             case DW_TAG_constant:
8673             case DW_TAG_variable:
8674             case DW_TAG_typedef:
8675             case DW_TAG_union_type:
8676               if (!pdi->is_declaration)
8677                 {
8678                   add_partial_symbol (pdi, cu);
8679                 }
8680               break;
8681             case DW_TAG_class_type:
8682             case DW_TAG_interface_type:
8683             case DW_TAG_structure_type:
8684               if (!pdi->is_declaration)
8685                 {
8686                   add_partial_symbol (pdi, cu);
8687                 }
8688               if ((cu->language == language_rust
8689                    || cu->language == language_cplus) && pdi->has_children)
8690                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8691                                       set_addrmap, cu);
8692               break;
8693             case DW_TAG_enumeration_type:
8694               if (!pdi->is_declaration)
8695                 add_partial_enumeration (pdi, cu);
8696               break;
8697             case DW_TAG_base_type:
8698             case DW_TAG_subrange_type:
8699               /* File scope base type definitions are added to the partial
8700                  symbol table.  */
8701               add_partial_symbol (pdi, cu);
8702               break;
8703             case DW_TAG_namespace:
8704               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8705               break;
8706             case DW_TAG_module:
8707               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8708               break;
8709             case DW_TAG_imported_unit:
8710               {
8711                 struct dwarf2_per_cu_data *per_cu;
8712
8713                 /* For now we don't handle imported units in type units.  */
8714                 if (cu->per_cu->is_debug_types)
8715                   {
8716                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8717                              " supported in type units [in module %s]"),
8718                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8719                   }
8720
8721                 per_cu = dwarf2_find_containing_comp_unit
8722                            (pdi->d.sect_off, pdi->is_dwz,
8723                             cu->per_cu->dwarf2_per_objfile);
8724
8725                 /* Go read the partial unit, if needed.  */
8726                 if (per_cu->v.psymtab == NULL)
8727                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8728
8729                 VEC_safe_push (dwarf2_per_cu_ptr,
8730                                cu->per_cu->imported_symtabs, per_cu);
8731               }
8732               break;
8733             case DW_TAG_imported_declaration:
8734               add_partial_symbol (pdi, cu);
8735               break;
8736             default:
8737               break;
8738             }
8739         }
8740
8741       /* If the die has a sibling, skip to the sibling.  */
8742
8743       pdi = pdi->die_sibling;
8744     }
8745 }
8746
8747 /* Functions used to compute the fully scoped name of a partial DIE.
8748
8749    Normally, this is simple.  For C++, the parent DIE's fully scoped
8750    name is concatenated with "::" and the partial DIE's name.
8751    Enumerators are an exception; they use the scope of their parent
8752    enumeration type, i.e. the name of the enumeration type is not
8753    prepended to the enumerator.
8754
8755    There are two complexities.  One is DW_AT_specification; in this
8756    case "parent" means the parent of the target of the specification,
8757    instead of the direct parent of the DIE.  The other is compilers
8758    which do not emit DW_TAG_namespace; in this case we try to guess
8759    the fully qualified name of structure types from their members'
8760    linkage names.  This must be done using the DIE's children rather
8761    than the children of any DW_AT_specification target.  We only need
8762    to do this for structures at the top level, i.e. if the target of
8763    any DW_AT_specification (if any; otherwise the DIE itself) does not
8764    have a parent.  */
8765
8766 /* Compute the scope prefix associated with PDI's parent, in
8767    compilation unit CU.  The result will be allocated on CU's
8768    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8769    field.  NULL is returned if no prefix is necessary.  */
8770 static const char *
8771 partial_die_parent_scope (struct partial_die_info *pdi,
8772                           struct dwarf2_cu *cu)
8773 {
8774   const char *grandparent_scope;
8775   struct partial_die_info *parent, *real_pdi;
8776
8777   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8778      then this means the parent of the specification DIE.  */
8779
8780   real_pdi = pdi;
8781   while (real_pdi->has_specification)
8782     real_pdi = find_partial_die (real_pdi->spec_offset,
8783                                  real_pdi->spec_is_dwz, cu);
8784
8785   parent = real_pdi->die_parent;
8786   if (parent == NULL)
8787     return NULL;
8788
8789   if (parent->scope_set)
8790     return parent->scope;
8791
8792   parent->fixup (cu);
8793
8794   grandparent_scope = partial_die_parent_scope (parent, cu);
8795
8796   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8797      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8798      Work around this problem here.  */
8799   if (cu->language == language_cplus
8800       && parent->tag == DW_TAG_namespace
8801       && strcmp (parent->name, "::") == 0
8802       && grandparent_scope == NULL)
8803     {
8804       parent->scope = NULL;
8805       parent->scope_set = 1;
8806       return NULL;
8807     }
8808
8809   if (pdi->tag == DW_TAG_enumerator)
8810     /* Enumerators should not get the name of the enumeration as a prefix.  */
8811     parent->scope = grandparent_scope;
8812   else if (parent->tag == DW_TAG_namespace
8813       || parent->tag == DW_TAG_module
8814       || parent->tag == DW_TAG_structure_type
8815       || parent->tag == DW_TAG_class_type
8816       || parent->tag == DW_TAG_interface_type
8817       || parent->tag == DW_TAG_union_type
8818       || parent->tag == DW_TAG_enumeration_type)
8819     {
8820       if (grandparent_scope == NULL)
8821         parent->scope = parent->name;
8822       else
8823         parent->scope = typename_concat (&cu->comp_unit_obstack,
8824                                          grandparent_scope,
8825                                          parent->name, 0, cu);
8826     }
8827   else
8828     {
8829       /* FIXME drow/2004-04-01: What should we be doing with
8830          function-local names?  For partial symbols, we should probably be
8831          ignoring them.  */
8832       complaint (&symfile_complaints,
8833                  _("unhandled containing DIE tag %d for DIE at %s"),
8834                  parent->tag, sect_offset_str (pdi->sect_off));
8835       parent->scope = grandparent_scope;
8836     }
8837
8838   parent->scope_set = 1;
8839   return parent->scope;
8840 }
8841
8842 /* Return the fully scoped name associated with PDI, from compilation unit
8843    CU.  The result will be allocated with malloc.  */
8844
8845 static char *
8846 partial_die_full_name (struct partial_die_info *pdi,
8847                        struct dwarf2_cu *cu)
8848 {
8849   const char *parent_scope;
8850
8851   /* If this is a template instantiation, we can not work out the
8852      template arguments from partial DIEs.  So, unfortunately, we have
8853      to go through the full DIEs.  At least any work we do building
8854      types here will be reused if full symbols are loaded later.  */
8855   if (pdi->has_template_arguments)
8856     {
8857       pdi->fixup (cu);
8858
8859       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8860         {
8861           struct die_info *die;
8862           struct attribute attr;
8863           struct dwarf2_cu *ref_cu = cu;
8864
8865           /* DW_FORM_ref_addr is using section offset.  */
8866           attr.name = (enum dwarf_attribute) 0;
8867           attr.form = DW_FORM_ref_addr;
8868           attr.u.unsnd = to_underlying (pdi->sect_off);
8869           die = follow_die_ref (NULL, &attr, &ref_cu);
8870
8871           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8872         }
8873     }
8874
8875   parent_scope = partial_die_parent_scope (pdi, cu);
8876   if (parent_scope == NULL)
8877     return NULL;
8878   else
8879     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8880 }
8881
8882 static void
8883 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8884 {
8885   struct dwarf2_per_objfile *dwarf2_per_objfile
8886     = cu->per_cu->dwarf2_per_objfile;
8887   struct objfile *objfile = dwarf2_per_objfile->objfile;
8888   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8889   CORE_ADDR addr = 0;
8890   const char *actual_name = NULL;
8891   CORE_ADDR baseaddr;
8892   char *built_actual_name;
8893
8894   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8895
8896   built_actual_name = partial_die_full_name (pdi, cu);
8897   if (built_actual_name != NULL)
8898     actual_name = built_actual_name;
8899
8900   if (actual_name == NULL)
8901     actual_name = pdi->name;
8902
8903   switch (pdi->tag)
8904     {
8905     case DW_TAG_inlined_subroutine:
8906     case DW_TAG_subprogram:
8907       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8908       if (pdi->is_external || cu->language == language_ada)
8909         {
8910           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8911              of the global scope.  But in Ada, we want to be able to access
8912              nested procedures globally.  So all Ada subprograms are stored
8913              in the global scope.  */
8914           add_psymbol_to_list (actual_name, strlen (actual_name),
8915                                built_actual_name != NULL,
8916                                VAR_DOMAIN, LOC_BLOCK,
8917                                &objfile->global_psymbols,
8918                                addr, cu->language, objfile);
8919         }
8920       else
8921         {
8922           add_psymbol_to_list (actual_name, strlen (actual_name),
8923                                built_actual_name != NULL,
8924                                VAR_DOMAIN, LOC_BLOCK,
8925                                &objfile->static_psymbols,
8926                                addr, cu->language, objfile);
8927         }
8928
8929       if (pdi->main_subprogram && actual_name != NULL)
8930         set_objfile_main_name (objfile, actual_name, cu->language);
8931       break;
8932     case DW_TAG_constant:
8933       {
8934         std::vector<partial_symbol *> *list;
8935
8936         if (pdi->is_external)
8937           list = &objfile->global_psymbols;
8938         else
8939           list = &objfile->static_psymbols;
8940         add_psymbol_to_list (actual_name, strlen (actual_name),
8941                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8942                              list, 0, cu->language, objfile);
8943       }
8944       break;
8945     case DW_TAG_variable:
8946       if (pdi->d.locdesc)
8947         addr = decode_locdesc (pdi->d.locdesc, cu);
8948
8949       if (pdi->d.locdesc
8950           && addr == 0
8951           && !dwarf2_per_objfile->has_section_at_zero)
8952         {
8953           /* A global or static variable may also have been stripped
8954              out by the linker if unused, in which case its address
8955              will be nullified; do not add such variables into partial
8956              symbol table then.  */
8957         }
8958       else if (pdi->is_external)
8959         {
8960           /* Global Variable.
8961              Don't enter into the minimal symbol tables as there is
8962              a minimal symbol table entry from the ELF symbols already.
8963              Enter into partial symbol table if it has a location
8964              descriptor or a type.
8965              If the location descriptor is missing, new_symbol will create
8966              a LOC_UNRESOLVED symbol, the address of the variable will then
8967              be determined from the minimal symbol table whenever the variable
8968              is referenced.
8969              The address for the partial symbol table entry is not
8970              used by GDB, but it comes in handy for debugging partial symbol
8971              table building.  */
8972
8973           if (pdi->d.locdesc || pdi->has_type)
8974             add_psymbol_to_list (actual_name, strlen (actual_name),
8975                                  built_actual_name != NULL,
8976                                  VAR_DOMAIN, LOC_STATIC,
8977                                  &objfile->global_psymbols,
8978                                  addr + baseaddr,
8979                                  cu->language, objfile);
8980         }
8981       else
8982         {
8983           int has_loc = pdi->d.locdesc != NULL;
8984
8985           /* Static Variable.  Skip symbols whose value we cannot know (those
8986              without location descriptors or constant values).  */
8987           if (!has_loc && !pdi->has_const_value)
8988             {
8989               xfree (built_actual_name);
8990               return;
8991             }
8992
8993           add_psymbol_to_list (actual_name, strlen (actual_name),
8994                                built_actual_name != NULL,
8995                                VAR_DOMAIN, LOC_STATIC,
8996                                &objfile->static_psymbols,
8997                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8998                                cu->language, objfile);
8999         }
9000       break;
9001     case DW_TAG_typedef:
9002     case DW_TAG_base_type:
9003     case DW_TAG_subrange_type:
9004       add_psymbol_to_list (actual_name, strlen (actual_name),
9005                            built_actual_name != NULL,
9006                            VAR_DOMAIN, LOC_TYPEDEF,
9007                            &objfile->static_psymbols,
9008                            0, cu->language, objfile);
9009       break;
9010     case DW_TAG_imported_declaration:
9011     case DW_TAG_namespace:
9012       add_psymbol_to_list (actual_name, strlen (actual_name),
9013                            built_actual_name != NULL,
9014                            VAR_DOMAIN, LOC_TYPEDEF,
9015                            &objfile->global_psymbols,
9016                            0, cu->language, objfile);
9017       break;
9018     case DW_TAG_module:
9019       add_psymbol_to_list (actual_name, strlen (actual_name),
9020                            built_actual_name != NULL,
9021                            MODULE_DOMAIN, LOC_TYPEDEF,
9022                            &objfile->global_psymbols,
9023                            0, cu->language, objfile);
9024       break;
9025     case DW_TAG_class_type:
9026     case DW_TAG_interface_type:
9027     case DW_TAG_structure_type:
9028     case DW_TAG_union_type:
9029     case DW_TAG_enumeration_type:
9030       /* Skip external references.  The DWARF standard says in the section
9031          about "Structure, Union, and Class Type Entries": "An incomplete
9032          structure, union or class type is represented by a structure,
9033          union or class entry that does not have a byte size attribute
9034          and that has a DW_AT_declaration attribute."  */
9035       if (!pdi->has_byte_size && pdi->is_declaration)
9036         {
9037           xfree (built_actual_name);
9038           return;
9039         }
9040
9041       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9042          static vs. global.  */
9043       add_psymbol_to_list (actual_name, strlen (actual_name),
9044                            built_actual_name != NULL,
9045                            STRUCT_DOMAIN, LOC_TYPEDEF,
9046                            cu->language == language_cplus
9047                            ? &objfile->global_psymbols
9048                            : &objfile->static_psymbols,
9049                            0, cu->language, objfile);
9050
9051       break;
9052     case DW_TAG_enumerator:
9053       add_psymbol_to_list (actual_name, strlen (actual_name),
9054                            built_actual_name != NULL,
9055                            VAR_DOMAIN, LOC_CONST,
9056                            cu->language == language_cplus
9057                            ? &objfile->global_psymbols
9058                            : &objfile->static_psymbols,
9059                            0, cu->language, objfile);
9060       break;
9061     default:
9062       break;
9063     }
9064
9065   xfree (built_actual_name);
9066 }
9067
9068 /* Read a partial die corresponding to a namespace; also, add a symbol
9069    corresponding to that namespace to the symbol table.  NAMESPACE is
9070    the name of the enclosing namespace.  */
9071
9072 static void
9073 add_partial_namespace (struct partial_die_info *pdi,
9074                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9075                        int set_addrmap, struct dwarf2_cu *cu)
9076 {
9077   /* Add a symbol for the namespace.  */
9078
9079   add_partial_symbol (pdi, cu);
9080
9081   /* Now scan partial symbols in that namespace.  */
9082
9083   if (pdi->has_children)
9084     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9085 }
9086
9087 /* Read a partial die corresponding to a Fortran module.  */
9088
9089 static void
9090 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9091                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9092 {
9093   /* Add a symbol for the namespace.  */
9094
9095   add_partial_symbol (pdi, cu);
9096
9097   /* Now scan partial symbols in that module.  */
9098
9099   if (pdi->has_children)
9100     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9101 }
9102
9103 /* Read a partial die corresponding to a subprogram or an inlined
9104    subprogram and create a partial symbol for that subprogram.
9105    When the CU language allows it, this routine also defines a partial
9106    symbol for each nested subprogram that this subprogram contains.
9107    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9108    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9109
9110    PDI may also be a lexical block, in which case we simply search
9111    recursively for subprograms defined inside that lexical block.
9112    Again, this is only performed when the CU language allows this
9113    type of definitions.  */
9114
9115 static void
9116 add_partial_subprogram (struct partial_die_info *pdi,
9117                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9118                         int set_addrmap, struct dwarf2_cu *cu)
9119 {
9120   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9121     {
9122       if (pdi->has_pc_info)
9123         {
9124           if (pdi->lowpc < *lowpc)
9125             *lowpc = pdi->lowpc;
9126           if (pdi->highpc > *highpc)
9127             *highpc = pdi->highpc;
9128           if (set_addrmap)
9129             {
9130               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9131               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9132               CORE_ADDR baseaddr;
9133               CORE_ADDR highpc;
9134               CORE_ADDR lowpc;
9135
9136               baseaddr = ANOFFSET (objfile->section_offsets,
9137                                    SECT_OFF_TEXT (objfile));
9138               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9139                                                   pdi->lowpc + baseaddr);
9140               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9141                                                    pdi->highpc + baseaddr);
9142               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9143                                  cu->per_cu->v.psymtab);
9144             }
9145         }
9146
9147       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9148         {
9149           if (!pdi->is_declaration)
9150             /* Ignore subprogram DIEs that do not have a name, they are
9151                illegal.  Do not emit a complaint at this point, we will
9152                do so when we convert this psymtab into a symtab.  */
9153             if (pdi->name)
9154               add_partial_symbol (pdi, cu);
9155         }
9156     }
9157
9158   if (! pdi->has_children)
9159     return;
9160
9161   if (cu->language == language_ada)
9162     {
9163       pdi = pdi->die_child;
9164       while (pdi != NULL)
9165         {
9166           pdi->fixup (cu);
9167           if (pdi->tag == DW_TAG_subprogram
9168               || pdi->tag == DW_TAG_inlined_subroutine
9169               || pdi->tag == DW_TAG_lexical_block)
9170             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9171           pdi = pdi->die_sibling;
9172         }
9173     }
9174 }
9175
9176 /* Read a partial die corresponding to an enumeration type.  */
9177
9178 static void
9179 add_partial_enumeration (struct partial_die_info *enum_pdi,
9180                          struct dwarf2_cu *cu)
9181 {
9182   struct partial_die_info *pdi;
9183
9184   if (enum_pdi->name != NULL)
9185     add_partial_symbol (enum_pdi, cu);
9186
9187   pdi = enum_pdi->die_child;
9188   while (pdi)
9189     {
9190       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9191         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9192       else
9193         add_partial_symbol (pdi, cu);
9194       pdi = pdi->die_sibling;
9195     }
9196 }
9197
9198 /* Return the initial uleb128 in the die at INFO_PTR.  */
9199
9200 static unsigned int
9201 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9202 {
9203   unsigned int bytes_read;
9204
9205   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9206 }
9207
9208 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9209    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9210
9211    Return the corresponding abbrev, or NULL if the number is zero (indicating
9212    an empty DIE).  In either case *BYTES_READ will be set to the length of
9213    the initial number.  */
9214
9215 static struct abbrev_info *
9216 peek_die_abbrev (const die_reader_specs &reader,
9217                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9218 {
9219   dwarf2_cu *cu = reader.cu;
9220   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9221   unsigned int abbrev_number
9222     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9223
9224   if (abbrev_number == 0)
9225     return NULL;
9226
9227   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9228   if (!abbrev)
9229     {
9230       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9231                " at offset %s [in module %s]"),
9232              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9233              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9234     }
9235
9236   return abbrev;
9237 }
9238
9239 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9240    Returns a pointer to the end of a series of DIEs, terminated by an empty
9241    DIE.  Any children of the skipped DIEs will also be skipped.  */
9242
9243 static const gdb_byte *
9244 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9245 {
9246   while (1)
9247     {
9248       unsigned int bytes_read;
9249       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9250
9251       if (abbrev == NULL)
9252         return info_ptr + bytes_read;
9253       else
9254         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9255     }
9256 }
9257
9258 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9259    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9260    abbrev corresponding to that skipped uleb128 should be passed in
9261    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9262    children.  */
9263
9264 static const gdb_byte *
9265 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9266               struct abbrev_info *abbrev)
9267 {
9268   unsigned int bytes_read;
9269   struct attribute attr;
9270   bfd *abfd = reader->abfd;
9271   struct dwarf2_cu *cu = reader->cu;
9272   const gdb_byte *buffer = reader->buffer;
9273   const gdb_byte *buffer_end = reader->buffer_end;
9274   unsigned int form, i;
9275
9276   for (i = 0; i < abbrev->num_attrs; i++)
9277     {
9278       /* The only abbrev we care about is DW_AT_sibling.  */
9279       if (abbrev->attrs[i].name == DW_AT_sibling)
9280         {
9281           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9282           if (attr.form == DW_FORM_ref_addr)
9283             complaint (&symfile_complaints,
9284                        _("ignoring absolute DW_AT_sibling"));
9285           else
9286             {
9287               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9288               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9289
9290               if (sibling_ptr < info_ptr)
9291                 complaint (&symfile_complaints,
9292                            _("DW_AT_sibling points backwards"));
9293               else if (sibling_ptr > reader->buffer_end)
9294                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9295               else
9296                 return sibling_ptr;
9297             }
9298         }
9299
9300       /* If it isn't DW_AT_sibling, skip this attribute.  */
9301       form = abbrev->attrs[i].form;
9302     skip_attribute:
9303       switch (form)
9304         {
9305         case DW_FORM_ref_addr:
9306           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9307              and later it is offset sized.  */
9308           if (cu->header.version == 2)
9309             info_ptr += cu->header.addr_size;
9310           else
9311             info_ptr += cu->header.offset_size;
9312           break;
9313         case DW_FORM_GNU_ref_alt:
9314           info_ptr += cu->header.offset_size;
9315           break;
9316         case DW_FORM_addr:
9317           info_ptr += cu->header.addr_size;
9318           break;
9319         case DW_FORM_data1:
9320         case DW_FORM_ref1:
9321         case DW_FORM_flag:
9322           info_ptr += 1;
9323           break;
9324         case DW_FORM_flag_present:
9325         case DW_FORM_implicit_const:
9326           break;
9327         case DW_FORM_data2:
9328         case DW_FORM_ref2:
9329           info_ptr += 2;
9330           break;
9331         case DW_FORM_data4:
9332         case DW_FORM_ref4:
9333           info_ptr += 4;
9334           break;
9335         case DW_FORM_data8:
9336         case DW_FORM_ref8:
9337         case DW_FORM_ref_sig8:
9338           info_ptr += 8;
9339           break;
9340         case DW_FORM_data16:
9341           info_ptr += 16;
9342           break;
9343         case DW_FORM_string:
9344           read_direct_string (abfd, info_ptr, &bytes_read);
9345           info_ptr += bytes_read;
9346           break;
9347         case DW_FORM_sec_offset:
9348         case DW_FORM_strp:
9349         case DW_FORM_GNU_strp_alt:
9350           info_ptr += cu->header.offset_size;
9351           break;
9352         case DW_FORM_exprloc:
9353         case DW_FORM_block:
9354           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9355           info_ptr += bytes_read;
9356           break;
9357         case DW_FORM_block1:
9358           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9359           break;
9360         case DW_FORM_block2:
9361           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9362           break;
9363         case DW_FORM_block4:
9364           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9365           break;
9366         case DW_FORM_sdata:
9367         case DW_FORM_udata:
9368         case DW_FORM_ref_udata:
9369         case DW_FORM_GNU_addr_index:
9370         case DW_FORM_GNU_str_index:
9371           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9372           break;
9373         case DW_FORM_indirect:
9374           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9375           info_ptr += bytes_read;
9376           /* We need to continue parsing from here, so just go back to
9377              the top.  */
9378           goto skip_attribute;
9379
9380         default:
9381           error (_("Dwarf Error: Cannot handle %s "
9382                    "in DWARF reader [in module %s]"),
9383                  dwarf_form_name (form),
9384                  bfd_get_filename (abfd));
9385         }
9386     }
9387
9388   if (abbrev->has_children)
9389     return skip_children (reader, info_ptr);
9390   else
9391     return info_ptr;
9392 }
9393
9394 /* Locate ORIG_PDI's sibling.
9395    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9396
9397 static const gdb_byte *
9398 locate_pdi_sibling (const struct die_reader_specs *reader,
9399                     struct partial_die_info *orig_pdi,
9400                     const gdb_byte *info_ptr)
9401 {
9402   /* Do we know the sibling already?  */
9403
9404   if (orig_pdi->sibling)
9405     return orig_pdi->sibling;
9406
9407   /* Are there any children to deal with?  */
9408
9409   if (!orig_pdi->has_children)
9410     return info_ptr;
9411
9412   /* Skip the children the long way.  */
9413
9414   return skip_children (reader, info_ptr);
9415 }
9416
9417 /* Expand this partial symbol table into a full symbol table.  SELF is
9418    not NULL.  */
9419
9420 static void
9421 dwarf2_read_symtab (struct partial_symtab *self,
9422                     struct objfile *objfile)
9423 {
9424   struct dwarf2_per_objfile *dwarf2_per_objfile
9425     = get_dwarf2_per_objfile (objfile);
9426
9427   if (self->readin)
9428     {
9429       warning (_("bug: psymtab for %s is already read in."),
9430                self->filename);
9431     }
9432   else
9433     {
9434       if (info_verbose)
9435         {
9436           printf_filtered (_("Reading in symbols for %s..."),
9437                            self->filename);
9438           gdb_flush (gdb_stdout);
9439         }
9440
9441       /* If this psymtab is constructed from a debug-only objfile, the
9442          has_section_at_zero flag will not necessarily be correct.  We
9443          can get the correct value for this flag by looking at the data
9444          associated with the (presumably stripped) associated objfile.  */
9445       if (objfile->separate_debug_objfile_backlink)
9446         {
9447           struct dwarf2_per_objfile *dpo_backlink
9448             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9449
9450           dwarf2_per_objfile->has_section_at_zero
9451             = dpo_backlink->has_section_at_zero;
9452         }
9453
9454       dwarf2_per_objfile->reading_partial_symbols = 0;
9455
9456       psymtab_to_symtab_1 (self);
9457
9458       /* Finish up the debug error message.  */
9459       if (info_verbose)
9460         printf_filtered (_("done.\n"));
9461     }
9462
9463   process_cu_includes (dwarf2_per_objfile);
9464 }
9465 \f
9466 /* Reading in full CUs.  */
9467
9468 /* Add PER_CU to the queue.  */
9469
9470 static void
9471 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9472                  enum language pretend_language)
9473 {
9474   struct dwarf2_queue_item *item;
9475
9476   per_cu->queued = 1;
9477   item = XNEW (struct dwarf2_queue_item);
9478   item->per_cu = per_cu;
9479   item->pretend_language = pretend_language;
9480   item->next = NULL;
9481
9482   if (dwarf2_queue == NULL)
9483     dwarf2_queue = item;
9484   else
9485     dwarf2_queue_tail->next = item;
9486
9487   dwarf2_queue_tail = item;
9488 }
9489
9490 /* If PER_CU is not yet queued, add it to the queue.
9491    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9492    dependency.
9493    The result is non-zero if PER_CU was queued, otherwise the result is zero
9494    meaning either PER_CU is already queued or it is already loaded.
9495
9496    N.B. There is an invariant here that if a CU is queued then it is loaded.
9497    The caller is required to load PER_CU if we return non-zero.  */
9498
9499 static int
9500 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9501                        struct dwarf2_per_cu_data *per_cu,
9502                        enum language pretend_language)
9503 {
9504   /* We may arrive here during partial symbol reading, if we need full
9505      DIEs to process an unusual case (e.g. template arguments).  Do
9506      not queue PER_CU, just tell our caller to load its DIEs.  */
9507   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9508     {
9509       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9510         return 1;
9511       return 0;
9512     }
9513
9514   /* Mark the dependence relation so that we don't flush PER_CU
9515      too early.  */
9516   if (dependent_cu != NULL)
9517     dwarf2_add_dependence (dependent_cu, per_cu);
9518
9519   /* If it's already on the queue, we have nothing to do.  */
9520   if (per_cu->queued)
9521     return 0;
9522
9523   /* If the compilation unit is already loaded, just mark it as
9524      used.  */
9525   if (per_cu->cu != NULL)
9526     {
9527       per_cu->cu->last_used = 0;
9528       return 0;
9529     }
9530
9531   /* Add it to the queue.  */
9532   queue_comp_unit (per_cu, pretend_language);
9533
9534   return 1;
9535 }
9536
9537 /* Process the queue.  */
9538
9539 static void
9540 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9541 {
9542   struct dwarf2_queue_item *item, *next_item;
9543
9544   if (dwarf_read_debug)
9545     {
9546       fprintf_unfiltered (gdb_stdlog,
9547                           "Expanding one or more symtabs of objfile %s ...\n",
9548                           objfile_name (dwarf2_per_objfile->objfile));
9549     }
9550
9551   /* The queue starts out with one item, but following a DIE reference
9552      may load a new CU, adding it to the end of the queue.  */
9553   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9554     {
9555       if ((dwarf2_per_objfile->using_index
9556            ? !item->per_cu->v.quick->compunit_symtab
9557            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9558           /* Skip dummy CUs.  */
9559           && item->per_cu->cu != NULL)
9560         {
9561           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9562           unsigned int debug_print_threshold;
9563           char buf[100];
9564
9565           if (per_cu->is_debug_types)
9566             {
9567               struct signatured_type *sig_type =
9568                 (struct signatured_type *) per_cu;
9569
9570               sprintf (buf, "TU %s at offset %s",
9571                        hex_string (sig_type->signature),
9572                        sect_offset_str (per_cu->sect_off));
9573               /* There can be 100s of TUs.
9574                  Only print them in verbose mode.  */
9575               debug_print_threshold = 2;
9576             }
9577           else
9578             {
9579               sprintf (buf, "CU at offset %s",
9580                        sect_offset_str (per_cu->sect_off));
9581               debug_print_threshold = 1;
9582             }
9583
9584           if (dwarf_read_debug >= debug_print_threshold)
9585             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9586
9587           if (per_cu->is_debug_types)
9588             process_full_type_unit (per_cu, item->pretend_language);
9589           else
9590             process_full_comp_unit (per_cu, item->pretend_language);
9591
9592           if (dwarf_read_debug >= debug_print_threshold)
9593             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9594         }
9595
9596       item->per_cu->queued = 0;
9597       next_item = item->next;
9598       xfree (item);
9599     }
9600
9601   dwarf2_queue_tail = NULL;
9602
9603   if (dwarf_read_debug)
9604     {
9605       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9606                           objfile_name (dwarf2_per_objfile->objfile));
9607     }
9608 }
9609
9610 /* Read in full symbols for PST, and anything it depends on.  */
9611
9612 static void
9613 psymtab_to_symtab_1 (struct partial_symtab *pst)
9614 {
9615   struct dwarf2_per_cu_data *per_cu;
9616   int i;
9617
9618   if (pst->readin)
9619     return;
9620
9621   for (i = 0; i < pst->number_of_dependencies; i++)
9622     if (!pst->dependencies[i]->readin
9623         && pst->dependencies[i]->user == NULL)
9624       {
9625         /* Inform about additional files that need to be read in.  */
9626         if (info_verbose)
9627           {
9628             /* FIXME: i18n: Need to make this a single string.  */
9629             fputs_filtered (" ", gdb_stdout);
9630             wrap_here ("");
9631             fputs_filtered ("and ", gdb_stdout);
9632             wrap_here ("");
9633             printf_filtered ("%s...", pst->dependencies[i]->filename);
9634             wrap_here ("");     /* Flush output.  */
9635             gdb_flush (gdb_stdout);
9636           }
9637         psymtab_to_symtab_1 (pst->dependencies[i]);
9638       }
9639
9640   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9641
9642   if (per_cu == NULL)
9643     {
9644       /* It's an include file, no symbols to read for it.
9645          Everything is in the parent symtab.  */
9646       pst->readin = 1;
9647       return;
9648     }
9649
9650   dw2_do_instantiate_symtab (per_cu);
9651 }
9652
9653 /* Trivial hash function for die_info: the hash value of a DIE
9654    is its offset in .debug_info for this objfile.  */
9655
9656 static hashval_t
9657 die_hash (const void *item)
9658 {
9659   const struct die_info *die = (const struct die_info *) item;
9660
9661   return to_underlying (die->sect_off);
9662 }
9663
9664 /* Trivial comparison function for die_info structures: two DIEs
9665    are equal if they have the same offset.  */
9666
9667 static int
9668 die_eq (const void *item_lhs, const void *item_rhs)
9669 {
9670   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9671   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9672
9673   return die_lhs->sect_off == die_rhs->sect_off;
9674 }
9675
9676 /* die_reader_func for load_full_comp_unit.
9677    This is identical to read_signatured_type_reader,
9678    but is kept separate for now.  */
9679
9680 static void
9681 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9682                             const gdb_byte *info_ptr,
9683                             struct die_info *comp_unit_die,
9684                             int has_children,
9685                             void *data)
9686 {
9687   struct dwarf2_cu *cu = reader->cu;
9688   enum language *language_ptr = (enum language *) data;
9689
9690   gdb_assert (cu->die_hash == NULL);
9691   cu->die_hash =
9692     htab_create_alloc_ex (cu->header.length / 12,
9693                           die_hash,
9694                           die_eq,
9695                           NULL,
9696                           &cu->comp_unit_obstack,
9697                           hashtab_obstack_allocate,
9698                           dummy_obstack_deallocate);
9699
9700   if (has_children)
9701     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9702                                                   &info_ptr, comp_unit_die);
9703   cu->dies = comp_unit_die;
9704   /* comp_unit_die is not stored in die_hash, no need.  */
9705
9706   /* We try not to read any attributes in this function, because not
9707      all CUs needed for references have been loaded yet, and symbol
9708      table processing isn't initialized.  But we have to set the CU language,
9709      or we won't be able to build types correctly.
9710      Similarly, if we do not read the producer, we can not apply
9711      producer-specific interpretation.  */
9712   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9713 }
9714
9715 /* Load the DIEs associated with PER_CU into memory.  */
9716
9717 static void
9718 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9719                      enum language pretend_language)
9720 {
9721   gdb_assert (! this_cu->is_debug_types);
9722
9723   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
9724                            load_full_comp_unit_reader, &pretend_language);
9725 }
9726
9727 /* Add a DIE to the delayed physname list.  */
9728
9729 static void
9730 add_to_method_list (struct type *type, int fnfield_index, int index,
9731                     const char *name, struct die_info *die,
9732                     struct dwarf2_cu *cu)
9733 {
9734   struct delayed_method_info mi;
9735   mi.type = type;
9736   mi.fnfield_index = fnfield_index;
9737   mi.index = index;
9738   mi.name = name;
9739   mi.die = die;
9740   cu->method_list.push_back (mi);
9741 }
9742
9743 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9744    "const" / "volatile".  If so, decrements LEN by the length of the
9745    modifier and return true.  Otherwise return false.  */
9746
9747 template<size_t N>
9748 static bool
9749 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9750 {
9751   size_t mod_len = sizeof (mod) - 1;
9752   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9753     {
9754       len -= mod_len;
9755       return true;
9756     }
9757   return false;
9758 }
9759
9760 /* Compute the physnames of any methods on the CU's method list.
9761
9762    The computation of method physnames is delayed in order to avoid the
9763    (bad) condition that one of the method's formal parameters is of an as yet
9764    incomplete type.  */
9765
9766 static void
9767 compute_delayed_physnames (struct dwarf2_cu *cu)
9768 {
9769   /* Only C++ delays computing physnames.  */
9770   if (cu->method_list.empty ())
9771     return;
9772   gdb_assert (cu->language == language_cplus);
9773
9774   for (struct delayed_method_info &mi : cu->method_list)
9775     {
9776       const char *physname;
9777       struct fn_fieldlist *fn_flp
9778         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9779       physname = dwarf2_physname (mi.name, mi.die, cu);
9780       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9781         = physname ? physname : "";
9782
9783       /* Since there's no tag to indicate whether a method is a
9784          const/volatile overload, extract that information out of the
9785          demangled name.  */
9786       if (physname != NULL)
9787         {
9788           size_t len = strlen (physname);
9789
9790           while (1)
9791             {
9792               if (physname[len] == ')') /* shortcut */
9793                 break;
9794               else if (check_modifier (physname, len, " const"))
9795                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9796               else if (check_modifier (physname, len, " volatile"))
9797                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9798               else
9799                 break;
9800             }
9801         }
9802     }
9803
9804   /* The list is no longer needed.  */
9805   cu->method_list.clear ();
9806 }
9807
9808 /* Go objects should be embedded in a DW_TAG_module DIE,
9809    and it's not clear if/how imported objects will appear.
9810    To keep Go support simple until that's worked out,
9811    go back through what we've read and create something usable.
9812    We could do this while processing each DIE, and feels kinda cleaner,
9813    but that way is more invasive.
9814    This is to, for example, allow the user to type "p var" or "b main"
9815    without having to specify the package name, and allow lookups
9816    of module.object to work in contexts that use the expression
9817    parser.  */
9818
9819 static void
9820 fixup_go_packaging (struct dwarf2_cu *cu)
9821 {
9822   char *package_name = NULL;
9823   struct pending *list;
9824   int i;
9825
9826   for (list = global_symbols; list != NULL; list = list->next)
9827     {
9828       for (i = 0; i < list->nsyms; ++i)
9829         {
9830           struct symbol *sym = list->symbol[i];
9831
9832           if (SYMBOL_LANGUAGE (sym) == language_go
9833               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9834             {
9835               char *this_package_name = go_symbol_package_name (sym);
9836
9837               if (this_package_name == NULL)
9838                 continue;
9839               if (package_name == NULL)
9840                 package_name = this_package_name;
9841               else
9842                 {
9843                   struct objfile *objfile
9844                     = cu->per_cu->dwarf2_per_objfile->objfile;
9845                   if (strcmp (package_name, this_package_name) != 0)
9846                     complaint (&symfile_complaints,
9847                                _("Symtab %s has objects from two different Go packages: %s and %s"),
9848                                (symbol_symtab (sym) != NULL
9849                                 ? symtab_to_filename_for_display
9850                                     (symbol_symtab (sym))
9851                                 : objfile_name (objfile)),
9852                                this_package_name, package_name);
9853                   xfree (this_package_name);
9854                 }
9855             }
9856         }
9857     }
9858
9859   if (package_name != NULL)
9860     {
9861       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9862       const char *saved_package_name
9863         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9864                                         package_name,
9865                                         strlen (package_name));
9866       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9867                                      saved_package_name);
9868       struct symbol *sym;
9869
9870       TYPE_TAG_NAME (type) = TYPE_NAME (type);
9871
9872       sym = allocate_symbol (objfile);
9873       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9874       SYMBOL_SET_NAMES (sym, saved_package_name,
9875                         strlen (saved_package_name), 0, objfile);
9876       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9877          e.g., "main" finds the "main" module and not C's main().  */
9878       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9879       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9880       SYMBOL_TYPE (sym) = type;
9881
9882       add_symbol_to_list (sym, &global_symbols);
9883
9884       xfree (package_name);
9885     }
9886 }
9887
9888 /* Allocate a fully-qualified name consisting of the two parts on the
9889    obstack.  */
9890
9891 static const char *
9892 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9893 {
9894   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9895 }
9896
9897 /* A helper that allocates a struct discriminant_info to attach to a
9898    union type.  */
9899
9900 static struct discriminant_info *
9901 alloc_discriminant_info (struct type *type, int discriminant_index,
9902                          int default_index)
9903 {
9904   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9905   gdb_assert (discriminant_index == -1
9906               || (discriminant_index >= 0
9907                   && discriminant_index < TYPE_NFIELDS (type)));
9908   gdb_assert (default_index == -1
9909               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9910
9911   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9912
9913   struct discriminant_info *disc
9914     = ((struct discriminant_info *)
9915        TYPE_ZALLOC (type,
9916                     offsetof (struct discriminant_info, discriminants)
9917                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9918   disc->default_index = default_index;
9919   disc->discriminant_index = discriminant_index;
9920
9921   struct dynamic_prop prop;
9922   prop.kind = PROP_UNDEFINED;
9923   prop.data.baton = disc;
9924
9925   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9926
9927   return disc;
9928 }
9929
9930 /* Some versions of rustc emitted enums in an unusual way.
9931
9932    Ordinary enums were emitted as unions.  The first element of each
9933    structure in the union was named "RUST$ENUM$DISR".  This element
9934    held the discriminant.
9935
9936    These versions of Rust also implemented the "non-zero"
9937    optimization.  When the enum had two values, and one is empty and
9938    the other holds a pointer that cannot be zero, the pointer is used
9939    as the discriminant, with a zero value meaning the empty variant.
9940    Here, the union's first member is of the form
9941    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9942    where the fieldnos are the indices of the fields that should be
9943    traversed in order to find the field (which may be several fields deep)
9944    and the variantname is the name of the variant of the case when the
9945    field is zero.
9946
9947    This function recognizes whether TYPE is of one of these forms,
9948    and, if so, smashes it to be a variant type.  */
9949
9950 static void
9951 quirk_rust_enum (struct type *type, struct objfile *objfile)
9952 {
9953   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9954
9955   /* We don't need to deal with empty enums.  */
9956   if (TYPE_NFIELDS (type) == 0)
9957     return;
9958
9959 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9960   if (TYPE_NFIELDS (type) == 1
9961       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9962     {
9963       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9964
9965       /* Decode the field name to find the offset of the
9966          discriminant.  */
9967       ULONGEST bit_offset = 0;
9968       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9969       while (name[0] >= '0' && name[0] <= '9')
9970         {
9971           char *tail;
9972           unsigned long index = strtoul (name, &tail, 10);
9973           name = tail;
9974           if (*name != '$'
9975               || index >= TYPE_NFIELDS (field_type)
9976               || (TYPE_FIELD_LOC_KIND (field_type, index)
9977                   != FIELD_LOC_KIND_BITPOS))
9978             {
9979               complaint (&symfile_complaints,
9980                          _("Could not parse Rust enum encoding string \"%s\""
9981                            "[in module %s]"),
9982                          TYPE_FIELD_NAME (type, 0),
9983                          objfile_name (objfile));
9984               return;
9985             }
9986           ++name;
9987
9988           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9989           field_type = TYPE_FIELD_TYPE (field_type, index);
9990         }
9991
9992       /* Make a union to hold the variants.  */
9993       struct type *union_type = alloc_type (objfile);
9994       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9995       TYPE_NFIELDS (union_type) = 3;
9996       TYPE_FIELDS (union_type)
9997         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9998       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9999
10000       /* Put the discriminant must at index 0.  */
10001       TYPE_FIELD_TYPE (union_type, 0) = field_type;
10002       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10003       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10004       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
10005
10006       /* The order of fields doesn't really matter, so put the real
10007          field at index 1 and the data-less field at index 2.  */
10008       struct discriminant_info *disc
10009         = alloc_discriminant_info (union_type, 0, 1);
10010       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
10011       TYPE_FIELD_NAME (union_type, 1)
10012         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
10013       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
10014         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10015                               TYPE_FIELD_NAME (union_type, 1));
10016
10017       const char *dataless_name
10018         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10019                               name);
10020       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
10021                                               dataless_name);
10022       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
10023       /* NAME points into the original discriminant name, which
10024          already has the correct lifetime.  */
10025       TYPE_FIELD_NAME (union_type, 2) = name;
10026       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10027       disc->discriminants[2] = 0;
10028
10029       /* Smash this type to be a structure type.  We have to do this
10030          because the type has already been recorded.  */
10031       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10032       TYPE_NFIELDS (type) = 1;
10033       TYPE_FIELDS (type)
10034         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10035
10036       /* Install the variant part.  */
10037       TYPE_FIELD_TYPE (type, 0) = union_type;
10038       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10039       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10040     }
10041   else if (TYPE_NFIELDS (type) == 1)
10042     {
10043       /* We assume that a union with a single field is a univariant
10044          enum.  */
10045       /* Smash this type to be a structure type.  We have to do this
10046          because the type has already been recorded.  */
10047       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10048
10049       /* Make a union to hold the variants.  */
10050       struct type *union_type = alloc_type (objfile);
10051       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10052       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10053       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10054       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10055
10056       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10057       const char *variant_name
10058         = rust_last_path_segment (TYPE_NAME (field_type));
10059       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10060       TYPE_NAME (field_type)
10061         = rust_fully_qualify (&objfile->objfile_obstack,
10062                               TYPE_NAME (type), variant_name);
10063
10064       /* Install the union in the outer struct type.  */
10065       TYPE_NFIELDS (type) = 1;
10066       TYPE_FIELDS (type)
10067         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10068       TYPE_FIELD_TYPE (type, 0) = union_type;
10069       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10070       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10071
10072       alloc_discriminant_info (union_type, -1, 0);
10073     }
10074   else
10075     {
10076       struct type *disr_type = nullptr;
10077       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10078         {
10079           disr_type = TYPE_FIELD_TYPE (type, i);
10080
10081           if (TYPE_NFIELDS (disr_type) == 0)
10082             {
10083               /* Could be data-less variant, so keep going.  */
10084             }
10085           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10086                            "RUST$ENUM$DISR") != 0)
10087             {
10088               /* Not a Rust enum.  */
10089               return;
10090             }
10091           else
10092             {
10093               /* Found one.  */
10094               break;
10095             }
10096         }
10097
10098       /* If we got here without a discriminant, then it's probably
10099          just a union.  */
10100       if (disr_type == nullptr)
10101         return;
10102
10103       /* Smash this type to be a structure type.  We have to do this
10104          because the type has already been recorded.  */
10105       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10106
10107       /* Make a union to hold the variants.  */
10108       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10109       struct type *union_type = alloc_type (objfile);
10110       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10111       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10112       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10113       TYPE_FIELDS (union_type)
10114         = (struct field *) TYPE_ZALLOC (union_type,
10115                                         (TYPE_NFIELDS (union_type)
10116                                          * sizeof (struct field)));
10117
10118       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10119               TYPE_NFIELDS (type) * sizeof (struct field));
10120
10121       /* Install the discriminant at index 0 in the union.  */
10122       TYPE_FIELD (union_type, 0) = *disr_field;
10123       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10124       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10125
10126       /* Install the union in the outer struct type.  */
10127       TYPE_FIELD_TYPE (type, 0) = union_type;
10128       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10129       TYPE_NFIELDS (type) = 1;
10130
10131       /* Set the size and offset of the union type.  */
10132       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10133
10134       /* We need a way to find the correct discriminant given a
10135          variant name.  For convenience we build a map here.  */
10136       struct type *enum_type = FIELD_TYPE (*disr_field);
10137       std::unordered_map<std::string, ULONGEST> discriminant_map;
10138       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10139         {
10140           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10141             {
10142               const char *name
10143                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10144               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10145             }
10146         }
10147
10148       int n_fields = TYPE_NFIELDS (union_type);
10149       struct discriminant_info *disc
10150         = alloc_discriminant_info (union_type, 0, -1);
10151       /* Skip the discriminant here.  */
10152       for (int i = 1; i < n_fields; ++i)
10153         {
10154           /* Find the final word in the name of this variant's type.
10155              That name can be used to look up the correct
10156              discriminant.  */
10157           const char *variant_name
10158             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10159                                                                   i)));
10160
10161           auto iter = discriminant_map.find (variant_name);
10162           if (iter != discriminant_map.end ())
10163             disc->discriminants[i] = iter->second;
10164
10165           /* Remove the discriminant field.  */
10166           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10167           --TYPE_NFIELDS (sub_type);
10168           ++TYPE_FIELDS (sub_type);
10169           TYPE_FIELD_NAME (union_type, i) = variant_name;
10170           TYPE_NAME (sub_type)
10171             = rust_fully_qualify (&objfile->objfile_obstack,
10172                                   TYPE_NAME (type), variant_name);
10173         }
10174     }
10175 }
10176
10177 /* Rewrite some Rust unions to be structures with variants parts.  */
10178
10179 static void
10180 rust_union_quirks (struct dwarf2_cu *cu)
10181 {
10182   gdb_assert (cu->language == language_rust);
10183   for (struct type *type : cu->rust_unions)
10184     quirk_rust_enum (type, cu->per_cu->dwarf2_per_objfile->objfile);
10185 }
10186
10187 /* Return the symtab for PER_CU.  This works properly regardless of
10188    whether we're using the index or psymtabs.  */
10189
10190 static struct compunit_symtab *
10191 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10192 {
10193   return (per_cu->dwarf2_per_objfile->using_index
10194           ? per_cu->v.quick->compunit_symtab
10195           : per_cu->v.psymtab->compunit_symtab);
10196 }
10197
10198 /* A helper function for computing the list of all symbol tables
10199    included by PER_CU.  */
10200
10201 static void
10202 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10203                                 htab_t all_children, htab_t all_type_symtabs,
10204                                 struct dwarf2_per_cu_data *per_cu,
10205                                 struct compunit_symtab *immediate_parent)
10206 {
10207   void **slot;
10208   int ix;
10209   struct compunit_symtab *cust;
10210   struct dwarf2_per_cu_data *iter;
10211
10212   slot = htab_find_slot (all_children, per_cu, INSERT);
10213   if (*slot != NULL)
10214     {
10215       /* This inclusion and its children have been processed.  */
10216       return;
10217     }
10218
10219   *slot = per_cu;
10220   /* Only add a CU if it has a symbol table.  */
10221   cust = get_compunit_symtab (per_cu);
10222   if (cust != NULL)
10223     {
10224       /* If this is a type unit only add its symbol table if we haven't
10225          seen it yet (type unit per_cu's can share symtabs).  */
10226       if (per_cu->is_debug_types)
10227         {
10228           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10229           if (*slot == NULL)
10230             {
10231               *slot = cust;
10232               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10233               if (cust->user == NULL)
10234                 cust->user = immediate_parent;
10235             }
10236         }
10237       else
10238         {
10239           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10240           if (cust->user == NULL)
10241             cust->user = immediate_parent;
10242         }
10243     }
10244
10245   for (ix = 0;
10246        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10247        ++ix)
10248     {
10249       recursively_compute_inclusions (result, all_children,
10250                                       all_type_symtabs, iter, cust);
10251     }
10252 }
10253
10254 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10255    PER_CU.  */
10256
10257 static void
10258 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10259 {
10260   gdb_assert (! per_cu->is_debug_types);
10261
10262   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10263     {
10264       int ix, len;
10265       struct dwarf2_per_cu_data *per_cu_iter;
10266       struct compunit_symtab *compunit_symtab_iter;
10267       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10268       htab_t all_children, all_type_symtabs;
10269       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10270
10271       /* If we don't have a symtab, we can just skip this case.  */
10272       if (cust == NULL)
10273         return;
10274
10275       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10276                                         NULL, xcalloc, xfree);
10277       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10278                                             NULL, xcalloc, xfree);
10279
10280       for (ix = 0;
10281            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10282                         ix, per_cu_iter);
10283            ++ix)
10284         {
10285           recursively_compute_inclusions (&result_symtabs, all_children,
10286                                           all_type_symtabs, per_cu_iter,
10287                                           cust);
10288         }
10289
10290       /* Now we have a transitive closure of all the included symtabs.  */
10291       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10292       cust->includes
10293         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10294                      struct compunit_symtab *, len + 1);
10295       for (ix = 0;
10296            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10297                         compunit_symtab_iter);
10298            ++ix)
10299         cust->includes[ix] = compunit_symtab_iter;
10300       cust->includes[len] = NULL;
10301
10302       VEC_free (compunit_symtab_ptr, result_symtabs);
10303       htab_delete (all_children);
10304       htab_delete (all_type_symtabs);
10305     }
10306 }
10307
10308 /* Compute the 'includes' field for the symtabs of all the CUs we just
10309    read.  */
10310
10311 static void
10312 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10313 {
10314   int ix;
10315   struct dwarf2_per_cu_data *iter;
10316
10317   for (ix = 0;
10318        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10319                     ix, iter);
10320        ++ix)
10321     {
10322       if (! iter->is_debug_types)
10323         compute_compunit_symtab_includes (iter);
10324     }
10325
10326   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10327 }
10328
10329 /* Generate full symbol information for PER_CU, whose DIEs have
10330    already been loaded into memory.  */
10331
10332 static void
10333 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10334                         enum language pretend_language)
10335 {
10336   struct dwarf2_cu *cu = per_cu->cu;
10337   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10338   struct objfile *objfile = dwarf2_per_objfile->objfile;
10339   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10340   CORE_ADDR lowpc, highpc;
10341   struct compunit_symtab *cust;
10342   CORE_ADDR baseaddr;
10343   struct block *static_block;
10344   CORE_ADDR addr;
10345
10346   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10347
10348   buildsym_init ();
10349   scoped_free_pendings free_pending;
10350
10351   /* Clear the list here in case something was left over.  */
10352   cu->method_list.clear ();
10353
10354   cu->list_in_scope = &file_symbols;
10355
10356   cu->language = pretend_language;
10357   cu->language_defn = language_def (cu->language);
10358
10359   /* Do line number decoding in read_file_scope () */
10360   process_die (cu->dies, cu);
10361
10362   /* For now fudge the Go package.  */
10363   if (cu->language == language_go)
10364     fixup_go_packaging (cu);
10365
10366   /* Now that we have processed all the DIEs in the CU, all the types 
10367      should be complete, and it should now be safe to compute all of the
10368      physnames.  */
10369   compute_delayed_physnames (cu);
10370
10371   if (cu->language == language_rust)
10372     rust_union_quirks (cu);
10373
10374   /* Some compilers don't define a DW_AT_high_pc attribute for the
10375      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10376      it, by scanning the DIE's below the compilation unit.  */
10377   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10378
10379   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10380   static_block = end_symtab_get_static_block (addr, 0, 1);
10381
10382   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10383      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10384      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10385      addrmap to help ensure it has an accurate map of pc values belonging to
10386      this comp unit.  */
10387   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10388
10389   cust = end_symtab_from_static_block (static_block,
10390                                        SECT_OFF_TEXT (objfile), 0);
10391
10392   if (cust != NULL)
10393     {
10394       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10395
10396       /* Set symtab language to language from DW_AT_language.  If the
10397          compilation is from a C file generated by language preprocessors, do
10398          not set the language if it was already deduced by start_subfile.  */
10399       if (!(cu->language == language_c
10400             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10401         COMPUNIT_FILETABS (cust)->language = cu->language;
10402
10403       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10404          produce DW_AT_location with location lists but it can be possibly
10405          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10406          there were bugs in prologue debug info, fixed later in GCC-4.5
10407          by "unwind info for epilogues" patch (which is not directly related).
10408
10409          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10410          needed, it would be wrong due to missing DW_AT_producer there.
10411
10412          Still one can confuse GDB by using non-standard GCC compilation
10413          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10414          */ 
10415       if (cu->has_loclist && gcc_4_minor >= 5)
10416         cust->locations_valid = 1;
10417
10418       if (gcc_4_minor >= 5)
10419         cust->epilogue_unwind_valid = 1;
10420
10421       cust->call_site_htab = cu->call_site_htab;
10422     }
10423
10424   if (dwarf2_per_objfile->using_index)
10425     per_cu->v.quick->compunit_symtab = cust;
10426   else
10427     {
10428       struct partial_symtab *pst = per_cu->v.psymtab;
10429       pst->compunit_symtab = cust;
10430       pst->readin = 1;
10431     }
10432
10433   /* Push it for inclusion processing later.  */
10434   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10435 }
10436
10437 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10438    already been loaded into memory.  */
10439
10440 static void
10441 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10442                         enum language pretend_language)
10443 {
10444   struct dwarf2_cu *cu = per_cu->cu;
10445   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10446   struct objfile *objfile = dwarf2_per_objfile->objfile;
10447   struct compunit_symtab *cust;
10448   struct signatured_type *sig_type;
10449
10450   gdb_assert (per_cu->is_debug_types);
10451   sig_type = (struct signatured_type *) per_cu;
10452
10453   buildsym_init ();
10454   scoped_free_pendings free_pending;
10455
10456   /* Clear the list here in case something was left over.  */
10457   cu->method_list.clear ();
10458
10459   cu->list_in_scope = &file_symbols;
10460
10461   cu->language = pretend_language;
10462   cu->language_defn = language_def (cu->language);
10463
10464   /* The symbol tables are set up in read_type_unit_scope.  */
10465   process_die (cu->dies, cu);
10466
10467   /* For now fudge the Go package.  */
10468   if (cu->language == language_go)
10469     fixup_go_packaging (cu);
10470
10471   /* Now that we have processed all the DIEs in the CU, all the types 
10472      should be complete, and it should now be safe to compute all of the
10473      physnames.  */
10474   compute_delayed_physnames (cu);
10475
10476   if (cu->language == language_rust)
10477     rust_union_quirks (cu);
10478
10479   /* TUs share symbol tables.
10480      If this is the first TU to use this symtab, complete the construction
10481      of it with end_expandable_symtab.  Otherwise, complete the addition of
10482      this TU's symbols to the existing symtab.  */
10483   if (sig_type->type_unit_group->compunit_symtab == NULL)
10484     {
10485       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10486       sig_type->type_unit_group->compunit_symtab = cust;
10487
10488       if (cust != NULL)
10489         {
10490           /* Set symtab language to language from DW_AT_language.  If the
10491              compilation is from a C file generated by language preprocessors,
10492              do not set the language if it was already deduced by
10493              start_subfile.  */
10494           if (!(cu->language == language_c
10495                 && COMPUNIT_FILETABS (cust)->language != language_c))
10496             COMPUNIT_FILETABS (cust)->language = cu->language;
10497         }
10498     }
10499   else
10500     {
10501       augment_type_symtab ();
10502       cust = sig_type->type_unit_group->compunit_symtab;
10503     }
10504
10505   if (dwarf2_per_objfile->using_index)
10506     per_cu->v.quick->compunit_symtab = cust;
10507   else
10508     {
10509       struct partial_symtab *pst = per_cu->v.psymtab;
10510       pst->compunit_symtab = cust;
10511       pst->readin = 1;
10512     }
10513 }
10514
10515 /* Process an imported unit DIE.  */
10516
10517 static void
10518 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10519 {
10520   struct attribute *attr;
10521
10522   /* For now we don't handle imported units in type units.  */
10523   if (cu->per_cu->is_debug_types)
10524     {
10525       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10526                " supported in type units [in module %s]"),
10527              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10528     }
10529
10530   attr = dwarf2_attr (die, DW_AT_import, cu);
10531   if (attr != NULL)
10532     {
10533       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10534       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10535       dwarf2_per_cu_data *per_cu
10536         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10537                                             cu->per_cu->dwarf2_per_objfile);
10538
10539       /* If necessary, add it to the queue and load its DIEs.  */
10540       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10541         load_full_comp_unit (per_cu, cu->language);
10542
10543       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10544                      per_cu);
10545     }
10546 }
10547
10548 /* RAII object that represents a process_die scope: i.e.,
10549    starts/finishes processing a DIE.  */
10550 class process_die_scope
10551 {
10552 public:
10553   process_die_scope (die_info *die, dwarf2_cu *cu)
10554     : m_die (die), m_cu (cu)
10555   {
10556     /* We should only be processing DIEs not already in process.  */
10557     gdb_assert (!m_die->in_process);
10558     m_die->in_process = true;
10559   }
10560
10561   ~process_die_scope ()
10562   {
10563     m_die->in_process = false;
10564
10565     /* If we're done processing the DIE for the CU that owns the line
10566        header, we don't need the line header anymore.  */
10567     if (m_cu->line_header_die_owner == m_die)
10568       {
10569         delete m_cu->line_header;
10570         m_cu->line_header = NULL;
10571         m_cu->line_header_die_owner = NULL;
10572       }
10573   }
10574
10575 private:
10576   die_info *m_die;
10577   dwarf2_cu *m_cu;
10578 };
10579
10580 /* Process a die and its children.  */
10581
10582 static void
10583 process_die (struct die_info *die, struct dwarf2_cu *cu)
10584 {
10585   process_die_scope scope (die, cu);
10586
10587   switch (die->tag)
10588     {
10589     case DW_TAG_padding:
10590       break;
10591     case DW_TAG_compile_unit:
10592     case DW_TAG_partial_unit:
10593       read_file_scope (die, cu);
10594       break;
10595     case DW_TAG_type_unit:
10596       read_type_unit_scope (die, cu);
10597       break;
10598     case DW_TAG_subprogram:
10599     case DW_TAG_inlined_subroutine:
10600       read_func_scope (die, cu);
10601       break;
10602     case DW_TAG_lexical_block:
10603     case DW_TAG_try_block:
10604     case DW_TAG_catch_block:
10605       read_lexical_block_scope (die, cu);
10606       break;
10607     case DW_TAG_call_site:
10608     case DW_TAG_GNU_call_site:
10609       read_call_site_scope (die, cu);
10610       break;
10611     case DW_TAG_class_type:
10612     case DW_TAG_interface_type:
10613     case DW_TAG_structure_type:
10614     case DW_TAG_union_type:
10615       process_structure_scope (die, cu);
10616       break;
10617     case DW_TAG_enumeration_type:
10618       process_enumeration_scope (die, cu);
10619       break;
10620
10621     /* These dies have a type, but processing them does not create
10622        a symbol or recurse to process the children.  Therefore we can
10623        read them on-demand through read_type_die.  */
10624     case DW_TAG_subroutine_type:
10625     case DW_TAG_set_type:
10626     case DW_TAG_array_type:
10627     case DW_TAG_pointer_type:
10628     case DW_TAG_ptr_to_member_type:
10629     case DW_TAG_reference_type:
10630     case DW_TAG_rvalue_reference_type:
10631     case DW_TAG_string_type:
10632       break;
10633
10634     case DW_TAG_base_type:
10635     case DW_TAG_subrange_type:
10636     case DW_TAG_typedef:
10637       /* Add a typedef symbol for the type definition, if it has a
10638          DW_AT_name.  */
10639       new_symbol (die, read_type_die (die, cu), cu);
10640       break;
10641     case DW_TAG_common_block:
10642       read_common_block (die, cu);
10643       break;
10644     case DW_TAG_common_inclusion:
10645       break;
10646     case DW_TAG_namespace:
10647       cu->processing_has_namespace_info = 1;
10648       read_namespace (die, cu);
10649       break;
10650     case DW_TAG_module:
10651       cu->processing_has_namespace_info = 1;
10652       read_module (die, cu);
10653       break;
10654     case DW_TAG_imported_declaration:
10655       cu->processing_has_namespace_info = 1;
10656       if (read_namespace_alias (die, cu))
10657         break;
10658       /* The declaration is not a global namespace alias: fall through.  */
10659     case DW_TAG_imported_module:
10660       cu->processing_has_namespace_info = 1;
10661       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10662                                  || cu->language != language_fortran))
10663         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10664                    dwarf_tag_name (die->tag));
10665       read_import_statement (die, cu);
10666       break;
10667
10668     case DW_TAG_imported_unit:
10669       process_imported_unit_die (die, cu);
10670       break;
10671
10672     case DW_TAG_variable:
10673       read_variable (die, cu);
10674       break;
10675
10676     default:
10677       new_symbol (die, NULL, cu);
10678       break;
10679     }
10680 }
10681 \f
10682 /* DWARF name computation.  */
10683
10684 /* A helper function for dwarf2_compute_name which determines whether DIE
10685    needs to have the name of the scope prepended to the name listed in the
10686    die.  */
10687
10688 static int
10689 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10690 {
10691   struct attribute *attr;
10692
10693   switch (die->tag)
10694     {
10695     case DW_TAG_namespace:
10696     case DW_TAG_typedef:
10697     case DW_TAG_class_type:
10698     case DW_TAG_interface_type:
10699     case DW_TAG_structure_type:
10700     case DW_TAG_union_type:
10701     case DW_TAG_enumeration_type:
10702     case DW_TAG_enumerator:
10703     case DW_TAG_subprogram:
10704     case DW_TAG_inlined_subroutine:
10705     case DW_TAG_member:
10706     case DW_TAG_imported_declaration:
10707       return 1;
10708
10709     case DW_TAG_variable:
10710     case DW_TAG_constant:
10711       /* We only need to prefix "globally" visible variables.  These include
10712          any variable marked with DW_AT_external or any variable that
10713          lives in a namespace.  [Variables in anonymous namespaces
10714          require prefixing, but they are not DW_AT_external.]  */
10715
10716       if (dwarf2_attr (die, DW_AT_specification, cu))
10717         {
10718           struct dwarf2_cu *spec_cu = cu;
10719
10720           return die_needs_namespace (die_specification (die, &spec_cu),
10721                                       spec_cu);
10722         }
10723
10724       attr = dwarf2_attr (die, DW_AT_external, cu);
10725       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10726           && die->parent->tag != DW_TAG_module)
10727         return 0;
10728       /* A variable in a lexical block of some kind does not need a
10729          namespace, even though in C++ such variables may be external
10730          and have a mangled name.  */
10731       if (die->parent->tag ==  DW_TAG_lexical_block
10732           || die->parent->tag ==  DW_TAG_try_block
10733           || die->parent->tag ==  DW_TAG_catch_block
10734           || die->parent->tag == DW_TAG_subprogram)
10735         return 0;
10736       return 1;
10737
10738     default:
10739       return 0;
10740     }
10741 }
10742
10743 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10744    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10745    defined for the given DIE.  */
10746
10747 static struct attribute *
10748 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10749 {
10750   struct attribute *attr;
10751
10752   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10753   if (attr == NULL)
10754     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10755
10756   return attr;
10757 }
10758
10759 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10760    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10761    defined for the given DIE.  */
10762
10763 static const char *
10764 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10765 {
10766   const char *linkage_name;
10767
10768   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10769   if (linkage_name == NULL)
10770     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10771
10772   return linkage_name;
10773 }
10774
10775 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10776    compute the physname for the object, which include a method's:
10777    - formal parameters (C++),
10778    - receiver type (Go),
10779
10780    The term "physname" is a bit confusing.
10781    For C++, for example, it is the demangled name.
10782    For Go, for example, it's the mangled name.
10783
10784    For Ada, return the DIE's linkage name rather than the fully qualified
10785    name.  PHYSNAME is ignored..
10786
10787    The result is allocated on the objfile_obstack and canonicalized.  */
10788
10789 static const char *
10790 dwarf2_compute_name (const char *name,
10791                      struct die_info *die, struct dwarf2_cu *cu,
10792                      int physname)
10793 {
10794   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10795
10796   if (name == NULL)
10797     name = dwarf2_name (die, cu);
10798
10799   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10800      but otherwise compute it by typename_concat inside GDB.
10801      FIXME: Actually this is not really true, or at least not always true.
10802      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10803      Fortran names because there is no mangling standard.  So new_symbol
10804      will set the demangled name to the result of dwarf2_full_name, and it is
10805      the demangled name that GDB uses if it exists.  */
10806   if (cu->language == language_ada
10807       || (cu->language == language_fortran && physname))
10808     {
10809       /* For Ada unit, we prefer the linkage name over the name, as
10810          the former contains the exported name, which the user expects
10811          to be able to reference.  Ideally, we want the user to be able
10812          to reference this entity using either natural or linkage name,
10813          but we haven't started looking at this enhancement yet.  */
10814       const char *linkage_name = dw2_linkage_name (die, cu);
10815
10816       if (linkage_name != NULL)
10817         return linkage_name;
10818     }
10819
10820   /* These are the only languages we know how to qualify names in.  */
10821   if (name != NULL
10822       && (cu->language == language_cplus
10823           || cu->language == language_fortran || cu->language == language_d
10824           || cu->language == language_rust))
10825     {
10826       if (die_needs_namespace (die, cu))
10827         {
10828           const char *prefix;
10829           const char *canonical_name = NULL;
10830
10831           string_file buf;
10832
10833           prefix = determine_prefix (die, cu);
10834           if (*prefix != '\0')
10835             {
10836               char *prefixed_name = typename_concat (NULL, prefix, name,
10837                                                      physname, cu);
10838
10839               buf.puts (prefixed_name);
10840               xfree (prefixed_name);
10841             }
10842           else
10843             buf.puts (name);
10844
10845           /* Template parameters may be specified in the DIE's DW_AT_name, or
10846              as children with DW_TAG_template_type_param or
10847              DW_TAG_value_type_param.  If the latter, add them to the name
10848              here.  If the name already has template parameters, then
10849              skip this step; some versions of GCC emit both, and
10850              it is more efficient to use the pre-computed name.
10851
10852              Something to keep in mind about this process: it is very
10853              unlikely, or in some cases downright impossible, to produce
10854              something that will match the mangled name of a function.
10855              If the definition of the function has the same debug info,
10856              we should be able to match up with it anyway.  But fallbacks
10857              using the minimal symbol, for instance to find a method
10858              implemented in a stripped copy of libstdc++, will not work.
10859              If we do not have debug info for the definition, we will have to
10860              match them up some other way.
10861
10862              When we do name matching there is a related problem with function
10863              templates; two instantiated function templates are allowed to
10864              differ only by their return types, which we do not add here.  */
10865
10866           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10867             {
10868               struct attribute *attr;
10869               struct die_info *child;
10870               int first = 1;
10871
10872               die->building_fullname = 1;
10873
10874               for (child = die->child; child != NULL; child = child->sibling)
10875                 {
10876                   struct type *type;
10877                   LONGEST value;
10878                   const gdb_byte *bytes;
10879                   struct dwarf2_locexpr_baton *baton;
10880                   struct value *v;
10881
10882                   if (child->tag != DW_TAG_template_type_param
10883                       && child->tag != DW_TAG_template_value_param)
10884                     continue;
10885
10886                   if (first)
10887                     {
10888                       buf.puts ("<");
10889                       first = 0;
10890                     }
10891                   else
10892                     buf.puts (", ");
10893
10894                   attr = dwarf2_attr (child, DW_AT_type, cu);
10895                   if (attr == NULL)
10896                     {
10897                       complaint (&symfile_complaints,
10898                                  _("template parameter missing DW_AT_type"));
10899                       buf.puts ("UNKNOWN_TYPE");
10900                       continue;
10901                     }
10902                   type = die_type (child, cu);
10903
10904                   if (child->tag == DW_TAG_template_type_param)
10905                     {
10906                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10907                       continue;
10908                     }
10909
10910                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10911                   if (attr == NULL)
10912                     {
10913                       complaint (&symfile_complaints,
10914                                  _("template parameter missing "
10915                                    "DW_AT_const_value"));
10916                       buf.puts ("UNKNOWN_VALUE");
10917                       continue;
10918                     }
10919
10920                   dwarf2_const_value_attr (attr, type, name,
10921                                            &cu->comp_unit_obstack, cu,
10922                                            &value, &bytes, &baton);
10923
10924                   if (TYPE_NOSIGN (type))
10925                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10926                        changed, this can use value_print instead.  */
10927                     c_printchar (value, type, &buf);
10928                   else
10929                     {
10930                       struct value_print_options opts;
10931
10932                       if (baton != NULL)
10933                         v = dwarf2_evaluate_loc_desc (type, NULL,
10934                                                       baton->data,
10935                                                       baton->size,
10936                                                       baton->per_cu);
10937                       else if (bytes != NULL)
10938                         {
10939                           v = allocate_value (type);
10940                           memcpy (value_contents_writeable (v), bytes,
10941                                   TYPE_LENGTH (type));
10942                         }
10943                       else
10944                         v = value_from_longest (type, value);
10945
10946                       /* Specify decimal so that we do not depend on
10947                          the radix.  */
10948                       get_formatted_print_options (&opts, 'd');
10949                       opts.raw = 1;
10950                       value_print (v, &buf, &opts);
10951                       release_value (v);
10952                       value_free (v);
10953                     }
10954                 }
10955
10956               die->building_fullname = 0;
10957
10958               if (!first)
10959                 {
10960                   /* Close the argument list, with a space if necessary
10961                      (nested templates).  */
10962                   if (!buf.empty () && buf.string ().back () == '>')
10963                     buf.puts (" >");
10964                   else
10965                     buf.puts (">");
10966                 }
10967             }
10968
10969           /* For C++ methods, append formal parameter type
10970              information, if PHYSNAME.  */
10971
10972           if (physname && die->tag == DW_TAG_subprogram
10973               && cu->language == language_cplus)
10974             {
10975               struct type *type = read_type_die (die, cu);
10976
10977               c_type_print_args (type, &buf, 1, cu->language,
10978                                  &type_print_raw_options);
10979
10980               if (cu->language == language_cplus)
10981                 {
10982                   /* Assume that an artificial first parameter is
10983                      "this", but do not crash if it is not.  RealView
10984                      marks unnamed (and thus unused) parameters as
10985                      artificial; there is no way to differentiate
10986                      the two cases.  */
10987                   if (TYPE_NFIELDS (type) > 0
10988                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10989                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10990                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10991                                                                         0))))
10992                     buf.puts (" const");
10993                 }
10994             }
10995
10996           const std::string &intermediate_name = buf.string ();
10997
10998           if (cu->language == language_cplus)
10999             canonical_name
11000               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11001                                           &objfile->per_bfd->storage_obstack);
11002
11003           /* If we only computed INTERMEDIATE_NAME, or if
11004              INTERMEDIATE_NAME is already canonical, then we need to
11005              copy it to the appropriate obstack.  */
11006           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11007             name = ((const char *)
11008                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11009                                    intermediate_name.c_str (),
11010                                    intermediate_name.length ()));
11011           else
11012             name = canonical_name;
11013         }
11014     }
11015
11016   return name;
11017 }
11018
11019 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11020    If scope qualifiers are appropriate they will be added.  The result
11021    will be allocated on the storage_obstack, or NULL if the DIE does
11022    not have a name.  NAME may either be from a previous call to
11023    dwarf2_name or NULL.
11024
11025    The output string will be canonicalized (if C++).  */
11026
11027 static const char *
11028 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11029 {
11030   return dwarf2_compute_name (name, die, cu, 0);
11031 }
11032
11033 /* Construct a physname for the given DIE in CU.  NAME may either be
11034    from a previous call to dwarf2_name or NULL.  The result will be
11035    allocated on the objfile_objstack or NULL if the DIE does not have a
11036    name.
11037
11038    The output string will be canonicalized (if C++).  */
11039
11040 static const char *
11041 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11042 {
11043   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11044   const char *retval, *mangled = NULL, *canon = NULL;
11045   int need_copy = 1;
11046
11047   /* In this case dwarf2_compute_name is just a shortcut not building anything
11048      on its own.  */
11049   if (!die_needs_namespace (die, cu))
11050     return dwarf2_compute_name (name, die, cu, 1);
11051
11052   mangled = dw2_linkage_name (die, cu);
11053
11054   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11055      See https://github.com/rust-lang/rust/issues/32925.  */
11056   if (cu->language == language_rust && mangled != NULL
11057       && strchr (mangled, '{') != NULL)
11058     mangled = NULL;
11059
11060   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11061      has computed.  */
11062   gdb::unique_xmalloc_ptr<char> demangled;
11063   if (mangled != NULL)
11064     {
11065
11066       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11067         {
11068           /* Do nothing (do not demangle the symbol name).  */
11069         }
11070       else if (cu->language == language_go)
11071         {
11072           /* This is a lie, but we already lie to the caller new_symbol.
11073              new_symbol assumes we return the mangled name.
11074              This just undoes that lie until things are cleaned up.  */
11075         }
11076       else
11077         {
11078           /* Use DMGL_RET_DROP for C++ template functions to suppress
11079              their return type.  It is easier for GDB users to search
11080              for such functions as `name(params)' than `long name(params)'.
11081              In such case the minimal symbol names do not match the full
11082              symbol names but for template functions there is never a need
11083              to look up their definition from their declaration so
11084              the only disadvantage remains the minimal symbol variant
11085              `long name(params)' does not have the proper inferior type.  */
11086           demangled.reset (gdb_demangle (mangled,
11087                                          (DMGL_PARAMS | DMGL_ANSI
11088                                           | DMGL_RET_DROP)));
11089         }
11090       if (demangled)
11091         canon = demangled.get ();
11092       else
11093         {
11094           canon = mangled;
11095           need_copy = 0;
11096         }
11097     }
11098
11099   if (canon == NULL || check_physname)
11100     {
11101       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11102
11103       if (canon != NULL && strcmp (physname, canon) != 0)
11104         {
11105           /* It may not mean a bug in GDB.  The compiler could also
11106              compute DW_AT_linkage_name incorrectly.  But in such case
11107              GDB would need to be bug-to-bug compatible.  */
11108
11109           complaint (&symfile_complaints,
11110                      _("Computed physname <%s> does not match demangled <%s> "
11111                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11112                      physname, canon, mangled, sect_offset_str (die->sect_off),
11113                      objfile_name (objfile));
11114
11115           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11116              is available here - over computed PHYSNAME.  It is safer
11117              against both buggy GDB and buggy compilers.  */
11118
11119           retval = canon;
11120         }
11121       else
11122         {
11123           retval = physname;
11124           need_copy = 0;
11125         }
11126     }
11127   else
11128     retval = canon;
11129
11130   if (need_copy)
11131     retval = ((const char *)
11132               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11133                              retval, strlen (retval)));
11134
11135   return retval;
11136 }
11137
11138 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11139    a new symbol for it.
11140
11141    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11142
11143 static int
11144 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11145 {
11146   struct attribute *attr;
11147
11148   /* If the die does not have a name, this is not a namespace
11149      alias.  */
11150   attr = dwarf2_attr (die, DW_AT_name, cu);
11151   if (attr != NULL)
11152     {
11153       int num;
11154       struct die_info *d = die;
11155       struct dwarf2_cu *imported_cu = cu;
11156
11157       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11158          keep inspecting DIEs until we hit the underlying import.  */
11159 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11160       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11161         {
11162           attr = dwarf2_attr (d, DW_AT_import, cu);
11163           if (attr == NULL)
11164             break;
11165
11166           d = follow_die_ref (d, attr, &imported_cu);
11167           if (d->tag != DW_TAG_imported_declaration)
11168             break;
11169         }
11170
11171       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11172         {
11173           complaint (&symfile_complaints,
11174                      _("DIE at %s has too many recursively imported "
11175                        "declarations"), sect_offset_str (d->sect_off));
11176           return 0;
11177         }
11178
11179       if (attr != NULL)
11180         {
11181           struct type *type;
11182           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11183
11184           type = get_die_type_at_offset (sect_off, cu->per_cu);
11185           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11186             {
11187               /* This declaration is a global namespace alias.  Add
11188                  a symbol for it whose type is the aliased namespace.  */
11189               new_symbol (die, type, cu);
11190               return 1;
11191             }
11192         }
11193     }
11194
11195   return 0;
11196 }
11197
11198 /* Return the using directives repository (global or local?) to use in the
11199    current context for LANGUAGE.
11200
11201    For Ada, imported declarations can materialize renamings, which *may* be
11202    global.  However it is impossible (for now?) in DWARF to distinguish
11203    "external" imported declarations and "static" ones.  As all imported
11204    declarations seem to be static in all other languages, make them all CU-wide
11205    global only in Ada.  */
11206
11207 static struct using_direct **
11208 using_directives (enum language language)
11209 {
11210   if (language == language_ada && context_stack_depth == 0)
11211     return &global_using_directives;
11212   else
11213     return &local_using_directives;
11214 }
11215
11216 /* Read the import statement specified by the given die and record it.  */
11217
11218 static void
11219 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11220 {
11221   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11222   struct attribute *import_attr;
11223   struct die_info *imported_die, *child_die;
11224   struct dwarf2_cu *imported_cu;
11225   const char *imported_name;
11226   const char *imported_name_prefix;
11227   const char *canonical_name;
11228   const char *import_alias;
11229   const char *imported_declaration = NULL;
11230   const char *import_prefix;
11231   std::vector<const char *> excludes;
11232
11233   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11234   if (import_attr == NULL)
11235     {
11236       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11237                  dwarf_tag_name (die->tag));
11238       return;
11239     }
11240
11241   imported_cu = cu;
11242   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11243   imported_name = dwarf2_name (imported_die, imported_cu);
11244   if (imported_name == NULL)
11245     {
11246       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11247
11248         The import in the following code:
11249         namespace A
11250           {
11251             typedef int B;
11252           }
11253
11254         int main ()
11255           {
11256             using A::B;
11257             B b;
11258             return b;
11259           }
11260
11261         ...
11262          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11263             <52>   DW_AT_decl_file   : 1
11264             <53>   DW_AT_decl_line   : 6
11265             <54>   DW_AT_import      : <0x75>
11266          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11267             <59>   DW_AT_name        : B
11268             <5b>   DW_AT_decl_file   : 1
11269             <5c>   DW_AT_decl_line   : 2
11270             <5d>   DW_AT_type        : <0x6e>
11271         ...
11272          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11273             <76>   DW_AT_byte_size   : 4
11274             <77>   DW_AT_encoding    : 5        (signed)
11275
11276         imports the wrong die ( 0x75 instead of 0x58 ).
11277         This case will be ignored until the gcc bug is fixed.  */
11278       return;
11279     }
11280
11281   /* Figure out the local name after import.  */
11282   import_alias = dwarf2_name (die, cu);
11283
11284   /* Figure out where the statement is being imported to.  */
11285   import_prefix = determine_prefix (die, cu);
11286
11287   /* Figure out what the scope of the imported die is and prepend it
11288      to the name of the imported die.  */
11289   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11290
11291   if (imported_die->tag != DW_TAG_namespace
11292       && imported_die->tag != DW_TAG_module)
11293     {
11294       imported_declaration = imported_name;
11295       canonical_name = imported_name_prefix;
11296     }
11297   else if (strlen (imported_name_prefix) > 0)
11298     canonical_name = obconcat (&objfile->objfile_obstack,
11299                                imported_name_prefix,
11300                                (cu->language == language_d ? "." : "::"),
11301                                imported_name, (char *) NULL);
11302   else
11303     canonical_name = imported_name;
11304
11305   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11306     for (child_die = die->child; child_die && child_die->tag;
11307          child_die = sibling_die (child_die))
11308       {
11309         /* DWARF-4: A Fortran use statement with a “rename list” may be
11310            represented by an imported module entry with an import attribute
11311            referring to the module and owned entries corresponding to those
11312            entities that are renamed as part of being imported.  */
11313
11314         if (child_die->tag != DW_TAG_imported_declaration)
11315           {
11316             complaint (&symfile_complaints,
11317                        _("child DW_TAG_imported_declaration expected "
11318                          "- DIE at %s [in module %s]"),
11319                        sect_offset_str (child_die->sect_off),
11320                        objfile_name (objfile));
11321             continue;
11322           }
11323
11324         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11325         if (import_attr == NULL)
11326           {
11327             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11328                        dwarf_tag_name (child_die->tag));
11329             continue;
11330           }
11331
11332         imported_cu = cu;
11333         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11334                                               &imported_cu);
11335         imported_name = dwarf2_name (imported_die, imported_cu);
11336         if (imported_name == NULL)
11337           {
11338             complaint (&symfile_complaints,
11339                        _("child DW_TAG_imported_declaration has unknown "
11340                          "imported name - DIE at %s [in module %s]"),
11341                        sect_offset_str (child_die->sect_off),
11342                        objfile_name (objfile));
11343             continue;
11344           }
11345
11346         excludes.push_back (imported_name);
11347
11348         process_die (child_die, cu);
11349       }
11350
11351   add_using_directive (using_directives (cu->language),
11352                        import_prefix,
11353                        canonical_name,
11354                        import_alias,
11355                        imported_declaration,
11356                        excludes,
11357                        0,
11358                        &objfile->objfile_obstack);
11359 }
11360
11361 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11362    types, but gives them a size of zero.  Starting with version 14,
11363    ICC is compatible with GCC.  */
11364
11365 static int
11366 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11367 {
11368   if (!cu->checked_producer)
11369     check_producer (cu);
11370
11371   return cu->producer_is_icc_lt_14;
11372 }
11373
11374 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11375    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11376    this, it was first present in GCC release 4.3.0.  */
11377
11378 static int
11379 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11380 {
11381   if (!cu->checked_producer)
11382     check_producer (cu);
11383
11384   return cu->producer_is_gcc_lt_4_3;
11385 }
11386
11387 static file_and_directory
11388 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11389 {
11390   file_and_directory res;
11391
11392   /* Find the filename.  Do not use dwarf2_name here, since the filename
11393      is not a source language identifier.  */
11394   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11395   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11396
11397   if (res.comp_dir == NULL
11398       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11399       && IS_ABSOLUTE_PATH (res.name))
11400     {
11401       res.comp_dir_storage = ldirname (res.name);
11402       if (!res.comp_dir_storage.empty ())
11403         res.comp_dir = res.comp_dir_storage.c_str ();
11404     }
11405   if (res.comp_dir != NULL)
11406     {
11407       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11408          directory, get rid of it.  */
11409       const char *cp = strchr (res.comp_dir, ':');
11410
11411       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11412         res.comp_dir = cp + 1;
11413     }
11414
11415   if (res.name == NULL)
11416     res.name = "<unknown>";
11417
11418   return res;
11419 }
11420
11421 /* Handle DW_AT_stmt_list for a compilation unit.
11422    DIE is the DW_TAG_compile_unit die for CU.
11423    COMP_DIR is the compilation directory.  LOWPC is passed to
11424    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11425
11426 static void
11427 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11428                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11429 {
11430   struct dwarf2_per_objfile *dwarf2_per_objfile
11431     = cu->per_cu->dwarf2_per_objfile;
11432   struct objfile *objfile = dwarf2_per_objfile->objfile;
11433   struct attribute *attr;
11434   struct line_header line_header_local;
11435   hashval_t line_header_local_hash;
11436   void **slot;
11437   int decode_mapping;
11438
11439   gdb_assert (! cu->per_cu->is_debug_types);
11440
11441   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11442   if (attr == NULL)
11443     return;
11444
11445   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11446
11447   /* The line header hash table is only created if needed (it exists to
11448      prevent redundant reading of the line table for partial_units).
11449      If we're given a partial_unit, we'll need it.  If we're given a
11450      compile_unit, then use the line header hash table if it's already
11451      created, but don't create one just yet.  */
11452
11453   if (dwarf2_per_objfile->line_header_hash == NULL
11454       && die->tag == DW_TAG_partial_unit)
11455     {
11456       dwarf2_per_objfile->line_header_hash
11457         = htab_create_alloc_ex (127, line_header_hash_voidp,
11458                                 line_header_eq_voidp,
11459                                 free_line_header_voidp,
11460                                 &objfile->objfile_obstack,
11461                                 hashtab_obstack_allocate,
11462                                 dummy_obstack_deallocate);
11463     }
11464
11465   line_header_local.sect_off = line_offset;
11466   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11467   line_header_local_hash = line_header_hash (&line_header_local);
11468   if (dwarf2_per_objfile->line_header_hash != NULL)
11469     {
11470       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11471                                        &line_header_local,
11472                                        line_header_local_hash, NO_INSERT);
11473
11474       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11475          is not present in *SLOT (since if there is something in *SLOT then
11476          it will be for a partial_unit).  */
11477       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11478         {
11479           gdb_assert (*slot != NULL);
11480           cu->line_header = (struct line_header *) *slot;
11481           return;
11482         }
11483     }
11484
11485   /* dwarf_decode_line_header does not yet provide sufficient information.
11486      We always have to call also dwarf_decode_lines for it.  */
11487   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11488   if (lh == NULL)
11489     return;
11490
11491   cu->line_header = lh.release ();
11492   cu->line_header_die_owner = die;
11493
11494   if (dwarf2_per_objfile->line_header_hash == NULL)
11495     slot = NULL;
11496   else
11497     {
11498       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11499                                        &line_header_local,
11500                                        line_header_local_hash, INSERT);
11501       gdb_assert (slot != NULL);
11502     }
11503   if (slot != NULL && *slot == NULL)
11504     {
11505       /* This newly decoded line number information unit will be owned
11506          by line_header_hash hash table.  */
11507       *slot = cu->line_header;
11508       cu->line_header_die_owner = NULL;
11509     }
11510   else
11511     {
11512       /* We cannot free any current entry in (*slot) as that struct line_header
11513          may be already used by multiple CUs.  Create only temporary decoded
11514          line_header for this CU - it may happen at most once for each line
11515          number information unit.  And if we're not using line_header_hash
11516          then this is what we want as well.  */
11517       gdb_assert (die->tag != DW_TAG_partial_unit);
11518     }
11519   decode_mapping = (die->tag != DW_TAG_partial_unit);
11520   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11521                       decode_mapping);
11522
11523 }
11524
11525 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11526
11527 static void
11528 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11529 {
11530   struct dwarf2_per_objfile *dwarf2_per_objfile
11531     = cu->per_cu->dwarf2_per_objfile;
11532   struct objfile *objfile = dwarf2_per_objfile->objfile;
11533   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11534   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11535   CORE_ADDR highpc = ((CORE_ADDR) 0);
11536   struct attribute *attr;
11537   struct die_info *child_die;
11538   CORE_ADDR baseaddr;
11539
11540   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11541
11542   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11543
11544   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11545      from finish_block.  */
11546   if (lowpc == ((CORE_ADDR) -1))
11547     lowpc = highpc;
11548   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11549
11550   file_and_directory fnd = find_file_and_directory (die, cu);
11551
11552   prepare_one_comp_unit (cu, die, cu->language);
11553
11554   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11555      standardised yet.  As a workaround for the language detection we fall
11556      back to the DW_AT_producer string.  */
11557   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11558     cu->language = language_opencl;
11559
11560   /* Similar hack for Go.  */
11561   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11562     set_cu_language (DW_LANG_Go, cu);
11563
11564   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11565
11566   /* Decode line number information if present.  We do this before
11567      processing child DIEs, so that the line header table is available
11568      for DW_AT_decl_file.  */
11569   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11570
11571   /* Process all dies in compilation unit.  */
11572   if (die->child != NULL)
11573     {
11574       child_die = die->child;
11575       while (child_die && child_die->tag)
11576         {
11577           process_die (child_die, cu);
11578           child_die = sibling_die (child_die);
11579         }
11580     }
11581
11582   /* Decode macro information, if present.  Dwarf 2 macro information
11583      refers to information in the line number info statement program
11584      header, so we can only read it if we've read the header
11585      successfully.  */
11586   attr = dwarf2_attr (die, DW_AT_macros, cu);
11587   if (attr == NULL)
11588     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11589   if (attr && cu->line_header)
11590     {
11591       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11592         complaint (&symfile_complaints,
11593                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11594
11595       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11596     }
11597   else
11598     {
11599       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11600       if (attr && cu->line_header)
11601         {
11602           unsigned int macro_offset = DW_UNSND (attr);
11603
11604           dwarf_decode_macros (cu, macro_offset, 0);
11605         }
11606     }
11607 }
11608
11609 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11610    Create the set of symtabs used by this TU, or if this TU is sharing
11611    symtabs with another TU and the symtabs have already been created
11612    then restore those symtabs in the line header.
11613    We don't need the pc/line-number mapping for type units.  */
11614
11615 static void
11616 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11617 {
11618   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11619   struct type_unit_group *tu_group;
11620   int first_time;
11621   struct attribute *attr;
11622   unsigned int i;
11623   struct signatured_type *sig_type;
11624
11625   gdb_assert (per_cu->is_debug_types);
11626   sig_type = (struct signatured_type *) per_cu;
11627
11628   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11629
11630   /* If we're using .gdb_index (includes -readnow) then
11631      per_cu->type_unit_group may not have been set up yet.  */
11632   if (sig_type->type_unit_group == NULL)
11633     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11634   tu_group = sig_type->type_unit_group;
11635
11636   /* If we've already processed this stmt_list there's no real need to
11637      do it again, we could fake it and just recreate the part we need
11638      (file name,index -> symtab mapping).  If data shows this optimization
11639      is useful we can do it then.  */
11640   first_time = tu_group->compunit_symtab == NULL;
11641
11642   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11643      debug info.  */
11644   line_header_up lh;
11645   if (attr != NULL)
11646     {
11647       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11648       lh = dwarf_decode_line_header (line_offset, cu);
11649     }
11650   if (lh == NULL)
11651     {
11652       if (first_time)
11653         dwarf2_start_symtab (cu, "", NULL, 0);
11654       else
11655         {
11656           gdb_assert (tu_group->symtabs == NULL);
11657           restart_symtab (tu_group->compunit_symtab, "", 0);
11658         }
11659       return;
11660     }
11661
11662   cu->line_header = lh.release ();
11663   cu->line_header_die_owner = die;
11664
11665   if (first_time)
11666     {
11667       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11668
11669       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11670          still initializing it, and our caller (a few levels up)
11671          process_full_type_unit still needs to know if this is the first
11672          time.  */
11673
11674       tu_group->num_symtabs = cu->line_header->file_names.size ();
11675       tu_group->symtabs = XNEWVEC (struct symtab *,
11676                                    cu->line_header->file_names.size ());
11677
11678       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11679         {
11680           file_entry &fe = cu->line_header->file_names[i];
11681
11682           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11683
11684           if (current_subfile->symtab == NULL)
11685             {
11686               /* NOTE: start_subfile will recognize when it's been
11687                  passed a file it has already seen.  So we can't
11688                  assume there's a simple mapping from
11689                  cu->line_header->file_names to subfiles, plus
11690                  cu->line_header->file_names may contain dups.  */
11691               current_subfile->symtab
11692                 = allocate_symtab (cust, current_subfile->name);
11693             }
11694
11695           fe.symtab = current_subfile->symtab;
11696           tu_group->symtabs[i] = fe.symtab;
11697         }
11698     }
11699   else
11700     {
11701       restart_symtab (tu_group->compunit_symtab, "", 0);
11702
11703       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11704         {
11705           file_entry &fe = cu->line_header->file_names[i];
11706
11707           fe.symtab = tu_group->symtabs[i];
11708         }
11709     }
11710
11711   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11712      so they don't have a "real" (so to speak) symtab anyway.
11713      There is later code that will assign the main symtab to all symbols
11714      that don't have one.  We need to handle the case of a symbol with a
11715      missing symtab (DW_AT_decl_file) anyway.  */
11716 }
11717
11718 /* Process DW_TAG_type_unit.
11719    For TUs we want to skip the first top level sibling if it's not the
11720    actual type being defined by this TU.  In this case the first top
11721    level sibling is there to provide context only.  */
11722
11723 static void
11724 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11725 {
11726   struct die_info *child_die;
11727
11728   prepare_one_comp_unit (cu, die, language_minimal);
11729
11730   /* Initialize (or reinitialize) the machinery for building symtabs.
11731      We do this before processing child DIEs, so that the line header table
11732      is available for DW_AT_decl_file.  */
11733   setup_type_unit_groups (die, cu);
11734
11735   if (die->child != NULL)
11736     {
11737       child_die = die->child;
11738       while (child_die && child_die->tag)
11739         {
11740           process_die (child_die, cu);
11741           child_die = sibling_die (child_die);
11742         }
11743     }
11744 }
11745 \f
11746 /* DWO/DWP files.
11747
11748    http://gcc.gnu.org/wiki/DebugFission
11749    http://gcc.gnu.org/wiki/DebugFissionDWP
11750
11751    To simplify handling of both DWO files ("object" files with the DWARF info)
11752    and DWP files (a file with the DWOs packaged up into one file), we treat
11753    DWP files as having a collection of virtual DWO files.  */
11754
11755 static hashval_t
11756 hash_dwo_file (const void *item)
11757 {
11758   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11759   hashval_t hash;
11760
11761   hash = htab_hash_string (dwo_file->dwo_name);
11762   if (dwo_file->comp_dir != NULL)
11763     hash += htab_hash_string (dwo_file->comp_dir);
11764   return hash;
11765 }
11766
11767 static int
11768 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11769 {
11770   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11771   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11772
11773   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11774     return 0;
11775   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11776     return lhs->comp_dir == rhs->comp_dir;
11777   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11778 }
11779
11780 /* Allocate a hash table for DWO files.  */
11781
11782 static htab_t
11783 allocate_dwo_file_hash_table (struct objfile *objfile)
11784 {
11785   return htab_create_alloc_ex (41,
11786                                hash_dwo_file,
11787                                eq_dwo_file,
11788                                NULL,
11789                                &objfile->objfile_obstack,
11790                                hashtab_obstack_allocate,
11791                                dummy_obstack_deallocate);
11792 }
11793
11794 /* Lookup DWO file DWO_NAME.  */
11795
11796 static void **
11797 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11798                       const char *dwo_name,
11799                       const char *comp_dir)
11800 {
11801   struct dwo_file find_entry;
11802   void **slot;
11803
11804   if (dwarf2_per_objfile->dwo_files == NULL)
11805     dwarf2_per_objfile->dwo_files
11806       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11807
11808   memset (&find_entry, 0, sizeof (find_entry));
11809   find_entry.dwo_name = dwo_name;
11810   find_entry.comp_dir = comp_dir;
11811   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11812
11813   return slot;
11814 }
11815
11816 static hashval_t
11817 hash_dwo_unit (const void *item)
11818 {
11819   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11820
11821   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11822   return dwo_unit->signature;
11823 }
11824
11825 static int
11826 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11827 {
11828   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11829   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11830
11831   /* The signature is assumed to be unique within the DWO file.
11832      So while object file CU dwo_id's always have the value zero,
11833      that's OK, assuming each object file DWO file has only one CU,
11834      and that's the rule for now.  */
11835   return lhs->signature == rhs->signature;
11836 }
11837
11838 /* Allocate a hash table for DWO CUs,TUs.
11839    There is one of these tables for each of CUs,TUs for each DWO file.  */
11840
11841 static htab_t
11842 allocate_dwo_unit_table (struct objfile *objfile)
11843 {
11844   /* Start out with a pretty small number.
11845      Generally DWO files contain only one CU and maybe some TUs.  */
11846   return htab_create_alloc_ex (3,
11847                                hash_dwo_unit,
11848                                eq_dwo_unit,
11849                                NULL,
11850                                &objfile->objfile_obstack,
11851                                hashtab_obstack_allocate,
11852                                dummy_obstack_deallocate);
11853 }
11854
11855 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11856
11857 struct create_dwo_cu_data
11858 {
11859   struct dwo_file *dwo_file;
11860   struct dwo_unit dwo_unit;
11861 };
11862
11863 /* die_reader_func for create_dwo_cu.  */
11864
11865 static void
11866 create_dwo_cu_reader (const struct die_reader_specs *reader,
11867                       const gdb_byte *info_ptr,
11868                       struct die_info *comp_unit_die,
11869                       int has_children,
11870                       void *datap)
11871 {
11872   struct dwarf2_cu *cu = reader->cu;
11873   sect_offset sect_off = cu->per_cu->sect_off;
11874   struct dwarf2_section_info *section = cu->per_cu->section;
11875   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11876   struct dwo_file *dwo_file = data->dwo_file;
11877   struct dwo_unit *dwo_unit = &data->dwo_unit;
11878   struct attribute *attr;
11879
11880   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11881   if (attr == NULL)
11882     {
11883       complaint (&symfile_complaints,
11884                  _("Dwarf Error: debug entry at offset %s is missing"
11885                    " its dwo_id [in module %s]"),
11886                  sect_offset_str (sect_off), dwo_file->dwo_name);
11887       return;
11888     }
11889
11890   dwo_unit->dwo_file = dwo_file;
11891   dwo_unit->signature = DW_UNSND (attr);
11892   dwo_unit->section = section;
11893   dwo_unit->sect_off = sect_off;
11894   dwo_unit->length = cu->per_cu->length;
11895
11896   if (dwarf_read_debug)
11897     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11898                         sect_offset_str (sect_off),
11899                         hex_string (dwo_unit->signature));
11900 }
11901
11902 /* Create the dwo_units for the CUs in a DWO_FILE.
11903    Note: This function processes DWO files only, not DWP files.  */
11904
11905 static void
11906 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11907                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11908                        htab_t &cus_htab)
11909 {
11910   struct objfile *objfile = dwarf2_per_objfile->objfile;
11911   const gdb_byte *info_ptr, *end_ptr;
11912
11913   dwarf2_read_section (objfile, &section);
11914   info_ptr = section.buffer;
11915
11916   if (info_ptr == NULL)
11917     return;
11918
11919   if (dwarf_read_debug)
11920     {
11921       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11922                           get_section_name (&section),
11923                           get_section_file_name (&section));
11924     }
11925
11926   end_ptr = info_ptr + section.size;
11927   while (info_ptr < end_ptr)
11928     {
11929       struct dwarf2_per_cu_data per_cu;
11930       struct create_dwo_cu_data create_dwo_cu_data;
11931       struct dwo_unit *dwo_unit;
11932       void **slot;
11933       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11934
11935       memset (&create_dwo_cu_data.dwo_unit, 0,
11936               sizeof (create_dwo_cu_data.dwo_unit));
11937       memset (&per_cu, 0, sizeof (per_cu));
11938       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11939       per_cu.is_debug_types = 0;
11940       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11941       per_cu.section = &section;
11942       create_dwo_cu_data.dwo_file = &dwo_file;
11943
11944       init_cutu_and_read_dies_no_follow (
11945           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11946       info_ptr += per_cu.length;
11947
11948       // If the unit could not be parsed, skip it.
11949       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11950         continue;
11951
11952       if (cus_htab == NULL)
11953         cus_htab = allocate_dwo_unit_table (objfile);
11954
11955       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11956       *dwo_unit = create_dwo_cu_data.dwo_unit;
11957       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11958       gdb_assert (slot != NULL);
11959       if (*slot != NULL)
11960         {
11961           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11962           sect_offset dup_sect_off = dup_cu->sect_off;
11963
11964           complaint (&symfile_complaints,
11965                      _("debug cu entry at offset %s is duplicate to"
11966                        " the entry at offset %s, signature %s"),
11967                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11968                      hex_string (dwo_unit->signature));
11969         }
11970       *slot = (void *)dwo_unit;
11971     }
11972 }
11973
11974 /* DWP file .debug_{cu,tu}_index section format:
11975    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11976
11977    DWP Version 1:
11978
11979    Both index sections have the same format, and serve to map a 64-bit
11980    signature to a set of section numbers.  Each section begins with a header,
11981    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11982    indexes, and a pool of 32-bit section numbers.  The index sections will be
11983    aligned at 8-byte boundaries in the file.
11984
11985    The index section header consists of:
11986
11987     V, 32 bit version number
11988     -, 32 bits unused
11989     N, 32 bit number of compilation units or type units in the index
11990     M, 32 bit number of slots in the hash table
11991
11992    Numbers are recorded using the byte order of the application binary.
11993
11994    The hash table begins at offset 16 in the section, and consists of an array
11995    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11996    order of the application binary).  Unused slots in the hash table are 0.
11997    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11998
11999    The parallel table begins immediately after the hash table
12000    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12001    array of 32-bit indexes (using the byte order of the application binary),
12002    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12003    table contains a 32-bit index into the pool of section numbers.  For unused
12004    hash table slots, the corresponding entry in the parallel table will be 0.
12005
12006    The pool of section numbers begins immediately following the hash table
12007    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12008    section numbers consists of an array of 32-bit words (using the byte order
12009    of the application binary).  Each item in the array is indexed starting
12010    from 0.  The hash table entry provides the index of the first section
12011    number in the set.  Additional section numbers in the set follow, and the
12012    set is terminated by a 0 entry (section number 0 is not used in ELF).
12013
12014    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12015    section must be the first entry in the set, and the .debug_abbrev.dwo must
12016    be the second entry. Other members of the set may follow in any order.
12017
12018    ---
12019
12020    DWP Version 2:
12021
12022    DWP Version 2 combines all the .debug_info, etc. sections into one,
12023    and the entries in the index tables are now offsets into these sections.
12024    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12025    section.
12026
12027    Index Section Contents:
12028     Header
12029     Hash Table of Signatures   dwp_hash_table.hash_table
12030     Parallel Table of Indices  dwp_hash_table.unit_table
12031     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12032     Table of Section Sizes     dwp_hash_table.v2.sizes
12033
12034    The index section header consists of:
12035
12036     V, 32 bit version number
12037     L, 32 bit number of columns in the table of section offsets
12038     N, 32 bit number of compilation units or type units in the index
12039     M, 32 bit number of slots in the hash table
12040
12041    Numbers are recorded using the byte order of the application binary.
12042
12043    The hash table has the same format as version 1.
12044    The parallel table of indices has the same format as version 1,
12045    except that the entries are origin-1 indices into the table of sections
12046    offsets and the table of section sizes.
12047
12048    The table of offsets begins immediately following the parallel table
12049    (at offset 16 + 12 * M from the beginning of the section).  The table is
12050    a two-dimensional array of 32-bit words (using the byte order of the
12051    application binary), with L columns and N+1 rows, in row-major order.
12052    Each row in the array is indexed starting from 0.  The first row provides
12053    a key to the remaining rows: each column in this row provides an identifier
12054    for a debug section, and the offsets in the same column of subsequent rows
12055    refer to that section.  The section identifiers are:
12056
12057     DW_SECT_INFO         1  .debug_info.dwo
12058     DW_SECT_TYPES        2  .debug_types.dwo
12059     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12060     DW_SECT_LINE         4  .debug_line.dwo
12061     DW_SECT_LOC          5  .debug_loc.dwo
12062     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12063     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12064     DW_SECT_MACRO        8  .debug_macro.dwo
12065
12066    The offsets provided by the CU and TU index sections are the base offsets
12067    for the contributions made by each CU or TU to the corresponding section
12068    in the package file.  Each CU and TU header contains an abbrev_offset
12069    field, used to find the abbreviations table for that CU or TU within the
12070    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12071    be interpreted as relative to the base offset given in the index section.
12072    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12073    should be interpreted as relative to the base offset for .debug_line.dwo,
12074    and offsets into other debug sections obtained from DWARF attributes should
12075    also be interpreted as relative to the corresponding base offset.
12076
12077    The table of sizes begins immediately following the table of offsets.
12078    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12079    with L columns and N rows, in row-major order.  Each row in the array is
12080    indexed starting from 1 (row 0 is shared by the two tables).
12081
12082    ---
12083
12084    Hash table lookup is handled the same in version 1 and 2:
12085
12086    We assume that N and M will not exceed 2^32 - 1.
12087    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12088
12089    Given a 64-bit compilation unit signature or a type signature S, an entry
12090    in the hash table is located as follows:
12091
12092    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12093       the low-order k bits all set to 1.
12094
12095    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12096
12097    3) If the hash table entry at index H matches the signature, use that
12098       entry.  If the hash table entry at index H is unused (all zeroes),
12099       terminate the search: the signature is not present in the table.
12100
12101    4) Let H = (H + H') modulo M. Repeat at Step 3.
12102
12103    Because M > N and H' and M are relatively prime, the search is guaranteed
12104    to stop at an unused slot or find the match.  */
12105
12106 /* Create a hash table to map DWO IDs to their CU/TU entry in
12107    .debug_{info,types}.dwo in DWP_FILE.
12108    Returns NULL if there isn't one.
12109    Note: This function processes DWP files only, not DWO files.  */
12110
12111 static struct dwp_hash_table *
12112 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12113                        struct dwp_file *dwp_file, int is_debug_types)
12114 {
12115   struct objfile *objfile = dwarf2_per_objfile->objfile;
12116   bfd *dbfd = dwp_file->dbfd;
12117   const gdb_byte *index_ptr, *index_end;
12118   struct dwarf2_section_info *index;
12119   uint32_t version, nr_columns, nr_units, nr_slots;
12120   struct dwp_hash_table *htab;
12121
12122   if (is_debug_types)
12123     index = &dwp_file->sections.tu_index;
12124   else
12125     index = &dwp_file->sections.cu_index;
12126
12127   if (dwarf2_section_empty_p (index))
12128     return NULL;
12129   dwarf2_read_section (objfile, index);
12130
12131   index_ptr = index->buffer;
12132   index_end = index_ptr + index->size;
12133
12134   version = read_4_bytes (dbfd, index_ptr);
12135   index_ptr += 4;
12136   if (version == 2)
12137     nr_columns = read_4_bytes (dbfd, index_ptr);
12138   else
12139     nr_columns = 0;
12140   index_ptr += 4;
12141   nr_units = read_4_bytes (dbfd, index_ptr);
12142   index_ptr += 4;
12143   nr_slots = read_4_bytes (dbfd, index_ptr);
12144   index_ptr += 4;
12145
12146   if (version != 1 && version != 2)
12147     {
12148       error (_("Dwarf Error: unsupported DWP file version (%s)"
12149                " [in module %s]"),
12150              pulongest (version), dwp_file->name);
12151     }
12152   if (nr_slots != (nr_slots & -nr_slots))
12153     {
12154       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12155                " is not power of 2 [in module %s]"),
12156              pulongest (nr_slots), dwp_file->name);
12157     }
12158
12159   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12160   htab->version = version;
12161   htab->nr_columns = nr_columns;
12162   htab->nr_units = nr_units;
12163   htab->nr_slots = nr_slots;
12164   htab->hash_table = index_ptr;
12165   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12166
12167   /* Exit early if the table is empty.  */
12168   if (nr_slots == 0 || nr_units == 0
12169       || (version == 2 && nr_columns == 0))
12170     {
12171       /* All must be zero.  */
12172       if (nr_slots != 0 || nr_units != 0
12173           || (version == 2 && nr_columns != 0))
12174         {
12175           complaint (&symfile_complaints,
12176                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12177                        " all zero [in modules %s]"),
12178                      dwp_file->name);
12179         }
12180       return htab;
12181     }
12182
12183   if (version == 1)
12184     {
12185       htab->section_pool.v1.indices =
12186         htab->unit_table + sizeof (uint32_t) * nr_slots;
12187       /* It's harder to decide whether the section is too small in v1.
12188          V1 is deprecated anyway so we punt.  */
12189     }
12190   else
12191     {
12192       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12193       int *ids = htab->section_pool.v2.section_ids;
12194       /* Reverse map for error checking.  */
12195       int ids_seen[DW_SECT_MAX + 1];
12196       int i;
12197
12198       if (nr_columns < 2)
12199         {
12200           error (_("Dwarf Error: bad DWP hash table, too few columns"
12201                    " in section table [in module %s]"),
12202                  dwp_file->name);
12203         }
12204       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12205         {
12206           error (_("Dwarf Error: bad DWP hash table, too many columns"
12207                    " in section table [in module %s]"),
12208                  dwp_file->name);
12209         }
12210       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12211       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12212       for (i = 0; i < nr_columns; ++i)
12213         {
12214           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12215
12216           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12217             {
12218               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12219                        " in section table [in module %s]"),
12220                      id, dwp_file->name);
12221             }
12222           if (ids_seen[id] != -1)
12223             {
12224               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12225                        " id %d in section table [in module %s]"),
12226                      id, dwp_file->name);
12227             }
12228           ids_seen[id] = i;
12229           ids[i] = id;
12230         }
12231       /* Must have exactly one info or types section.  */
12232       if (((ids_seen[DW_SECT_INFO] != -1)
12233            + (ids_seen[DW_SECT_TYPES] != -1))
12234           != 1)
12235         {
12236           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12237                    " DWO info/types section [in module %s]"),
12238                  dwp_file->name);
12239         }
12240       /* Must have an abbrev section.  */
12241       if (ids_seen[DW_SECT_ABBREV] == -1)
12242         {
12243           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12244                    " section [in module %s]"),
12245                  dwp_file->name);
12246         }
12247       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12248       htab->section_pool.v2.sizes =
12249         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12250                                          * nr_units * nr_columns);
12251       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12252                                           * nr_units * nr_columns))
12253           > index_end)
12254         {
12255           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12256                    " [in module %s]"),
12257                  dwp_file->name);
12258         }
12259     }
12260
12261   return htab;
12262 }
12263
12264 /* Update SECTIONS with the data from SECTP.
12265
12266    This function is like the other "locate" section routines that are
12267    passed to bfd_map_over_sections, but in this context the sections to
12268    read comes from the DWP V1 hash table, not the full ELF section table.
12269
12270    The result is non-zero for success, or zero if an error was found.  */
12271
12272 static int
12273 locate_v1_virtual_dwo_sections (asection *sectp,
12274                                 struct virtual_v1_dwo_sections *sections)
12275 {
12276   const struct dwop_section_names *names = &dwop_section_names;
12277
12278   if (section_is_p (sectp->name, &names->abbrev_dwo))
12279     {
12280       /* There can be only one.  */
12281       if (sections->abbrev.s.section != NULL)
12282         return 0;
12283       sections->abbrev.s.section = sectp;
12284       sections->abbrev.size = bfd_get_section_size (sectp);
12285     }
12286   else if (section_is_p (sectp->name, &names->info_dwo)
12287            || section_is_p (sectp->name, &names->types_dwo))
12288     {
12289       /* There can be only one.  */
12290       if (sections->info_or_types.s.section != NULL)
12291         return 0;
12292       sections->info_or_types.s.section = sectp;
12293       sections->info_or_types.size = bfd_get_section_size (sectp);
12294     }
12295   else if (section_is_p (sectp->name, &names->line_dwo))
12296     {
12297       /* There can be only one.  */
12298       if (sections->line.s.section != NULL)
12299         return 0;
12300       sections->line.s.section = sectp;
12301       sections->line.size = bfd_get_section_size (sectp);
12302     }
12303   else if (section_is_p (sectp->name, &names->loc_dwo))
12304     {
12305       /* There can be only one.  */
12306       if (sections->loc.s.section != NULL)
12307         return 0;
12308       sections->loc.s.section = sectp;
12309       sections->loc.size = bfd_get_section_size (sectp);
12310     }
12311   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12312     {
12313       /* There can be only one.  */
12314       if (sections->macinfo.s.section != NULL)
12315         return 0;
12316       sections->macinfo.s.section = sectp;
12317       sections->macinfo.size = bfd_get_section_size (sectp);
12318     }
12319   else if (section_is_p (sectp->name, &names->macro_dwo))
12320     {
12321       /* There can be only one.  */
12322       if (sections->macro.s.section != NULL)
12323         return 0;
12324       sections->macro.s.section = sectp;
12325       sections->macro.size = bfd_get_section_size (sectp);
12326     }
12327   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12328     {
12329       /* There can be only one.  */
12330       if (sections->str_offsets.s.section != NULL)
12331         return 0;
12332       sections->str_offsets.s.section = sectp;
12333       sections->str_offsets.size = bfd_get_section_size (sectp);
12334     }
12335   else
12336     {
12337       /* No other kind of section is valid.  */
12338       return 0;
12339     }
12340
12341   return 1;
12342 }
12343
12344 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12345    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12346    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12347    This is for DWP version 1 files.  */
12348
12349 static struct dwo_unit *
12350 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12351                            struct dwp_file *dwp_file,
12352                            uint32_t unit_index,
12353                            const char *comp_dir,
12354                            ULONGEST signature, int is_debug_types)
12355 {
12356   struct objfile *objfile = dwarf2_per_objfile->objfile;
12357   const struct dwp_hash_table *dwp_htab =
12358     is_debug_types ? dwp_file->tus : dwp_file->cus;
12359   bfd *dbfd = dwp_file->dbfd;
12360   const char *kind = is_debug_types ? "TU" : "CU";
12361   struct dwo_file *dwo_file;
12362   struct dwo_unit *dwo_unit;
12363   struct virtual_v1_dwo_sections sections;
12364   void **dwo_file_slot;
12365   int i;
12366
12367   gdb_assert (dwp_file->version == 1);
12368
12369   if (dwarf_read_debug)
12370     {
12371       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12372                           kind,
12373                           pulongest (unit_index), hex_string (signature),
12374                           dwp_file->name);
12375     }
12376
12377   /* Fetch the sections of this DWO unit.
12378      Put a limit on the number of sections we look for so that bad data
12379      doesn't cause us to loop forever.  */
12380
12381 #define MAX_NR_V1_DWO_SECTIONS \
12382   (1 /* .debug_info or .debug_types */ \
12383    + 1 /* .debug_abbrev */ \
12384    + 1 /* .debug_line */ \
12385    + 1 /* .debug_loc */ \
12386    + 1 /* .debug_str_offsets */ \
12387    + 1 /* .debug_macro or .debug_macinfo */ \
12388    + 1 /* trailing zero */)
12389
12390   memset (&sections, 0, sizeof (sections));
12391
12392   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12393     {
12394       asection *sectp;
12395       uint32_t section_nr =
12396         read_4_bytes (dbfd,
12397                       dwp_htab->section_pool.v1.indices
12398                       + (unit_index + i) * sizeof (uint32_t));
12399
12400       if (section_nr == 0)
12401         break;
12402       if (section_nr >= dwp_file->num_sections)
12403         {
12404           error (_("Dwarf Error: bad DWP hash table, section number too large"
12405                    " [in module %s]"),
12406                  dwp_file->name);
12407         }
12408
12409       sectp = dwp_file->elf_sections[section_nr];
12410       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12411         {
12412           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12413                    " [in module %s]"),
12414                  dwp_file->name);
12415         }
12416     }
12417
12418   if (i < 2
12419       || dwarf2_section_empty_p (&sections.info_or_types)
12420       || dwarf2_section_empty_p (&sections.abbrev))
12421     {
12422       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12423                " [in module %s]"),
12424              dwp_file->name);
12425     }
12426   if (i == MAX_NR_V1_DWO_SECTIONS)
12427     {
12428       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12429                " [in module %s]"),
12430              dwp_file->name);
12431     }
12432
12433   /* It's easier for the rest of the code if we fake a struct dwo_file and
12434      have dwo_unit "live" in that.  At least for now.
12435
12436      The DWP file can be made up of a random collection of CUs and TUs.
12437      However, for each CU + set of TUs that came from the same original DWO
12438      file, we can combine them back into a virtual DWO file to save space
12439      (fewer struct dwo_file objects to allocate).  Remember that for really
12440      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12441
12442   std::string virtual_dwo_name =
12443     string_printf ("virtual-dwo/%d-%d-%d-%d",
12444                    get_section_id (&sections.abbrev),
12445                    get_section_id (&sections.line),
12446                    get_section_id (&sections.loc),
12447                    get_section_id (&sections.str_offsets));
12448   /* Can we use an existing virtual DWO file?  */
12449   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12450                                         virtual_dwo_name.c_str (),
12451                                         comp_dir);
12452   /* Create one if necessary.  */
12453   if (*dwo_file_slot == NULL)
12454     {
12455       if (dwarf_read_debug)
12456         {
12457           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12458                               virtual_dwo_name.c_str ());
12459         }
12460       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12461       dwo_file->dwo_name
12462         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12463                                         virtual_dwo_name.c_str (),
12464                                         virtual_dwo_name.size ());
12465       dwo_file->comp_dir = comp_dir;
12466       dwo_file->sections.abbrev = sections.abbrev;
12467       dwo_file->sections.line = sections.line;
12468       dwo_file->sections.loc = sections.loc;
12469       dwo_file->sections.macinfo = sections.macinfo;
12470       dwo_file->sections.macro = sections.macro;
12471       dwo_file->sections.str_offsets = sections.str_offsets;
12472       /* The "str" section is global to the entire DWP file.  */
12473       dwo_file->sections.str = dwp_file->sections.str;
12474       /* The info or types section is assigned below to dwo_unit,
12475          there's no need to record it in dwo_file.
12476          Also, we can't simply record type sections in dwo_file because
12477          we record a pointer into the vector in dwo_unit.  As we collect more
12478          types we'll grow the vector and eventually have to reallocate space
12479          for it, invalidating all copies of pointers into the previous
12480          contents.  */
12481       *dwo_file_slot = dwo_file;
12482     }
12483   else
12484     {
12485       if (dwarf_read_debug)
12486         {
12487           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12488                               virtual_dwo_name.c_str ());
12489         }
12490       dwo_file = (struct dwo_file *) *dwo_file_slot;
12491     }
12492
12493   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12494   dwo_unit->dwo_file = dwo_file;
12495   dwo_unit->signature = signature;
12496   dwo_unit->section =
12497     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12498   *dwo_unit->section = sections.info_or_types;
12499   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12500
12501   return dwo_unit;
12502 }
12503
12504 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12505    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12506    piece within that section used by a TU/CU, return a virtual section
12507    of just that piece.  */
12508
12509 static struct dwarf2_section_info
12510 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12511                        struct dwarf2_section_info *section,
12512                        bfd_size_type offset, bfd_size_type size)
12513 {
12514   struct dwarf2_section_info result;
12515   asection *sectp;
12516
12517   gdb_assert (section != NULL);
12518   gdb_assert (!section->is_virtual);
12519
12520   memset (&result, 0, sizeof (result));
12521   result.s.containing_section = section;
12522   result.is_virtual = 1;
12523
12524   if (size == 0)
12525     return result;
12526
12527   sectp = get_section_bfd_section (section);
12528
12529   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12530      bounds of the real section.  This is a pretty-rare event, so just
12531      flag an error (easier) instead of a warning and trying to cope.  */
12532   if (sectp == NULL
12533       || offset + size > bfd_get_section_size (sectp))
12534     {
12535       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12536                " in section %s [in module %s]"),
12537              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12538              objfile_name (dwarf2_per_objfile->objfile));
12539     }
12540
12541   result.virtual_offset = offset;
12542   result.size = size;
12543   return result;
12544 }
12545
12546 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12547    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12548    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12549    This is for DWP version 2 files.  */
12550
12551 static struct dwo_unit *
12552 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12553                            struct dwp_file *dwp_file,
12554                            uint32_t unit_index,
12555                            const char *comp_dir,
12556                            ULONGEST signature, int is_debug_types)
12557 {
12558   struct objfile *objfile = dwarf2_per_objfile->objfile;
12559   const struct dwp_hash_table *dwp_htab =
12560     is_debug_types ? dwp_file->tus : dwp_file->cus;
12561   bfd *dbfd = dwp_file->dbfd;
12562   const char *kind = is_debug_types ? "TU" : "CU";
12563   struct dwo_file *dwo_file;
12564   struct dwo_unit *dwo_unit;
12565   struct virtual_v2_dwo_sections sections;
12566   void **dwo_file_slot;
12567   int i;
12568
12569   gdb_assert (dwp_file->version == 2);
12570
12571   if (dwarf_read_debug)
12572     {
12573       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12574                           kind,
12575                           pulongest (unit_index), hex_string (signature),
12576                           dwp_file->name);
12577     }
12578
12579   /* Fetch the section offsets of this DWO unit.  */
12580
12581   memset (&sections, 0, sizeof (sections));
12582
12583   for (i = 0; i < dwp_htab->nr_columns; ++i)
12584     {
12585       uint32_t offset = read_4_bytes (dbfd,
12586                                       dwp_htab->section_pool.v2.offsets
12587                                       + (((unit_index - 1) * dwp_htab->nr_columns
12588                                           + i)
12589                                          * sizeof (uint32_t)));
12590       uint32_t size = read_4_bytes (dbfd,
12591                                     dwp_htab->section_pool.v2.sizes
12592                                     + (((unit_index - 1) * dwp_htab->nr_columns
12593                                         + i)
12594                                        * sizeof (uint32_t)));
12595
12596       switch (dwp_htab->section_pool.v2.section_ids[i])
12597         {
12598         case DW_SECT_INFO:
12599         case DW_SECT_TYPES:
12600           sections.info_or_types_offset = offset;
12601           sections.info_or_types_size = size;
12602           break;
12603         case DW_SECT_ABBREV:
12604           sections.abbrev_offset = offset;
12605           sections.abbrev_size = size;
12606           break;
12607         case DW_SECT_LINE:
12608           sections.line_offset = offset;
12609           sections.line_size = size;
12610           break;
12611         case DW_SECT_LOC:
12612           sections.loc_offset = offset;
12613           sections.loc_size = size;
12614           break;
12615         case DW_SECT_STR_OFFSETS:
12616           sections.str_offsets_offset = offset;
12617           sections.str_offsets_size = size;
12618           break;
12619         case DW_SECT_MACINFO:
12620           sections.macinfo_offset = offset;
12621           sections.macinfo_size = size;
12622           break;
12623         case DW_SECT_MACRO:
12624           sections.macro_offset = offset;
12625           sections.macro_size = size;
12626           break;
12627         }
12628     }
12629
12630   /* It's easier for the rest of the code if we fake a struct dwo_file and
12631      have dwo_unit "live" in that.  At least for now.
12632
12633      The DWP file can be made up of a random collection of CUs and TUs.
12634      However, for each CU + set of TUs that came from the same original DWO
12635      file, we can combine them back into a virtual DWO file to save space
12636      (fewer struct dwo_file objects to allocate).  Remember that for really
12637      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12638
12639   std::string virtual_dwo_name =
12640     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12641                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12642                    (long) (sections.line_size ? sections.line_offset : 0),
12643                    (long) (sections.loc_size ? sections.loc_offset : 0),
12644                    (long) (sections.str_offsets_size
12645                            ? sections.str_offsets_offset : 0));
12646   /* Can we use an existing virtual DWO file?  */
12647   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12648                                         virtual_dwo_name.c_str (),
12649                                         comp_dir);
12650   /* Create one if necessary.  */
12651   if (*dwo_file_slot == NULL)
12652     {
12653       if (dwarf_read_debug)
12654         {
12655           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12656                               virtual_dwo_name.c_str ());
12657         }
12658       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12659       dwo_file->dwo_name
12660         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12661                                         virtual_dwo_name.c_str (),
12662                                         virtual_dwo_name.size ());
12663       dwo_file->comp_dir = comp_dir;
12664       dwo_file->sections.abbrev =
12665         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12666                                sections.abbrev_offset, sections.abbrev_size);
12667       dwo_file->sections.line =
12668         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12669                                sections.line_offset, sections.line_size);
12670       dwo_file->sections.loc =
12671         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12672                                sections.loc_offset, sections.loc_size);
12673       dwo_file->sections.macinfo =
12674         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12675                                sections.macinfo_offset, sections.macinfo_size);
12676       dwo_file->sections.macro =
12677         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12678                                sections.macro_offset, sections.macro_size);
12679       dwo_file->sections.str_offsets =
12680         create_dwp_v2_section (dwarf2_per_objfile,
12681                                &dwp_file->sections.str_offsets,
12682                                sections.str_offsets_offset,
12683                                sections.str_offsets_size);
12684       /* The "str" section is global to the entire DWP file.  */
12685       dwo_file->sections.str = dwp_file->sections.str;
12686       /* The info or types section is assigned below to dwo_unit,
12687          there's no need to record it in dwo_file.
12688          Also, we can't simply record type sections in dwo_file because
12689          we record a pointer into the vector in dwo_unit.  As we collect more
12690          types we'll grow the vector and eventually have to reallocate space
12691          for it, invalidating all copies of pointers into the previous
12692          contents.  */
12693       *dwo_file_slot = dwo_file;
12694     }
12695   else
12696     {
12697       if (dwarf_read_debug)
12698         {
12699           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12700                               virtual_dwo_name.c_str ());
12701         }
12702       dwo_file = (struct dwo_file *) *dwo_file_slot;
12703     }
12704
12705   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12706   dwo_unit->dwo_file = dwo_file;
12707   dwo_unit->signature = signature;
12708   dwo_unit->section =
12709     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12710   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12711                                               is_debug_types
12712                                               ? &dwp_file->sections.types
12713                                               : &dwp_file->sections.info,
12714                                               sections.info_or_types_offset,
12715                                               sections.info_or_types_size);
12716   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12717
12718   return dwo_unit;
12719 }
12720
12721 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12722    Returns NULL if the signature isn't found.  */
12723
12724 static struct dwo_unit *
12725 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12726                         struct dwp_file *dwp_file, const char *comp_dir,
12727                         ULONGEST signature, int is_debug_types)
12728 {
12729   const struct dwp_hash_table *dwp_htab =
12730     is_debug_types ? dwp_file->tus : dwp_file->cus;
12731   bfd *dbfd = dwp_file->dbfd;
12732   uint32_t mask = dwp_htab->nr_slots - 1;
12733   uint32_t hash = signature & mask;
12734   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12735   unsigned int i;
12736   void **slot;
12737   struct dwo_unit find_dwo_cu;
12738
12739   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12740   find_dwo_cu.signature = signature;
12741   slot = htab_find_slot (is_debug_types
12742                          ? dwp_file->loaded_tus
12743                          : dwp_file->loaded_cus,
12744                          &find_dwo_cu, INSERT);
12745
12746   if (*slot != NULL)
12747     return (struct dwo_unit *) *slot;
12748
12749   /* Use a for loop so that we don't loop forever on bad debug info.  */
12750   for (i = 0; i < dwp_htab->nr_slots; ++i)
12751     {
12752       ULONGEST signature_in_table;
12753
12754       signature_in_table =
12755         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12756       if (signature_in_table == signature)
12757         {
12758           uint32_t unit_index =
12759             read_4_bytes (dbfd,
12760                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12761
12762           if (dwp_file->version == 1)
12763             {
12764               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12765                                                  dwp_file, unit_index,
12766                                                  comp_dir, signature,
12767                                                  is_debug_types);
12768             }
12769           else
12770             {
12771               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12772                                                  dwp_file, unit_index,
12773                                                  comp_dir, signature,
12774                                                  is_debug_types);
12775             }
12776           return (struct dwo_unit *) *slot;
12777         }
12778       if (signature_in_table == 0)
12779         return NULL;
12780       hash = (hash + hash2) & mask;
12781     }
12782
12783   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12784            " [in module %s]"),
12785          dwp_file->name);
12786 }
12787
12788 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12789    Open the file specified by FILE_NAME and hand it off to BFD for
12790    preliminary analysis.  Return a newly initialized bfd *, which
12791    includes a canonicalized copy of FILE_NAME.
12792    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12793    SEARCH_CWD is true if the current directory is to be searched.
12794    It will be searched before debug-file-directory.
12795    If successful, the file is added to the bfd include table of the
12796    objfile's bfd (see gdb_bfd_record_inclusion).
12797    If unable to find/open the file, return NULL.
12798    NOTE: This function is derived from symfile_bfd_open.  */
12799
12800 static gdb_bfd_ref_ptr
12801 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12802                     const char *file_name, int is_dwp, int search_cwd)
12803 {
12804   int desc;
12805   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12806      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12807      to debug_file_directory.  */
12808   const char *search_path;
12809   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12810
12811   gdb::unique_xmalloc_ptr<char> search_path_holder;
12812   if (search_cwd)
12813     {
12814       if (*debug_file_directory != '\0')
12815         {
12816           search_path_holder.reset (concat (".", dirname_separator_string,
12817                                             debug_file_directory,
12818                                             (char *) NULL));
12819           search_path = search_path_holder.get ();
12820         }
12821       else
12822         search_path = ".";
12823     }
12824   else
12825     search_path = debug_file_directory;
12826
12827   openp_flags flags = OPF_RETURN_REALPATH;
12828   if (is_dwp)
12829     flags |= OPF_SEARCH_IN_PATH;
12830
12831   gdb::unique_xmalloc_ptr<char> absolute_name;
12832   desc = openp (search_path, flags, file_name,
12833                 O_RDONLY | O_BINARY, &absolute_name);
12834   if (desc < 0)
12835     return NULL;
12836
12837   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12838                                          gnutarget, desc));
12839   if (sym_bfd == NULL)
12840     return NULL;
12841   bfd_set_cacheable (sym_bfd.get (), 1);
12842
12843   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12844     return NULL;
12845
12846   /* Success.  Record the bfd as having been included by the objfile's bfd.
12847      This is important because things like demangled_names_hash lives in the
12848      objfile's per_bfd space and may have references to things like symbol
12849      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12850   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12851
12852   return sym_bfd;
12853 }
12854
12855 /* Try to open DWO file FILE_NAME.
12856    COMP_DIR is the DW_AT_comp_dir attribute.
12857    The result is the bfd handle of the file.
12858    If there is a problem finding or opening the file, return NULL.
12859    Upon success, the canonicalized path of the file is stored in the bfd,
12860    same as symfile_bfd_open.  */
12861
12862 static gdb_bfd_ref_ptr
12863 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12864                const char *file_name, const char *comp_dir)
12865 {
12866   if (IS_ABSOLUTE_PATH (file_name))
12867     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12868                                0 /*is_dwp*/, 0 /*search_cwd*/);
12869
12870   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12871
12872   if (comp_dir != NULL)
12873     {
12874       char *path_to_try = concat (comp_dir, SLASH_STRING,
12875                                   file_name, (char *) NULL);
12876
12877       /* NOTE: If comp_dir is a relative path, this will also try the
12878          search path, which seems useful.  */
12879       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12880                                                 path_to_try,
12881                                                 0 /*is_dwp*/,
12882                                                 1 /*search_cwd*/));
12883       xfree (path_to_try);
12884       if (abfd != NULL)
12885         return abfd;
12886     }
12887
12888   /* That didn't work, try debug-file-directory, which, despite its name,
12889      is a list of paths.  */
12890
12891   if (*debug_file_directory == '\0')
12892     return NULL;
12893
12894   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12895                              0 /*is_dwp*/, 1 /*search_cwd*/);
12896 }
12897
12898 /* This function is mapped across the sections and remembers the offset and
12899    size of each of the DWO debugging sections we are interested in.  */
12900
12901 static void
12902 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12903 {
12904   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12905   const struct dwop_section_names *names = &dwop_section_names;
12906
12907   if (section_is_p (sectp->name, &names->abbrev_dwo))
12908     {
12909       dwo_sections->abbrev.s.section = sectp;
12910       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12911     }
12912   else if (section_is_p (sectp->name, &names->info_dwo))
12913     {
12914       dwo_sections->info.s.section = sectp;
12915       dwo_sections->info.size = bfd_get_section_size (sectp);
12916     }
12917   else if (section_is_p (sectp->name, &names->line_dwo))
12918     {
12919       dwo_sections->line.s.section = sectp;
12920       dwo_sections->line.size = bfd_get_section_size (sectp);
12921     }
12922   else if (section_is_p (sectp->name, &names->loc_dwo))
12923     {
12924       dwo_sections->loc.s.section = sectp;
12925       dwo_sections->loc.size = bfd_get_section_size (sectp);
12926     }
12927   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12928     {
12929       dwo_sections->macinfo.s.section = sectp;
12930       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12931     }
12932   else if (section_is_p (sectp->name, &names->macro_dwo))
12933     {
12934       dwo_sections->macro.s.section = sectp;
12935       dwo_sections->macro.size = bfd_get_section_size (sectp);
12936     }
12937   else if (section_is_p (sectp->name, &names->str_dwo))
12938     {
12939       dwo_sections->str.s.section = sectp;
12940       dwo_sections->str.size = bfd_get_section_size (sectp);
12941     }
12942   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12943     {
12944       dwo_sections->str_offsets.s.section = sectp;
12945       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12946     }
12947   else if (section_is_p (sectp->name, &names->types_dwo))
12948     {
12949       struct dwarf2_section_info type_section;
12950
12951       memset (&type_section, 0, sizeof (type_section));
12952       type_section.s.section = sectp;
12953       type_section.size = bfd_get_section_size (sectp);
12954       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12955                      &type_section);
12956     }
12957 }
12958
12959 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12960    by PER_CU.  This is for the non-DWP case.
12961    The result is NULL if DWO_NAME can't be found.  */
12962
12963 static struct dwo_file *
12964 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12965                         const char *dwo_name, const char *comp_dir)
12966 {
12967   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12968   struct objfile *objfile = dwarf2_per_objfile->objfile;
12969   struct dwo_file *dwo_file;
12970   struct cleanup *cleanups;
12971
12972   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12973   if (dbfd == NULL)
12974     {
12975       if (dwarf_read_debug)
12976         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12977       return NULL;
12978     }
12979   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12980   dwo_file->dwo_name = dwo_name;
12981   dwo_file->comp_dir = comp_dir;
12982   dwo_file->dbfd = dbfd.release ();
12983
12984   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
12985   cleanup_data->dwo_file = dwo_file;
12986   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
12987
12988   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
12989
12990   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12991                          &dwo_file->sections);
12992
12993   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12994                          dwo_file->cus);
12995
12996   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
12997                                  dwo_file->sections.types, dwo_file->tus);
12998
12999   discard_cleanups (cleanups);
13000
13001   if (dwarf_read_debug)
13002     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13003
13004   return dwo_file;
13005 }
13006
13007 /* This function is mapped across the sections and remembers the offset and
13008    size of each of the DWP debugging sections common to version 1 and 2 that
13009    we are interested in.  */
13010
13011 static void
13012 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13013                                    void *dwp_file_ptr)
13014 {
13015   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13016   const struct dwop_section_names *names = &dwop_section_names;
13017   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13018
13019   /* Record the ELF section number for later lookup: this is what the
13020      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13021   gdb_assert (elf_section_nr < dwp_file->num_sections);
13022   dwp_file->elf_sections[elf_section_nr] = sectp;
13023
13024   /* Look for specific sections that we need.  */
13025   if (section_is_p (sectp->name, &names->str_dwo))
13026     {
13027       dwp_file->sections.str.s.section = sectp;
13028       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13029     }
13030   else if (section_is_p (sectp->name, &names->cu_index))
13031     {
13032       dwp_file->sections.cu_index.s.section = sectp;
13033       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13034     }
13035   else if (section_is_p (sectp->name, &names->tu_index))
13036     {
13037       dwp_file->sections.tu_index.s.section = sectp;
13038       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13039     }
13040 }
13041
13042 /* This function is mapped across the sections and remembers the offset and
13043    size of each of the DWP version 2 debugging sections that we are interested
13044    in.  This is split into a separate function because we don't know if we
13045    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13046
13047 static void
13048 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13049 {
13050   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13051   const struct dwop_section_names *names = &dwop_section_names;
13052   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13053
13054   /* Record the ELF section number for later lookup: this is what the
13055      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13056   gdb_assert (elf_section_nr < dwp_file->num_sections);
13057   dwp_file->elf_sections[elf_section_nr] = sectp;
13058
13059   /* Look for specific sections that we need.  */
13060   if (section_is_p (sectp->name, &names->abbrev_dwo))
13061     {
13062       dwp_file->sections.abbrev.s.section = sectp;
13063       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13064     }
13065   else if (section_is_p (sectp->name, &names->info_dwo))
13066     {
13067       dwp_file->sections.info.s.section = sectp;
13068       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13069     }
13070   else if (section_is_p (sectp->name, &names->line_dwo))
13071     {
13072       dwp_file->sections.line.s.section = sectp;
13073       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13074     }
13075   else if (section_is_p (sectp->name, &names->loc_dwo))
13076     {
13077       dwp_file->sections.loc.s.section = sectp;
13078       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13079     }
13080   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13081     {
13082       dwp_file->sections.macinfo.s.section = sectp;
13083       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13084     }
13085   else if (section_is_p (sectp->name, &names->macro_dwo))
13086     {
13087       dwp_file->sections.macro.s.section = sectp;
13088       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13089     }
13090   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13091     {
13092       dwp_file->sections.str_offsets.s.section = sectp;
13093       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13094     }
13095   else if (section_is_p (sectp->name, &names->types_dwo))
13096     {
13097       dwp_file->sections.types.s.section = sectp;
13098       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13099     }
13100 }
13101
13102 /* Hash function for dwp_file loaded CUs/TUs.  */
13103
13104 static hashval_t
13105 hash_dwp_loaded_cutus (const void *item)
13106 {
13107   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13108
13109   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13110   return dwo_unit->signature;
13111 }
13112
13113 /* Equality function for dwp_file loaded CUs/TUs.  */
13114
13115 static int
13116 eq_dwp_loaded_cutus (const void *a, const void *b)
13117 {
13118   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13119   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13120
13121   return dua->signature == dub->signature;
13122 }
13123
13124 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13125
13126 static htab_t
13127 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13128 {
13129   return htab_create_alloc_ex (3,
13130                                hash_dwp_loaded_cutus,
13131                                eq_dwp_loaded_cutus,
13132                                NULL,
13133                                &objfile->objfile_obstack,
13134                                hashtab_obstack_allocate,
13135                                dummy_obstack_deallocate);
13136 }
13137
13138 /* Try to open DWP file FILE_NAME.
13139    The result is the bfd handle of the file.
13140    If there is a problem finding or opening the file, return NULL.
13141    Upon success, the canonicalized path of the file is stored in the bfd,
13142    same as symfile_bfd_open.  */
13143
13144 static gdb_bfd_ref_ptr
13145 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13146                const char *file_name)
13147 {
13148   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13149                                             1 /*is_dwp*/,
13150                                             1 /*search_cwd*/));
13151   if (abfd != NULL)
13152     return abfd;
13153
13154   /* Work around upstream bug 15652.
13155      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13156      [Whether that's a "bug" is debatable, but it is getting in our way.]
13157      We have no real idea where the dwp file is, because gdb's realpath-ing
13158      of the executable's path may have discarded the needed info.
13159      [IWBN if the dwp file name was recorded in the executable, akin to
13160      .gnu_debuglink, but that doesn't exist yet.]
13161      Strip the directory from FILE_NAME and search again.  */
13162   if (*debug_file_directory != '\0')
13163     {
13164       /* Don't implicitly search the current directory here.
13165          If the user wants to search "." to handle this case,
13166          it must be added to debug-file-directory.  */
13167       return try_open_dwop_file (dwarf2_per_objfile,
13168                                  lbasename (file_name), 1 /*is_dwp*/,
13169                                  0 /*search_cwd*/);
13170     }
13171
13172   return NULL;
13173 }
13174
13175 /* Initialize the use of the DWP file for the current objfile.
13176    By convention the name of the DWP file is ${objfile}.dwp.
13177    The result is NULL if it can't be found.  */
13178
13179 static struct dwp_file *
13180 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13181 {
13182   struct objfile *objfile = dwarf2_per_objfile->objfile;
13183   struct dwp_file *dwp_file;
13184
13185   /* Try to find first .dwp for the binary file before any symbolic links
13186      resolving.  */
13187
13188   /* If the objfile is a debug file, find the name of the real binary
13189      file and get the name of dwp file from there.  */
13190   std::string dwp_name;
13191   if (objfile->separate_debug_objfile_backlink != NULL)
13192     {
13193       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13194       const char *backlink_basename = lbasename (backlink->original_name);
13195
13196       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13197     }
13198   else
13199     dwp_name = objfile->original_name;
13200
13201   dwp_name += ".dwp";
13202
13203   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13204   if (dbfd == NULL
13205       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13206     {
13207       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13208       dwp_name = objfile_name (objfile);
13209       dwp_name += ".dwp";
13210       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13211     }
13212
13213   if (dbfd == NULL)
13214     {
13215       if (dwarf_read_debug)
13216         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13217       return NULL;
13218     }
13219   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13220   dwp_file->name = bfd_get_filename (dbfd.get ());
13221   dwp_file->dbfd = dbfd.release ();
13222
13223   /* +1: section 0 is unused */
13224   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13225   dwp_file->elf_sections =
13226     OBSTACK_CALLOC (&objfile->objfile_obstack,
13227                     dwp_file->num_sections, asection *);
13228
13229   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13230                          dwp_file);
13231
13232   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13233
13234   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13235
13236   /* The DWP file version is stored in the hash table.  Oh well.  */
13237   if (dwp_file->cus && dwp_file->tus
13238       && dwp_file->cus->version != dwp_file->tus->version)
13239     {
13240       /* Technically speaking, we should try to limp along, but this is
13241          pretty bizarre.  We use pulongest here because that's the established
13242          portability solution (e.g, we cannot use %u for uint32_t).  */
13243       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13244                " TU version %s [in DWP file %s]"),
13245              pulongest (dwp_file->cus->version),
13246              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13247     }
13248
13249   if (dwp_file->cus)
13250     dwp_file->version = dwp_file->cus->version;
13251   else if (dwp_file->tus)
13252     dwp_file->version = dwp_file->tus->version;
13253   else
13254     dwp_file->version = 2;
13255
13256   if (dwp_file->version == 2)
13257     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13258                            dwp_file);
13259
13260   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13261   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13262
13263   if (dwarf_read_debug)
13264     {
13265       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13266       fprintf_unfiltered (gdb_stdlog,
13267                           "    %s CUs, %s TUs\n",
13268                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13269                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13270     }
13271
13272   return dwp_file;
13273 }
13274
13275 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13276
13277 static struct dwp_file *
13278 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13279 {
13280   if (! dwarf2_per_objfile->dwp_checked)
13281     {
13282       dwarf2_per_objfile->dwp_file
13283         = open_and_init_dwp_file (dwarf2_per_objfile);
13284       dwarf2_per_objfile->dwp_checked = 1;
13285     }
13286   return dwarf2_per_objfile->dwp_file;
13287 }
13288
13289 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13290    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13291    or in the DWP file for the objfile, referenced by THIS_UNIT.
13292    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13293    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13294
13295    This is called, for example, when wanting to read a variable with a
13296    complex location.  Therefore we don't want to do file i/o for every call.
13297    Therefore we don't want to look for a DWO file on every call.
13298    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13299    then we check if we've already seen DWO_NAME, and only THEN do we check
13300    for a DWO file.
13301
13302    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13303    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13304
13305 static struct dwo_unit *
13306 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13307                  const char *dwo_name, const char *comp_dir,
13308                  ULONGEST signature, int is_debug_types)
13309 {
13310   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13311   struct objfile *objfile = dwarf2_per_objfile->objfile;
13312   const char *kind = is_debug_types ? "TU" : "CU";
13313   void **dwo_file_slot;
13314   struct dwo_file *dwo_file;
13315   struct dwp_file *dwp_file;
13316
13317   /* First see if there's a DWP file.
13318      If we have a DWP file but didn't find the DWO inside it, don't
13319      look for the original DWO file.  It makes gdb behave differently
13320      depending on whether one is debugging in the build tree.  */
13321
13322   dwp_file = get_dwp_file (dwarf2_per_objfile);
13323   if (dwp_file != NULL)
13324     {
13325       const struct dwp_hash_table *dwp_htab =
13326         is_debug_types ? dwp_file->tus : dwp_file->cus;
13327
13328       if (dwp_htab != NULL)
13329         {
13330           struct dwo_unit *dwo_cutu =
13331             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13332                                     signature, is_debug_types);
13333
13334           if (dwo_cutu != NULL)
13335             {
13336               if (dwarf_read_debug)
13337                 {
13338                   fprintf_unfiltered (gdb_stdlog,
13339                                       "Virtual DWO %s %s found: @%s\n",
13340                                       kind, hex_string (signature),
13341                                       host_address_to_string (dwo_cutu));
13342                 }
13343               return dwo_cutu;
13344             }
13345         }
13346     }
13347   else
13348     {
13349       /* No DWP file, look for the DWO file.  */
13350
13351       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13352                                             dwo_name, comp_dir);
13353       if (*dwo_file_slot == NULL)
13354         {
13355           /* Read in the file and build a table of the CUs/TUs it contains.  */
13356           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13357         }
13358       /* NOTE: This will be NULL if unable to open the file.  */
13359       dwo_file = (struct dwo_file *) *dwo_file_slot;
13360
13361       if (dwo_file != NULL)
13362         {
13363           struct dwo_unit *dwo_cutu = NULL;
13364
13365           if (is_debug_types && dwo_file->tus)
13366             {
13367               struct dwo_unit find_dwo_cutu;
13368
13369               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13370               find_dwo_cutu.signature = signature;
13371               dwo_cutu
13372                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13373             }
13374           else if (!is_debug_types && dwo_file->cus)
13375             {
13376               struct dwo_unit find_dwo_cutu;
13377
13378               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13379               find_dwo_cutu.signature = signature;
13380               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13381                                                        &find_dwo_cutu);
13382             }
13383
13384           if (dwo_cutu != NULL)
13385             {
13386               if (dwarf_read_debug)
13387                 {
13388                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13389                                       kind, dwo_name, hex_string (signature),
13390                                       host_address_to_string (dwo_cutu));
13391                 }
13392               return dwo_cutu;
13393             }
13394         }
13395     }
13396
13397   /* We didn't find it.  This could mean a dwo_id mismatch, or
13398      someone deleted the DWO/DWP file, or the search path isn't set up
13399      correctly to find the file.  */
13400
13401   if (dwarf_read_debug)
13402     {
13403       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13404                           kind, dwo_name, hex_string (signature));
13405     }
13406
13407   /* This is a warning and not a complaint because it can be caused by
13408      pilot error (e.g., user accidentally deleting the DWO).  */
13409   {
13410     /* Print the name of the DWP file if we looked there, helps the user
13411        better diagnose the problem.  */
13412     std::string dwp_text;
13413
13414     if (dwp_file != NULL)
13415       dwp_text = string_printf (" [in DWP file %s]",
13416                                 lbasename (dwp_file->name));
13417
13418     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13419                " [in module %s]"),
13420              kind, dwo_name, hex_string (signature),
13421              dwp_text.c_str (),
13422              this_unit->is_debug_types ? "TU" : "CU",
13423              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13424   }
13425   return NULL;
13426 }
13427
13428 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13429    See lookup_dwo_cutu_unit for details.  */
13430
13431 static struct dwo_unit *
13432 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13433                       const char *dwo_name, const char *comp_dir,
13434                       ULONGEST signature)
13435 {
13436   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13437 }
13438
13439 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13440    See lookup_dwo_cutu_unit for details.  */
13441
13442 static struct dwo_unit *
13443 lookup_dwo_type_unit (struct signatured_type *this_tu,
13444                       const char *dwo_name, const char *comp_dir)
13445 {
13446   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13447 }
13448
13449 /* Traversal function for queue_and_load_all_dwo_tus.  */
13450
13451 static int
13452 queue_and_load_dwo_tu (void **slot, void *info)
13453 {
13454   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13455   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13456   ULONGEST signature = dwo_unit->signature;
13457   struct signatured_type *sig_type =
13458     lookup_dwo_signatured_type (per_cu->cu, signature);
13459
13460   if (sig_type != NULL)
13461     {
13462       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13463
13464       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13465          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13466          while processing PER_CU.  */
13467       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13468         load_full_type_unit (sig_cu);
13469       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13470     }
13471
13472   return 1;
13473 }
13474
13475 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13476    The DWO may have the only definition of the type, though it may not be
13477    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13478    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13479
13480 static void
13481 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13482 {
13483   struct dwo_unit *dwo_unit;
13484   struct dwo_file *dwo_file;
13485
13486   gdb_assert (!per_cu->is_debug_types);
13487   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13488   gdb_assert (per_cu->cu != NULL);
13489
13490   dwo_unit = per_cu->cu->dwo_unit;
13491   gdb_assert (dwo_unit != NULL);
13492
13493   dwo_file = dwo_unit->dwo_file;
13494   if (dwo_file->tus != NULL)
13495     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13496 }
13497
13498 /* Free all resources associated with DWO_FILE.
13499    Close the DWO file and munmap the sections.
13500    All memory should be on the objfile obstack.  */
13501
13502 static void
13503 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13504 {
13505
13506   /* Note: dbfd is NULL for virtual DWO files.  */
13507   gdb_bfd_unref (dwo_file->dbfd);
13508
13509   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13510 }
13511
13512 /* Wrapper for free_dwo_file for use in cleanups.  */
13513
13514 static void
13515 free_dwo_file_cleanup (void *arg)
13516 {
13517   struct free_dwo_file_cleanup_data *data
13518     = (struct free_dwo_file_cleanup_data *) arg;
13519   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13520
13521   free_dwo_file (data->dwo_file, objfile);
13522
13523   xfree (data);
13524 }
13525
13526 /* Traversal function for free_dwo_files.  */
13527
13528 static int
13529 free_dwo_file_from_slot (void **slot, void *info)
13530 {
13531   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13532   struct objfile *objfile = (struct objfile *) info;
13533
13534   free_dwo_file (dwo_file, objfile);
13535
13536   return 1;
13537 }
13538
13539 /* Free all resources associated with DWO_FILES.  */
13540
13541 static void
13542 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13543 {
13544   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13545 }
13546 \f
13547 /* Read in various DIEs.  */
13548
13549 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13550    Inherit only the children of the DW_AT_abstract_origin DIE not being
13551    already referenced by DW_AT_abstract_origin from the children of the
13552    current DIE.  */
13553
13554 static void
13555 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13556 {
13557   struct die_info *child_die;
13558   sect_offset *offsetp;
13559   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13560   struct die_info *origin_die;
13561   /* Iterator of the ORIGIN_DIE children.  */
13562   struct die_info *origin_child_die;
13563   struct attribute *attr;
13564   struct dwarf2_cu *origin_cu;
13565   struct pending **origin_previous_list_in_scope;
13566
13567   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13568   if (!attr)
13569     return;
13570
13571   /* Note that following die references may follow to a die in a
13572      different cu.  */
13573
13574   origin_cu = cu;
13575   origin_die = follow_die_ref (die, attr, &origin_cu);
13576
13577   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13578      symbols in.  */
13579   origin_previous_list_in_scope = origin_cu->list_in_scope;
13580   origin_cu->list_in_scope = cu->list_in_scope;
13581
13582   if (die->tag != origin_die->tag
13583       && !(die->tag == DW_TAG_inlined_subroutine
13584            && origin_die->tag == DW_TAG_subprogram))
13585     complaint (&symfile_complaints,
13586                _("DIE %s and its abstract origin %s have different tags"),
13587                sect_offset_str (die->sect_off),
13588                sect_offset_str (origin_die->sect_off));
13589
13590   std::vector<sect_offset> offsets;
13591
13592   for (child_die = die->child;
13593        child_die && child_die->tag;
13594        child_die = sibling_die (child_die))
13595     {
13596       struct die_info *child_origin_die;
13597       struct dwarf2_cu *child_origin_cu;
13598
13599       /* We are trying to process concrete instance entries:
13600          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13601          it's not relevant to our analysis here. i.e. detecting DIEs that are
13602          present in the abstract instance but not referenced in the concrete
13603          one.  */
13604       if (child_die->tag == DW_TAG_call_site
13605           || child_die->tag == DW_TAG_GNU_call_site)
13606         continue;
13607
13608       /* For each CHILD_DIE, find the corresponding child of
13609          ORIGIN_DIE.  If there is more than one layer of
13610          DW_AT_abstract_origin, follow them all; there shouldn't be,
13611          but GCC versions at least through 4.4 generate this (GCC PR
13612          40573).  */
13613       child_origin_die = child_die;
13614       child_origin_cu = cu;
13615       while (1)
13616         {
13617           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13618                               child_origin_cu);
13619           if (attr == NULL)
13620             break;
13621           child_origin_die = follow_die_ref (child_origin_die, attr,
13622                                              &child_origin_cu);
13623         }
13624
13625       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13626          counterpart may exist.  */
13627       if (child_origin_die != child_die)
13628         {
13629           if (child_die->tag != child_origin_die->tag
13630               && !(child_die->tag == DW_TAG_inlined_subroutine
13631                    && child_origin_die->tag == DW_TAG_subprogram))
13632             complaint (&symfile_complaints,
13633                        _("Child DIE %s and its abstract origin %s have "
13634                          "different tags"),
13635                        sect_offset_str (child_die->sect_off),
13636                        sect_offset_str (child_origin_die->sect_off));
13637           if (child_origin_die->parent != origin_die)
13638             complaint (&symfile_complaints,
13639                        _("Child DIE %s and its abstract origin %s have "
13640                          "different parents"),
13641                        sect_offset_str (child_die->sect_off),
13642                        sect_offset_str (child_origin_die->sect_off));
13643           else
13644             offsets.push_back (child_origin_die->sect_off);
13645         }
13646     }
13647   std::sort (offsets.begin (), offsets.end ());
13648   sect_offset *offsets_end = offsets.data () + offsets.size ();
13649   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13650     if (offsetp[-1] == *offsetp)
13651       complaint (&symfile_complaints,
13652                  _("Multiple children of DIE %s refer "
13653                    "to DIE %s as their abstract origin"),
13654                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13655
13656   offsetp = offsets.data ();
13657   origin_child_die = origin_die->child;
13658   while (origin_child_die && origin_child_die->tag)
13659     {
13660       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13661       while (offsetp < offsets_end
13662              && *offsetp < origin_child_die->sect_off)
13663         offsetp++;
13664       if (offsetp >= offsets_end
13665           || *offsetp > origin_child_die->sect_off)
13666         {
13667           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13668              Check whether we're already processing ORIGIN_CHILD_DIE.
13669              This can happen with mutually referenced abstract_origins.
13670              PR 16581.  */
13671           if (!origin_child_die->in_process)
13672             process_die (origin_child_die, origin_cu);
13673         }
13674       origin_child_die = sibling_die (origin_child_die);
13675     }
13676   origin_cu->list_in_scope = origin_previous_list_in_scope;
13677 }
13678
13679 static void
13680 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13681 {
13682   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13683   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13684   struct context_stack *newobj;
13685   CORE_ADDR lowpc;
13686   CORE_ADDR highpc;
13687   struct die_info *child_die;
13688   struct attribute *attr, *call_line, *call_file;
13689   const char *name;
13690   CORE_ADDR baseaddr;
13691   struct block *block;
13692   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13693   std::vector<struct symbol *> template_args;
13694   struct template_symbol *templ_func = NULL;
13695
13696   if (inlined_func)
13697     {
13698       /* If we do not have call site information, we can't show the
13699          caller of this inlined function.  That's too confusing, so
13700          only use the scope for local variables.  */
13701       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13702       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13703       if (call_line == NULL || call_file == NULL)
13704         {
13705           read_lexical_block_scope (die, cu);
13706           return;
13707         }
13708     }
13709
13710   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13711
13712   name = dwarf2_name (die, cu);
13713
13714   /* Ignore functions with missing or empty names.  These are actually
13715      illegal according to the DWARF standard.  */
13716   if (name == NULL)
13717     {
13718       complaint (&symfile_complaints,
13719                  _("missing name for subprogram DIE at %s"),
13720                  sect_offset_str (die->sect_off));
13721       return;
13722     }
13723
13724   /* Ignore functions with missing or invalid low and high pc attributes.  */
13725   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13726       <= PC_BOUNDS_INVALID)
13727     {
13728       attr = dwarf2_attr (die, DW_AT_external, cu);
13729       if (!attr || !DW_UNSND (attr))
13730         complaint (&symfile_complaints,
13731                    _("cannot get low and high bounds "
13732                      "for subprogram DIE at %s"),
13733                    sect_offset_str (die->sect_off));
13734       return;
13735     }
13736
13737   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13738   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13739
13740   /* If we have any template arguments, then we must allocate a
13741      different sort of symbol.  */
13742   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13743     {
13744       if (child_die->tag == DW_TAG_template_type_param
13745           || child_die->tag == DW_TAG_template_value_param)
13746         {
13747           templ_func = allocate_template_symbol (objfile);
13748           templ_func->subclass = SYMBOL_TEMPLATE;
13749           break;
13750         }
13751     }
13752
13753   newobj = push_context (0, lowpc);
13754   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13755                              (struct symbol *) templ_func);
13756
13757   /* If there is a location expression for DW_AT_frame_base, record
13758      it.  */
13759   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13760   if (attr)
13761     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13762
13763   /* If there is a location for the static link, record it.  */
13764   newobj->static_link = NULL;
13765   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13766   if (attr)
13767     {
13768       newobj->static_link
13769         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13770       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13771     }
13772
13773   cu->list_in_scope = &local_symbols;
13774
13775   if (die->child != NULL)
13776     {
13777       child_die = die->child;
13778       while (child_die && child_die->tag)
13779         {
13780           if (child_die->tag == DW_TAG_template_type_param
13781               || child_die->tag == DW_TAG_template_value_param)
13782             {
13783               struct symbol *arg = new_symbol (child_die, NULL, cu);
13784
13785               if (arg != NULL)
13786                 template_args.push_back (arg);
13787             }
13788           else
13789             process_die (child_die, cu);
13790           child_die = sibling_die (child_die);
13791         }
13792     }
13793
13794   inherit_abstract_dies (die, cu);
13795
13796   /* If we have a DW_AT_specification, we might need to import using
13797      directives from the context of the specification DIE.  See the
13798      comment in determine_prefix.  */
13799   if (cu->language == language_cplus
13800       && dwarf2_attr (die, DW_AT_specification, cu))
13801     {
13802       struct dwarf2_cu *spec_cu = cu;
13803       struct die_info *spec_die = die_specification (die, &spec_cu);
13804
13805       while (spec_die)
13806         {
13807           child_die = spec_die->child;
13808           while (child_die && child_die->tag)
13809             {
13810               if (child_die->tag == DW_TAG_imported_module)
13811                 process_die (child_die, spec_cu);
13812               child_die = sibling_die (child_die);
13813             }
13814
13815           /* In some cases, GCC generates specification DIEs that
13816              themselves contain DW_AT_specification attributes.  */
13817           spec_die = die_specification (spec_die, &spec_cu);
13818         }
13819     }
13820
13821   newobj = pop_context ();
13822   /* Make a block for the local symbols within.  */
13823   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13824                         newobj->static_link, lowpc, highpc);
13825
13826   /* For C++, set the block's scope.  */
13827   if ((cu->language == language_cplus
13828        || cu->language == language_fortran
13829        || cu->language == language_d
13830        || cu->language == language_rust)
13831       && cu->processing_has_namespace_info)
13832     block_set_scope (block, determine_prefix (die, cu),
13833                      &objfile->objfile_obstack);
13834
13835   /* If we have address ranges, record them.  */
13836   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13837
13838   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13839
13840   /* Attach template arguments to function.  */
13841   if (!template_args.empty ())
13842     {
13843       gdb_assert (templ_func != NULL);
13844
13845       templ_func->n_template_arguments = template_args.size ();
13846       templ_func->template_arguments
13847         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13848                      templ_func->n_template_arguments);
13849       memcpy (templ_func->template_arguments,
13850               template_args.data (),
13851               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13852     }
13853
13854   /* In C++, we can have functions nested inside functions (e.g., when
13855      a function declares a class that has methods).  This means that
13856      when we finish processing a function scope, we may need to go
13857      back to building a containing block's symbol lists.  */
13858   local_symbols = newobj->locals;
13859   local_using_directives = newobj->local_using_directives;
13860
13861   /* If we've finished processing a top-level function, subsequent
13862      symbols go in the file symbol list.  */
13863   if (outermost_context_p ())
13864     cu->list_in_scope = &file_symbols;
13865 }
13866
13867 /* Process all the DIES contained within a lexical block scope.  Start
13868    a new scope, process the dies, and then close the scope.  */
13869
13870 static void
13871 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13872 {
13873   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13874   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13875   struct context_stack *newobj;
13876   CORE_ADDR lowpc, highpc;
13877   struct die_info *child_die;
13878   CORE_ADDR baseaddr;
13879
13880   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13881
13882   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13883   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13884      as multiple lexical blocks?  Handling children in a sane way would
13885      be nasty.  Might be easier to properly extend generic blocks to
13886      describe ranges.  */
13887   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13888     {
13889     case PC_BOUNDS_NOT_PRESENT:
13890       /* DW_TAG_lexical_block has no attributes, process its children as if
13891          there was no wrapping by that DW_TAG_lexical_block.
13892          GCC does no longer produces such DWARF since GCC r224161.  */
13893       for (child_die = die->child;
13894            child_die != NULL && child_die->tag;
13895            child_die = sibling_die (child_die))
13896         process_die (child_die, cu);
13897       return;
13898     case PC_BOUNDS_INVALID:
13899       return;
13900     }
13901   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13902   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13903
13904   push_context (0, lowpc);
13905   if (die->child != NULL)
13906     {
13907       child_die = die->child;
13908       while (child_die && child_die->tag)
13909         {
13910           process_die (child_die, cu);
13911           child_die = sibling_die (child_die);
13912         }
13913     }
13914   inherit_abstract_dies (die, cu);
13915   newobj = pop_context ();
13916
13917   if (local_symbols != NULL || local_using_directives != NULL)
13918     {
13919       struct block *block
13920         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13921                         newobj->start_addr, highpc);
13922
13923       /* Note that recording ranges after traversing children, as we
13924          do here, means that recording a parent's ranges entails
13925          walking across all its children's ranges as they appear in
13926          the address map, which is quadratic behavior.
13927
13928          It would be nicer to record the parent's ranges before
13929          traversing its children, simply overriding whatever you find
13930          there.  But since we don't even decide whether to create a
13931          block until after we've traversed its children, that's hard
13932          to do.  */
13933       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13934     }
13935   local_symbols = newobj->locals;
13936   local_using_directives = newobj->local_using_directives;
13937 }
13938
13939 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13940
13941 static void
13942 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13943 {
13944   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13945   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13946   CORE_ADDR pc, baseaddr;
13947   struct attribute *attr;
13948   struct call_site *call_site, call_site_local;
13949   void **slot;
13950   int nparams;
13951   struct die_info *child_die;
13952
13953   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13954
13955   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13956   if (attr == NULL)
13957     {
13958       /* This was a pre-DWARF-5 GNU extension alias
13959          for DW_AT_call_return_pc.  */
13960       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13961     }
13962   if (!attr)
13963     {
13964       complaint (&symfile_complaints,
13965                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
13966                    "DIE %s [in module %s]"),
13967                  sect_offset_str (die->sect_off), objfile_name (objfile));
13968       return;
13969     }
13970   pc = attr_value_as_address (attr) + baseaddr;
13971   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13972
13973   if (cu->call_site_htab == NULL)
13974     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13975                                                NULL, &objfile->objfile_obstack,
13976                                                hashtab_obstack_allocate, NULL);
13977   call_site_local.pc = pc;
13978   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13979   if (*slot != NULL)
13980     {
13981       complaint (&symfile_complaints,
13982                  _("Duplicate PC %s for DW_TAG_call_site "
13983                    "DIE %s [in module %s]"),
13984                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13985                  objfile_name (objfile));
13986       return;
13987     }
13988
13989   /* Count parameters at the caller.  */
13990
13991   nparams = 0;
13992   for (child_die = die->child; child_die && child_die->tag;
13993        child_die = sibling_die (child_die))
13994     {
13995       if (child_die->tag != DW_TAG_call_site_parameter
13996           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13997         {
13998           complaint (&symfile_complaints,
13999                      _("Tag %d is not DW_TAG_call_site_parameter in "
14000                        "DW_TAG_call_site child DIE %s [in module %s]"),
14001                      child_die->tag, sect_offset_str (child_die->sect_off),
14002                      objfile_name (objfile));
14003           continue;
14004         }
14005
14006       nparams++;
14007     }
14008
14009   call_site
14010     = ((struct call_site *)
14011        obstack_alloc (&objfile->objfile_obstack,
14012                       sizeof (*call_site)
14013                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14014   *slot = call_site;
14015   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14016   call_site->pc = pc;
14017
14018   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14019       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14020     {
14021       struct die_info *func_die;
14022
14023       /* Skip also over DW_TAG_inlined_subroutine.  */
14024       for (func_die = die->parent;
14025            func_die && func_die->tag != DW_TAG_subprogram
14026            && func_die->tag != DW_TAG_subroutine_type;
14027            func_die = func_die->parent);
14028
14029       /* DW_AT_call_all_calls is a superset
14030          of DW_AT_call_all_tail_calls.  */
14031       if (func_die
14032           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14033           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14034           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14035           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14036         {
14037           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14038              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14039              both the initial caller containing the real return address PC and
14040              the final callee containing the current PC of a chain of tail
14041              calls do not need to have the tail call list complete.  But any
14042              function candidate for a virtual tail call frame searched via
14043              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14044              determined unambiguously.  */
14045         }
14046       else
14047         {
14048           struct type *func_type = NULL;
14049
14050           if (func_die)
14051             func_type = get_die_type (func_die, cu);
14052           if (func_type != NULL)
14053             {
14054               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14055
14056               /* Enlist this call site to the function.  */
14057               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14058               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14059             }
14060           else
14061             complaint (&symfile_complaints,
14062                        _("Cannot find function owning DW_TAG_call_site "
14063                          "DIE %s [in module %s]"),
14064                        sect_offset_str (die->sect_off), objfile_name (objfile));
14065         }
14066     }
14067
14068   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14069   if (attr == NULL)
14070     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14071   if (attr == NULL)
14072     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14073   if (attr == NULL)
14074     {
14075       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14076       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14077     }
14078   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14079   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14080     /* Keep NULL DWARF_BLOCK.  */;
14081   else if (attr_form_is_block (attr))
14082     {
14083       struct dwarf2_locexpr_baton *dlbaton;
14084
14085       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14086       dlbaton->data = DW_BLOCK (attr)->data;
14087       dlbaton->size = DW_BLOCK (attr)->size;
14088       dlbaton->per_cu = cu->per_cu;
14089
14090       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14091     }
14092   else if (attr_form_is_ref (attr))
14093     {
14094       struct dwarf2_cu *target_cu = cu;
14095       struct die_info *target_die;
14096
14097       target_die = follow_die_ref (die, attr, &target_cu);
14098       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14099       if (die_is_declaration (target_die, target_cu))
14100         {
14101           const char *target_physname;
14102
14103           /* Prefer the mangled name; otherwise compute the demangled one.  */
14104           target_physname = dw2_linkage_name (target_die, target_cu);
14105           if (target_physname == NULL)
14106             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14107           if (target_physname == NULL)
14108             complaint (&symfile_complaints,
14109                        _("DW_AT_call_target target DIE has invalid "
14110                          "physname, for referencing DIE %s [in module %s]"),
14111                        sect_offset_str (die->sect_off), objfile_name (objfile));
14112           else
14113             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14114         }
14115       else
14116         {
14117           CORE_ADDR lowpc;
14118
14119           /* DW_AT_entry_pc should be preferred.  */
14120           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14121               <= PC_BOUNDS_INVALID)
14122             complaint (&symfile_complaints,
14123                        _("DW_AT_call_target target DIE has invalid "
14124                          "low pc, for referencing DIE %s [in module %s]"),
14125                        sect_offset_str (die->sect_off), objfile_name (objfile));
14126           else
14127             {
14128               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14129               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14130             }
14131         }
14132     }
14133   else
14134     complaint (&symfile_complaints,
14135                _("DW_TAG_call_site DW_AT_call_target is neither "
14136                  "block nor reference, for DIE %s [in module %s]"),
14137                sect_offset_str (die->sect_off), objfile_name (objfile));
14138
14139   call_site->per_cu = cu->per_cu;
14140
14141   for (child_die = die->child;
14142        child_die && child_die->tag;
14143        child_die = sibling_die (child_die))
14144     {
14145       struct call_site_parameter *parameter;
14146       struct attribute *loc, *origin;
14147
14148       if (child_die->tag != DW_TAG_call_site_parameter
14149           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14150         {
14151           /* Already printed the complaint above.  */
14152           continue;
14153         }
14154
14155       gdb_assert (call_site->parameter_count < nparams);
14156       parameter = &call_site->parameter[call_site->parameter_count];
14157
14158       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14159          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14160          register is contained in DW_AT_call_value.  */
14161
14162       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14163       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14164       if (origin == NULL)
14165         {
14166           /* This was a pre-DWARF-5 GNU extension alias
14167              for DW_AT_call_parameter.  */
14168           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14169         }
14170       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14171         {
14172           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14173
14174           sect_offset sect_off
14175             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14176           if (!offset_in_cu_p (&cu->header, sect_off))
14177             {
14178               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14179                  binding can be done only inside one CU.  Such referenced DIE
14180                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14181               complaint (&symfile_complaints,
14182                          _("DW_AT_call_parameter offset is not in CU for "
14183                            "DW_TAG_call_site child DIE %s [in module %s]"),
14184                          sect_offset_str (child_die->sect_off),
14185                          objfile_name (objfile));
14186               continue;
14187             }
14188           parameter->u.param_cu_off
14189             = (cu_offset) (sect_off - cu->header.sect_off);
14190         }
14191       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14192         {
14193           complaint (&symfile_complaints,
14194                      _("No DW_FORM_block* DW_AT_location for "
14195                        "DW_TAG_call_site child DIE %s [in module %s]"),
14196                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14197           continue;
14198         }
14199       else
14200         {
14201           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14202             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14203           if (parameter->u.dwarf_reg != -1)
14204             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14205           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14206                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14207                                              &parameter->u.fb_offset))
14208             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14209           else
14210             {
14211               complaint (&symfile_complaints,
14212                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14213                            "for DW_FORM_block* DW_AT_location is supported for "
14214                            "DW_TAG_call_site child DIE %s "
14215                            "[in module %s]"),
14216                          sect_offset_str (child_die->sect_off),
14217                          objfile_name (objfile));
14218               continue;
14219             }
14220         }
14221
14222       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14223       if (attr == NULL)
14224         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14225       if (!attr_form_is_block (attr))
14226         {
14227           complaint (&symfile_complaints,
14228                      _("No DW_FORM_block* DW_AT_call_value for "
14229                        "DW_TAG_call_site child DIE %s [in module %s]"),
14230                      sect_offset_str (child_die->sect_off),
14231                      objfile_name (objfile));
14232           continue;
14233         }
14234       parameter->value = DW_BLOCK (attr)->data;
14235       parameter->value_size = DW_BLOCK (attr)->size;
14236
14237       /* Parameters are not pre-cleared by memset above.  */
14238       parameter->data_value = NULL;
14239       parameter->data_value_size = 0;
14240       call_site->parameter_count++;
14241
14242       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14243       if (attr == NULL)
14244         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14245       if (attr)
14246         {
14247           if (!attr_form_is_block (attr))
14248             complaint (&symfile_complaints,
14249                        _("No DW_FORM_block* DW_AT_call_data_value for "
14250                          "DW_TAG_call_site child DIE %s [in module %s]"),
14251                        sect_offset_str (child_die->sect_off),
14252                        objfile_name (objfile));
14253           else
14254             {
14255               parameter->data_value = DW_BLOCK (attr)->data;
14256               parameter->data_value_size = DW_BLOCK (attr)->size;
14257             }
14258         }
14259     }
14260 }
14261
14262 /* Helper function for read_variable.  If DIE represents a virtual
14263    table, then return the type of the concrete object that is
14264    associated with the virtual table.  Otherwise, return NULL.  */
14265
14266 static struct type *
14267 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14268 {
14269   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14270   if (attr == NULL)
14271     return NULL;
14272
14273   /* Find the type DIE.  */
14274   struct die_info *type_die = NULL;
14275   struct dwarf2_cu *type_cu = cu;
14276
14277   if (attr_form_is_ref (attr))
14278     type_die = follow_die_ref (die, attr, &type_cu);
14279   if (type_die == NULL)
14280     return NULL;
14281
14282   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14283     return NULL;
14284   return die_containing_type (type_die, type_cu);
14285 }
14286
14287 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14288
14289 static void
14290 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14291 {
14292   struct rust_vtable_symbol *storage = NULL;
14293
14294   if (cu->language == language_rust)
14295     {
14296       struct type *containing_type = rust_containing_type (die, cu);
14297
14298       if (containing_type != NULL)
14299         {
14300           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14301
14302           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14303                                     struct rust_vtable_symbol);
14304           initialize_objfile_symbol (storage);
14305           storage->concrete_type = containing_type;
14306           storage->subclass = SYMBOL_RUST_VTABLE;
14307         }
14308     }
14309
14310   new_symbol (die, NULL, cu, storage);
14311 }
14312
14313 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14314    reading .debug_rnglists.
14315    Callback's type should be:
14316     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14317    Return true if the attributes are present and valid, otherwise,
14318    return false.  */
14319
14320 template <typename Callback>
14321 static bool
14322 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14323                          Callback &&callback)
14324 {
14325   struct dwarf2_per_objfile *dwarf2_per_objfile
14326     = cu->per_cu->dwarf2_per_objfile;
14327   struct objfile *objfile = dwarf2_per_objfile->objfile;
14328   bfd *obfd = objfile->obfd;
14329   /* Base address selection entry.  */
14330   CORE_ADDR base;
14331   int found_base;
14332   const gdb_byte *buffer;
14333   CORE_ADDR baseaddr;
14334   bool overflow = false;
14335
14336   found_base = cu->base_known;
14337   base = cu->base_address;
14338
14339   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14340   if (offset >= dwarf2_per_objfile->rnglists.size)
14341     {
14342       complaint (&symfile_complaints,
14343                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14344                  offset);
14345       return false;
14346     }
14347   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14348
14349   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14350
14351   while (1)
14352     {
14353       /* Initialize it due to a false compiler warning.  */
14354       CORE_ADDR range_beginning = 0, range_end = 0;
14355       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14356                                  + dwarf2_per_objfile->rnglists.size);
14357       unsigned int bytes_read;
14358
14359       if (buffer == buf_end)
14360         {
14361           overflow = true;
14362           break;
14363         }
14364       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14365       switch (rlet)
14366         {
14367         case DW_RLE_end_of_list:
14368           break;
14369         case DW_RLE_base_address:
14370           if (buffer + cu->header.addr_size > buf_end)
14371             {
14372               overflow = true;
14373               break;
14374             }
14375           base = read_address (obfd, buffer, cu, &bytes_read);
14376           found_base = 1;
14377           buffer += bytes_read;
14378           break;
14379         case DW_RLE_start_length:
14380           if (buffer + cu->header.addr_size > buf_end)
14381             {
14382               overflow = true;
14383               break;
14384             }
14385           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14386           buffer += bytes_read;
14387           range_end = (range_beginning
14388                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14389           buffer += bytes_read;
14390           if (buffer > buf_end)
14391             {
14392               overflow = true;
14393               break;
14394             }
14395           break;
14396         case DW_RLE_offset_pair:
14397           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14398           buffer += bytes_read;
14399           if (buffer > buf_end)
14400             {
14401               overflow = true;
14402               break;
14403             }
14404           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14405           buffer += bytes_read;
14406           if (buffer > buf_end)
14407             {
14408               overflow = true;
14409               break;
14410             }
14411           break;
14412         case DW_RLE_start_end:
14413           if (buffer + 2 * cu->header.addr_size > buf_end)
14414             {
14415               overflow = true;
14416               break;
14417             }
14418           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14419           buffer += bytes_read;
14420           range_end = read_address (obfd, buffer, cu, &bytes_read);
14421           buffer += bytes_read;
14422           break;
14423         default:
14424           complaint (&symfile_complaints,
14425                      _("Invalid .debug_rnglists data (no base address)"));
14426           return false;
14427         }
14428       if (rlet == DW_RLE_end_of_list || overflow)
14429         break;
14430       if (rlet == DW_RLE_base_address)
14431         continue;
14432
14433       if (!found_base)
14434         {
14435           /* We have no valid base address for the ranges
14436              data.  */
14437           complaint (&symfile_complaints,
14438                      _("Invalid .debug_rnglists data (no base address)"));
14439           return false;
14440         }
14441
14442       if (range_beginning > range_end)
14443         {
14444           /* Inverted range entries are invalid.  */
14445           complaint (&symfile_complaints,
14446                      _("Invalid .debug_rnglists data (inverted range)"));
14447           return false;
14448         }
14449
14450       /* Empty range entries have no effect.  */
14451       if (range_beginning == range_end)
14452         continue;
14453
14454       range_beginning += base;
14455       range_end += base;
14456
14457       /* A not-uncommon case of bad debug info.
14458          Don't pollute the addrmap with bad data.  */
14459       if (range_beginning + baseaddr == 0
14460           && !dwarf2_per_objfile->has_section_at_zero)
14461         {
14462           complaint (&symfile_complaints,
14463                      _(".debug_rnglists entry has start address of zero"
14464                        " [in module %s]"), objfile_name (objfile));
14465           continue;
14466         }
14467
14468       callback (range_beginning, range_end);
14469     }
14470
14471   if (overflow)
14472     {
14473       complaint (&symfile_complaints,
14474                  _("Offset %d is not terminated "
14475                    "for DW_AT_ranges attribute"),
14476                  offset);
14477       return false;
14478     }
14479
14480   return true;
14481 }
14482
14483 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14484    Callback's type should be:
14485     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14486    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14487
14488 template <typename Callback>
14489 static int
14490 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14491                        Callback &&callback)
14492 {
14493   struct dwarf2_per_objfile *dwarf2_per_objfile
14494       = cu->per_cu->dwarf2_per_objfile;
14495   struct objfile *objfile = dwarf2_per_objfile->objfile;
14496   struct comp_unit_head *cu_header = &cu->header;
14497   bfd *obfd = objfile->obfd;
14498   unsigned int addr_size = cu_header->addr_size;
14499   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14500   /* Base address selection entry.  */
14501   CORE_ADDR base;
14502   int found_base;
14503   unsigned int dummy;
14504   const gdb_byte *buffer;
14505   CORE_ADDR baseaddr;
14506
14507   if (cu_header->version >= 5)
14508     return dwarf2_rnglists_process (offset, cu, callback);
14509
14510   found_base = cu->base_known;
14511   base = cu->base_address;
14512
14513   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14514   if (offset >= dwarf2_per_objfile->ranges.size)
14515     {
14516       complaint (&symfile_complaints,
14517                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14518                  offset);
14519       return 0;
14520     }
14521   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14522
14523   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14524
14525   while (1)
14526     {
14527       CORE_ADDR range_beginning, range_end;
14528
14529       range_beginning = read_address (obfd, buffer, cu, &dummy);
14530       buffer += addr_size;
14531       range_end = read_address (obfd, buffer, cu, &dummy);
14532       buffer += addr_size;
14533       offset += 2 * addr_size;
14534
14535       /* An end of list marker is a pair of zero addresses.  */
14536       if (range_beginning == 0 && range_end == 0)
14537         /* Found the end of list entry.  */
14538         break;
14539
14540       /* Each base address selection entry is a pair of 2 values.
14541          The first is the largest possible address, the second is
14542          the base address.  Check for a base address here.  */
14543       if ((range_beginning & mask) == mask)
14544         {
14545           /* If we found the largest possible address, then we already
14546              have the base address in range_end.  */
14547           base = range_end;
14548           found_base = 1;
14549           continue;
14550         }
14551
14552       if (!found_base)
14553         {
14554           /* We have no valid base address for the ranges
14555              data.  */
14556           complaint (&symfile_complaints,
14557                      _("Invalid .debug_ranges data (no base address)"));
14558           return 0;
14559         }
14560
14561       if (range_beginning > range_end)
14562         {
14563           /* Inverted range entries are invalid.  */
14564           complaint (&symfile_complaints,
14565                      _("Invalid .debug_ranges data (inverted range)"));
14566           return 0;
14567         }
14568
14569       /* Empty range entries have no effect.  */
14570       if (range_beginning == range_end)
14571         continue;
14572
14573       range_beginning += base;
14574       range_end += base;
14575
14576       /* A not-uncommon case of bad debug info.
14577          Don't pollute the addrmap with bad data.  */
14578       if (range_beginning + baseaddr == 0
14579           && !dwarf2_per_objfile->has_section_at_zero)
14580         {
14581           complaint (&symfile_complaints,
14582                      _(".debug_ranges entry has start address of zero"
14583                        " [in module %s]"), objfile_name (objfile));
14584           continue;
14585         }
14586
14587       callback (range_beginning, range_end);
14588     }
14589
14590   return 1;
14591 }
14592
14593 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14594    Return 1 if the attributes are present and valid, otherwise, return 0.
14595    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14596
14597 static int
14598 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14599                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14600                     struct partial_symtab *ranges_pst)
14601 {
14602   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14603   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14604   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14605                                        SECT_OFF_TEXT (objfile));
14606   int low_set = 0;
14607   CORE_ADDR low = 0;
14608   CORE_ADDR high = 0;
14609   int retval;
14610
14611   retval = dwarf2_ranges_process (offset, cu,
14612     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14613     {
14614       if (ranges_pst != NULL)
14615         {
14616           CORE_ADDR lowpc;
14617           CORE_ADDR highpc;
14618
14619           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14620                                               range_beginning + baseaddr);
14621           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14622                                                range_end + baseaddr);
14623           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14624                              ranges_pst);
14625         }
14626
14627       /* FIXME: This is recording everything as a low-high
14628          segment of consecutive addresses.  We should have a
14629          data structure for discontiguous block ranges
14630          instead.  */
14631       if (! low_set)
14632         {
14633           low = range_beginning;
14634           high = range_end;
14635           low_set = 1;
14636         }
14637       else
14638         {
14639           if (range_beginning < low)
14640             low = range_beginning;
14641           if (range_end > high)
14642             high = range_end;
14643         }
14644     });
14645   if (!retval)
14646     return 0;
14647
14648   if (! low_set)
14649     /* If the first entry is an end-of-list marker, the range
14650        describes an empty scope, i.e. no instructions.  */
14651     return 0;
14652
14653   if (low_return)
14654     *low_return = low;
14655   if (high_return)
14656     *high_return = high;
14657   return 1;
14658 }
14659
14660 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14661    definition for the return value.  *LOWPC and *HIGHPC are set iff
14662    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14663
14664 static enum pc_bounds_kind
14665 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14666                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14667                       struct partial_symtab *pst)
14668 {
14669   struct dwarf2_per_objfile *dwarf2_per_objfile
14670     = cu->per_cu->dwarf2_per_objfile;
14671   struct attribute *attr;
14672   struct attribute *attr_high;
14673   CORE_ADDR low = 0;
14674   CORE_ADDR high = 0;
14675   enum pc_bounds_kind ret;
14676
14677   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14678   if (attr_high)
14679     {
14680       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14681       if (attr)
14682         {
14683           low = attr_value_as_address (attr);
14684           high = attr_value_as_address (attr_high);
14685           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14686             high += low;
14687         }
14688       else
14689         /* Found high w/o low attribute.  */
14690         return PC_BOUNDS_INVALID;
14691
14692       /* Found consecutive range of addresses.  */
14693       ret = PC_BOUNDS_HIGH_LOW;
14694     }
14695   else
14696     {
14697       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14698       if (attr != NULL)
14699         {
14700           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14701              We take advantage of the fact that DW_AT_ranges does not appear
14702              in DW_TAG_compile_unit of DWO files.  */
14703           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14704           unsigned int ranges_offset = (DW_UNSND (attr)
14705                                         + (need_ranges_base
14706                                            ? cu->ranges_base
14707                                            : 0));
14708
14709           /* Value of the DW_AT_ranges attribute is the offset in the
14710              .debug_ranges section.  */
14711           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14712             return PC_BOUNDS_INVALID;
14713           /* Found discontinuous range of addresses.  */
14714           ret = PC_BOUNDS_RANGES;
14715         }
14716       else
14717         return PC_BOUNDS_NOT_PRESENT;
14718     }
14719
14720   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14721   if (high <= low)
14722     return PC_BOUNDS_INVALID;
14723
14724   /* When using the GNU linker, .gnu.linkonce. sections are used to
14725      eliminate duplicate copies of functions and vtables and such.
14726      The linker will arbitrarily choose one and discard the others.
14727      The AT_*_pc values for such functions refer to local labels in
14728      these sections.  If the section from that file was discarded, the
14729      labels are not in the output, so the relocs get a value of 0.
14730      If this is a discarded function, mark the pc bounds as invalid,
14731      so that GDB will ignore it.  */
14732   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14733     return PC_BOUNDS_INVALID;
14734
14735   *lowpc = low;
14736   if (highpc)
14737     *highpc = high;
14738   return ret;
14739 }
14740
14741 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14742    its low and high PC addresses.  Do nothing if these addresses could not
14743    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14744    and HIGHPC to the high address if greater than HIGHPC.  */
14745
14746 static void
14747 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14748                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14749                                  struct dwarf2_cu *cu)
14750 {
14751   CORE_ADDR low, high;
14752   struct die_info *child = die->child;
14753
14754   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14755     {
14756       *lowpc = std::min (*lowpc, low);
14757       *highpc = std::max (*highpc, high);
14758     }
14759
14760   /* If the language does not allow nested subprograms (either inside
14761      subprograms or lexical blocks), we're done.  */
14762   if (cu->language != language_ada)
14763     return;
14764
14765   /* Check all the children of the given DIE.  If it contains nested
14766      subprograms, then check their pc bounds.  Likewise, we need to
14767      check lexical blocks as well, as they may also contain subprogram
14768      definitions.  */
14769   while (child && child->tag)
14770     {
14771       if (child->tag == DW_TAG_subprogram
14772           || child->tag == DW_TAG_lexical_block)
14773         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14774       child = sibling_die (child);
14775     }
14776 }
14777
14778 /* Get the low and high pc's represented by the scope DIE, and store
14779    them in *LOWPC and *HIGHPC.  If the correct values can't be
14780    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14781
14782 static void
14783 get_scope_pc_bounds (struct die_info *die,
14784                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14785                      struct dwarf2_cu *cu)
14786 {
14787   CORE_ADDR best_low = (CORE_ADDR) -1;
14788   CORE_ADDR best_high = (CORE_ADDR) 0;
14789   CORE_ADDR current_low, current_high;
14790
14791   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14792       >= PC_BOUNDS_RANGES)
14793     {
14794       best_low = current_low;
14795       best_high = current_high;
14796     }
14797   else
14798     {
14799       struct die_info *child = die->child;
14800
14801       while (child && child->tag)
14802         {
14803           switch (child->tag) {
14804           case DW_TAG_subprogram:
14805             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14806             break;
14807           case DW_TAG_namespace:
14808           case DW_TAG_module:
14809             /* FIXME: carlton/2004-01-16: Should we do this for
14810                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14811                that current GCC's always emit the DIEs corresponding
14812                to definitions of methods of classes as children of a
14813                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14814                the DIEs giving the declarations, which could be
14815                anywhere).  But I don't see any reason why the
14816                standards says that they have to be there.  */
14817             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14818
14819             if (current_low != ((CORE_ADDR) -1))
14820               {
14821                 best_low = std::min (best_low, current_low);
14822                 best_high = std::max (best_high, current_high);
14823               }
14824             break;
14825           default:
14826             /* Ignore.  */
14827             break;
14828           }
14829
14830           child = sibling_die (child);
14831         }
14832     }
14833
14834   *lowpc = best_low;
14835   *highpc = best_high;
14836 }
14837
14838 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14839    in DIE.  */
14840
14841 static void
14842 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14843                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14844 {
14845   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14846   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14847   struct attribute *attr;
14848   struct attribute *attr_high;
14849
14850   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14851   if (attr_high)
14852     {
14853       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14854       if (attr)
14855         {
14856           CORE_ADDR low = attr_value_as_address (attr);
14857           CORE_ADDR high = attr_value_as_address (attr_high);
14858
14859           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14860             high += low;
14861
14862           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14863           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14864           record_block_range (block, low, high - 1);
14865         }
14866     }
14867
14868   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14869   if (attr)
14870     {
14871       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14872          We take advantage of the fact that DW_AT_ranges does not appear
14873          in DW_TAG_compile_unit of DWO files.  */
14874       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14875
14876       /* The value of the DW_AT_ranges attribute is the offset of the
14877          address range list in the .debug_ranges section.  */
14878       unsigned long offset = (DW_UNSND (attr)
14879                               + (need_ranges_base ? cu->ranges_base : 0));
14880       const gdb_byte *buffer;
14881
14882       /* For some target architectures, but not others, the
14883          read_address function sign-extends the addresses it returns.
14884          To recognize base address selection entries, we need a
14885          mask.  */
14886       unsigned int addr_size = cu->header.addr_size;
14887       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14888
14889       /* The base address, to which the next pair is relative.  Note
14890          that this 'base' is a DWARF concept: most entries in a range
14891          list are relative, to reduce the number of relocs against the
14892          debugging information.  This is separate from this function's
14893          'baseaddr' argument, which GDB uses to relocate debugging
14894          information from a shared library based on the address at
14895          which the library was loaded.  */
14896       CORE_ADDR base = cu->base_address;
14897       int base_known = cu->base_known;
14898
14899       dwarf2_ranges_process (offset, cu,
14900         [&] (CORE_ADDR start, CORE_ADDR end)
14901         {
14902           start += baseaddr;
14903           end += baseaddr;
14904           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14905           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14906           record_block_range (block, start, end - 1);
14907         });
14908     }
14909 }
14910
14911 /* Check whether the producer field indicates either of GCC < 4.6, or the
14912    Intel C/C++ compiler, and cache the result in CU.  */
14913
14914 static void
14915 check_producer (struct dwarf2_cu *cu)
14916 {
14917   int major, minor;
14918
14919   if (cu->producer == NULL)
14920     {
14921       /* For unknown compilers expect their behavior is DWARF version
14922          compliant.
14923
14924          GCC started to support .debug_types sections by -gdwarf-4 since
14925          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14926          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14927          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14928          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14929     }
14930   else if (producer_is_gcc (cu->producer, &major, &minor))
14931     {
14932       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14933       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14934     }
14935   else if (producer_is_icc (cu->producer, &major, &minor))
14936     cu->producer_is_icc_lt_14 = major < 14;
14937   else
14938     {
14939       /* For other non-GCC compilers, expect their behavior is DWARF version
14940          compliant.  */
14941     }
14942
14943   cu->checked_producer = 1;
14944 }
14945
14946 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14947    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14948    during 4.6.0 experimental.  */
14949
14950 static int
14951 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14952 {
14953   if (!cu->checked_producer)
14954     check_producer (cu);
14955
14956   return cu->producer_is_gxx_lt_4_6;
14957 }
14958
14959 /* Return the default accessibility type if it is not overriden by
14960    DW_AT_accessibility.  */
14961
14962 static enum dwarf_access_attribute
14963 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14964 {
14965   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14966     {
14967       /* The default DWARF 2 accessibility for members is public, the default
14968          accessibility for inheritance is private.  */
14969
14970       if (die->tag != DW_TAG_inheritance)
14971         return DW_ACCESS_public;
14972       else
14973         return DW_ACCESS_private;
14974     }
14975   else
14976     {
14977       /* DWARF 3+ defines the default accessibility a different way.  The same
14978          rules apply now for DW_TAG_inheritance as for the members and it only
14979          depends on the container kind.  */
14980
14981       if (die->parent->tag == DW_TAG_class_type)
14982         return DW_ACCESS_private;
14983       else
14984         return DW_ACCESS_public;
14985     }
14986 }
14987
14988 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14989    offset.  If the attribute was not found return 0, otherwise return
14990    1.  If it was found but could not properly be handled, set *OFFSET
14991    to 0.  */
14992
14993 static int
14994 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14995                              LONGEST *offset)
14996 {
14997   struct attribute *attr;
14998
14999   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15000   if (attr != NULL)
15001     {
15002       *offset = 0;
15003
15004       /* Note that we do not check for a section offset first here.
15005          This is because DW_AT_data_member_location is new in DWARF 4,
15006          so if we see it, we can assume that a constant form is really
15007          a constant and not a section offset.  */
15008       if (attr_form_is_constant (attr))
15009         *offset = dwarf2_get_attr_constant_value (attr, 0);
15010       else if (attr_form_is_section_offset (attr))
15011         dwarf2_complex_location_expr_complaint ();
15012       else if (attr_form_is_block (attr))
15013         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15014       else
15015         dwarf2_complex_location_expr_complaint ();
15016
15017       return 1;
15018     }
15019
15020   return 0;
15021 }
15022
15023 /* Add an aggregate field to the field list.  */
15024
15025 static void
15026 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15027                   struct dwarf2_cu *cu)
15028 {
15029   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15030   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15031   struct nextfield *new_field;
15032   struct attribute *attr;
15033   struct field *fp;
15034   const char *fieldname = "";
15035
15036   if (die->tag == DW_TAG_inheritance)
15037     {
15038       fip->baseclasses.emplace_back ();
15039       new_field = &fip->baseclasses.back ();
15040     }
15041   else
15042     {
15043       fip->fields.emplace_back ();
15044       new_field = &fip->fields.back ();
15045     }
15046
15047   fip->nfields++;
15048
15049   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15050   if (attr)
15051     new_field->accessibility = DW_UNSND (attr);
15052   else
15053     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15054   if (new_field->accessibility != DW_ACCESS_public)
15055     fip->non_public_fields = 1;
15056
15057   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15058   if (attr)
15059     new_field->virtuality = DW_UNSND (attr);
15060   else
15061     new_field->virtuality = DW_VIRTUALITY_none;
15062
15063   fp = &new_field->field;
15064
15065   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15066     {
15067       LONGEST offset;
15068
15069       /* Data member other than a C++ static data member.  */
15070
15071       /* Get type of field.  */
15072       fp->type = die_type (die, cu);
15073
15074       SET_FIELD_BITPOS (*fp, 0);
15075
15076       /* Get bit size of field (zero if none).  */
15077       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15078       if (attr)
15079         {
15080           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15081         }
15082       else
15083         {
15084           FIELD_BITSIZE (*fp) = 0;
15085         }
15086
15087       /* Get bit offset of field.  */
15088       if (handle_data_member_location (die, cu, &offset))
15089         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15090       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15091       if (attr)
15092         {
15093           if (gdbarch_bits_big_endian (gdbarch))
15094             {
15095               /* For big endian bits, the DW_AT_bit_offset gives the
15096                  additional bit offset from the MSB of the containing
15097                  anonymous object to the MSB of the field.  We don't
15098                  have to do anything special since we don't need to
15099                  know the size of the anonymous object.  */
15100               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15101             }
15102           else
15103             {
15104               /* For little endian bits, compute the bit offset to the
15105                  MSB of the anonymous object, subtract off the number of
15106                  bits from the MSB of the field to the MSB of the
15107                  object, and then subtract off the number of bits of
15108                  the field itself.  The result is the bit offset of
15109                  the LSB of the field.  */
15110               int anonymous_size;
15111               int bit_offset = DW_UNSND (attr);
15112
15113               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15114               if (attr)
15115                 {
15116                   /* The size of the anonymous object containing
15117                      the bit field is explicit, so use the
15118                      indicated size (in bytes).  */
15119                   anonymous_size = DW_UNSND (attr);
15120                 }
15121               else
15122                 {
15123                   /* The size of the anonymous object containing
15124                      the bit field must be inferred from the type
15125                      attribute of the data member containing the
15126                      bit field.  */
15127                   anonymous_size = TYPE_LENGTH (fp->type);
15128                 }
15129               SET_FIELD_BITPOS (*fp,
15130                                 (FIELD_BITPOS (*fp)
15131                                  + anonymous_size * bits_per_byte
15132                                  - bit_offset - FIELD_BITSIZE (*fp)));
15133             }
15134         }
15135       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15136       if (attr != NULL)
15137         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15138                                 + dwarf2_get_attr_constant_value (attr, 0)));
15139
15140       /* Get name of field.  */
15141       fieldname = dwarf2_name (die, cu);
15142       if (fieldname == NULL)
15143         fieldname = "";
15144
15145       /* The name is already allocated along with this objfile, so we don't
15146          need to duplicate it for the type.  */
15147       fp->name = fieldname;
15148
15149       /* Change accessibility for artificial fields (e.g. virtual table
15150          pointer or virtual base class pointer) to private.  */
15151       if (dwarf2_attr (die, DW_AT_artificial, cu))
15152         {
15153           FIELD_ARTIFICIAL (*fp) = 1;
15154           new_field->accessibility = DW_ACCESS_private;
15155           fip->non_public_fields = 1;
15156         }
15157     }
15158   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15159     {
15160       /* C++ static member.  */
15161
15162       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15163          is a declaration, but all versions of G++ as of this writing
15164          (so through at least 3.2.1) incorrectly generate
15165          DW_TAG_variable tags.  */
15166
15167       const char *physname;
15168
15169       /* Get name of field.  */
15170       fieldname = dwarf2_name (die, cu);
15171       if (fieldname == NULL)
15172         return;
15173
15174       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15175       if (attr
15176           /* Only create a symbol if this is an external value.
15177              new_symbol checks this and puts the value in the global symbol
15178              table, which we want.  If it is not external, new_symbol
15179              will try to put the value in cu->list_in_scope which is wrong.  */
15180           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15181         {
15182           /* A static const member, not much different than an enum as far as
15183              we're concerned, except that we can support more types.  */
15184           new_symbol (die, NULL, cu);
15185         }
15186
15187       /* Get physical name.  */
15188       physname = dwarf2_physname (fieldname, die, cu);
15189
15190       /* The name is already allocated along with this objfile, so we don't
15191          need to duplicate it for the type.  */
15192       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15193       FIELD_TYPE (*fp) = die_type (die, cu);
15194       FIELD_NAME (*fp) = fieldname;
15195     }
15196   else if (die->tag == DW_TAG_inheritance)
15197     {
15198       LONGEST offset;
15199
15200       /* C++ base class field.  */
15201       if (handle_data_member_location (die, cu, &offset))
15202         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15203       FIELD_BITSIZE (*fp) = 0;
15204       FIELD_TYPE (*fp) = die_type (die, cu);
15205       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15206     }
15207   else if (die->tag == DW_TAG_variant_part)
15208     {
15209       /* process_structure_scope will treat this DIE as a union.  */
15210       process_structure_scope (die, cu);
15211
15212       /* The variant part is relative to the start of the enclosing
15213          structure.  */
15214       SET_FIELD_BITPOS (*fp, 0);
15215       fp->type = get_die_type (die, cu);
15216       fp->artificial = 1;
15217       fp->name = "<<variant>>";
15218     }
15219   else
15220     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15221 }
15222
15223 /* Can the type given by DIE define another type?  */
15224
15225 static bool
15226 type_can_define_types (const struct die_info *die)
15227 {
15228   switch (die->tag)
15229     {
15230     case DW_TAG_typedef:
15231     case DW_TAG_class_type:
15232     case DW_TAG_structure_type:
15233     case DW_TAG_union_type:
15234     case DW_TAG_enumeration_type:
15235       return true;
15236
15237     default:
15238       return false;
15239     }
15240 }
15241
15242 /* Add a type definition defined in the scope of the FIP's class.  */
15243
15244 static void
15245 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15246                       struct dwarf2_cu *cu)
15247 {
15248   struct decl_field fp;
15249   memset (&fp, 0, sizeof (fp));
15250
15251   gdb_assert (type_can_define_types (die));
15252
15253   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15254   fp.name = dwarf2_name (die, cu);
15255   fp.type = read_type_die (die, cu);
15256
15257   /* Save accessibility.  */
15258   enum dwarf_access_attribute accessibility;
15259   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15260   if (attr != NULL)
15261     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15262   else
15263     accessibility = dwarf2_default_access_attribute (die, cu);
15264   switch (accessibility)
15265     {
15266     case DW_ACCESS_public:
15267       /* The assumed value if neither private nor protected.  */
15268       break;
15269     case DW_ACCESS_private:
15270       fp.is_private = 1;
15271       break;
15272     case DW_ACCESS_protected:
15273       fp.is_protected = 1;
15274       break;
15275     default:
15276       complaint (&symfile_complaints,
15277                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15278     }
15279
15280   if (die->tag == DW_TAG_typedef)
15281     fip->typedef_field_list.push_back (fp);
15282   else
15283     fip->nested_types_list.push_back (fp);
15284 }
15285
15286 /* Create the vector of fields, and attach it to the type.  */
15287
15288 static void
15289 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15290                               struct dwarf2_cu *cu)
15291 {
15292   int nfields = fip->nfields;
15293
15294   /* Record the field count, allocate space for the array of fields,
15295      and create blank accessibility bitfields if necessary.  */
15296   TYPE_NFIELDS (type) = nfields;
15297   TYPE_FIELDS (type) = (struct field *)
15298     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15299
15300   if (fip->non_public_fields && cu->language != language_ada)
15301     {
15302       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15303
15304       TYPE_FIELD_PRIVATE_BITS (type) =
15305         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15306       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15307
15308       TYPE_FIELD_PROTECTED_BITS (type) =
15309         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15310       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15311
15312       TYPE_FIELD_IGNORE_BITS (type) =
15313         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15314       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15315     }
15316
15317   /* If the type has baseclasses, allocate and clear a bit vector for
15318      TYPE_FIELD_VIRTUAL_BITS.  */
15319   if (!fip->baseclasses.empty () && cu->language != language_ada)
15320     {
15321       int num_bytes = B_BYTES (fip->baseclasses.size ());
15322       unsigned char *pointer;
15323
15324       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15325       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15326       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15327       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15328       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15329     }
15330
15331   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15332     {
15333       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15334
15335       for (int index = 0; index < nfields; ++index)
15336         {
15337           struct nextfield &field = fip->fields[index];
15338
15339           if (field.variant.is_discriminant)
15340             di->discriminant_index = index;
15341           else if (field.variant.default_branch)
15342             di->default_index = index;
15343           else
15344             di->discriminants[index] = field.variant.discriminant_value;
15345         }
15346     }
15347
15348   /* Copy the saved-up fields into the field vector.  */
15349   for (int i = 0; i < nfields; ++i)
15350     {
15351       struct nextfield &field
15352         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15353            : fip->fields[i - fip->baseclasses.size ()]);
15354
15355       TYPE_FIELD (type, i) = field.field;
15356       switch (field.accessibility)
15357         {
15358         case DW_ACCESS_private:
15359           if (cu->language != language_ada)
15360             SET_TYPE_FIELD_PRIVATE (type, i);
15361           break;
15362
15363         case DW_ACCESS_protected:
15364           if (cu->language != language_ada)
15365             SET_TYPE_FIELD_PROTECTED (type, i);
15366           break;
15367
15368         case DW_ACCESS_public:
15369           break;
15370
15371         default:
15372           /* Unknown accessibility.  Complain and treat it as public.  */
15373           {
15374             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15375                        field.accessibility);
15376           }
15377           break;
15378         }
15379       if (i < fip->baseclasses.size ())
15380         {
15381           switch (field.virtuality)
15382             {
15383             case DW_VIRTUALITY_virtual:
15384             case DW_VIRTUALITY_pure_virtual:
15385               if (cu->language == language_ada)
15386                 error (_("unexpected virtuality in component of Ada type"));
15387               SET_TYPE_FIELD_VIRTUAL (type, i);
15388               break;
15389             }
15390         }
15391     }
15392 }
15393
15394 /* Return true if this member function is a constructor, false
15395    otherwise.  */
15396
15397 static int
15398 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15399 {
15400   const char *fieldname;
15401   const char *type_name;
15402   int len;
15403
15404   if (die->parent == NULL)
15405     return 0;
15406
15407   if (die->parent->tag != DW_TAG_structure_type
15408       && die->parent->tag != DW_TAG_union_type
15409       && die->parent->tag != DW_TAG_class_type)
15410     return 0;
15411
15412   fieldname = dwarf2_name (die, cu);
15413   type_name = dwarf2_name (die->parent, cu);
15414   if (fieldname == NULL || type_name == NULL)
15415     return 0;
15416
15417   len = strlen (fieldname);
15418   return (strncmp (fieldname, type_name, len) == 0
15419           && (type_name[len] == '\0' || type_name[len] == '<'));
15420 }
15421
15422 /* Add a member function to the proper fieldlist.  */
15423
15424 static void
15425 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15426                       struct type *type, struct dwarf2_cu *cu)
15427 {
15428   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15429   struct attribute *attr;
15430   int i;
15431   struct fnfieldlist *flp = nullptr;
15432   struct fn_field *fnp;
15433   const char *fieldname;
15434   struct type *this_type;
15435   enum dwarf_access_attribute accessibility;
15436
15437   if (cu->language == language_ada)
15438     error (_("unexpected member function in Ada type"));
15439
15440   /* Get name of member function.  */
15441   fieldname = dwarf2_name (die, cu);
15442   if (fieldname == NULL)
15443     return;
15444
15445   /* Look up member function name in fieldlist.  */
15446   for (i = 0; i < fip->fnfieldlists.size (); i++)
15447     {
15448       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15449         {
15450           flp = &fip->fnfieldlists[i];
15451           break;
15452         }
15453     }
15454
15455   /* Create a new fnfieldlist if necessary.  */
15456   if (flp == nullptr)
15457     {
15458       fip->fnfieldlists.emplace_back ();
15459       flp = &fip->fnfieldlists.back ();
15460       flp->name = fieldname;
15461       i = fip->fnfieldlists.size () - 1;
15462     }
15463
15464   /* Create a new member function field and add it to the vector of
15465      fnfieldlists.  */
15466   flp->fnfields.emplace_back ();
15467   fnp = &flp->fnfields.back ();
15468
15469   /* Delay processing of the physname until later.  */
15470   if (cu->language == language_cplus)
15471     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15472                         die, cu);
15473   else
15474     {
15475       const char *physname = dwarf2_physname (fieldname, die, cu);
15476       fnp->physname = physname ? physname : "";
15477     }
15478
15479   fnp->type = alloc_type (objfile);
15480   this_type = read_type_die (die, cu);
15481   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15482     {
15483       int nparams = TYPE_NFIELDS (this_type);
15484
15485       /* TYPE is the domain of this method, and THIS_TYPE is the type
15486            of the method itself (TYPE_CODE_METHOD).  */
15487       smash_to_method_type (fnp->type, type,
15488                             TYPE_TARGET_TYPE (this_type),
15489                             TYPE_FIELDS (this_type),
15490                             TYPE_NFIELDS (this_type),
15491                             TYPE_VARARGS (this_type));
15492
15493       /* Handle static member functions.
15494          Dwarf2 has no clean way to discern C++ static and non-static
15495          member functions.  G++ helps GDB by marking the first
15496          parameter for non-static member functions (which is the this
15497          pointer) as artificial.  We obtain this information from
15498          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15499       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15500         fnp->voffset = VOFFSET_STATIC;
15501     }
15502   else
15503     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15504                dwarf2_full_name (fieldname, die, cu));
15505
15506   /* Get fcontext from DW_AT_containing_type if present.  */
15507   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15508     fnp->fcontext = die_containing_type (die, cu);
15509
15510   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15511      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15512
15513   /* Get accessibility.  */
15514   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15515   if (attr)
15516     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15517   else
15518     accessibility = dwarf2_default_access_attribute (die, cu);
15519   switch (accessibility)
15520     {
15521     case DW_ACCESS_private:
15522       fnp->is_private = 1;
15523       break;
15524     case DW_ACCESS_protected:
15525       fnp->is_protected = 1;
15526       break;
15527     }
15528
15529   /* Check for artificial methods.  */
15530   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15531   if (attr && DW_UNSND (attr) != 0)
15532     fnp->is_artificial = 1;
15533
15534   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15535
15536   /* Get index in virtual function table if it is a virtual member
15537      function.  For older versions of GCC, this is an offset in the
15538      appropriate virtual table, as specified by DW_AT_containing_type.
15539      For everyone else, it is an expression to be evaluated relative
15540      to the object address.  */
15541
15542   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15543   if (attr)
15544     {
15545       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15546         {
15547           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15548             {
15549               /* Old-style GCC.  */
15550               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15551             }
15552           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15553                    || (DW_BLOCK (attr)->size > 1
15554                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15555                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15556             {
15557               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15558               if ((fnp->voffset % cu->header.addr_size) != 0)
15559                 dwarf2_complex_location_expr_complaint ();
15560               else
15561                 fnp->voffset /= cu->header.addr_size;
15562               fnp->voffset += 2;
15563             }
15564           else
15565             dwarf2_complex_location_expr_complaint ();
15566
15567           if (!fnp->fcontext)
15568             {
15569               /* If there is no `this' field and no DW_AT_containing_type,
15570                  we cannot actually find a base class context for the
15571                  vtable!  */
15572               if (TYPE_NFIELDS (this_type) == 0
15573                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15574                 {
15575                   complaint (&symfile_complaints,
15576                              _("cannot determine context for virtual member "
15577                                "function \"%s\" (offset %s)"),
15578                              fieldname, sect_offset_str (die->sect_off));
15579                 }
15580               else
15581                 {
15582                   fnp->fcontext
15583                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15584                 }
15585             }
15586         }
15587       else if (attr_form_is_section_offset (attr))
15588         {
15589           dwarf2_complex_location_expr_complaint ();
15590         }
15591       else
15592         {
15593           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15594                                                  fieldname);
15595         }
15596     }
15597   else
15598     {
15599       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15600       if (attr && DW_UNSND (attr))
15601         {
15602           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15603           complaint (&symfile_complaints,
15604                      _("Member function \"%s\" (offset %s) is virtual "
15605                        "but the vtable offset is not specified"),
15606                      fieldname, sect_offset_str (die->sect_off));
15607           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15608           TYPE_CPLUS_DYNAMIC (type) = 1;
15609         }
15610     }
15611 }
15612
15613 /* Create the vector of member function fields, and attach it to the type.  */
15614
15615 static void
15616 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15617                                  struct dwarf2_cu *cu)
15618 {
15619   if (cu->language == language_ada)
15620     error (_("unexpected member functions in Ada type"));
15621
15622   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15623   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15624     TYPE_ALLOC (type,
15625                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15626
15627   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15628     {
15629       struct fnfieldlist &nf = fip->fnfieldlists[i];
15630       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15631
15632       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15633       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15634       fn_flp->fn_fields = (struct fn_field *)
15635         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15636
15637       for (int k = 0; k < nf.fnfields.size (); ++k)
15638         fn_flp->fn_fields[k] = nf.fnfields[k];
15639     }
15640
15641   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15642 }
15643
15644 /* Returns non-zero if NAME is the name of a vtable member in CU's
15645    language, zero otherwise.  */
15646 static int
15647 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15648 {
15649   static const char vptr[] = "_vptr";
15650
15651   /* Look for the C++ form of the vtable.  */
15652   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15653     return 1;
15654
15655   return 0;
15656 }
15657
15658 /* GCC outputs unnamed structures that are really pointers to member
15659    functions, with the ABI-specified layout.  If TYPE describes
15660    such a structure, smash it into a member function type.
15661
15662    GCC shouldn't do this; it should just output pointer to member DIEs.
15663    This is GCC PR debug/28767.  */
15664
15665 static void
15666 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15667 {
15668   struct type *pfn_type, *self_type, *new_type;
15669
15670   /* Check for a structure with no name and two children.  */
15671   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15672     return;
15673
15674   /* Check for __pfn and __delta members.  */
15675   if (TYPE_FIELD_NAME (type, 0) == NULL
15676       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15677       || TYPE_FIELD_NAME (type, 1) == NULL
15678       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15679     return;
15680
15681   /* Find the type of the method.  */
15682   pfn_type = TYPE_FIELD_TYPE (type, 0);
15683   if (pfn_type == NULL
15684       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15685       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15686     return;
15687
15688   /* Look for the "this" argument.  */
15689   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15690   if (TYPE_NFIELDS (pfn_type) == 0
15691       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15692       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15693     return;
15694
15695   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15696   new_type = alloc_type (objfile);
15697   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15698                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15699                         TYPE_VARARGS (pfn_type));
15700   smash_to_methodptr_type (type, new_type);
15701 }
15702
15703
15704 /* Called when we find the DIE that starts a structure or union scope
15705    (definition) to create a type for the structure or union.  Fill in
15706    the type's name and general properties; the members will not be
15707    processed until process_structure_scope.  A symbol table entry for
15708    the type will also not be done until process_structure_scope (assuming
15709    the type has a name).
15710
15711    NOTE: we need to call these functions regardless of whether or not the
15712    DIE has a DW_AT_name attribute, since it might be an anonymous
15713    structure or union.  This gets the type entered into our set of
15714    user defined types.  */
15715
15716 static struct type *
15717 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15718 {
15719   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15720   struct type *type;
15721   struct attribute *attr;
15722   const char *name;
15723
15724   /* If the definition of this type lives in .debug_types, read that type.
15725      Don't follow DW_AT_specification though, that will take us back up
15726      the chain and we want to go down.  */
15727   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15728   if (attr)
15729     {
15730       type = get_DW_AT_signature_type (die, attr, cu);
15731
15732       /* The type's CU may not be the same as CU.
15733          Ensure TYPE is recorded with CU in die_type_hash.  */
15734       return set_die_type (die, type, cu);
15735     }
15736
15737   type = alloc_type (objfile);
15738   INIT_CPLUS_SPECIFIC (type);
15739
15740   name = dwarf2_name (die, cu);
15741   if (name != NULL)
15742     {
15743       if (cu->language == language_cplus
15744           || cu->language == language_d
15745           || cu->language == language_rust)
15746         {
15747           const char *full_name = dwarf2_full_name (name, die, cu);
15748
15749           /* dwarf2_full_name might have already finished building the DIE's
15750              type.  If so, there is no need to continue.  */
15751           if (get_die_type (die, cu) != NULL)
15752             return get_die_type (die, cu);
15753
15754           TYPE_TAG_NAME (type) = full_name;
15755           if (die->tag == DW_TAG_structure_type
15756               || die->tag == DW_TAG_class_type)
15757             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15758         }
15759       else
15760         {
15761           /* The name is already allocated along with this objfile, so
15762              we don't need to duplicate it for the type.  */
15763           TYPE_TAG_NAME (type) = name;
15764           if (die->tag == DW_TAG_class_type)
15765             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15766         }
15767     }
15768
15769   if (die->tag == DW_TAG_structure_type)
15770     {
15771       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15772     }
15773   else if (die->tag == DW_TAG_union_type)
15774     {
15775       TYPE_CODE (type) = TYPE_CODE_UNION;
15776     }
15777   else if (die->tag == DW_TAG_variant_part)
15778     {
15779       TYPE_CODE (type) = TYPE_CODE_UNION;
15780       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15781     }
15782   else
15783     {
15784       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15785     }
15786
15787   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15788     TYPE_DECLARED_CLASS (type) = 1;
15789
15790   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15791   if (attr)
15792     {
15793       if (attr_form_is_constant (attr))
15794         TYPE_LENGTH (type) = DW_UNSND (attr);
15795       else
15796         {
15797           /* For the moment, dynamic type sizes are not supported
15798              by GDB's struct type.  The actual size is determined
15799              on-demand when resolving the type of a given object,
15800              so set the type's length to zero for now.  Otherwise,
15801              we record an expression as the length, and that expression
15802              could lead to a very large value, which could eventually
15803              lead to us trying to allocate that much memory when creating
15804              a value of that type.  */
15805           TYPE_LENGTH (type) = 0;
15806         }
15807     }
15808   else
15809     {
15810       TYPE_LENGTH (type) = 0;
15811     }
15812
15813   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15814     {
15815       /* ICC<14 does not output the required DW_AT_declaration on
15816          incomplete types, but gives them a size of zero.  */
15817       TYPE_STUB (type) = 1;
15818     }
15819   else
15820     TYPE_STUB_SUPPORTED (type) = 1;
15821
15822   if (die_is_declaration (die, cu))
15823     TYPE_STUB (type) = 1;
15824   else if (attr == NULL && die->child == NULL
15825            && producer_is_realview (cu->producer))
15826     /* RealView does not output the required DW_AT_declaration
15827        on incomplete types.  */
15828     TYPE_STUB (type) = 1;
15829
15830   /* We need to add the type field to the die immediately so we don't
15831      infinitely recurse when dealing with pointers to the structure
15832      type within the structure itself.  */
15833   set_die_type (die, type, cu);
15834
15835   /* set_die_type should be already done.  */
15836   set_descriptive_type (type, die, cu);
15837
15838   return type;
15839 }
15840
15841 /* A helper for process_structure_scope that handles a single member
15842    DIE.  */
15843
15844 static void
15845 handle_struct_member_die (struct die_info *child_die, struct type *type,
15846                           struct field_info *fi,
15847                           std::vector<struct symbol *> *template_args,
15848                           struct dwarf2_cu *cu)
15849 {
15850   if (child_die->tag == DW_TAG_member
15851       || child_die->tag == DW_TAG_variable
15852       || child_die->tag == DW_TAG_variant_part)
15853     {
15854       /* NOTE: carlton/2002-11-05: A C++ static data member
15855          should be a DW_TAG_member that is a declaration, but
15856          all versions of G++ as of this writing (so through at
15857          least 3.2.1) incorrectly generate DW_TAG_variable
15858          tags for them instead.  */
15859       dwarf2_add_field (fi, child_die, cu);
15860     }
15861   else if (child_die->tag == DW_TAG_subprogram)
15862     {
15863       /* Rust doesn't have member functions in the C++ sense.
15864          However, it does emit ordinary functions as children
15865          of a struct DIE.  */
15866       if (cu->language == language_rust)
15867         read_func_scope (child_die, cu);
15868       else
15869         {
15870           /* C++ member function.  */
15871           dwarf2_add_member_fn (fi, child_die, type, cu);
15872         }
15873     }
15874   else if (child_die->tag == DW_TAG_inheritance)
15875     {
15876       /* C++ base class field.  */
15877       dwarf2_add_field (fi, child_die, cu);
15878     }
15879   else if (type_can_define_types (child_die))
15880     dwarf2_add_type_defn (fi, child_die, cu);
15881   else if (child_die->tag == DW_TAG_template_type_param
15882            || child_die->tag == DW_TAG_template_value_param)
15883     {
15884       struct symbol *arg = new_symbol (child_die, NULL, cu);
15885
15886       if (arg != NULL)
15887         template_args->push_back (arg);
15888     }
15889   else if (child_die->tag == DW_TAG_variant)
15890     {
15891       /* In a variant we want to get the discriminant and also add a
15892          field for our sole member child.  */
15893       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15894
15895       for (struct die_info *variant_child = child_die->child;
15896            variant_child != NULL;
15897            variant_child = sibling_die (variant_child))
15898         {
15899           if (variant_child->tag == DW_TAG_member)
15900             {
15901               handle_struct_member_die (variant_child, type, fi,
15902                                         template_args, cu);
15903               /* Only handle the one.  */
15904               break;
15905             }
15906         }
15907
15908       /* We don't handle this but we might as well report it if we see
15909          it.  */
15910       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15911           complaint (&symfile_complaints,
15912                      _("DW_AT_discr_list is not supported yet"
15913                        " - DIE at %s [in module %s]"),
15914                      sect_offset_str (child_die->sect_off),
15915                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15916
15917       /* The first field was just added, so we can stash the
15918          discriminant there.  */
15919       gdb_assert (!fi->fields.empty ());
15920       if (discr == NULL)
15921         fi->fields.back ().variant.default_branch = true;
15922       else
15923         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15924     }
15925 }
15926
15927 /* Finish creating a structure or union type, including filling in
15928    its members and creating a symbol for it.  */
15929
15930 static void
15931 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15932 {
15933   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15934   struct die_info *child_die;
15935   struct type *type;
15936
15937   type = get_die_type (die, cu);
15938   if (type == NULL)
15939     type = read_structure_type (die, cu);
15940
15941   /* When reading a DW_TAG_variant_part, we need to notice when we
15942      read the discriminant member, so we can record it later in the
15943      discriminant_info.  */
15944   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15945   sect_offset discr_offset;
15946
15947   if (is_variant_part)
15948     {
15949       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15950       if (discr == NULL)
15951         {
15952           /* Maybe it's a univariant form, an extension we support.
15953              In this case arrange not to check the offset.  */
15954           is_variant_part = false;
15955         }
15956       else if (attr_form_is_ref (discr))
15957         {
15958           struct dwarf2_cu *target_cu = cu;
15959           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15960
15961           discr_offset = target_die->sect_off;
15962         }
15963       else
15964         {
15965           complaint (&symfile_complaints,
15966                      _("DW_AT_discr does not have DIE reference form"
15967                        " - DIE at %s [in module %s]"),
15968                      sect_offset_str (die->sect_off),
15969                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15970           is_variant_part = false;
15971         }
15972     }
15973
15974   if (die->child != NULL && ! die_is_declaration (die, cu))
15975     {
15976       struct field_info fi;
15977       std::vector<struct symbol *> template_args;
15978
15979       child_die = die->child;
15980
15981       while (child_die && child_die->tag)
15982         {
15983           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15984
15985           if (is_variant_part && discr_offset == child_die->sect_off)
15986             fi.fields.back ().variant.is_discriminant = true;
15987
15988           child_die = sibling_die (child_die);
15989         }
15990
15991       /* Attach template arguments to type.  */
15992       if (!template_args.empty ())
15993         {
15994           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15995           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15996           TYPE_TEMPLATE_ARGUMENTS (type)
15997             = XOBNEWVEC (&objfile->objfile_obstack,
15998                          struct symbol *,
15999                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16000           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16001                   template_args.data (),
16002                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16003                    * sizeof (struct symbol *)));
16004         }
16005
16006       /* Attach fields and member functions to the type.  */
16007       if (fi.nfields)
16008         dwarf2_attach_fields_to_type (&fi, type, cu);
16009       if (!fi.fnfieldlists.empty ())
16010         {
16011           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16012
16013           /* Get the type which refers to the base class (possibly this
16014              class itself) which contains the vtable pointer for the current
16015              class from the DW_AT_containing_type attribute.  This use of
16016              DW_AT_containing_type is a GNU extension.  */
16017
16018           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16019             {
16020               struct type *t = die_containing_type (die, cu);
16021
16022               set_type_vptr_basetype (type, t);
16023               if (type == t)
16024                 {
16025                   int i;
16026
16027                   /* Our own class provides vtbl ptr.  */
16028                   for (i = TYPE_NFIELDS (t) - 1;
16029                        i >= TYPE_N_BASECLASSES (t);
16030                        --i)
16031                     {
16032                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16033
16034                       if (is_vtable_name (fieldname, cu))
16035                         {
16036                           set_type_vptr_fieldno (type, i);
16037                           break;
16038                         }
16039                     }
16040
16041                   /* Complain if virtual function table field not found.  */
16042                   if (i < TYPE_N_BASECLASSES (t))
16043                     complaint (&symfile_complaints,
16044                                _("virtual function table pointer "
16045                                  "not found when defining class '%s'"),
16046                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16047                                "");
16048                 }
16049               else
16050                 {
16051                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16052                 }
16053             }
16054           else if (cu->producer
16055                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16056             {
16057               /* The IBM XLC compiler does not provide direct indication
16058                  of the containing type, but the vtable pointer is
16059                  always named __vfp.  */
16060
16061               int i;
16062
16063               for (i = TYPE_NFIELDS (type) - 1;
16064                    i >= TYPE_N_BASECLASSES (type);
16065                    --i)
16066                 {
16067                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16068                     {
16069                       set_type_vptr_fieldno (type, i);
16070                       set_type_vptr_basetype (type, type);
16071                       break;
16072                     }
16073                 }
16074             }
16075         }
16076
16077       /* Copy fi.typedef_field_list linked list elements content into the
16078          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16079       if (!fi.typedef_field_list.empty ())
16080         {
16081           int count = fi.typedef_field_list.size ();
16082
16083           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16084           TYPE_TYPEDEF_FIELD_ARRAY (type)
16085             = ((struct decl_field *)
16086                TYPE_ALLOC (type,
16087                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16088           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16089
16090           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16091             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16092         }
16093
16094       /* Copy fi.nested_types_list linked list elements content into the
16095          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16096       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16097         {
16098           int count = fi.nested_types_list.size ();
16099
16100           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16101           TYPE_NESTED_TYPES_ARRAY (type)
16102             = ((struct decl_field *)
16103                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16104           TYPE_NESTED_TYPES_COUNT (type) = count;
16105
16106           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16107             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16108         }
16109     }
16110
16111   quirk_gcc_member_function_pointer (type, objfile);
16112   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16113     cu->rust_unions.push_back (type);
16114
16115   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16116      snapshots) has been known to create a die giving a declaration
16117      for a class that has, as a child, a die giving a definition for a
16118      nested class.  So we have to process our children even if the
16119      current die is a declaration.  Normally, of course, a declaration
16120      won't have any children at all.  */
16121
16122   child_die = die->child;
16123
16124   while (child_die != NULL && child_die->tag)
16125     {
16126       if (child_die->tag == DW_TAG_member
16127           || child_die->tag == DW_TAG_variable
16128           || child_die->tag == DW_TAG_inheritance
16129           || child_die->tag == DW_TAG_template_value_param
16130           || child_die->tag == DW_TAG_template_type_param)
16131         {
16132           /* Do nothing.  */
16133         }
16134       else
16135         process_die (child_die, cu);
16136
16137       child_die = sibling_die (child_die);
16138     }
16139
16140   /* Do not consider external references.  According to the DWARF standard,
16141      these DIEs are identified by the fact that they have no byte_size
16142      attribute, and a declaration attribute.  */
16143   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16144       || !die_is_declaration (die, cu))
16145     new_symbol (die, type, cu);
16146 }
16147
16148 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16149    update TYPE using some information only available in DIE's children.  */
16150
16151 static void
16152 update_enumeration_type_from_children (struct die_info *die,
16153                                        struct type *type,
16154                                        struct dwarf2_cu *cu)
16155 {
16156   struct die_info *child_die;
16157   int unsigned_enum = 1;
16158   int flag_enum = 1;
16159   ULONGEST mask = 0;
16160
16161   auto_obstack obstack;
16162
16163   for (child_die = die->child;
16164        child_die != NULL && child_die->tag;
16165        child_die = sibling_die (child_die))
16166     {
16167       struct attribute *attr;
16168       LONGEST value;
16169       const gdb_byte *bytes;
16170       struct dwarf2_locexpr_baton *baton;
16171       const char *name;
16172
16173       if (child_die->tag != DW_TAG_enumerator)
16174         continue;
16175
16176       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16177       if (attr == NULL)
16178         continue;
16179
16180       name = dwarf2_name (child_die, cu);
16181       if (name == NULL)
16182         name = "<anonymous enumerator>";
16183
16184       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16185                                &value, &bytes, &baton);
16186       if (value < 0)
16187         {
16188           unsigned_enum = 0;
16189           flag_enum = 0;
16190         }
16191       else if ((mask & value) != 0)
16192         flag_enum = 0;
16193       else
16194         mask |= value;
16195
16196       /* If we already know that the enum type is neither unsigned, nor
16197          a flag type, no need to look at the rest of the enumerates.  */
16198       if (!unsigned_enum && !flag_enum)
16199         break;
16200     }
16201
16202   if (unsigned_enum)
16203     TYPE_UNSIGNED (type) = 1;
16204   if (flag_enum)
16205     TYPE_FLAG_ENUM (type) = 1;
16206 }
16207
16208 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16209    complete the type's fields yet, or create any symbols.  */
16210
16211 static struct type *
16212 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16213 {
16214   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16215   struct type *type;
16216   struct attribute *attr;
16217   const char *name;
16218
16219   /* If the definition of this type lives in .debug_types, read that type.
16220      Don't follow DW_AT_specification though, that will take us back up
16221      the chain and we want to go down.  */
16222   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16223   if (attr)
16224     {
16225       type = get_DW_AT_signature_type (die, attr, cu);
16226
16227       /* The type's CU may not be the same as CU.
16228          Ensure TYPE is recorded with CU in die_type_hash.  */
16229       return set_die_type (die, type, cu);
16230     }
16231
16232   type = alloc_type (objfile);
16233
16234   TYPE_CODE (type) = TYPE_CODE_ENUM;
16235   name = dwarf2_full_name (NULL, die, cu);
16236   if (name != NULL)
16237     TYPE_TAG_NAME (type) = name;
16238
16239   attr = dwarf2_attr (die, DW_AT_type, cu);
16240   if (attr != NULL)
16241     {
16242       struct type *underlying_type = die_type (die, cu);
16243
16244       TYPE_TARGET_TYPE (type) = underlying_type;
16245     }
16246
16247   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16248   if (attr)
16249     {
16250       TYPE_LENGTH (type) = DW_UNSND (attr);
16251     }
16252   else
16253     {
16254       TYPE_LENGTH (type) = 0;
16255     }
16256
16257   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16258      declared as private in the package spec, and then defined only
16259      inside the package body.  Such types are known as Taft Amendment
16260      Types.  When another package uses such a type, an incomplete DIE
16261      may be generated by the compiler.  */
16262   if (die_is_declaration (die, cu))
16263     TYPE_STUB (type) = 1;
16264
16265   /* Finish the creation of this type by using the enum's children.
16266      We must call this even when the underlying type has been provided
16267      so that we can determine if we're looking at a "flag" enum.  */
16268   update_enumeration_type_from_children (die, type, cu);
16269
16270   /* If this type has an underlying type that is not a stub, then we
16271      may use its attributes.  We always use the "unsigned" attribute
16272      in this situation, because ordinarily we guess whether the type
16273      is unsigned -- but the guess can be wrong and the underlying type
16274      can tell us the reality.  However, we defer to a local size
16275      attribute if one exists, because this lets the compiler override
16276      the underlying type if needed.  */
16277   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16278     {
16279       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16280       if (TYPE_LENGTH (type) == 0)
16281         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16282     }
16283
16284   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16285
16286   return set_die_type (die, type, cu);
16287 }
16288
16289 /* Given a pointer to a die which begins an enumeration, process all
16290    the dies that define the members of the enumeration, and create the
16291    symbol for the enumeration type.
16292
16293    NOTE: We reverse the order of the element list.  */
16294
16295 static void
16296 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16297 {
16298   struct type *this_type;
16299
16300   this_type = get_die_type (die, cu);
16301   if (this_type == NULL)
16302     this_type = read_enumeration_type (die, cu);
16303
16304   if (die->child != NULL)
16305     {
16306       struct die_info *child_die;
16307       struct symbol *sym;
16308       struct field *fields = NULL;
16309       int num_fields = 0;
16310       const char *name;
16311
16312       child_die = die->child;
16313       while (child_die && child_die->tag)
16314         {
16315           if (child_die->tag != DW_TAG_enumerator)
16316             {
16317               process_die (child_die, cu);
16318             }
16319           else
16320             {
16321               name = dwarf2_name (child_die, cu);
16322               if (name)
16323                 {
16324                   sym = new_symbol (child_die, this_type, cu);
16325
16326                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16327                     {
16328                       fields = (struct field *)
16329                         xrealloc (fields,
16330                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16331                                   * sizeof (struct field));
16332                     }
16333
16334                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16335                   FIELD_TYPE (fields[num_fields]) = NULL;
16336                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16337                   FIELD_BITSIZE (fields[num_fields]) = 0;
16338
16339                   num_fields++;
16340                 }
16341             }
16342
16343           child_die = sibling_die (child_die);
16344         }
16345
16346       if (num_fields)
16347         {
16348           TYPE_NFIELDS (this_type) = num_fields;
16349           TYPE_FIELDS (this_type) = (struct field *)
16350             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16351           memcpy (TYPE_FIELDS (this_type), fields,
16352                   sizeof (struct field) * num_fields);
16353           xfree (fields);
16354         }
16355     }
16356
16357   /* If we are reading an enum from a .debug_types unit, and the enum
16358      is a declaration, and the enum is not the signatured type in the
16359      unit, then we do not want to add a symbol for it.  Adding a
16360      symbol would in some cases obscure the true definition of the
16361      enum, giving users an incomplete type when the definition is
16362      actually available.  Note that we do not want to do this for all
16363      enums which are just declarations, because C++0x allows forward
16364      enum declarations.  */
16365   if (cu->per_cu->is_debug_types
16366       && die_is_declaration (die, cu))
16367     {
16368       struct signatured_type *sig_type;
16369
16370       sig_type = (struct signatured_type *) cu->per_cu;
16371       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16372       if (sig_type->type_offset_in_section != die->sect_off)
16373         return;
16374     }
16375
16376   new_symbol (die, this_type, cu);
16377 }
16378
16379 /* Extract all information from a DW_TAG_array_type DIE and put it in
16380    the DIE's type field.  For now, this only handles one dimensional
16381    arrays.  */
16382
16383 static struct type *
16384 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16385 {
16386   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16387   struct die_info *child_die;
16388   struct type *type;
16389   struct type *element_type, *range_type, *index_type;
16390   struct attribute *attr;
16391   const char *name;
16392   struct dynamic_prop *byte_stride_prop = NULL;
16393   unsigned int bit_stride = 0;
16394
16395   element_type = die_type (die, cu);
16396
16397   /* The die_type call above may have already set the type for this DIE.  */
16398   type = get_die_type (die, cu);
16399   if (type)
16400     return type;
16401
16402   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16403   if (attr != NULL)
16404     {
16405       int stride_ok;
16406
16407       byte_stride_prop
16408         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16409       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16410       if (!stride_ok)
16411         {
16412           complaint (&symfile_complaints,
16413                      _("unable to read array DW_AT_byte_stride "
16414                        " - DIE at %s [in module %s]"),
16415                      sect_offset_str (die->sect_off),
16416                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16417           /* Ignore this attribute.  We will likely not be able to print
16418              arrays of this type correctly, but there is little we can do
16419              to help if we cannot read the attribute's value.  */
16420           byte_stride_prop = NULL;
16421         }
16422     }
16423
16424   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16425   if (attr != NULL)
16426     bit_stride = DW_UNSND (attr);
16427
16428   /* Irix 6.2 native cc creates array types without children for
16429      arrays with unspecified length.  */
16430   if (die->child == NULL)
16431     {
16432       index_type = objfile_type (objfile)->builtin_int;
16433       range_type = create_static_range_type (NULL, index_type, 0, -1);
16434       type = create_array_type_with_stride (NULL, element_type, range_type,
16435                                             byte_stride_prop, bit_stride);
16436       return set_die_type (die, type, cu);
16437     }
16438
16439   std::vector<struct type *> range_types;
16440   child_die = die->child;
16441   while (child_die && child_die->tag)
16442     {
16443       if (child_die->tag == DW_TAG_subrange_type)
16444         {
16445           struct type *child_type = read_type_die (child_die, cu);
16446
16447           if (child_type != NULL)
16448             {
16449               /* The range type was succesfully read.  Save it for the
16450                  array type creation.  */
16451               range_types.push_back (child_type);
16452             }
16453         }
16454       child_die = sibling_die (child_die);
16455     }
16456
16457   /* Dwarf2 dimensions are output from left to right, create the
16458      necessary array types in backwards order.  */
16459
16460   type = element_type;
16461
16462   if (read_array_order (die, cu) == DW_ORD_col_major)
16463     {
16464       int i = 0;
16465
16466       while (i < range_types.size ())
16467         type = create_array_type_with_stride (NULL, type, range_types[i++],
16468                                               byte_stride_prop, bit_stride);
16469     }
16470   else
16471     {
16472       size_t ndim = range_types.size ();
16473       while (ndim-- > 0)
16474         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16475                                               byte_stride_prop, bit_stride);
16476     }
16477
16478   /* Understand Dwarf2 support for vector types (like they occur on
16479      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16480      array type.  This is not part of the Dwarf2/3 standard yet, but a
16481      custom vendor extension.  The main difference between a regular
16482      array and the vector variant is that vectors are passed by value
16483      to functions.  */
16484   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16485   if (attr)
16486     make_vector_type (type);
16487
16488   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16489      implementation may choose to implement triple vectors using this
16490      attribute.  */
16491   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16492   if (attr)
16493     {
16494       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16495         TYPE_LENGTH (type) = DW_UNSND (attr);
16496       else
16497         complaint (&symfile_complaints,
16498                    _("DW_AT_byte_size for array type smaller "
16499                      "than the total size of elements"));
16500     }
16501
16502   name = dwarf2_name (die, cu);
16503   if (name)
16504     TYPE_NAME (type) = name;
16505
16506   /* Install the type in the die.  */
16507   set_die_type (die, type, cu);
16508
16509   /* set_die_type should be already done.  */
16510   set_descriptive_type (type, die, cu);
16511
16512   return type;
16513 }
16514
16515 static enum dwarf_array_dim_ordering
16516 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16517 {
16518   struct attribute *attr;
16519
16520   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16521
16522   if (attr)
16523     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16524
16525   /* GNU F77 is a special case, as at 08/2004 array type info is the
16526      opposite order to the dwarf2 specification, but data is still
16527      laid out as per normal fortran.
16528
16529      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16530      version checking.  */
16531
16532   if (cu->language == language_fortran
16533       && cu->producer && strstr (cu->producer, "GNU F77"))
16534     {
16535       return DW_ORD_row_major;
16536     }
16537
16538   switch (cu->language_defn->la_array_ordering)
16539     {
16540     case array_column_major:
16541       return DW_ORD_col_major;
16542     case array_row_major:
16543     default:
16544       return DW_ORD_row_major;
16545     };
16546 }
16547
16548 /* Extract all information from a DW_TAG_set_type DIE and put it in
16549    the DIE's type field.  */
16550
16551 static struct type *
16552 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16553 {
16554   struct type *domain_type, *set_type;
16555   struct attribute *attr;
16556
16557   domain_type = die_type (die, cu);
16558
16559   /* The die_type call above may have already set the type for this DIE.  */
16560   set_type = get_die_type (die, cu);
16561   if (set_type)
16562     return set_type;
16563
16564   set_type = create_set_type (NULL, domain_type);
16565
16566   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16567   if (attr)
16568     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16569
16570   return set_die_type (die, set_type, cu);
16571 }
16572
16573 /* A helper for read_common_block that creates a locexpr baton.
16574    SYM is the symbol which we are marking as computed.
16575    COMMON_DIE is the DIE for the common block.
16576    COMMON_LOC is the location expression attribute for the common
16577    block itself.
16578    MEMBER_LOC is the location expression attribute for the particular
16579    member of the common block that we are processing.
16580    CU is the CU from which the above come.  */
16581
16582 static void
16583 mark_common_block_symbol_computed (struct symbol *sym,
16584                                    struct die_info *common_die,
16585                                    struct attribute *common_loc,
16586                                    struct attribute *member_loc,
16587                                    struct dwarf2_cu *cu)
16588 {
16589   struct dwarf2_per_objfile *dwarf2_per_objfile
16590     = cu->per_cu->dwarf2_per_objfile;
16591   struct objfile *objfile = dwarf2_per_objfile->objfile;
16592   struct dwarf2_locexpr_baton *baton;
16593   gdb_byte *ptr;
16594   unsigned int cu_off;
16595   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16596   LONGEST offset = 0;
16597
16598   gdb_assert (common_loc && member_loc);
16599   gdb_assert (attr_form_is_block (common_loc));
16600   gdb_assert (attr_form_is_block (member_loc)
16601               || attr_form_is_constant (member_loc));
16602
16603   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16604   baton->per_cu = cu->per_cu;
16605   gdb_assert (baton->per_cu);
16606
16607   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16608
16609   if (attr_form_is_constant (member_loc))
16610     {
16611       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16612       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16613     }
16614   else
16615     baton->size += DW_BLOCK (member_loc)->size;
16616
16617   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16618   baton->data = ptr;
16619
16620   *ptr++ = DW_OP_call4;
16621   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16622   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16623   ptr += 4;
16624
16625   if (attr_form_is_constant (member_loc))
16626     {
16627       *ptr++ = DW_OP_addr;
16628       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16629       ptr += cu->header.addr_size;
16630     }
16631   else
16632     {
16633       /* We have to copy the data here, because DW_OP_call4 will only
16634          use a DW_AT_location attribute.  */
16635       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16636       ptr += DW_BLOCK (member_loc)->size;
16637     }
16638
16639   *ptr++ = DW_OP_plus;
16640   gdb_assert (ptr - baton->data == baton->size);
16641
16642   SYMBOL_LOCATION_BATON (sym) = baton;
16643   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16644 }
16645
16646 /* Create appropriate locally-scoped variables for all the
16647    DW_TAG_common_block entries.  Also create a struct common_block
16648    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16649    is used to sepate the common blocks name namespace from regular
16650    variable names.  */
16651
16652 static void
16653 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16654 {
16655   struct attribute *attr;
16656
16657   attr = dwarf2_attr (die, DW_AT_location, cu);
16658   if (attr)
16659     {
16660       /* Support the .debug_loc offsets.  */
16661       if (attr_form_is_block (attr))
16662         {
16663           /* Ok.  */
16664         }
16665       else if (attr_form_is_section_offset (attr))
16666         {
16667           dwarf2_complex_location_expr_complaint ();
16668           attr = NULL;
16669         }
16670       else
16671         {
16672           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16673                                                  "common block member");
16674           attr = NULL;
16675         }
16676     }
16677
16678   if (die->child != NULL)
16679     {
16680       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16681       struct die_info *child_die;
16682       size_t n_entries = 0, size;
16683       struct common_block *common_block;
16684       struct symbol *sym;
16685
16686       for (child_die = die->child;
16687            child_die && child_die->tag;
16688            child_die = sibling_die (child_die))
16689         ++n_entries;
16690
16691       size = (sizeof (struct common_block)
16692               + (n_entries - 1) * sizeof (struct symbol *));
16693       common_block
16694         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16695                                                  size);
16696       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16697       common_block->n_entries = 0;
16698
16699       for (child_die = die->child;
16700            child_die && child_die->tag;
16701            child_die = sibling_die (child_die))
16702         {
16703           /* Create the symbol in the DW_TAG_common_block block in the current
16704              symbol scope.  */
16705           sym = new_symbol (child_die, NULL, cu);
16706           if (sym != NULL)
16707             {
16708               struct attribute *member_loc;
16709
16710               common_block->contents[common_block->n_entries++] = sym;
16711
16712               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16713                                         cu);
16714               if (member_loc)
16715                 {
16716                   /* GDB has handled this for a long time, but it is
16717                      not specified by DWARF.  It seems to have been
16718                      emitted by gfortran at least as recently as:
16719                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16720                   complaint (&symfile_complaints,
16721                              _("Variable in common block has "
16722                                "DW_AT_data_member_location "
16723                                "- DIE at %s [in module %s]"),
16724                                sect_offset_str (child_die->sect_off),
16725                              objfile_name (objfile));
16726
16727                   if (attr_form_is_section_offset (member_loc))
16728                     dwarf2_complex_location_expr_complaint ();
16729                   else if (attr_form_is_constant (member_loc)
16730                            || attr_form_is_block (member_loc))
16731                     {
16732                       if (attr)
16733                         mark_common_block_symbol_computed (sym, die, attr,
16734                                                            member_loc, cu);
16735                     }
16736                   else
16737                     dwarf2_complex_location_expr_complaint ();
16738                 }
16739             }
16740         }
16741
16742       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16743       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16744     }
16745 }
16746
16747 /* Create a type for a C++ namespace.  */
16748
16749 static struct type *
16750 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16751 {
16752   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16753   const char *previous_prefix, *name;
16754   int is_anonymous;
16755   struct type *type;
16756
16757   /* For extensions, reuse the type of the original namespace.  */
16758   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16759     {
16760       struct die_info *ext_die;
16761       struct dwarf2_cu *ext_cu = cu;
16762
16763       ext_die = dwarf2_extension (die, &ext_cu);
16764       type = read_type_die (ext_die, ext_cu);
16765
16766       /* EXT_CU may not be the same as CU.
16767          Ensure TYPE is recorded with CU in die_type_hash.  */
16768       return set_die_type (die, type, cu);
16769     }
16770
16771   name = namespace_name (die, &is_anonymous, cu);
16772
16773   /* Now build the name of the current namespace.  */
16774
16775   previous_prefix = determine_prefix (die, cu);
16776   if (previous_prefix[0] != '\0')
16777     name = typename_concat (&objfile->objfile_obstack,
16778                             previous_prefix, name, 0, cu);
16779
16780   /* Create the type.  */
16781   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16782   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16783
16784   return set_die_type (die, type, cu);
16785 }
16786
16787 /* Read a namespace scope.  */
16788
16789 static void
16790 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16791 {
16792   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16793   int is_anonymous;
16794
16795   /* Add a symbol associated to this if we haven't seen the namespace
16796      before.  Also, add a using directive if it's an anonymous
16797      namespace.  */
16798
16799   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16800     {
16801       struct type *type;
16802
16803       type = read_type_die (die, cu);
16804       new_symbol (die, type, cu);
16805
16806       namespace_name (die, &is_anonymous, cu);
16807       if (is_anonymous)
16808         {
16809           const char *previous_prefix = determine_prefix (die, cu);
16810
16811           std::vector<const char *> excludes;
16812           add_using_directive (using_directives (cu->language),
16813                                previous_prefix, TYPE_NAME (type), NULL,
16814                                NULL, excludes, 0, &objfile->objfile_obstack);
16815         }
16816     }
16817
16818   if (die->child != NULL)
16819     {
16820       struct die_info *child_die = die->child;
16821
16822       while (child_die && child_die->tag)
16823         {
16824           process_die (child_die, cu);
16825           child_die = sibling_die (child_die);
16826         }
16827     }
16828 }
16829
16830 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16831    imported module.  Still we need that type as local Fortran "use ... only"
16832    declaration imports depend on the created type in determine_prefix.  */
16833
16834 static struct type *
16835 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16836 {
16837   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16838   const char *module_name;
16839   struct type *type;
16840
16841   module_name = dwarf2_name (die, cu);
16842   if (!module_name)
16843     complaint (&symfile_complaints,
16844                _("DW_TAG_module has no name, offset %s"),
16845                sect_offset_str (die->sect_off));
16846   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16847
16848   /* determine_prefix uses TYPE_TAG_NAME.  */
16849   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16850
16851   return set_die_type (die, type, cu);
16852 }
16853
16854 /* Read a Fortran module.  */
16855
16856 static void
16857 read_module (struct die_info *die, struct dwarf2_cu *cu)
16858 {
16859   struct die_info *child_die = die->child;
16860   struct type *type;
16861
16862   type = read_type_die (die, cu);
16863   new_symbol (die, type, cu);
16864
16865   while (child_die && child_die->tag)
16866     {
16867       process_die (child_die, cu);
16868       child_die = sibling_die (child_die);
16869     }
16870 }
16871
16872 /* Return the name of the namespace represented by DIE.  Set
16873    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16874    namespace.  */
16875
16876 static const char *
16877 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16878 {
16879   struct die_info *current_die;
16880   const char *name = NULL;
16881
16882   /* Loop through the extensions until we find a name.  */
16883
16884   for (current_die = die;
16885        current_die != NULL;
16886        current_die = dwarf2_extension (die, &cu))
16887     {
16888       /* We don't use dwarf2_name here so that we can detect the absence
16889          of a name -> anonymous namespace.  */
16890       name = dwarf2_string_attr (die, DW_AT_name, cu);
16891
16892       if (name != NULL)
16893         break;
16894     }
16895
16896   /* Is it an anonymous namespace?  */
16897
16898   *is_anonymous = (name == NULL);
16899   if (*is_anonymous)
16900     name = CP_ANONYMOUS_NAMESPACE_STR;
16901
16902   return name;
16903 }
16904
16905 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16906    the user defined type vector.  */
16907
16908 static struct type *
16909 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16910 {
16911   struct gdbarch *gdbarch
16912     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16913   struct comp_unit_head *cu_header = &cu->header;
16914   struct type *type;
16915   struct attribute *attr_byte_size;
16916   struct attribute *attr_address_class;
16917   int byte_size, addr_class;
16918   struct type *target_type;
16919
16920   target_type = die_type (die, cu);
16921
16922   /* The die_type call above may have already set the type for this DIE.  */
16923   type = get_die_type (die, cu);
16924   if (type)
16925     return type;
16926
16927   type = lookup_pointer_type (target_type);
16928
16929   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16930   if (attr_byte_size)
16931     byte_size = DW_UNSND (attr_byte_size);
16932   else
16933     byte_size = cu_header->addr_size;
16934
16935   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16936   if (attr_address_class)
16937     addr_class = DW_UNSND (attr_address_class);
16938   else
16939     addr_class = DW_ADDR_none;
16940
16941   /* If the pointer size or address class is different than the
16942      default, create a type variant marked as such and set the
16943      length accordingly.  */
16944   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16945     {
16946       if (gdbarch_address_class_type_flags_p (gdbarch))
16947         {
16948           int type_flags;
16949
16950           type_flags = gdbarch_address_class_type_flags
16951                          (gdbarch, byte_size, addr_class);
16952           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16953                       == 0);
16954           type = make_type_with_address_space (type, type_flags);
16955         }
16956       else if (TYPE_LENGTH (type) != byte_size)
16957         {
16958           complaint (&symfile_complaints,
16959                      _("invalid pointer size %d"), byte_size);
16960         }
16961       else
16962         {
16963           /* Should we also complain about unhandled address classes?  */
16964         }
16965     }
16966
16967   TYPE_LENGTH (type) = byte_size;
16968   return set_die_type (die, type, cu);
16969 }
16970
16971 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16972    the user defined type vector.  */
16973
16974 static struct type *
16975 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16976 {
16977   struct type *type;
16978   struct type *to_type;
16979   struct type *domain;
16980
16981   to_type = die_type (die, cu);
16982   domain = die_containing_type (die, cu);
16983
16984   /* The calls above may have already set the type for this DIE.  */
16985   type = get_die_type (die, cu);
16986   if (type)
16987     return type;
16988
16989   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16990     type = lookup_methodptr_type (to_type);
16991   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16992     {
16993       struct type *new_type
16994         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16995
16996       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16997                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16998                             TYPE_VARARGS (to_type));
16999       type = lookup_methodptr_type (new_type);
17000     }
17001   else
17002     type = lookup_memberptr_type (to_type, domain);
17003
17004   return set_die_type (die, type, cu);
17005 }
17006
17007 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17008    the user defined type vector.  */
17009
17010 static struct type *
17011 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17012                           enum type_code refcode)
17013 {
17014   struct comp_unit_head *cu_header = &cu->header;
17015   struct type *type, *target_type;
17016   struct attribute *attr;
17017
17018   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17019
17020   target_type = die_type (die, cu);
17021
17022   /* The die_type call above may have already set the type for this DIE.  */
17023   type = get_die_type (die, cu);
17024   if (type)
17025     return type;
17026
17027   type = lookup_reference_type (target_type, refcode);
17028   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17029   if (attr)
17030     {
17031       TYPE_LENGTH (type) = DW_UNSND (attr);
17032     }
17033   else
17034     {
17035       TYPE_LENGTH (type) = cu_header->addr_size;
17036     }
17037   return set_die_type (die, type, cu);
17038 }
17039
17040 /* Add the given cv-qualifiers to the element type of the array.  GCC
17041    outputs DWARF type qualifiers that apply to an array, not the
17042    element type.  But GDB relies on the array element type to carry
17043    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17044    specification.  */
17045
17046 static struct type *
17047 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17048                    struct type *base_type, int cnst, int voltl)
17049 {
17050   struct type *el_type, *inner_array;
17051
17052   base_type = copy_type (base_type);
17053   inner_array = base_type;
17054
17055   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17056     {
17057       TYPE_TARGET_TYPE (inner_array) =
17058         copy_type (TYPE_TARGET_TYPE (inner_array));
17059       inner_array = TYPE_TARGET_TYPE (inner_array);
17060     }
17061
17062   el_type = TYPE_TARGET_TYPE (inner_array);
17063   cnst |= TYPE_CONST (el_type);
17064   voltl |= TYPE_VOLATILE (el_type);
17065   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17066
17067   return set_die_type (die, base_type, cu);
17068 }
17069
17070 static struct type *
17071 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17072 {
17073   struct type *base_type, *cv_type;
17074
17075   base_type = die_type (die, cu);
17076
17077   /* The die_type call above may have already set the type for this DIE.  */
17078   cv_type = get_die_type (die, cu);
17079   if (cv_type)
17080     return cv_type;
17081
17082   /* In case the const qualifier is applied to an array type, the element type
17083      is so qualified, not the array type (section 6.7.3 of C99).  */
17084   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17085     return add_array_cv_type (die, cu, base_type, 1, 0);
17086
17087   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17088   return set_die_type (die, cv_type, cu);
17089 }
17090
17091 static struct type *
17092 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17093 {
17094   struct type *base_type, *cv_type;
17095
17096   base_type = die_type (die, cu);
17097
17098   /* The die_type call above may have already set the type for this DIE.  */
17099   cv_type = get_die_type (die, cu);
17100   if (cv_type)
17101     return cv_type;
17102
17103   /* In case the volatile qualifier is applied to an array type, the
17104      element type is so qualified, not the array type (section 6.7.3
17105      of C99).  */
17106   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17107     return add_array_cv_type (die, cu, base_type, 0, 1);
17108
17109   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17110   return set_die_type (die, cv_type, cu);
17111 }
17112
17113 /* Handle DW_TAG_restrict_type.  */
17114
17115 static struct type *
17116 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17117 {
17118   struct type *base_type, *cv_type;
17119
17120   base_type = die_type (die, cu);
17121
17122   /* The die_type call above may have already set the type for this DIE.  */
17123   cv_type = get_die_type (die, cu);
17124   if (cv_type)
17125     return cv_type;
17126
17127   cv_type = make_restrict_type (base_type);
17128   return set_die_type (die, cv_type, cu);
17129 }
17130
17131 /* Handle DW_TAG_atomic_type.  */
17132
17133 static struct type *
17134 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17135 {
17136   struct type *base_type, *cv_type;
17137
17138   base_type = die_type (die, cu);
17139
17140   /* The die_type call above may have already set the type for this DIE.  */
17141   cv_type = get_die_type (die, cu);
17142   if (cv_type)
17143     return cv_type;
17144
17145   cv_type = make_atomic_type (base_type);
17146   return set_die_type (die, cv_type, cu);
17147 }
17148
17149 /* Extract all information from a DW_TAG_string_type DIE and add to
17150    the user defined type vector.  It isn't really a user defined type,
17151    but it behaves like one, with other DIE's using an AT_user_def_type
17152    attribute to reference it.  */
17153
17154 static struct type *
17155 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17156 {
17157   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17158   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17159   struct type *type, *range_type, *index_type, *char_type;
17160   struct attribute *attr;
17161   unsigned int length;
17162
17163   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17164   if (attr)
17165     {
17166       length = DW_UNSND (attr);
17167     }
17168   else
17169     {
17170       /* Check for the DW_AT_byte_size attribute.  */
17171       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17172       if (attr)
17173         {
17174           length = DW_UNSND (attr);
17175         }
17176       else
17177         {
17178           length = 1;
17179         }
17180     }
17181
17182   index_type = objfile_type (objfile)->builtin_int;
17183   range_type = create_static_range_type (NULL, index_type, 1, length);
17184   char_type = language_string_char_type (cu->language_defn, gdbarch);
17185   type = create_string_type (NULL, char_type, range_type);
17186
17187   return set_die_type (die, type, cu);
17188 }
17189
17190 /* Assuming that DIE corresponds to a function, returns nonzero
17191    if the function is prototyped.  */
17192
17193 static int
17194 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17195 {
17196   struct attribute *attr;
17197
17198   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17199   if (attr && (DW_UNSND (attr) != 0))
17200     return 1;
17201
17202   /* The DWARF standard implies that the DW_AT_prototyped attribute
17203      is only meaninful for C, but the concept also extends to other
17204      languages that allow unprototyped functions (Eg: Objective C).
17205      For all other languages, assume that functions are always
17206      prototyped.  */
17207   if (cu->language != language_c
17208       && cu->language != language_objc
17209       && cu->language != language_opencl)
17210     return 1;
17211
17212   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17213      prototyped and unprototyped functions; default to prototyped,
17214      since that is more common in modern code (and RealView warns
17215      about unprototyped functions).  */
17216   if (producer_is_realview (cu->producer))
17217     return 1;
17218
17219   return 0;
17220 }
17221
17222 /* Handle DIES due to C code like:
17223
17224    struct foo
17225    {
17226    int (*funcp)(int a, long l);
17227    int b;
17228    };
17229
17230    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17231
17232 static struct type *
17233 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17234 {
17235   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17236   struct type *type;            /* Type that this function returns.  */
17237   struct type *ftype;           /* Function that returns above type.  */
17238   struct attribute *attr;
17239
17240   type = die_type (die, cu);
17241
17242   /* The die_type call above may have already set the type for this DIE.  */
17243   ftype = get_die_type (die, cu);
17244   if (ftype)
17245     return ftype;
17246
17247   ftype = lookup_function_type (type);
17248
17249   if (prototyped_function_p (die, cu))
17250     TYPE_PROTOTYPED (ftype) = 1;
17251
17252   /* Store the calling convention in the type if it's available in
17253      the subroutine die.  Otherwise set the calling convention to
17254      the default value DW_CC_normal.  */
17255   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17256   if (attr)
17257     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17258   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17259     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17260   else
17261     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17262
17263   /* Record whether the function returns normally to its caller or not
17264      if the DWARF producer set that information.  */
17265   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17266   if (attr && (DW_UNSND (attr) != 0))
17267     TYPE_NO_RETURN (ftype) = 1;
17268
17269   /* We need to add the subroutine type to the die immediately so
17270      we don't infinitely recurse when dealing with parameters
17271      declared as the same subroutine type.  */
17272   set_die_type (die, ftype, cu);
17273
17274   if (die->child != NULL)
17275     {
17276       struct type *void_type = objfile_type (objfile)->builtin_void;
17277       struct die_info *child_die;
17278       int nparams, iparams;
17279
17280       /* Count the number of parameters.
17281          FIXME: GDB currently ignores vararg functions, but knows about
17282          vararg member functions.  */
17283       nparams = 0;
17284       child_die = die->child;
17285       while (child_die && child_die->tag)
17286         {
17287           if (child_die->tag == DW_TAG_formal_parameter)
17288             nparams++;
17289           else if (child_die->tag == DW_TAG_unspecified_parameters)
17290             TYPE_VARARGS (ftype) = 1;
17291           child_die = sibling_die (child_die);
17292         }
17293
17294       /* Allocate storage for parameters and fill them in.  */
17295       TYPE_NFIELDS (ftype) = nparams;
17296       TYPE_FIELDS (ftype) = (struct field *)
17297         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17298
17299       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17300          even if we error out during the parameters reading below.  */
17301       for (iparams = 0; iparams < nparams; iparams++)
17302         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17303
17304       iparams = 0;
17305       child_die = die->child;
17306       while (child_die && child_die->tag)
17307         {
17308           if (child_die->tag == DW_TAG_formal_parameter)
17309             {
17310               struct type *arg_type;
17311
17312               /* DWARF version 2 has no clean way to discern C++
17313                  static and non-static member functions.  G++ helps
17314                  GDB by marking the first parameter for non-static
17315                  member functions (which is the this pointer) as
17316                  artificial.  We pass this information to
17317                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17318
17319                  DWARF version 3 added DW_AT_object_pointer, which GCC
17320                  4.5 does not yet generate.  */
17321               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17322               if (attr)
17323                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17324               else
17325                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17326               arg_type = die_type (child_die, cu);
17327
17328               /* RealView does not mark THIS as const, which the testsuite
17329                  expects.  GCC marks THIS as const in method definitions,
17330                  but not in the class specifications (GCC PR 43053).  */
17331               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17332                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17333                 {
17334                   int is_this = 0;
17335                   struct dwarf2_cu *arg_cu = cu;
17336                   const char *name = dwarf2_name (child_die, cu);
17337
17338                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17339                   if (attr)
17340                     {
17341                       /* If the compiler emits this, use it.  */
17342                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17343                         is_this = 1;
17344                     }
17345                   else if (name && strcmp (name, "this") == 0)
17346                     /* Function definitions will have the argument names.  */
17347                     is_this = 1;
17348                   else if (name == NULL && iparams == 0)
17349                     /* Declarations may not have the names, so like
17350                        elsewhere in GDB, assume an artificial first
17351                        argument is "this".  */
17352                     is_this = 1;
17353
17354                   if (is_this)
17355                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17356                                              arg_type, 0);
17357                 }
17358
17359               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17360               iparams++;
17361             }
17362           child_die = sibling_die (child_die);
17363         }
17364     }
17365
17366   return ftype;
17367 }
17368
17369 static struct type *
17370 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17371 {
17372   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17373   const char *name = NULL;
17374   struct type *this_type, *target_type;
17375
17376   name = dwarf2_full_name (NULL, die, cu);
17377   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17378   TYPE_TARGET_STUB (this_type) = 1;
17379   set_die_type (die, this_type, cu);
17380   target_type = die_type (die, cu);
17381   if (target_type != this_type)
17382     TYPE_TARGET_TYPE (this_type) = target_type;
17383   else
17384     {
17385       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17386          spec and cause infinite loops in GDB.  */
17387       complaint (&symfile_complaints,
17388                  _("Self-referential DW_TAG_typedef "
17389                    "- DIE at %s [in module %s]"),
17390                  sect_offset_str (die->sect_off), objfile_name (objfile));
17391       TYPE_TARGET_TYPE (this_type) = NULL;
17392     }
17393   return this_type;
17394 }
17395
17396 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17397    (which may be different from NAME) to the architecture back-end to allow
17398    it to guess the correct format if necessary.  */
17399
17400 static struct type *
17401 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17402                         const char *name_hint)
17403 {
17404   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17405   const struct floatformat **format;
17406   struct type *type;
17407
17408   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17409   if (format)
17410     type = init_float_type (objfile, bits, name, format);
17411   else
17412     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17413
17414   return type;
17415 }
17416
17417 /* Find a representation of a given base type and install
17418    it in the TYPE field of the die.  */
17419
17420 static struct type *
17421 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17422 {
17423   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17424   struct type *type;
17425   struct attribute *attr;
17426   int encoding = 0, bits = 0;
17427   const char *name;
17428
17429   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17430   if (attr)
17431     {
17432       encoding = DW_UNSND (attr);
17433     }
17434   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17435   if (attr)
17436     {
17437       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17438     }
17439   name = dwarf2_name (die, cu);
17440   if (!name)
17441     {
17442       complaint (&symfile_complaints,
17443                  _("DW_AT_name missing from DW_TAG_base_type"));
17444     }
17445
17446   switch (encoding)
17447     {
17448       case DW_ATE_address:
17449         /* Turn DW_ATE_address into a void * pointer.  */
17450         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17451         type = init_pointer_type (objfile, bits, name, type);
17452         break;
17453       case DW_ATE_boolean:
17454         type = init_boolean_type (objfile, bits, 1, name);
17455         break;
17456       case DW_ATE_complex_float:
17457         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17458         type = init_complex_type (objfile, name, type);
17459         break;
17460       case DW_ATE_decimal_float:
17461         type = init_decfloat_type (objfile, bits, name);
17462         break;
17463       case DW_ATE_float:
17464         type = dwarf2_init_float_type (objfile, bits, name, name);
17465         break;
17466       case DW_ATE_signed:
17467         type = init_integer_type (objfile, bits, 0, name);
17468         break;
17469       case DW_ATE_unsigned:
17470         if (cu->language == language_fortran
17471             && name
17472             && startswith (name, "character("))
17473           type = init_character_type (objfile, bits, 1, name);
17474         else
17475           type = init_integer_type (objfile, bits, 1, name);
17476         break;
17477       case DW_ATE_signed_char:
17478         if (cu->language == language_ada || cu->language == language_m2
17479             || cu->language == language_pascal
17480             || cu->language == language_fortran)
17481           type = init_character_type (objfile, bits, 0, name);
17482         else
17483           type = init_integer_type (objfile, bits, 0, name);
17484         break;
17485       case DW_ATE_unsigned_char:
17486         if (cu->language == language_ada || cu->language == language_m2
17487             || cu->language == language_pascal
17488             || cu->language == language_fortran
17489             || cu->language == language_rust)
17490           type = init_character_type (objfile, bits, 1, name);
17491         else
17492           type = init_integer_type (objfile, bits, 1, name);
17493         break;
17494       case DW_ATE_UTF:
17495         {
17496           gdbarch *arch = get_objfile_arch (objfile);
17497
17498           if (bits == 16)
17499             type = builtin_type (arch)->builtin_char16;
17500           else if (bits == 32)
17501             type = builtin_type (arch)->builtin_char32;
17502           else
17503             {
17504               complaint (&symfile_complaints,
17505                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17506                          bits);
17507               type = init_integer_type (objfile, bits, 1, name);
17508             }
17509           return set_die_type (die, type, cu);
17510         }
17511         break;
17512
17513       default:
17514         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17515                    dwarf_type_encoding_name (encoding));
17516         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17517         break;
17518     }
17519
17520   if (name && strcmp (name, "char") == 0)
17521     TYPE_NOSIGN (type) = 1;
17522
17523   return set_die_type (die, type, cu);
17524 }
17525
17526 /* Parse dwarf attribute if it's a block, reference or constant and put the
17527    resulting value of the attribute into struct bound_prop.
17528    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17529
17530 static int
17531 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17532                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17533 {
17534   struct dwarf2_property_baton *baton;
17535   struct obstack *obstack
17536     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17537
17538   if (attr == NULL || prop == NULL)
17539     return 0;
17540
17541   if (attr_form_is_block (attr))
17542     {
17543       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17544       baton->referenced_type = NULL;
17545       baton->locexpr.per_cu = cu->per_cu;
17546       baton->locexpr.size = DW_BLOCK (attr)->size;
17547       baton->locexpr.data = DW_BLOCK (attr)->data;
17548       prop->data.baton = baton;
17549       prop->kind = PROP_LOCEXPR;
17550       gdb_assert (prop->data.baton != NULL);
17551     }
17552   else if (attr_form_is_ref (attr))
17553     {
17554       struct dwarf2_cu *target_cu = cu;
17555       struct die_info *target_die;
17556       struct attribute *target_attr;
17557
17558       target_die = follow_die_ref (die, attr, &target_cu);
17559       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17560       if (target_attr == NULL)
17561         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17562                                    target_cu);
17563       if (target_attr == NULL)
17564         return 0;
17565
17566       switch (target_attr->name)
17567         {
17568           case DW_AT_location:
17569             if (attr_form_is_section_offset (target_attr))
17570               {
17571                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17572                 baton->referenced_type = die_type (target_die, target_cu);
17573                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17574                 prop->data.baton = baton;
17575                 prop->kind = PROP_LOCLIST;
17576                 gdb_assert (prop->data.baton != NULL);
17577               }
17578             else if (attr_form_is_block (target_attr))
17579               {
17580                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17581                 baton->referenced_type = die_type (target_die, target_cu);
17582                 baton->locexpr.per_cu = cu->per_cu;
17583                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17584                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17585                 prop->data.baton = baton;
17586                 prop->kind = PROP_LOCEXPR;
17587                 gdb_assert (prop->data.baton != NULL);
17588               }
17589             else
17590               {
17591                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17592                                                        "dynamic property");
17593                 return 0;
17594               }
17595             break;
17596           case DW_AT_data_member_location:
17597             {
17598               LONGEST offset;
17599
17600               if (!handle_data_member_location (target_die, target_cu,
17601                                                 &offset))
17602                 return 0;
17603
17604               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17605               baton->referenced_type = read_type_die (target_die->parent,
17606                                                       target_cu);
17607               baton->offset_info.offset = offset;
17608               baton->offset_info.type = die_type (target_die, target_cu);
17609               prop->data.baton = baton;
17610               prop->kind = PROP_ADDR_OFFSET;
17611               break;
17612             }
17613         }
17614     }
17615   else if (attr_form_is_constant (attr))
17616     {
17617       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17618       prop->kind = PROP_CONST;
17619     }
17620   else
17621     {
17622       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17623                                              dwarf2_name (die, cu));
17624       return 0;
17625     }
17626
17627   return 1;
17628 }
17629
17630 /* Read the given DW_AT_subrange DIE.  */
17631
17632 static struct type *
17633 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17634 {
17635   struct type *base_type, *orig_base_type;
17636   struct type *range_type;
17637   struct attribute *attr;
17638   struct dynamic_prop low, high;
17639   int low_default_is_valid;
17640   int high_bound_is_count = 0;
17641   const char *name;
17642   LONGEST negative_mask;
17643
17644   orig_base_type = die_type (die, cu);
17645   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17646      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17647      creating the range type, but we use the result of check_typedef
17648      when examining properties of the type.  */
17649   base_type = check_typedef (orig_base_type);
17650
17651   /* The die_type call above may have already set the type for this DIE.  */
17652   range_type = get_die_type (die, cu);
17653   if (range_type)
17654     return range_type;
17655
17656   low.kind = PROP_CONST;
17657   high.kind = PROP_CONST;
17658   high.data.const_val = 0;
17659
17660   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17661      omitting DW_AT_lower_bound.  */
17662   switch (cu->language)
17663     {
17664     case language_c:
17665     case language_cplus:
17666       low.data.const_val = 0;
17667       low_default_is_valid = 1;
17668       break;
17669     case language_fortran:
17670       low.data.const_val = 1;
17671       low_default_is_valid = 1;
17672       break;
17673     case language_d:
17674     case language_objc:
17675     case language_rust:
17676       low.data.const_val = 0;
17677       low_default_is_valid = (cu->header.version >= 4);
17678       break;
17679     case language_ada:
17680     case language_m2:
17681     case language_pascal:
17682       low.data.const_val = 1;
17683       low_default_is_valid = (cu->header.version >= 4);
17684       break;
17685     default:
17686       low.data.const_val = 0;
17687       low_default_is_valid = 0;
17688       break;
17689     }
17690
17691   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17692   if (attr)
17693     attr_to_dynamic_prop (attr, die, cu, &low);
17694   else if (!low_default_is_valid)
17695     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17696                                       "- DIE at %s [in module %s]"),
17697                sect_offset_str (die->sect_off),
17698                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17699
17700   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17701   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17702     {
17703       attr = dwarf2_attr (die, DW_AT_count, cu);
17704       if (attr_to_dynamic_prop (attr, die, cu, &high))
17705         {
17706           /* If bounds are constant do the final calculation here.  */
17707           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17708             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17709           else
17710             high_bound_is_count = 1;
17711         }
17712     }
17713
17714   /* Dwarf-2 specifications explicitly allows to create subrange types
17715      without specifying a base type.
17716      In that case, the base type must be set to the type of
17717      the lower bound, upper bound or count, in that order, if any of these
17718      three attributes references an object that has a type.
17719      If no base type is found, the Dwarf-2 specifications say that
17720      a signed integer type of size equal to the size of an address should
17721      be used.
17722      For the following C code: `extern char gdb_int [];'
17723      GCC produces an empty range DIE.
17724      FIXME: muller/2010-05-28: Possible references to object for low bound,
17725      high bound or count are not yet handled by this code.  */
17726   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17727     {
17728       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17729       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17730       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17731       struct type *int_type = objfile_type (objfile)->builtin_int;
17732
17733       /* Test "int", "long int", and "long long int" objfile types,
17734          and select the first one having a size above or equal to the
17735          architecture address size.  */
17736       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17737         base_type = int_type;
17738       else
17739         {
17740           int_type = objfile_type (objfile)->builtin_long;
17741           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17742             base_type = int_type;
17743           else
17744             {
17745               int_type = objfile_type (objfile)->builtin_long_long;
17746               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17747                 base_type = int_type;
17748             }
17749         }
17750     }
17751
17752   /* Normally, the DWARF producers are expected to use a signed
17753      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17754      But this is unfortunately not always the case, as witnessed
17755      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17756      is used instead.  To work around that ambiguity, we treat
17757      the bounds as signed, and thus sign-extend their values, when
17758      the base type is signed.  */
17759   negative_mask =
17760     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17761   if (low.kind == PROP_CONST
17762       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17763     low.data.const_val |= negative_mask;
17764   if (high.kind == PROP_CONST
17765       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17766     high.data.const_val |= negative_mask;
17767
17768   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17769
17770   if (high_bound_is_count)
17771     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17772
17773   /* Ada expects an empty array on no boundary attributes.  */
17774   if (attr == NULL && cu->language != language_ada)
17775     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17776
17777   name = dwarf2_name (die, cu);
17778   if (name)
17779     TYPE_NAME (range_type) = name;
17780
17781   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17782   if (attr)
17783     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17784
17785   set_die_type (die, range_type, cu);
17786
17787   /* set_die_type should be already done.  */
17788   set_descriptive_type (range_type, die, cu);
17789
17790   return range_type;
17791 }
17792
17793 static struct type *
17794 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17795 {
17796   struct type *type;
17797
17798   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17799                     NULL);
17800   TYPE_NAME (type) = dwarf2_name (die, cu);
17801
17802   /* In Ada, an unspecified type is typically used when the description
17803      of the type is defered to a different unit.  When encountering
17804      such a type, we treat it as a stub, and try to resolve it later on,
17805      when needed.  */
17806   if (cu->language == language_ada)
17807     TYPE_STUB (type) = 1;
17808
17809   return set_die_type (die, type, cu);
17810 }
17811
17812 /* Read a single die and all its descendents.  Set the die's sibling
17813    field to NULL; set other fields in the die correctly, and set all
17814    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17815    location of the info_ptr after reading all of those dies.  PARENT
17816    is the parent of the die in question.  */
17817
17818 static struct die_info *
17819 read_die_and_children (const struct die_reader_specs *reader,
17820                        const gdb_byte *info_ptr,
17821                        const gdb_byte **new_info_ptr,
17822                        struct die_info *parent)
17823 {
17824   struct die_info *die;
17825   const gdb_byte *cur_ptr;
17826   int has_children;
17827
17828   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17829   if (die == NULL)
17830     {
17831       *new_info_ptr = cur_ptr;
17832       return NULL;
17833     }
17834   store_in_ref_table (die, reader->cu);
17835
17836   if (has_children)
17837     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17838   else
17839     {
17840       die->child = NULL;
17841       *new_info_ptr = cur_ptr;
17842     }
17843
17844   die->sibling = NULL;
17845   die->parent = parent;
17846   return die;
17847 }
17848
17849 /* Read a die, all of its descendents, and all of its siblings; set
17850    all of the fields of all of the dies correctly.  Arguments are as
17851    in read_die_and_children.  */
17852
17853 static struct die_info *
17854 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17855                          const gdb_byte *info_ptr,
17856                          const gdb_byte **new_info_ptr,
17857                          struct die_info *parent)
17858 {
17859   struct die_info *first_die, *last_sibling;
17860   const gdb_byte *cur_ptr;
17861
17862   cur_ptr = info_ptr;
17863   first_die = last_sibling = NULL;
17864
17865   while (1)
17866     {
17867       struct die_info *die
17868         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17869
17870       if (die == NULL)
17871         {
17872           *new_info_ptr = cur_ptr;
17873           return first_die;
17874         }
17875
17876       if (!first_die)
17877         first_die = die;
17878       else
17879         last_sibling->sibling = die;
17880
17881       last_sibling = die;
17882     }
17883 }
17884
17885 /* Read a die, all of its descendents, and all of its siblings; set
17886    all of the fields of all of the dies correctly.  Arguments are as
17887    in read_die_and_children.
17888    This the main entry point for reading a DIE and all its children.  */
17889
17890 static struct die_info *
17891 read_die_and_siblings (const struct die_reader_specs *reader,
17892                        const gdb_byte *info_ptr,
17893                        const gdb_byte **new_info_ptr,
17894                        struct die_info *parent)
17895 {
17896   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17897                                                   new_info_ptr, parent);
17898
17899   if (dwarf_die_debug)
17900     {
17901       fprintf_unfiltered (gdb_stdlog,
17902                           "Read die from %s@0x%x of %s:\n",
17903                           get_section_name (reader->die_section),
17904                           (unsigned) (info_ptr - reader->die_section->buffer),
17905                           bfd_get_filename (reader->abfd));
17906       dump_die (die, dwarf_die_debug);
17907     }
17908
17909   return die;
17910 }
17911
17912 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17913    attributes.
17914    The caller is responsible for filling in the extra attributes
17915    and updating (*DIEP)->num_attrs.
17916    Set DIEP to point to a newly allocated die with its information,
17917    except for its child, sibling, and parent fields.
17918    Set HAS_CHILDREN to tell whether the die has children or not.  */
17919
17920 static const gdb_byte *
17921 read_full_die_1 (const struct die_reader_specs *reader,
17922                  struct die_info **diep, const gdb_byte *info_ptr,
17923                  int *has_children, int num_extra_attrs)
17924 {
17925   unsigned int abbrev_number, bytes_read, i;
17926   struct abbrev_info *abbrev;
17927   struct die_info *die;
17928   struct dwarf2_cu *cu = reader->cu;
17929   bfd *abfd = reader->abfd;
17930
17931   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17932   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17933   info_ptr += bytes_read;
17934   if (!abbrev_number)
17935     {
17936       *diep = NULL;
17937       *has_children = 0;
17938       return info_ptr;
17939     }
17940
17941   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17942   if (!abbrev)
17943     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17944            abbrev_number,
17945            bfd_get_filename (abfd));
17946
17947   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17948   die->sect_off = sect_off;
17949   die->tag = abbrev->tag;
17950   die->abbrev = abbrev_number;
17951
17952   /* Make the result usable.
17953      The caller needs to update num_attrs after adding the extra
17954      attributes.  */
17955   die->num_attrs = abbrev->num_attrs;
17956
17957   for (i = 0; i < abbrev->num_attrs; ++i)
17958     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17959                                info_ptr);
17960
17961   *diep = die;
17962   *has_children = abbrev->has_children;
17963   return info_ptr;
17964 }
17965
17966 /* Read a die and all its attributes.
17967    Set DIEP to point to a newly allocated die with its information,
17968    except for its child, sibling, and parent fields.
17969    Set HAS_CHILDREN to tell whether the die has children or not.  */
17970
17971 static const gdb_byte *
17972 read_full_die (const struct die_reader_specs *reader,
17973                struct die_info **diep, const gdb_byte *info_ptr,
17974                int *has_children)
17975 {
17976   const gdb_byte *result;
17977
17978   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17979
17980   if (dwarf_die_debug)
17981     {
17982       fprintf_unfiltered (gdb_stdlog,
17983                           "Read die from %s@0x%x of %s:\n",
17984                           get_section_name (reader->die_section),
17985                           (unsigned) (info_ptr - reader->die_section->buffer),
17986                           bfd_get_filename (reader->abfd));
17987       dump_die (*diep, dwarf_die_debug);
17988     }
17989
17990   return result;
17991 }
17992 \f
17993 /* Abbreviation tables.
17994
17995    In DWARF version 2, the description of the debugging information is
17996    stored in a separate .debug_abbrev section.  Before we read any
17997    dies from a section we read in all abbreviations and install them
17998    in a hash table.  */
17999
18000 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18001
18002 struct abbrev_info *
18003 abbrev_table::alloc_abbrev ()
18004 {
18005   struct abbrev_info *abbrev;
18006
18007   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18008   memset (abbrev, 0, sizeof (struct abbrev_info));
18009
18010   return abbrev;
18011 }
18012
18013 /* Add an abbreviation to the table.  */
18014
18015 void
18016 abbrev_table::add_abbrev (unsigned int abbrev_number,
18017                           struct abbrev_info *abbrev)
18018 {
18019   unsigned int hash_number;
18020
18021   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18022   abbrev->next = m_abbrevs[hash_number];
18023   m_abbrevs[hash_number] = abbrev;
18024 }
18025
18026 /* Look up an abbrev in the table.
18027    Returns NULL if the abbrev is not found.  */
18028
18029 struct abbrev_info *
18030 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18031 {
18032   unsigned int hash_number;
18033   struct abbrev_info *abbrev;
18034
18035   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18036   abbrev = m_abbrevs[hash_number];
18037
18038   while (abbrev)
18039     {
18040       if (abbrev->number == abbrev_number)
18041         return abbrev;
18042       abbrev = abbrev->next;
18043     }
18044   return NULL;
18045 }
18046
18047 /* Read in an abbrev table.  */
18048
18049 static abbrev_table_up
18050 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18051                          struct dwarf2_section_info *section,
18052                          sect_offset sect_off)
18053 {
18054   struct objfile *objfile = dwarf2_per_objfile->objfile;
18055   bfd *abfd = get_section_bfd_owner (section);
18056   const gdb_byte *abbrev_ptr;
18057   struct abbrev_info *cur_abbrev;
18058   unsigned int abbrev_number, bytes_read, abbrev_name;
18059   unsigned int abbrev_form;
18060   struct attr_abbrev *cur_attrs;
18061   unsigned int allocated_attrs;
18062
18063   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18064
18065   dwarf2_read_section (objfile, section);
18066   abbrev_ptr = section->buffer + to_underlying (sect_off);
18067   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18068   abbrev_ptr += bytes_read;
18069
18070   allocated_attrs = ATTR_ALLOC_CHUNK;
18071   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18072
18073   /* Loop until we reach an abbrev number of 0.  */
18074   while (abbrev_number)
18075     {
18076       cur_abbrev = abbrev_table->alloc_abbrev ();
18077
18078       /* read in abbrev header */
18079       cur_abbrev->number = abbrev_number;
18080       cur_abbrev->tag
18081         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18082       abbrev_ptr += bytes_read;
18083       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18084       abbrev_ptr += 1;
18085
18086       /* now read in declarations */
18087       for (;;)
18088         {
18089           LONGEST implicit_const;
18090
18091           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18092           abbrev_ptr += bytes_read;
18093           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18094           abbrev_ptr += bytes_read;
18095           if (abbrev_form == DW_FORM_implicit_const)
18096             {
18097               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18098                                                    &bytes_read);
18099               abbrev_ptr += bytes_read;
18100             }
18101           else
18102             {
18103               /* Initialize it due to a false compiler warning.  */
18104               implicit_const = -1;
18105             }
18106
18107           if (abbrev_name == 0)
18108             break;
18109
18110           if (cur_abbrev->num_attrs == allocated_attrs)
18111             {
18112               allocated_attrs += ATTR_ALLOC_CHUNK;
18113               cur_attrs
18114                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18115             }
18116
18117           cur_attrs[cur_abbrev->num_attrs].name
18118             = (enum dwarf_attribute) abbrev_name;
18119           cur_attrs[cur_abbrev->num_attrs].form
18120             = (enum dwarf_form) abbrev_form;
18121           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18122           ++cur_abbrev->num_attrs;
18123         }
18124
18125       cur_abbrev->attrs =
18126         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18127                    cur_abbrev->num_attrs);
18128       memcpy (cur_abbrev->attrs, cur_attrs,
18129               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18130
18131       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18132
18133       /* Get next abbreviation.
18134          Under Irix6 the abbreviations for a compilation unit are not
18135          always properly terminated with an abbrev number of 0.
18136          Exit loop if we encounter an abbreviation which we have
18137          already read (which means we are about to read the abbreviations
18138          for the next compile unit) or if the end of the abbreviation
18139          table is reached.  */
18140       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18141         break;
18142       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18143       abbrev_ptr += bytes_read;
18144       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18145         break;
18146     }
18147
18148   xfree (cur_attrs);
18149   return abbrev_table;
18150 }
18151
18152 /* Returns nonzero if TAG represents a type that we might generate a partial
18153    symbol for.  */
18154
18155 static int
18156 is_type_tag_for_partial (int tag)
18157 {
18158   switch (tag)
18159     {
18160 #if 0
18161     /* Some types that would be reasonable to generate partial symbols for,
18162        that we don't at present.  */
18163     case DW_TAG_array_type:
18164     case DW_TAG_file_type:
18165     case DW_TAG_ptr_to_member_type:
18166     case DW_TAG_set_type:
18167     case DW_TAG_string_type:
18168     case DW_TAG_subroutine_type:
18169 #endif
18170     case DW_TAG_base_type:
18171     case DW_TAG_class_type:
18172     case DW_TAG_interface_type:
18173     case DW_TAG_enumeration_type:
18174     case DW_TAG_structure_type:
18175     case DW_TAG_subrange_type:
18176     case DW_TAG_typedef:
18177     case DW_TAG_union_type:
18178       return 1;
18179     default:
18180       return 0;
18181     }
18182 }
18183
18184 /* Load all DIEs that are interesting for partial symbols into memory.  */
18185
18186 static struct partial_die_info *
18187 load_partial_dies (const struct die_reader_specs *reader,
18188                    const gdb_byte *info_ptr, int building_psymtab)
18189 {
18190   struct dwarf2_cu *cu = reader->cu;
18191   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18192   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18193   unsigned int bytes_read;
18194   unsigned int load_all = 0;
18195   int nesting_level = 1;
18196
18197   parent_die = NULL;
18198   last_die = NULL;
18199
18200   gdb_assert (cu->per_cu != NULL);
18201   if (cu->per_cu->load_all_dies)
18202     load_all = 1;
18203
18204   cu->partial_dies
18205     = htab_create_alloc_ex (cu->header.length / 12,
18206                             partial_die_hash,
18207                             partial_die_eq,
18208                             NULL,
18209                             &cu->comp_unit_obstack,
18210                             hashtab_obstack_allocate,
18211                             dummy_obstack_deallocate);
18212
18213   while (1)
18214     {
18215       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18216
18217       /* A NULL abbrev means the end of a series of children.  */
18218       if (abbrev == NULL)
18219         {
18220           if (--nesting_level == 0)
18221             return first_die;
18222
18223           info_ptr += bytes_read;
18224           last_die = parent_die;
18225           parent_die = parent_die->die_parent;
18226           continue;
18227         }
18228
18229       /* Check for template arguments.  We never save these; if
18230          they're seen, we just mark the parent, and go on our way.  */
18231       if (parent_die != NULL
18232           && cu->language == language_cplus
18233           && (abbrev->tag == DW_TAG_template_type_param
18234               || abbrev->tag == DW_TAG_template_value_param))
18235         {
18236           parent_die->has_template_arguments = 1;
18237
18238           if (!load_all)
18239             {
18240               /* We don't need a partial DIE for the template argument.  */
18241               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18242               continue;
18243             }
18244         }
18245
18246       /* We only recurse into c++ subprograms looking for template arguments.
18247          Skip their other children.  */
18248       if (!load_all
18249           && cu->language == language_cplus
18250           && parent_die != NULL
18251           && parent_die->tag == DW_TAG_subprogram)
18252         {
18253           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18254           continue;
18255         }
18256
18257       /* Check whether this DIE is interesting enough to save.  Normally
18258          we would not be interested in members here, but there may be
18259          later variables referencing them via DW_AT_specification (for
18260          static members).  */
18261       if (!load_all
18262           && !is_type_tag_for_partial (abbrev->tag)
18263           && abbrev->tag != DW_TAG_constant
18264           && abbrev->tag != DW_TAG_enumerator
18265           && abbrev->tag != DW_TAG_subprogram
18266           && abbrev->tag != DW_TAG_inlined_subroutine
18267           && abbrev->tag != DW_TAG_lexical_block
18268           && abbrev->tag != DW_TAG_variable
18269           && abbrev->tag != DW_TAG_namespace
18270           && abbrev->tag != DW_TAG_module
18271           && abbrev->tag != DW_TAG_member
18272           && abbrev->tag != DW_TAG_imported_unit
18273           && abbrev->tag != DW_TAG_imported_declaration)
18274         {
18275           /* Otherwise we skip to the next sibling, if any.  */
18276           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18277           continue;
18278         }
18279
18280       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18281                                    abbrev);
18282
18283       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18284
18285       /* This two-pass algorithm for processing partial symbols has a
18286          high cost in cache pressure.  Thus, handle some simple cases
18287          here which cover the majority of C partial symbols.  DIEs
18288          which neither have specification tags in them, nor could have
18289          specification tags elsewhere pointing at them, can simply be
18290          processed and discarded.
18291
18292          This segment is also optional; scan_partial_symbols and
18293          add_partial_symbol will handle these DIEs if we chain
18294          them in normally.  When compilers which do not emit large
18295          quantities of duplicate debug information are more common,
18296          this code can probably be removed.  */
18297
18298       /* Any complete simple types at the top level (pretty much all
18299          of them, for a language without namespaces), can be processed
18300          directly.  */
18301       if (parent_die == NULL
18302           && pdi.has_specification == 0
18303           && pdi.is_declaration == 0
18304           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18305               || pdi.tag == DW_TAG_base_type
18306               || pdi.tag == DW_TAG_subrange_type))
18307         {
18308           if (building_psymtab && pdi.name != NULL)
18309             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18310                                  VAR_DOMAIN, LOC_TYPEDEF,
18311                                  &objfile->static_psymbols,
18312                                  0, cu->language, objfile);
18313           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18314           continue;
18315         }
18316
18317       /* The exception for DW_TAG_typedef with has_children above is
18318          a workaround of GCC PR debug/47510.  In the case of this complaint
18319          type_name_no_tag_or_error will error on such types later.
18320
18321          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18322          it could not find the child DIEs referenced later, this is checked
18323          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18324
18325       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18326         complaint (&symfile_complaints,
18327                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18328                      "- DIE at %s [in module %s]"),
18329                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18330
18331       /* If we're at the second level, and we're an enumerator, and
18332          our parent has no specification (meaning possibly lives in a
18333          namespace elsewhere), then we can add the partial symbol now
18334          instead of queueing it.  */
18335       if (pdi.tag == DW_TAG_enumerator
18336           && parent_die != NULL
18337           && parent_die->die_parent == NULL
18338           && parent_die->tag == DW_TAG_enumeration_type
18339           && parent_die->has_specification == 0)
18340         {
18341           if (pdi.name == NULL)
18342             complaint (&symfile_complaints,
18343                        _("malformed enumerator DIE ignored"));
18344           else if (building_psymtab)
18345             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18346                                  VAR_DOMAIN, LOC_CONST,
18347                                  cu->language == language_cplus
18348                                  ? &objfile->global_psymbols
18349                                  : &objfile->static_psymbols,
18350                                  0, cu->language, objfile);
18351
18352           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18353           continue;
18354         }
18355
18356       struct partial_die_info *part_die
18357         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18358
18359       /* We'll save this DIE so link it in.  */
18360       part_die->die_parent = parent_die;
18361       part_die->die_sibling = NULL;
18362       part_die->die_child = NULL;
18363
18364       if (last_die && last_die == parent_die)
18365         last_die->die_child = part_die;
18366       else if (last_die)
18367         last_die->die_sibling = part_die;
18368
18369       last_die = part_die;
18370
18371       if (first_die == NULL)
18372         first_die = part_die;
18373
18374       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18375          find interesting need to be in the hash table, because we
18376          also have the parent/sibling/child chains; only those that we
18377          might refer to by offset later during partial symbol reading.
18378
18379          For now this means things that might have be the target of a
18380          DW_AT_specification, DW_AT_abstract_origin, or
18381          DW_AT_extension.  DW_AT_extension will refer only to
18382          namespaces; DW_AT_abstract_origin refers to functions (and
18383          many things under the function DIE, but we do not recurse
18384          into function DIEs during partial symbol reading) and
18385          possibly variables as well; DW_AT_specification refers to
18386          declarations.  Declarations ought to have the DW_AT_declaration
18387          flag.  It happens that GCC forgets to put it in sometimes, but
18388          only for functions, not for types.
18389
18390          Adding more things than necessary to the hash table is harmless
18391          except for the performance cost.  Adding too few will result in
18392          wasted time in find_partial_die, when we reread the compilation
18393          unit with load_all_dies set.  */
18394
18395       if (load_all
18396           || abbrev->tag == DW_TAG_constant
18397           || abbrev->tag == DW_TAG_subprogram
18398           || abbrev->tag == DW_TAG_variable
18399           || abbrev->tag == DW_TAG_namespace
18400           || part_die->is_declaration)
18401         {
18402           void **slot;
18403
18404           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18405                                            to_underlying (part_die->sect_off),
18406                                            INSERT);
18407           *slot = part_die;
18408         }
18409
18410       /* For some DIEs we want to follow their children (if any).  For C
18411          we have no reason to follow the children of structures; for other
18412          languages we have to, so that we can get at method physnames
18413          to infer fully qualified class names, for DW_AT_specification,
18414          and for C++ template arguments.  For C++, we also look one level
18415          inside functions to find template arguments (if the name of the
18416          function does not already contain the template arguments).
18417
18418          For Ada, we need to scan the children of subprograms and lexical
18419          blocks as well because Ada allows the definition of nested
18420          entities that could be interesting for the debugger, such as
18421          nested subprograms for instance.  */
18422       if (last_die->has_children
18423           && (load_all
18424               || last_die->tag == DW_TAG_namespace
18425               || last_die->tag == DW_TAG_module
18426               || last_die->tag == DW_TAG_enumeration_type
18427               || (cu->language == language_cplus
18428                   && last_die->tag == DW_TAG_subprogram
18429                   && (last_die->name == NULL
18430                       || strchr (last_die->name, '<') == NULL))
18431               || (cu->language != language_c
18432                   && (last_die->tag == DW_TAG_class_type
18433                       || last_die->tag == DW_TAG_interface_type
18434                       || last_die->tag == DW_TAG_structure_type
18435                       || last_die->tag == DW_TAG_union_type))
18436               || (cu->language == language_ada
18437                   && (last_die->tag == DW_TAG_subprogram
18438                       || last_die->tag == DW_TAG_lexical_block))))
18439         {
18440           nesting_level++;
18441           parent_die = last_die;
18442           continue;
18443         }
18444
18445       /* Otherwise we skip to the next sibling, if any.  */
18446       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18447
18448       /* Back to the top, do it again.  */
18449     }
18450 }
18451
18452 partial_die_info::partial_die_info (sect_offset sect_off_,
18453                                     struct abbrev_info *abbrev)
18454   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18455 {
18456 }
18457
18458 /* Read a minimal amount of information into the minimal die structure.
18459    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18460
18461 const gdb_byte *
18462 partial_die_info::read (const struct die_reader_specs *reader,
18463                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18464 {
18465   struct dwarf2_cu *cu = reader->cu;
18466   struct dwarf2_per_objfile *dwarf2_per_objfile
18467     = cu->per_cu->dwarf2_per_objfile;
18468   unsigned int i;
18469   int has_low_pc_attr = 0;
18470   int has_high_pc_attr = 0;
18471   int high_pc_relative = 0;
18472
18473   for (i = 0; i < abbrev.num_attrs; ++i)
18474     {
18475       struct attribute attr;
18476
18477       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18478
18479       /* Store the data if it is of an attribute we want to keep in a
18480          partial symbol table.  */
18481       switch (attr.name)
18482         {
18483         case DW_AT_name:
18484           switch (tag)
18485             {
18486             case DW_TAG_compile_unit:
18487             case DW_TAG_partial_unit:
18488             case DW_TAG_type_unit:
18489               /* Compilation units have a DW_AT_name that is a filename, not
18490                  a source language identifier.  */
18491             case DW_TAG_enumeration_type:
18492             case DW_TAG_enumerator:
18493               /* These tags always have simple identifiers already; no need
18494                  to canonicalize them.  */
18495               name = DW_STRING (&attr);
18496               break;
18497             default:
18498               {
18499                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18500
18501                 name
18502                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18503                                               &objfile->per_bfd->storage_obstack);
18504               }
18505               break;
18506             }
18507           break;
18508         case DW_AT_linkage_name:
18509         case DW_AT_MIPS_linkage_name:
18510           /* Note that both forms of linkage name might appear.  We
18511              assume they will be the same, and we only store the last
18512              one we see.  */
18513           if (cu->language == language_ada)
18514             name = DW_STRING (&attr);
18515           linkage_name = DW_STRING (&attr);
18516           break;
18517         case DW_AT_low_pc:
18518           has_low_pc_attr = 1;
18519           lowpc = attr_value_as_address (&attr);
18520           break;
18521         case DW_AT_high_pc:
18522           has_high_pc_attr = 1;
18523           highpc = attr_value_as_address (&attr);
18524           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18525                 high_pc_relative = 1;
18526           break;
18527         case DW_AT_location:
18528           /* Support the .debug_loc offsets.  */
18529           if (attr_form_is_block (&attr))
18530             {
18531                d.locdesc = DW_BLOCK (&attr);
18532             }
18533           else if (attr_form_is_section_offset (&attr))
18534             {
18535               dwarf2_complex_location_expr_complaint ();
18536             }
18537           else
18538             {
18539               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18540                                                      "partial symbol information");
18541             }
18542           break;
18543         case DW_AT_external:
18544           is_external = DW_UNSND (&attr);
18545           break;
18546         case DW_AT_declaration:
18547           is_declaration = DW_UNSND (&attr);
18548           break;
18549         case DW_AT_type:
18550           has_type = 1;
18551           break;
18552         case DW_AT_abstract_origin:
18553         case DW_AT_specification:
18554         case DW_AT_extension:
18555           has_specification = 1;
18556           spec_offset = dwarf2_get_ref_die_offset (&attr);
18557           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18558                                    || cu->per_cu->is_dwz);
18559           break;
18560         case DW_AT_sibling:
18561           /* Ignore absolute siblings, they might point outside of
18562              the current compile unit.  */
18563           if (attr.form == DW_FORM_ref_addr)
18564             complaint (&symfile_complaints,
18565                        _("ignoring absolute DW_AT_sibling"));
18566           else
18567             {
18568               const gdb_byte *buffer = reader->buffer;
18569               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18570               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18571
18572               if (sibling_ptr < info_ptr)
18573                 complaint (&symfile_complaints,
18574                            _("DW_AT_sibling points backwards"));
18575               else if (sibling_ptr > reader->buffer_end)
18576                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18577               else
18578                 sibling = sibling_ptr;
18579             }
18580           break;
18581         case DW_AT_byte_size:
18582           has_byte_size = 1;
18583           break;
18584         case DW_AT_const_value:
18585           has_const_value = 1;
18586           break;
18587         case DW_AT_calling_convention:
18588           /* DWARF doesn't provide a way to identify a program's source-level
18589              entry point.  DW_AT_calling_convention attributes are only meant
18590              to describe functions' calling conventions.
18591
18592              However, because it's a necessary piece of information in
18593              Fortran, and before DWARF 4 DW_CC_program was the only
18594              piece of debugging information whose definition refers to
18595              a 'main program' at all, several compilers marked Fortran
18596              main programs with DW_CC_program --- even when those
18597              functions use the standard calling conventions.
18598
18599              Although DWARF now specifies a way to provide this
18600              information, we support this practice for backward
18601              compatibility.  */
18602           if (DW_UNSND (&attr) == DW_CC_program
18603               && cu->language == language_fortran)
18604             main_subprogram = 1;
18605           break;
18606         case DW_AT_inline:
18607           if (DW_UNSND (&attr) == DW_INL_inlined
18608               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18609             may_be_inlined = 1;
18610           break;
18611
18612         case DW_AT_import:
18613           if (tag == DW_TAG_imported_unit)
18614             {
18615               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18616               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18617                                   || cu->per_cu->is_dwz);
18618             }
18619           break;
18620
18621         case DW_AT_main_subprogram:
18622           main_subprogram = DW_UNSND (&attr);
18623           break;
18624
18625         default:
18626           break;
18627         }
18628     }
18629
18630   if (high_pc_relative)
18631     highpc += lowpc;
18632
18633   if (has_low_pc_attr && has_high_pc_attr)
18634     {
18635       /* When using the GNU linker, .gnu.linkonce. sections are used to
18636          eliminate duplicate copies of functions and vtables and such.
18637          The linker will arbitrarily choose one and discard the others.
18638          The AT_*_pc values for such functions refer to local labels in
18639          these sections.  If the section from that file was discarded, the
18640          labels are not in the output, so the relocs get a value of 0.
18641          If this is a discarded function, mark the pc bounds as invalid,
18642          so that GDB will ignore it.  */
18643       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18644         {
18645           struct objfile *objfile = dwarf2_per_objfile->objfile;
18646           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18647
18648           complaint (&symfile_complaints,
18649                      _("DW_AT_low_pc %s is zero "
18650                        "for DIE at %s [in module %s]"),
18651                      paddress (gdbarch, lowpc),
18652                      sect_offset_str (sect_off),
18653                      objfile_name (objfile));
18654         }
18655       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18656       else if (lowpc >= highpc)
18657         {
18658           struct objfile *objfile = dwarf2_per_objfile->objfile;
18659           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18660
18661           complaint (&symfile_complaints,
18662                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18663                        "for DIE at %s [in module %s]"),
18664                      paddress (gdbarch, lowpc),
18665                      paddress (gdbarch, highpc),
18666                      sect_offset_str (sect_off),
18667                      objfile_name (objfile));
18668         }
18669       else
18670         has_pc_info = 1;
18671     }
18672
18673   return info_ptr;
18674 }
18675
18676 /* Find a cached partial DIE at OFFSET in CU.  */
18677
18678 struct partial_die_info *
18679 dwarf2_cu::find_partial_die (sect_offset sect_off)
18680 {
18681   struct partial_die_info *lookup_die = NULL;
18682   struct partial_die_info part_die (sect_off);
18683
18684   lookup_die = ((struct partial_die_info *)
18685                 htab_find_with_hash (partial_dies, &part_die,
18686                                      to_underlying (sect_off)));
18687
18688   return lookup_die;
18689 }
18690
18691 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18692    except in the case of .debug_types DIEs which do not reference
18693    outside their CU (they do however referencing other types via
18694    DW_FORM_ref_sig8).  */
18695
18696 static struct partial_die_info *
18697 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18698 {
18699   struct dwarf2_per_objfile *dwarf2_per_objfile
18700     = cu->per_cu->dwarf2_per_objfile;
18701   struct objfile *objfile = dwarf2_per_objfile->objfile;
18702   struct dwarf2_per_cu_data *per_cu = NULL;
18703   struct partial_die_info *pd = NULL;
18704
18705   if (offset_in_dwz == cu->per_cu->is_dwz
18706       && offset_in_cu_p (&cu->header, sect_off))
18707     {
18708       pd = cu->find_partial_die (sect_off);
18709       if (pd != NULL)
18710         return pd;
18711       /* We missed recording what we needed.
18712          Load all dies and try again.  */
18713       per_cu = cu->per_cu;
18714     }
18715   else
18716     {
18717       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18718       if (cu->per_cu->is_debug_types)
18719         {
18720           error (_("Dwarf Error: Type Unit at offset %s contains"
18721                    " external reference to offset %s [in module %s].\n"),
18722                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18723                  bfd_get_filename (objfile->obfd));
18724         }
18725       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18726                                                  dwarf2_per_objfile);
18727
18728       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18729         load_partial_comp_unit (per_cu);
18730
18731       per_cu->cu->last_used = 0;
18732       pd = per_cu->cu->find_partial_die (sect_off);
18733     }
18734
18735   /* If we didn't find it, and not all dies have been loaded,
18736      load them all and try again.  */
18737
18738   if (pd == NULL && per_cu->load_all_dies == 0)
18739     {
18740       per_cu->load_all_dies = 1;
18741
18742       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18743          THIS_CU->cu may already be in use.  So we can't just free it and
18744          replace its DIEs with the ones we read in.  Instead, we leave those
18745          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18746          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18747          set.  */
18748       load_partial_comp_unit (per_cu);
18749
18750       pd = per_cu->cu->find_partial_die (sect_off);
18751     }
18752
18753   if (pd == NULL)
18754     internal_error (__FILE__, __LINE__,
18755                     _("could not find partial DIE %s "
18756                       "in cache [from module %s]\n"),
18757                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18758   return pd;
18759 }
18760
18761 /* See if we can figure out if the class lives in a namespace.  We do
18762    this by looking for a member function; its demangled name will
18763    contain namespace info, if there is any.  */
18764
18765 static void
18766 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18767                                   struct dwarf2_cu *cu)
18768 {
18769   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18770      what template types look like, because the demangler
18771      frequently doesn't give the same name as the debug info.  We
18772      could fix this by only using the demangled name to get the
18773      prefix (but see comment in read_structure_type).  */
18774
18775   struct partial_die_info *real_pdi;
18776   struct partial_die_info *child_pdi;
18777
18778   /* If this DIE (this DIE's specification, if any) has a parent, then
18779      we should not do this.  We'll prepend the parent's fully qualified
18780      name when we create the partial symbol.  */
18781
18782   real_pdi = struct_pdi;
18783   while (real_pdi->has_specification)
18784     real_pdi = find_partial_die (real_pdi->spec_offset,
18785                                  real_pdi->spec_is_dwz, cu);
18786
18787   if (real_pdi->die_parent != NULL)
18788     return;
18789
18790   for (child_pdi = struct_pdi->die_child;
18791        child_pdi != NULL;
18792        child_pdi = child_pdi->die_sibling)
18793     {
18794       if (child_pdi->tag == DW_TAG_subprogram
18795           && child_pdi->linkage_name != NULL)
18796         {
18797           char *actual_class_name
18798             = language_class_name_from_physname (cu->language_defn,
18799                                                  child_pdi->linkage_name);
18800           if (actual_class_name != NULL)
18801             {
18802               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18803               struct_pdi->name
18804                 = ((const char *)
18805                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18806                                   actual_class_name,
18807                                   strlen (actual_class_name)));
18808               xfree (actual_class_name);
18809             }
18810           break;
18811         }
18812     }
18813 }
18814
18815 void
18816 partial_die_info::fixup (struct dwarf2_cu *cu)
18817 {
18818   /* Once we've fixed up a die, there's no point in doing so again.
18819      This also avoids a memory leak if we were to call
18820      guess_partial_die_structure_name multiple times.  */
18821   if (fixup_called)
18822     return;
18823
18824   /* If we found a reference attribute and the DIE has no name, try
18825      to find a name in the referred to DIE.  */
18826
18827   if (name == NULL && has_specification)
18828     {
18829       struct partial_die_info *spec_die;
18830
18831       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18832
18833       spec_die->fixup (cu);
18834
18835       if (spec_die->name)
18836         {
18837           name = spec_die->name;
18838
18839           /* Copy DW_AT_external attribute if it is set.  */
18840           if (spec_die->is_external)
18841             is_external = spec_die->is_external;
18842         }
18843     }
18844
18845   /* Set default names for some unnamed DIEs.  */
18846
18847   if (name == NULL && tag == DW_TAG_namespace)
18848     name = CP_ANONYMOUS_NAMESPACE_STR;
18849
18850   /* If there is no parent die to provide a namespace, and there are
18851      children, see if we can determine the namespace from their linkage
18852      name.  */
18853   if (cu->language == language_cplus
18854       && !VEC_empty (dwarf2_section_info_def,
18855                      cu->per_cu->dwarf2_per_objfile->types)
18856       && die_parent == NULL
18857       && has_children
18858       && (tag == DW_TAG_class_type
18859           || tag == DW_TAG_structure_type
18860           || tag == DW_TAG_union_type))
18861     guess_partial_die_structure_name (this, cu);
18862
18863   /* GCC might emit a nameless struct or union that has a linkage
18864      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18865   if (name == NULL
18866       && (tag == DW_TAG_class_type
18867           || tag == DW_TAG_interface_type
18868           || tag == DW_TAG_structure_type
18869           || tag == DW_TAG_union_type)
18870       && linkage_name != NULL)
18871     {
18872       char *demangled;
18873
18874       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18875       if (demangled)
18876         {
18877           const char *base;
18878
18879           /* Strip any leading namespaces/classes, keep only the base name.
18880              DW_AT_name for named DIEs does not contain the prefixes.  */
18881           base = strrchr (demangled, ':');
18882           if (base && base > demangled && base[-1] == ':')
18883             base++;
18884           else
18885             base = demangled;
18886
18887           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18888           name
18889             = ((const char *)
18890                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18891                               base, strlen (base)));
18892           xfree (demangled);
18893         }
18894     }
18895
18896   fixup_called = 1;
18897 }
18898
18899 /* Read an attribute value described by an attribute form.  */
18900
18901 static const gdb_byte *
18902 read_attribute_value (const struct die_reader_specs *reader,
18903                       struct attribute *attr, unsigned form,
18904                       LONGEST implicit_const, const gdb_byte *info_ptr)
18905 {
18906   struct dwarf2_cu *cu = reader->cu;
18907   struct dwarf2_per_objfile *dwarf2_per_objfile
18908     = cu->per_cu->dwarf2_per_objfile;
18909   struct objfile *objfile = dwarf2_per_objfile->objfile;
18910   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18911   bfd *abfd = reader->abfd;
18912   struct comp_unit_head *cu_header = &cu->header;
18913   unsigned int bytes_read;
18914   struct dwarf_block *blk;
18915
18916   attr->form = (enum dwarf_form) form;
18917   switch (form)
18918     {
18919     case DW_FORM_ref_addr:
18920       if (cu->header.version == 2)
18921         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18922       else
18923         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18924                                        &cu->header, &bytes_read);
18925       info_ptr += bytes_read;
18926       break;
18927     case DW_FORM_GNU_ref_alt:
18928       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18929       info_ptr += bytes_read;
18930       break;
18931     case DW_FORM_addr:
18932       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18933       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18934       info_ptr += bytes_read;
18935       break;
18936     case DW_FORM_block2:
18937       blk = dwarf_alloc_block (cu);
18938       blk->size = read_2_bytes (abfd, info_ptr);
18939       info_ptr += 2;
18940       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18941       info_ptr += blk->size;
18942       DW_BLOCK (attr) = blk;
18943       break;
18944     case DW_FORM_block4:
18945       blk = dwarf_alloc_block (cu);
18946       blk->size = read_4_bytes (abfd, info_ptr);
18947       info_ptr += 4;
18948       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18949       info_ptr += blk->size;
18950       DW_BLOCK (attr) = blk;
18951       break;
18952     case DW_FORM_data2:
18953       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18954       info_ptr += 2;
18955       break;
18956     case DW_FORM_data4:
18957       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18958       info_ptr += 4;
18959       break;
18960     case DW_FORM_data8:
18961       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18962       info_ptr += 8;
18963       break;
18964     case DW_FORM_data16:
18965       blk = dwarf_alloc_block (cu);
18966       blk->size = 16;
18967       blk->data = read_n_bytes (abfd, info_ptr, 16);
18968       info_ptr += 16;
18969       DW_BLOCK (attr) = blk;
18970       break;
18971     case DW_FORM_sec_offset:
18972       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18973       info_ptr += bytes_read;
18974       break;
18975     case DW_FORM_string:
18976       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18977       DW_STRING_IS_CANONICAL (attr) = 0;
18978       info_ptr += bytes_read;
18979       break;
18980     case DW_FORM_strp:
18981       if (!cu->per_cu->is_dwz)
18982         {
18983           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18984                                                    abfd, info_ptr, cu_header,
18985                                                    &bytes_read);
18986           DW_STRING_IS_CANONICAL (attr) = 0;
18987           info_ptr += bytes_read;
18988           break;
18989         }
18990       /* FALLTHROUGH */
18991     case DW_FORM_line_strp:
18992       if (!cu->per_cu->is_dwz)
18993         {
18994           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18995                                                         abfd, info_ptr,
18996                                                         cu_header, &bytes_read);
18997           DW_STRING_IS_CANONICAL (attr) = 0;
18998           info_ptr += bytes_read;
18999           break;
19000         }
19001       /* FALLTHROUGH */
19002     case DW_FORM_GNU_strp_alt:
19003       {
19004         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19005         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19006                                           &bytes_read);
19007
19008         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19009                                                           dwz, str_offset);
19010         DW_STRING_IS_CANONICAL (attr) = 0;
19011         info_ptr += bytes_read;
19012       }
19013       break;
19014     case DW_FORM_exprloc:
19015     case DW_FORM_block:
19016       blk = dwarf_alloc_block (cu);
19017       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19018       info_ptr += bytes_read;
19019       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19020       info_ptr += blk->size;
19021       DW_BLOCK (attr) = blk;
19022       break;
19023     case DW_FORM_block1:
19024       blk = dwarf_alloc_block (cu);
19025       blk->size = read_1_byte (abfd, info_ptr);
19026       info_ptr += 1;
19027       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19028       info_ptr += blk->size;
19029       DW_BLOCK (attr) = blk;
19030       break;
19031     case DW_FORM_data1:
19032       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19033       info_ptr += 1;
19034       break;
19035     case DW_FORM_flag:
19036       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19037       info_ptr += 1;
19038       break;
19039     case DW_FORM_flag_present:
19040       DW_UNSND (attr) = 1;
19041       break;
19042     case DW_FORM_sdata:
19043       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19044       info_ptr += bytes_read;
19045       break;
19046     case DW_FORM_udata:
19047       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19048       info_ptr += bytes_read;
19049       break;
19050     case DW_FORM_ref1:
19051       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19052                          + read_1_byte (abfd, info_ptr));
19053       info_ptr += 1;
19054       break;
19055     case DW_FORM_ref2:
19056       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19057                          + read_2_bytes (abfd, info_ptr));
19058       info_ptr += 2;
19059       break;
19060     case DW_FORM_ref4:
19061       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19062                          + read_4_bytes (abfd, info_ptr));
19063       info_ptr += 4;
19064       break;
19065     case DW_FORM_ref8:
19066       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19067                          + read_8_bytes (abfd, info_ptr));
19068       info_ptr += 8;
19069       break;
19070     case DW_FORM_ref_sig8:
19071       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19072       info_ptr += 8;
19073       break;
19074     case DW_FORM_ref_udata:
19075       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19076                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19077       info_ptr += bytes_read;
19078       break;
19079     case DW_FORM_indirect:
19080       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19081       info_ptr += bytes_read;
19082       if (form == DW_FORM_implicit_const)
19083         {
19084           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19085           info_ptr += bytes_read;
19086         }
19087       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19088                                        info_ptr);
19089       break;
19090     case DW_FORM_implicit_const:
19091       DW_SND (attr) = implicit_const;
19092       break;
19093     case DW_FORM_GNU_addr_index:
19094       if (reader->dwo_file == NULL)
19095         {
19096           /* For now flag a hard error.
19097              Later we can turn this into a complaint.  */
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       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19103       info_ptr += bytes_read;
19104       break;
19105     case DW_FORM_GNU_str_index:
19106       if (reader->dwo_file == NULL)
19107         {
19108           /* For now flag a hard error.
19109              Later we can turn this into a complaint if warranted.  */
19110           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19111                  dwarf_form_name (form),
19112                  bfd_get_filename (abfd));
19113         }
19114       {
19115         ULONGEST str_index =
19116           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19117
19118         DW_STRING (attr) = read_str_index (reader, str_index);
19119         DW_STRING_IS_CANONICAL (attr) = 0;
19120         info_ptr += bytes_read;
19121       }
19122       break;
19123     default:
19124       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19125              dwarf_form_name (form),
19126              bfd_get_filename (abfd));
19127     }
19128
19129   /* Super hack.  */
19130   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19131     attr->form = DW_FORM_GNU_ref_alt;
19132
19133   /* We have seen instances where the compiler tried to emit a byte
19134      size attribute of -1 which ended up being encoded as an unsigned
19135      0xffffffff.  Although 0xffffffff is technically a valid size value,
19136      an object of this size seems pretty unlikely so we can relatively
19137      safely treat these cases as if the size attribute was invalid and
19138      treat them as zero by default.  */
19139   if (attr->name == DW_AT_byte_size
19140       && form == DW_FORM_data4
19141       && DW_UNSND (attr) >= 0xffffffff)
19142     {
19143       complaint
19144         (&symfile_complaints,
19145          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19146          hex_string (DW_UNSND (attr)));
19147       DW_UNSND (attr) = 0;
19148     }
19149
19150   return info_ptr;
19151 }
19152
19153 /* Read an attribute described by an abbreviated attribute.  */
19154
19155 static const gdb_byte *
19156 read_attribute (const struct die_reader_specs *reader,
19157                 struct attribute *attr, struct attr_abbrev *abbrev,
19158                 const gdb_byte *info_ptr)
19159 {
19160   attr->name = abbrev->name;
19161   return read_attribute_value (reader, attr, abbrev->form,
19162                                abbrev->implicit_const, info_ptr);
19163 }
19164
19165 /* Read dwarf information from a buffer.  */
19166
19167 static unsigned int
19168 read_1_byte (bfd *abfd, const gdb_byte *buf)
19169 {
19170   return bfd_get_8 (abfd, buf);
19171 }
19172
19173 static int
19174 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19175 {
19176   return bfd_get_signed_8 (abfd, buf);
19177 }
19178
19179 static unsigned int
19180 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19181 {
19182   return bfd_get_16 (abfd, buf);
19183 }
19184
19185 static int
19186 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19187 {
19188   return bfd_get_signed_16 (abfd, buf);
19189 }
19190
19191 static unsigned int
19192 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19193 {
19194   return bfd_get_32 (abfd, buf);
19195 }
19196
19197 static int
19198 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19199 {
19200   return bfd_get_signed_32 (abfd, buf);
19201 }
19202
19203 static ULONGEST
19204 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19205 {
19206   return bfd_get_64 (abfd, buf);
19207 }
19208
19209 static CORE_ADDR
19210 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19211               unsigned int *bytes_read)
19212 {
19213   struct comp_unit_head *cu_header = &cu->header;
19214   CORE_ADDR retval = 0;
19215
19216   if (cu_header->signed_addr_p)
19217     {
19218       switch (cu_header->addr_size)
19219         {
19220         case 2:
19221           retval = bfd_get_signed_16 (abfd, buf);
19222           break;
19223         case 4:
19224           retval = bfd_get_signed_32 (abfd, buf);
19225           break;
19226         case 8:
19227           retval = bfd_get_signed_64 (abfd, buf);
19228           break;
19229         default:
19230           internal_error (__FILE__, __LINE__,
19231                           _("read_address: bad switch, signed [in module %s]"),
19232                           bfd_get_filename (abfd));
19233         }
19234     }
19235   else
19236     {
19237       switch (cu_header->addr_size)
19238         {
19239         case 2:
19240           retval = bfd_get_16 (abfd, buf);
19241           break;
19242         case 4:
19243           retval = bfd_get_32 (abfd, buf);
19244           break;
19245         case 8:
19246           retval = bfd_get_64 (abfd, buf);
19247           break;
19248         default:
19249           internal_error (__FILE__, __LINE__,
19250                           _("read_address: bad switch, "
19251                             "unsigned [in module %s]"),
19252                           bfd_get_filename (abfd));
19253         }
19254     }
19255
19256   *bytes_read = cu_header->addr_size;
19257   return retval;
19258 }
19259
19260 /* Read the initial length from a section.  The (draft) DWARF 3
19261    specification allows the initial length to take up either 4 bytes
19262    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19263    bytes describe the length and all offsets will be 8 bytes in length
19264    instead of 4.
19265
19266    An older, non-standard 64-bit format is also handled by this
19267    function.  The older format in question stores the initial length
19268    as an 8-byte quantity without an escape value.  Lengths greater
19269    than 2^32 aren't very common which means that the initial 4 bytes
19270    is almost always zero.  Since a length value of zero doesn't make
19271    sense for the 32-bit format, this initial zero can be considered to
19272    be an escape value which indicates the presence of the older 64-bit
19273    format.  As written, the code can't detect (old format) lengths
19274    greater than 4GB.  If it becomes necessary to handle lengths
19275    somewhat larger than 4GB, we could allow other small values (such
19276    as the non-sensical values of 1, 2, and 3) to also be used as
19277    escape values indicating the presence of the old format.
19278
19279    The value returned via bytes_read should be used to increment the
19280    relevant pointer after calling read_initial_length().
19281
19282    [ Note:  read_initial_length() and read_offset() are based on the
19283      document entitled "DWARF Debugging Information Format", revision
19284      3, draft 8, dated November 19, 2001.  This document was obtained
19285      from:
19286
19287         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19288
19289      This document is only a draft and is subject to change.  (So beware.)
19290
19291      Details regarding the older, non-standard 64-bit format were
19292      determined empirically by examining 64-bit ELF files produced by
19293      the SGI toolchain on an IRIX 6.5 machine.
19294
19295      - Kevin, July 16, 2002
19296    ] */
19297
19298 static LONGEST
19299 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19300 {
19301   LONGEST length = bfd_get_32 (abfd, buf);
19302
19303   if (length == 0xffffffff)
19304     {
19305       length = bfd_get_64 (abfd, buf + 4);
19306       *bytes_read = 12;
19307     }
19308   else if (length == 0)
19309     {
19310       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19311       length = bfd_get_64 (abfd, buf);
19312       *bytes_read = 8;
19313     }
19314   else
19315     {
19316       *bytes_read = 4;
19317     }
19318
19319   return length;
19320 }
19321
19322 /* Cover function for read_initial_length.
19323    Returns the length of the object at BUF, and stores the size of the
19324    initial length in *BYTES_READ and stores the size that offsets will be in
19325    *OFFSET_SIZE.
19326    If the initial length size is not equivalent to that specified in
19327    CU_HEADER then issue a complaint.
19328    This is useful when reading non-comp-unit headers.  */
19329
19330 static LONGEST
19331 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19332                                         const struct comp_unit_head *cu_header,
19333                                         unsigned int *bytes_read,
19334                                         unsigned int *offset_size)
19335 {
19336   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19337
19338   gdb_assert (cu_header->initial_length_size == 4
19339               || cu_header->initial_length_size == 8
19340               || cu_header->initial_length_size == 12);
19341
19342   if (cu_header->initial_length_size != *bytes_read)
19343     complaint (&symfile_complaints,
19344                _("intermixed 32-bit and 64-bit DWARF sections"));
19345
19346   *offset_size = (*bytes_read == 4) ? 4 : 8;
19347   return length;
19348 }
19349
19350 /* Read an offset from the data stream.  The size of the offset is
19351    given by cu_header->offset_size.  */
19352
19353 static LONGEST
19354 read_offset (bfd *abfd, const gdb_byte *buf,
19355              const struct comp_unit_head *cu_header,
19356              unsigned int *bytes_read)
19357 {
19358   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19359
19360   *bytes_read = cu_header->offset_size;
19361   return offset;
19362 }
19363
19364 /* Read an offset from the data stream.  */
19365
19366 static LONGEST
19367 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19368 {
19369   LONGEST retval = 0;
19370
19371   switch (offset_size)
19372     {
19373     case 4:
19374       retval = bfd_get_32 (abfd, buf);
19375       break;
19376     case 8:
19377       retval = bfd_get_64 (abfd, buf);
19378       break;
19379     default:
19380       internal_error (__FILE__, __LINE__,
19381                       _("read_offset_1: bad switch [in module %s]"),
19382                       bfd_get_filename (abfd));
19383     }
19384
19385   return retval;
19386 }
19387
19388 static const gdb_byte *
19389 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19390 {
19391   /* If the size of a host char is 8 bits, we can return a pointer
19392      to the buffer, otherwise we have to copy the data to a buffer
19393      allocated on the temporary obstack.  */
19394   gdb_assert (HOST_CHAR_BIT == 8);
19395   return buf;
19396 }
19397
19398 static const char *
19399 read_direct_string (bfd *abfd, const gdb_byte *buf,
19400                     unsigned int *bytes_read_ptr)
19401 {
19402   /* If the size of a host char is 8 bits, we can return a pointer
19403      to the string, otherwise we have to copy the string to a buffer
19404      allocated on the temporary obstack.  */
19405   gdb_assert (HOST_CHAR_BIT == 8);
19406   if (*buf == '\0')
19407     {
19408       *bytes_read_ptr = 1;
19409       return NULL;
19410     }
19411   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19412   return (const char *) buf;
19413 }
19414
19415 /* Return pointer to string at section SECT offset STR_OFFSET with error
19416    reporting strings FORM_NAME and SECT_NAME.  */
19417
19418 static const char *
19419 read_indirect_string_at_offset_from (struct objfile *objfile,
19420                                      bfd *abfd, LONGEST str_offset,
19421                                      struct dwarf2_section_info *sect,
19422                                      const char *form_name,
19423                                      const char *sect_name)
19424 {
19425   dwarf2_read_section (objfile, sect);
19426   if (sect->buffer == NULL)
19427     error (_("%s used without %s section [in module %s]"),
19428            form_name, sect_name, bfd_get_filename (abfd));
19429   if (str_offset >= sect->size)
19430     error (_("%s pointing outside of %s section [in module %s]"),
19431            form_name, sect_name, bfd_get_filename (abfd));
19432   gdb_assert (HOST_CHAR_BIT == 8);
19433   if (sect->buffer[str_offset] == '\0')
19434     return NULL;
19435   return (const char *) (sect->buffer + str_offset);
19436 }
19437
19438 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19439
19440 static const char *
19441 read_indirect_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->str,
19447                                               "DW_FORM_strp", ".debug_str");
19448 }
19449
19450 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19451
19452 static const char *
19453 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19454                                      bfd *abfd, LONGEST str_offset)
19455 {
19456   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19457                                               abfd, str_offset,
19458                                               &dwarf2_per_objfile->line_str,
19459                                               "DW_FORM_line_strp",
19460                                               ".debug_line_str");
19461 }
19462
19463 /* Read a string at offset STR_OFFSET in the .debug_str section from
19464    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19465    the string consists of a single NUL byte, return NULL; otherwise
19466    return a pointer to the string.  */
19467
19468 static const char *
19469 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19470                                LONGEST str_offset)
19471 {
19472   dwarf2_read_section (objfile, &dwz->str);
19473
19474   if (dwz->str.buffer == NULL)
19475     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19476              "section [in module %s]"),
19477            bfd_get_filename (dwz->dwz_bfd));
19478   if (str_offset >= dwz->str.size)
19479     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19480              ".debug_str section [in module %s]"),
19481            bfd_get_filename (dwz->dwz_bfd));
19482   gdb_assert (HOST_CHAR_BIT == 8);
19483   if (dwz->str.buffer[str_offset] == '\0')
19484     return NULL;
19485   return (const char *) (dwz->str.buffer + str_offset);
19486 }
19487
19488 /* Return pointer to string at .debug_str offset as read from BUF.
19489    BUF is assumed to be in a compilation unit described by CU_HEADER.
19490    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19491
19492 static const char *
19493 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19494                       const gdb_byte *buf,
19495                       const struct comp_unit_head *cu_header,
19496                       unsigned int *bytes_read_ptr)
19497 {
19498   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19499
19500   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19501 }
19502
19503 /* Return pointer to string at .debug_line_str offset as read from BUF.
19504    BUF is assumed to be in a compilation unit described by CU_HEADER.
19505    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19506
19507 static const char *
19508 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19509                            bfd *abfd, const gdb_byte *buf,
19510                            const struct comp_unit_head *cu_header,
19511                            unsigned int *bytes_read_ptr)
19512 {
19513   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19514
19515   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19516                                               str_offset);
19517 }
19518
19519 ULONGEST
19520 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19521                           unsigned int *bytes_read_ptr)
19522 {
19523   ULONGEST result;
19524   unsigned int num_read;
19525   int shift;
19526   unsigned char byte;
19527
19528   result = 0;
19529   shift = 0;
19530   num_read = 0;
19531   while (1)
19532     {
19533       byte = bfd_get_8 (abfd, buf);
19534       buf++;
19535       num_read++;
19536       result |= ((ULONGEST) (byte & 127) << shift);
19537       if ((byte & 128) == 0)
19538         {
19539           break;
19540         }
19541       shift += 7;
19542     }
19543   *bytes_read_ptr = num_read;
19544   return result;
19545 }
19546
19547 static LONGEST
19548 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19549                     unsigned int *bytes_read_ptr)
19550 {
19551   LONGEST result;
19552   int shift, num_read;
19553   unsigned char byte;
19554
19555   result = 0;
19556   shift = 0;
19557   num_read = 0;
19558   while (1)
19559     {
19560       byte = bfd_get_8 (abfd, buf);
19561       buf++;
19562       num_read++;
19563       result |= ((LONGEST) (byte & 127) << shift);
19564       shift += 7;
19565       if ((byte & 128) == 0)
19566         {
19567           break;
19568         }
19569     }
19570   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19571     result |= -(((LONGEST) 1) << shift);
19572   *bytes_read_ptr = num_read;
19573   return result;
19574 }
19575
19576 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19577    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19578    ADDR_SIZE is the size of addresses from the CU header.  */
19579
19580 static CORE_ADDR
19581 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19582                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19583 {
19584   struct objfile *objfile = dwarf2_per_objfile->objfile;
19585   bfd *abfd = objfile->obfd;
19586   const gdb_byte *info_ptr;
19587
19588   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19589   if (dwarf2_per_objfile->addr.buffer == NULL)
19590     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19591            objfile_name (objfile));
19592   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19593     error (_("DW_FORM_addr_index pointing outside of "
19594              ".debug_addr section [in module %s]"),
19595            objfile_name (objfile));
19596   info_ptr = (dwarf2_per_objfile->addr.buffer
19597               + addr_base + addr_index * addr_size);
19598   if (addr_size == 4)
19599     return bfd_get_32 (abfd, info_ptr);
19600   else
19601     return bfd_get_64 (abfd, info_ptr);
19602 }
19603
19604 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19605
19606 static CORE_ADDR
19607 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19608 {
19609   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19610                             cu->addr_base, cu->header.addr_size);
19611 }
19612
19613 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19614
19615 static CORE_ADDR
19616 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19617                              unsigned int *bytes_read)
19618 {
19619   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19620   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19621
19622   return read_addr_index (cu, addr_index);
19623 }
19624
19625 /* Data structure to pass results from dwarf2_read_addr_index_reader
19626    back to dwarf2_read_addr_index.  */
19627
19628 struct dwarf2_read_addr_index_data
19629 {
19630   ULONGEST addr_base;
19631   int addr_size;
19632 };
19633
19634 /* die_reader_func for dwarf2_read_addr_index.  */
19635
19636 static void
19637 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19638                                const gdb_byte *info_ptr,
19639                                struct die_info *comp_unit_die,
19640                                int has_children,
19641                                void *data)
19642 {
19643   struct dwarf2_cu *cu = reader->cu;
19644   struct dwarf2_read_addr_index_data *aidata =
19645     (struct dwarf2_read_addr_index_data *) data;
19646
19647   aidata->addr_base = cu->addr_base;
19648   aidata->addr_size = cu->header.addr_size;
19649 }
19650
19651 /* Given an index in .debug_addr, fetch the value.
19652    NOTE: This can be called during dwarf expression evaluation,
19653    long after the debug information has been read, and thus per_cu->cu
19654    may no longer exist.  */
19655
19656 CORE_ADDR
19657 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19658                         unsigned int addr_index)
19659 {
19660   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19661   struct objfile *objfile = dwarf2_per_objfile->objfile;
19662   struct dwarf2_cu *cu = per_cu->cu;
19663   ULONGEST addr_base;
19664   int addr_size;
19665
19666   /* We need addr_base and addr_size.
19667      If we don't have PER_CU->cu, we have to get it.
19668      Nasty, but the alternative is storing the needed info in PER_CU,
19669      which at this point doesn't seem justified: it's not clear how frequently
19670      it would get used and it would increase the size of every PER_CU.
19671      Entry points like dwarf2_per_cu_addr_size do a similar thing
19672      so we're not in uncharted territory here.
19673      Alas we need to be a bit more complicated as addr_base is contained
19674      in the DIE.
19675
19676      We don't need to read the entire CU(/TU).
19677      We just need the header and top level die.
19678
19679      IWBN to use the aging mechanism to let us lazily later discard the CU.
19680      For now we skip this optimization.  */
19681
19682   if (cu != NULL)
19683     {
19684       addr_base = cu->addr_base;
19685       addr_size = cu->header.addr_size;
19686     }
19687   else
19688     {
19689       struct dwarf2_read_addr_index_data aidata;
19690
19691       /* Note: We can't use init_cutu_and_read_dies_simple here,
19692          we need addr_base.  */
19693       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19694                                dwarf2_read_addr_index_reader, &aidata);
19695       addr_base = aidata.addr_base;
19696       addr_size = aidata.addr_size;
19697     }
19698
19699   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19700                             addr_size);
19701 }
19702
19703 /* Given a DW_FORM_GNU_str_index, fetch the string.
19704    This is only used by the Fission support.  */
19705
19706 static const char *
19707 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19708 {
19709   struct dwarf2_cu *cu = reader->cu;
19710   struct dwarf2_per_objfile *dwarf2_per_objfile
19711     = cu->per_cu->dwarf2_per_objfile;
19712   struct objfile *objfile = dwarf2_per_objfile->objfile;
19713   const char *objf_name = objfile_name (objfile);
19714   bfd *abfd = objfile->obfd;
19715   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19716   struct dwarf2_section_info *str_offsets_section =
19717     &reader->dwo_file->sections.str_offsets;
19718   const gdb_byte *info_ptr;
19719   ULONGEST str_offset;
19720   static const char form_name[] = "DW_FORM_GNU_str_index";
19721
19722   dwarf2_read_section (objfile, str_section);
19723   dwarf2_read_section (objfile, str_offsets_section);
19724   if (str_section->buffer == NULL)
19725     error (_("%s used without .debug_str.dwo section"
19726              " in CU at offset %s [in module %s]"),
19727            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19728   if (str_offsets_section->buffer == NULL)
19729     error (_("%s used without .debug_str_offsets.dwo section"
19730              " in CU at offset %s [in module %s]"),
19731            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19732   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19733     error (_("%s pointing outside of .debug_str_offsets.dwo"
19734              " section in CU at offset %s [in module %s]"),
19735            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19736   info_ptr = (str_offsets_section->buffer
19737               + str_index * cu->header.offset_size);
19738   if (cu->header.offset_size == 4)
19739     str_offset = bfd_get_32 (abfd, info_ptr);
19740   else
19741     str_offset = bfd_get_64 (abfd, info_ptr);
19742   if (str_offset >= str_section->size)
19743     error (_("Offset from %s pointing outside of"
19744              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19745            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19746   return (const char *) (str_section->buffer + str_offset);
19747 }
19748
19749 /* Return the length of an LEB128 number in BUF.  */
19750
19751 static int
19752 leb128_size (const gdb_byte *buf)
19753 {
19754   const gdb_byte *begin = buf;
19755   gdb_byte byte;
19756
19757   while (1)
19758     {
19759       byte = *buf++;
19760       if ((byte & 128) == 0)
19761         return buf - begin;
19762     }
19763 }
19764
19765 static void
19766 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19767 {
19768   switch (lang)
19769     {
19770     case DW_LANG_C89:
19771     case DW_LANG_C99:
19772     case DW_LANG_C11:
19773     case DW_LANG_C:
19774     case DW_LANG_UPC:
19775       cu->language = language_c;
19776       break;
19777     case DW_LANG_Java:
19778     case DW_LANG_C_plus_plus:
19779     case DW_LANG_C_plus_plus_11:
19780     case DW_LANG_C_plus_plus_14:
19781       cu->language = language_cplus;
19782       break;
19783     case DW_LANG_D:
19784       cu->language = language_d;
19785       break;
19786     case DW_LANG_Fortran77:
19787     case DW_LANG_Fortran90:
19788     case DW_LANG_Fortran95:
19789     case DW_LANG_Fortran03:
19790     case DW_LANG_Fortran08:
19791       cu->language = language_fortran;
19792       break;
19793     case DW_LANG_Go:
19794       cu->language = language_go;
19795       break;
19796     case DW_LANG_Mips_Assembler:
19797       cu->language = language_asm;
19798       break;
19799     case DW_LANG_Ada83:
19800     case DW_LANG_Ada95:
19801       cu->language = language_ada;
19802       break;
19803     case DW_LANG_Modula2:
19804       cu->language = language_m2;
19805       break;
19806     case DW_LANG_Pascal83:
19807       cu->language = language_pascal;
19808       break;
19809     case DW_LANG_ObjC:
19810       cu->language = language_objc;
19811       break;
19812     case DW_LANG_Rust:
19813     case DW_LANG_Rust_old:
19814       cu->language = language_rust;
19815       break;
19816     case DW_LANG_Cobol74:
19817     case DW_LANG_Cobol85:
19818     default:
19819       cu->language = language_minimal;
19820       break;
19821     }
19822   cu->language_defn = language_def (cu->language);
19823 }
19824
19825 /* Return the named attribute or NULL if not there.  */
19826
19827 static struct attribute *
19828 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19829 {
19830   for (;;)
19831     {
19832       unsigned int i;
19833       struct attribute *spec = NULL;
19834
19835       for (i = 0; i < die->num_attrs; ++i)
19836         {
19837           if (die->attrs[i].name == name)
19838             return &die->attrs[i];
19839           if (die->attrs[i].name == DW_AT_specification
19840               || die->attrs[i].name == DW_AT_abstract_origin)
19841             spec = &die->attrs[i];
19842         }
19843
19844       if (!spec)
19845         break;
19846
19847       die = follow_die_ref (die, spec, &cu);
19848     }
19849
19850   return NULL;
19851 }
19852
19853 /* Return the named attribute or NULL if not there,
19854    but do not follow DW_AT_specification, etc.
19855    This is for use in contexts where we're reading .debug_types dies.
19856    Following DW_AT_specification, DW_AT_abstract_origin will take us
19857    back up the chain, and we want to go down.  */
19858
19859 static struct attribute *
19860 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19861 {
19862   unsigned int i;
19863
19864   for (i = 0; i < die->num_attrs; ++i)
19865     if (die->attrs[i].name == name)
19866       return &die->attrs[i];
19867
19868   return NULL;
19869 }
19870
19871 /* Return the string associated with a string-typed attribute, or NULL if it
19872    is either not found or is of an incorrect type.  */
19873
19874 static const char *
19875 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19876 {
19877   struct attribute *attr;
19878   const char *str = NULL;
19879
19880   attr = dwarf2_attr (die, name, cu);
19881
19882   if (attr != NULL)
19883     {
19884       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19885           || attr->form == DW_FORM_string
19886           || attr->form == DW_FORM_GNU_str_index
19887           || attr->form == DW_FORM_GNU_strp_alt)
19888         str = DW_STRING (attr);
19889       else
19890         complaint (&symfile_complaints,
19891                    _("string type expected for attribute %s for "
19892                      "DIE at %s in module %s"),
19893                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19894                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19895     }
19896
19897   return str;
19898 }
19899
19900 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19901    and holds a non-zero value.  This function should only be used for
19902    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19903
19904 static int
19905 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19906 {
19907   struct attribute *attr = dwarf2_attr (die, name, cu);
19908
19909   return (attr && DW_UNSND (attr));
19910 }
19911
19912 static int
19913 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19914 {
19915   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19916      which value is non-zero.  However, we have to be careful with
19917      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19918      (via dwarf2_flag_true_p) follows this attribute.  So we may
19919      end up accidently finding a declaration attribute that belongs
19920      to a different DIE referenced by the specification attribute,
19921      even though the given DIE does not have a declaration attribute.  */
19922   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19923           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19924 }
19925
19926 /* Return the die giving the specification for DIE, if there is
19927    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19928    containing the return value on output.  If there is no
19929    specification, but there is an abstract origin, that is
19930    returned.  */
19931
19932 static struct die_info *
19933 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19934 {
19935   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19936                                              *spec_cu);
19937
19938   if (spec_attr == NULL)
19939     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19940
19941   if (spec_attr == NULL)
19942     return NULL;
19943   else
19944     return follow_die_ref (die, spec_attr, spec_cu);
19945 }
19946
19947 /* Stub for free_line_header to match void * callback types.  */
19948
19949 static void
19950 free_line_header_voidp (void *arg)
19951 {
19952   struct line_header *lh = (struct line_header *) arg;
19953
19954   delete lh;
19955 }
19956
19957 void
19958 line_header::add_include_dir (const char *include_dir)
19959 {
19960   if (dwarf_line_debug >= 2)
19961     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19962                         include_dirs.size () + 1, include_dir);
19963
19964   include_dirs.push_back (include_dir);
19965 }
19966
19967 void
19968 line_header::add_file_name (const char *name,
19969                             dir_index d_index,
19970                             unsigned int mod_time,
19971                             unsigned int length)
19972 {
19973   if (dwarf_line_debug >= 2)
19974     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19975                         (unsigned) file_names.size () + 1, name);
19976
19977   file_names.emplace_back (name, d_index, mod_time, length);
19978 }
19979
19980 /* A convenience function to find the proper .debug_line section for a CU.  */
19981
19982 static struct dwarf2_section_info *
19983 get_debug_line_section (struct dwarf2_cu *cu)
19984 {
19985   struct dwarf2_section_info *section;
19986   struct dwarf2_per_objfile *dwarf2_per_objfile
19987     = cu->per_cu->dwarf2_per_objfile;
19988
19989   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19990      DWO file.  */
19991   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19992     section = &cu->dwo_unit->dwo_file->sections.line;
19993   else if (cu->per_cu->is_dwz)
19994     {
19995       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19996
19997       section = &dwz->line;
19998     }
19999   else
20000     section = &dwarf2_per_objfile->line;
20001
20002   return section;
20003 }
20004
20005 /* Read directory or file name entry format, starting with byte of
20006    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20007    entries count and the entries themselves in the described entry
20008    format.  */
20009
20010 static void
20011 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20012                         bfd *abfd, const gdb_byte **bufp,
20013                         struct line_header *lh,
20014                         const struct comp_unit_head *cu_header,
20015                         void (*callback) (struct line_header *lh,
20016                                           const char *name,
20017                                           dir_index d_index,
20018                                           unsigned int mod_time,
20019                                           unsigned int length))
20020 {
20021   gdb_byte format_count, formati;
20022   ULONGEST data_count, datai;
20023   const gdb_byte *buf = *bufp;
20024   const gdb_byte *format_header_data;
20025   unsigned int bytes_read;
20026
20027   format_count = read_1_byte (abfd, buf);
20028   buf += 1;
20029   format_header_data = buf;
20030   for (formati = 0; formati < format_count; formati++)
20031     {
20032       read_unsigned_leb128 (abfd, buf, &bytes_read);
20033       buf += bytes_read;
20034       read_unsigned_leb128 (abfd, buf, &bytes_read);
20035       buf += bytes_read;
20036     }
20037
20038   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20039   buf += bytes_read;
20040   for (datai = 0; datai < data_count; datai++)
20041     {
20042       const gdb_byte *format = format_header_data;
20043       struct file_entry fe;
20044
20045       for (formati = 0; formati < format_count; formati++)
20046         {
20047           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20048           format += bytes_read;
20049
20050           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20051           format += bytes_read;
20052
20053           gdb::optional<const char *> string;
20054           gdb::optional<unsigned int> uint;
20055
20056           switch (form)
20057             {
20058             case DW_FORM_string:
20059               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20060               buf += bytes_read;
20061               break;
20062
20063             case DW_FORM_line_strp:
20064               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20065                                                          abfd, buf,
20066                                                          cu_header,
20067                                                          &bytes_read));
20068               buf += bytes_read;
20069               break;
20070
20071             case DW_FORM_data1:
20072               uint.emplace (read_1_byte (abfd, buf));
20073               buf += 1;
20074               break;
20075
20076             case DW_FORM_data2:
20077               uint.emplace (read_2_bytes (abfd, buf));
20078               buf += 2;
20079               break;
20080
20081             case DW_FORM_data4:
20082               uint.emplace (read_4_bytes (abfd, buf));
20083               buf += 4;
20084               break;
20085
20086             case DW_FORM_data8:
20087               uint.emplace (read_8_bytes (abfd, buf));
20088               buf += 8;
20089               break;
20090
20091             case DW_FORM_udata:
20092               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20093               buf += bytes_read;
20094               break;
20095
20096             case DW_FORM_block:
20097               /* It is valid only for DW_LNCT_timestamp which is ignored by
20098                  current GDB.  */
20099               break;
20100             }
20101
20102           switch (content_type)
20103             {
20104             case DW_LNCT_path:
20105               if (string.has_value ())
20106                 fe.name = *string;
20107               break;
20108             case DW_LNCT_directory_index:
20109               if (uint.has_value ())
20110                 fe.d_index = (dir_index) *uint;
20111               break;
20112             case DW_LNCT_timestamp:
20113               if (uint.has_value ())
20114                 fe.mod_time = *uint;
20115               break;
20116             case DW_LNCT_size:
20117               if (uint.has_value ())
20118                 fe.length = *uint;
20119               break;
20120             case DW_LNCT_MD5:
20121               break;
20122             default:
20123               complaint (&symfile_complaints,
20124                          _("Unknown format content type %s"),
20125                          pulongest (content_type));
20126             }
20127         }
20128
20129       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20130     }
20131
20132   *bufp = buf;
20133 }
20134
20135 /* Read the statement program header starting at OFFSET in
20136    .debug_line, or .debug_line.dwo.  Return a pointer
20137    to a struct line_header, allocated using xmalloc.
20138    Returns NULL if there is a problem reading the header, e.g., if it
20139    has a version we don't understand.
20140
20141    NOTE: the strings in the include directory and file name tables of
20142    the returned object point into the dwarf line section buffer,
20143    and must not be freed.  */
20144
20145 static line_header_up
20146 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20147 {
20148   const gdb_byte *line_ptr;
20149   unsigned int bytes_read, offset_size;
20150   int i;
20151   const char *cur_dir, *cur_file;
20152   struct dwarf2_section_info *section;
20153   bfd *abfd;
20154   struct dwarf2_per_objfile *dwarf2_per_objfile
20155     = cu->per_cu->dwarf2_per_objfile;
20156
20157   section = get_debug_line_section (cu);
20158   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20159   if (section->buffer == NULL)
20160     {
20161       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20162         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20163       else
20164         complaint (&symfile_complaints, _("missing .debug_line section"));
20165       return 0;
20166     }
20167
20168   /* We can't do this until we know the section is non-empty.
20169      Only then do we know we have such a section.  */
20170   abfd = get_section_bfd_owner (section);
20171
20172   /* Make sure that at least there's room for the total_length field.
20173      That could be 12 bytes long, but we're just going to fudge that.  */
20174   if (to_underlying (sect_off) + 4 >= section->size)
20175     {
20176       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20177       return 0;
20178     }
20179
20180   line_header_up lh (new line_header ());
20181
20182   lh->sect_off = sect_off;
20183   lh->offset_in_dwz = cu->per_cu->is_dwz;
20184
20185   line_ptr = section->buffer + to_underlying (sect_off);
20186
20187   /* Read in the header.  */
20188   lh->total_length =
20189     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20190                                             &bytes_read, &offset_size);
20191   line_ptr += bytes_read;
20192   if (line_ptr + lh->total_length > (section->buffer + section->size))
20193     {
20194       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20195       return 0;
20196     }
20197   lh->statement_program_end = line_ptr + lh->total_length;
20198   lh->version = read_2_bytes (abfd, line_ptr);
20199   line_ptr += 2;
20200   if (lh->version > 5)
20201     {
20202       /* This is a version we don't understand.  The format could have
20203          changed in ways we don't handle properly so just punt.  */
20204       complaint (&symfile_complaints,
20205                  _("unsupported version in .debug_line section"));
20206       return NULL;
20207     }
20208   if (lh->version >= 5)
20209     {
20210       gdb_byte segment_selector_size;
20211
20212       /* Skip address size.  */
20213       read_1_byte (abfd, line_ptr);
20214       line_ptr += 1;
20215
20216       segment_selector_size = read_1_byte (abfd, line_ptr);
20217       line_ptr += 1;
20218       if (segment_selector_size != 0)
20219         {
20220           complaint (&symfile_complaints,
20221                      _("unsupported segment selector size %u "
20222                        "in .debug_line section"),
20223                      segment_selector_size);
20224           return NULL;
20225         }
20226     }
20227   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20228   line_ptr += offset_size;
20229   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20230   line_ptr += 1;
20231   if (lh->version >= 4)
20232     {
20233       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20234       line_ptr += 1;
20235     }
20236   else
20237     lh->maximum_ops_per_instruction = 1;
20238
20239   if (lh->maximum_ops_per_instruction == 0)
20240     {
20241       lh->maximum_ops_per_instruction = 1;
20242       complaint (&symfile_complaints,
20243                  _("invalid maximum_ops_per_instruction "
20244                    "in `.debug_line' section"));
20245     }
20246
20247   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20248   line_ptr += 1;
20249   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20250   line_ptr += 1;
20251   lh->line_range = read_1_byte (abfd, line_ptr);
20252   line_ptr += 1;
20253   lh->opcode_base = read_1_byte (abfd, line_ptr);
20254   line_ptr += 1;
20255   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20256
20257   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20258   for (i = 1; i < lh->opcode_base; ++i)
20259     {
20260       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20261       line_ptr += 1;
20262     }
20263
20264   if (lh->version >= 5)
20265     {
20266       /* Read directory table.  */
20267       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20268                               &cu->header,
20269                               [] (struct line_header *lh, const char *name,
20270                                   dir_index d_index, unsigned int mod_time,
20271                                   unsigned int length)
20272         {
20273           lh->add_include_dir (name);
20274         });
20275
20276       /* Read file name table.  */
20277       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20278                               &cu->header,
20279                               [] (struct line_header *lh, const char *name,
20280                                   dir_index d_index, unsigned int mod_time,
20281                                   unsigned int length)
20282         {
20283           lh->add_file_name (name, d_index, mod_time, length);
20284         });
20285     }
20286   else
20287     {
20288       /* Read directory table.  */
20289       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20290         {
20291           line_ptr += bytes_read;
20292           lh->add_include_dir (cur_dir);
20293         }
20294       line_ptr += bytes_read;
20295
20296       /* Read file name table.  */
20297       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20298         {
20299           unsigned int mod_time, length;
20300           dir_index d_index;
20301
20302           line_ptr += bytes_read;
20303           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20304           line_ptr += bytes_read;
20305           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20306           line_ptr += bytes_read;
20307           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20308           line_ptr += bytes_read;
20309
20310           lh->add_file_name (cur_file, d_index, mod_time, length);
20311         }
20312       line_ptr += bytes_read;
20313     }
20314   lh->statement_program_start = line_ptr;
20315
20316   if (line_ptr > (section->buffer + section->size))
20317     complaint (&symfile_complaints,
20318                _("line number info header doesn't "
20319                  "fit in `.debug_line' section"));
20320
20321   return lh;
20322 }
20323
20324 /* Subroutine of dwarf_decode_lines to simplify it.
20325    Return the file name of the psymtab for included file FILE_INDEX
20326    in line header LH of PST.
20327    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20328    If space for the result is malloc'd, *NAME_HOLDER will be set.
20329    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20330
20331 static const char *
20332 psymtab_include_file_name (const struct line_header *lh, int file_index,
20333                            const struct partial_symtab *pst,
20334                            const char *comp_dir,
20335                            gdb::unique_xmalloc_ptr<char> *name_holder)
20336 {
20337   const file_entry &fe = lh->file_names[file_index];
20338   const char *include_name = fe.name;
20339   const char *include_name_to_compare = include_name;
20340   const char *pst_filename;
20341   int file_is_pst;
20342
20343   const char *dir_name = fe.include_dir (lh);
20344
20345   gdb::unique_xmalloc_ptr<char> hold_compare;
20346   if (!IS_ABSOLUTE_PATH (include_name)
20347       && (dir_name != NULL || comp_dir != NULL))
20348     {
20349       /* Avoid creating a duplicate psymtab for PST.
20350          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20351          Before we do the comparison, however, we need to account
20352          for DIR_NAME and COMP_DIR.
20353          First prepend dir_name (if non-NULL).  If we still don't
20354          have an absolute path prepend comp_dir (if non-NULL).
20355          However, the directory we record in the include-file's
20356          psymtab does not contain COMP_DIR (to match the
20357          corresponding symtab(s)).
20358
20359          Example:
20360
20361          bash$ cd /tmp
20362          bash$ gcc -g ./hello.c
20363          include_name = "hello.c"
20364          dir_name = "."
20365          DW_AT_comp_dir = comp_dir = "/tmp"
20366          DW_AT_name = "./hello.c"
20367
20368       */
20369
20370       if (dir_name != NULL)
20371         {
20372           name_holder->reset (concat (dir_name, SLASH_STRING,
20373                                       include_name, (char *) NULL));
20374           include_name = name_holder->get ();
20375           include_name_to_compare = include_name;
20376         }
20377       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20378         {
20379           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20380                                       include_name, (char *) NULL));
20381           include_name_to_compare = hold_compare.get ();
20382         }
20383     }
20384
20385   pst_filename = pst->filename;
20386   gdb::unique_xmalloc_ptr<char> copied_name;
20387   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20388     {
20389       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20390                                  pst_filename, (char *) NULL));
20391       pst_filename = copied_name.get ();
20392     }
20393
20394   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20395
20396   if (file_is_pst)
20397     return NULL;
20398   return include_name;
20399 }
20400
20401 /* State machine to track the state of the line number program.  */
20402
20403 class lnp_state_machine
20404 {
20405 public:
20406   /* Initialize a machine state for the start of a line number
20407      program.  */
20408   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20409
20410   file_entry *current_file ()
20411   {
20412     /* lh->file_names is 0-based, but the file name numbers in the
20413        statement program are 1-based.  */
20414     return m_line_header->file_name_at (m_file);
20415   }
20416
20417   /* Record the line in the state machine.  END_SEQUENCE is true if
20418      we're processing the end of a sequence.  */
20419   void record_line (bool end_sequence);
20420
20421   /* Check address and if invalid nop-out the rest of the lines in this
20422      sequence.  */
20423   void check_line_address (struct dwarf2_cu *cu,
20424                            const gdb_byte *line_ptr,
20425                            CORE_ADDR lowpc, CORE_ADDR address);
20426
20427   void handle_set_discriminator (unsigned int discriminator)
20428   {
20429     m_discriminator = discriminator;
20430     m_line_has_non_zero_discriminator |= discriminator != 0;
20431   }
20432
20433   /* Handle DW_LNE_set_address.  */
20434   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20435   {
20436     m_op_index = 0;
20437     address += baseaddr;
20438     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20439   }
20440
20441   /* Handle DW_LNS_advance_pc.  */
20442   void handle_advance_pc (CORE_ADDR adjust);
20443
20444   /* Handle a special opcode.  */
20445   void handle_special_opcode (unsigned char op_code);
20446
20447   /* Handle DW_LNS_advance_line.  */
20448   void handle_advance_line (int line_delta)
20449   {
20450     advance_line (line_delta);
20451   }
20452
20453   /* Handle DW_LNS_set_file.  */
20454   void handle_set_file (file_name_index file);
20455
20456   /* Handle DW_LNS_negate_stmt.  */
20457   void handle_negate_stmt ()
20458   {
20459     m_is_stmt = !m_is_stmt;
20460   }
20461
20462   /* Handle DW_LNS_const_add_pc.  */
20463   void handle_const_add_pc ();
20464
20465   /* Handle DW_LNS_fixed_advance_pc.  */
20466   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20467   {
20468     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20469     m_op_index = 0;
20470   }
20471
20472   /* Handle DW_LNS_copy.  */
20473   void handle_copy ()
20474   {
20475     record_line (false);
20476     m_discriminator = 0;
20477   }
20478
20479   /* Handle DW_LNE_end_sequence.  */
20480   void handle_end_sequence ()
20481   {
20482     m_record_line_callback = ::record_line;
20483   }
20484
20485 private:
20486   /* Advance the line by LINE_DELTA.  */
20487   void advance_line (int line_delta)
20488   {
20489     m_line += line_delta;
20490
20491     if (line_delta != 0)
20492       m_line_has_non_zero_discriminator = m_discriminator != 0;
20493   }
20494
20495   gdbarch *m_gdbarch;
20496
20497   /* True if we're recording lines.
20498      Otherwise we're building partial symtabs and are just interested in
20499      finding include files mentioned by the line number program.  */
20500   bool m_record_lines_p;
20501
20502   /* The line number header.  */
20503   line_header *m_line_header;
20504
20505   /* These are part of the standard DWARF line number state machine,
20506      and initialized according to the DWARF spec.  */
20507
20508   unsigned char m_op_index = 0;
20509   /* The line table index (1-based) of the current file.  */
20510   file_name_index m_file = (file_name_index) 1;
20511   unsigned int m_line = 1;
20512
20513   /* These are initialized in the constructor.  */
20514
20515   CORE_ADDR m_address;
20516   bool m_is_stmt;
20517   unsigned int m_discriminator;
20518
20519   /* Additional bits of state we need to track.  */
20520
20521   /* The last file that we called dwarf2_start_subfile for.
20522      This is only used for TLLs.  */
20523   unsigned int m_last_file = 0;
20524   /* The last file a line number was recorded for.  */
20525   struct subfile *m_last_subfile = NULL;
20526
20527   /* The function to call to record a line.  */
20528   record_line_ftype *m_record_line_callback = NULL;
20529
20530   /* The last line number that was recorded, used to coalesce
20531      consecutive entries for the same line.  This can happen, for
20532      example, when discriminators are present.  PR 17276.  */
20533   unsigned int m_last_line = 0;
20534   bool m_line_has_non_zero_discriminator = false;
20535 };
20536
20537 void
20538 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20539 {
20540   CORE_ADDR addr_adj = (((m_op_index + adjust)
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 + adjust)
20545                 % m_line_header->maximum_ops_per_instruction);
20546 }
20547
20548 void
20549 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20550 {
20551   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20552   CORE_ADDR addr_adj = (((m_op_index
20553                           + (adj_opcode / m_line_header->line_range))
20554                          / m_line_header->maximum_ops_per_instruction)
20555                         * m_line_header->minimum_instruction_length);
20556   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20557   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20558                 % m_line_header->maximum_ops_per_instruction);
20559
20560   int line_delta = (m_line_header->line_base
20561                     + (adj_opcode % m_line_header->line_range));
20562   advance_line (line_delta);
20563   record_line (false);
20564   m_discriminator = 0;
20565 }
20566
20567 void
20568 lnp_state_machine::handle_set_file (file_name_index file)
20569 {
20570   m_file = file;
20571
20572   const file_entry *fe = current_file ();
20573   if (fe == NULL)
20574     dwarf2_debug_line_missing_file_complaint ();
20575   else if (m_record_lines_p)
20576     {
20577       const char *dir = fe->include_dir (m_line_header);
20578
20579       m_last_subfile = current_subfile;
20580       m_line_has_non_zero_discriminator = m_discriminator != 0;
20581       dwarf2_start_subfile (fe->name, dir);
20582     }
20583 }
20584
20585 void
20586 lnp_state_machine::handle_const_add_pc ()
20587 {
20588   CORE_ADDR adjust
20589     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20590
20591   CORE_ADDR addr_adj
20592     = (((m_op_index + adjust)
20593         / m_line_header->maximum_ops_per_instruction)
20594        * m_line_header->minimum_instruction_length);
20595
20596   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20597   m_op_index = ((m_op_index + adjust)
20598                 % m_line_header->maximum_ops_per_instruction);
20599 }
20600
20601 /* Ignore this record_line request.  */
20602
20603 static void
20604 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20605 {
20606   return;
20607 }
20608
20609 /* Return non-zero if we should add LINE to the line number table.
20610    LINE is the line to add, LAST_LINE is the last line that was added,
20611    LAST_SUBFILE is the subfile for LAST_LINE.
20612    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20613    had a non-zero discriminator.
20614
20615    We have to be careful in the presence of discriminators.
20616    E.g., for this line:
20617
20618      for (i = 0; i < 100000; i++);
20619
20620    clang can emit four line number entries for that one line,
20621    each with a different discriminator.
20622    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20623
20624    However, we want gdb to coalesce all four entries into one.
20625    Otherwise the user could stepi into the middle of the line and
20626    gdb would get confused about whether the pc really was in the
20627    middle of the line.
20628
20629    Things are further complicated by the fact that two consecutive
20630    line number entries for the same line is a heuristic used by gcc
20631    to denote the end of the prologue.  So we can't just discard duplicate
20632    entries, we have to be selective about it.  The heuristic we use is
20633    that we only collapse consecutive entries for the same line if at least
20634    one of those entries has a non-zero discriminator.  PR 17276.
20635
20636    Note: Addresses in the line number state machine can never go backwards
20637    within one sequence, thus this coalescing is ok.  */
20638
20639 static int
20640 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20641                      int line_has_non_zero_discriminator,
20642                      struct subfile *last_subfile)
20643 {
20644   if (current_subfile != last_subfile)
20645     return 1;
20646   if (line != last_line)
20647     return 1;
20648   /* Same line for the same file that we've seen already.
20649      As a last check, for pr 17276, only record the line if the line
20650      has never had a non-zero discriminator.  */
20651   if (!line_has_non_zero_discriminator)
20652     return 1;
20653   return 0;
20654 }
20655
20656 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20657    in the line table of subfile SUBFILE.  */
20658
20659 static void
20660 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20661                      unsigned int line, CORE_ADDR address,
20662                      record_line_ftype p_record_line)
20663 {
20664   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20665
20666   if (dwarf_line_debug)
20667     {
20668       fprintf_unfiltered (gdb_stdlog,
20669                           "Recording line %u, file %s, address %s\n",
20670                           line, lbasename (subfile->name),
20671                           paddress (gdbarch, address));
20672     }
20673
20674   (*p_record_line) (subfile, line, addr);
20675 }
20676
20677 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20678    Mark the end of a set of line number records.
20679    The arguments are the same as for dwarf_record_line_1.
20680    If SUBFILE is NULL the request is ignored.  */
20681
20682 static void
20683 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20684                    CORE_ADDR address, record_line_ftype p_record_line)
20685 {
20686   if (subfile == NULL)
20687     return;
20688
20689   if (dwarf_line_debug)
20690     {
20691       fprintf_unfiltered (gdb_stdlog,
20692                           "Finishing current line, file %s, address %s\n",
20693                           lbasename (subfile->name),
20694                           paddress (gdbarch, address));
20695     }
20696
20697   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20698 }
20699
20700 void
20701 lnp_state_machine::record_line (bool end_sequence)
20702 {
20703   if (dwarf_line_debug)
20704     {
20705       fprintf_unfiltered (gdb_stdlog,
20706                           "Processing actual line %u: file %u,"
20707                           " address %s, is_stmt %u, discrim %u\n",
20708                           m_line, to_underlying (m_file),
20709                           paddress (m_gdbarch, m_address),
20710                           m_is_stmt, m_discriminator);
20711     }
20712
20713   file_entry *fe = current_file ();
20714
20715   if (fe == NULL)
20716     dwarf2_debug_line_missing_file_complaint ();
20717   /* For now we ignore lines not starting on an instruction boundary.
20718      But not when processing end_sequence for compatibility with the
20719      previous version of the code.  */
20720   else if (m_op_index == 0 || end_sequence)
20721     {
20722       fe->included_p = 1;
20723       if (m_record_lines_p && m_is_stmt)
20724         {
20725           if (m_last_subfile != current_subfile || end_sequence)
20726             {
20727               dwarf_finish_line (m_gdbarch, m_last_subfile,
20728                                  m_address, m_record_line_callback);
20729             }
20730
20731           if (!end_sequence)
20732             {
20733               if (dwarf_record_line_p (m_line, m_last_line,
20734                                        m_line_has_non_zero_discriminator,
20735                                        m_last_subfile))
20736                 {
20737                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20738                                        m_line, m_address,
20739                                        m_record_line_callback);
20740                 }
20741               m_last_subfile = current_subfile;
20742               m_last_line = m_line;
20743             }
20744         }
20745     }
20746 }
20747
20748 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20749                                       bool record_lines_p)
20750 {
20751   m_gdbarch = arch;
20752   m_record_lines_p = record_lines_p;
20753   m_line_header = lh;
20754
20755   m_record_line_callback = ::record_line;
20756
20757   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20758      was a line entry for it so that the backend has a chance to adjust it
20759      and also record it in case it needs it.  This is currently used by MIPS
20760      code, cf. `mips_adjust_dwarf2_line'.  */
20761   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20762   m_is_stmt = lh->default_is_stmt;
20763   m_discriminator = 0;
20764 }
20765
20766 void
20767 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20768                                        const gdb_byte *line_ptr,
20769                                        CORE_ADDR lowpc, CORE_ADDR address)
20770 {
20771   /* If address < lowpc then it's not a usable value, it's outside the
20772      pc range of the CU.  However, we restrict the test to only address
20773      values of zero to preserve GDB's previous behaviour which is to
20774      handle the specific case of a function being GC'd by the linker.  */
20775
20776   if (address == 0 && address < lowpc)
20777     {
20778       /* This line table is for a function which has been
20779          GCd by the linker.  Ignore it.  PR gdb/12528 */
20780
20781       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20782       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20783
20784       complaint (&symfile_complaints,
20785                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20786                  line_offset, objfile_name (objfile));
20787       m_record_line_callback = noop_record_line;
20788       /* Note: record_line_callback is left as noop_record_line until
20789          we see DW_LNE_end_sequence.  */
20790     }
20791 }
20792
20793 /* Subroutine of dwarf_decode_lines to simplify it.
20794    Process the line number information in LH.
20795    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20796    program in order to set included_p for every referenced header.  */
20797
20798 static void
20799 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20800                       const int decode_for_pst_p, CORE_ADDR lowpc)
20801 {
20802   const gdb_byte *line_ptr, *extended_end;
20803   const gdb_byte *line_end;
20804   unsigned int bytes_read, extended_len;
20805   unsigned char op_code, extended_op;
20806   CORE_ADDR baseaddr;
20807   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20808   bfd *abfd = objfile->obfd;
20809   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20810   /* True if we're recording line info (as opposed to building partial
20811      symtabs and just interested in finding include files mentioned by
20812      the line number program).  */
20813   bool record_lines_p = !decode_for_pst_p;
20814
20815   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20816
20817   line_ptr = lh->statement_program_start;
20818   line_end = lh->statement_program_end;
20819
20820   /* Read the statement sequences until there's nothing left.  */
20821   while (line_ptr < line_end)
20822     {
20823       /* The DWARF line number program state machine.  Reset the state
20824          machine at the start of each sequence.  */
20825       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20826       bool end_sequence = false;
20827
20828       if (record_lines_p)
20829         {
20830           /* Start a subfile for the current file of the state
20831              machine.  */
20832           const file_entry *fe = state_machine.current_file ();
20833
20834           if (fe != NULL)
20835             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20836         }
20837
20838       /* Decode the table.  */
20839       while (line_ptr < line_end && !end_sequence)
20840         {
20841           op_code = read_1_byte (abfd, line_ptr);
20842           line_ptr += 1;
20843
20844           if (op_code >= lh->opcode_base)
20845             {
20846               /* Special opcode.  */
20847               state_machine.handle_special_opcode (op_code);
20848             }
20849           else switch (op_code)
20850             {
20851             case DW_LNS_extended_op:
20852               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20853                                                    &bytes_read);
20854               line_ptr += bytes_read;
20855               extended_end = line_ptr + extended_len;
20856               extended_op = read_1_byte (abfd, line_ptr);
20857               line_ptr += 1;
20858               switch (extended_op)
20859                 {
20860                 case DW_LNE_end_sequence:
20861                   state_machine.handle_end_sequence ();
20862                   end_sequence = true;
20863                   break;
20864                 case DW_LNE_set_address:
20865                   {
20866                     CORE_ADDR address
20867                       = read_address (abfd, line_ptr, cu, &bytes_read);
20868                     line_ptr += bytes_read;
20869
20870                     state_machine.check_line_address (cu, line_ptr,
20871                                                       lowpc, address);
20872                     state_machine.handle_set_address (baseaddr, address);
20873                   }
20874                   break;
20875                 case DW_LNE_define_file:
20876                   {
20877                     const char *cur_file;
20878                     unsigned int mod_time, length;
20879                     dir_index dindex;
20880
20881                     cur_file = read_direct_string (abfd, line_ptr,
20882                                                    &bytes_read);
20883                     line_ptr += bytes_read;
20884                     dindex = (dir_index)
20885                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20886                     line_ptr += bytes_read;
20887                     mod_time =
20888                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20889                     line_ptr += bytes_read;
20890                     length =
20891                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20892                     line_ptr += bytes_read;
20893                     lh->add_file_name (cur_file, dindex, mod_time, length);
20894                   }
20895                   break;
20896                 case DW_LNE_set_discriminator:
20897                   {
20898                     /* The discriminator is not interesting to the
20899                        debugger; just ignore it.  We still need to
20900                        check its value though:
20901                        if there are consecutive entries for the same
20902                        (non-prologue) line we want to coalesce them.
20903                        PR 17276.  */
20904                     unsigned int discr
20905                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20906                     line_ptr += bytes_read;
20907
20908                     state_machine.handle_set_discriminator (discr);
20909                   }
20910                   break;
20911                 default:
20912                   complaint (&symfile_complaints,
20913                              _("mangled .debug_line section"));
20914                   return;
20915                 }
20916               /* Make sure that we parsed the extended op correctly.  If e.g.
20917                  we expected a different address size than the producer used,
20918                  we may have read the wrong number of bytes.  */
20919               if (line_ptr != extended_end)
20920                 {
20921                   complaint (&symfile_complaints,
20922                              _("mangled .debug_line section"));
20923                   return;
20924                 }
20925               break;
20926             case DW_LNS_copy:
20927               state_machine.handle_copy ();
20928               break;
20929             case DW_LNS_advance_pc:
20930               {
20931                 CORE_ADDR adjust
20932                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20933                 line_ptr += bytes_read;
20934
20935                 state_machine.handle_advance_pc (adjust);
20936               }
20937               break;
20938             case DW_LNS_advance_line:
20939               {
20940                 int line_delta
20941                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20942                 line_ptr += bytes_read;
20943
20944                 state_machine.handle_advance_line (line_delta);
20945               }
20946               break;
20947             case DW_LNS_set_file:
20948               {
20949                 file_name_index file
20950                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20951                                                             &bytes_read);
20952                 line_ptr += bytes_read;
20953
20954                 state_machine.handle_set_file (file);
20955               }
20956               break;
20957             case DW_LNS_set_column:
20958               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20959               line_ptr += bytes_read;
20960               break;
20961             case DW_LNS_negate_stmt:
20962               state_machine.handle_negate_stmt ();
20963               break;
20964             case DW_LNS_set_basic_block:
20965               break;
20966             /* Add to the address register of the state machine the
20967                address increment value corresponding to special opcode
20968                255.  I.e., this value is scaled by the minimum
20969                instruction length since special opcode 255 would have
20970                scaled the increment.  */
20971             case DW_LNS_const_add_pc:
20972               state_machine.handle_const_add_pc ();
20973               break;
20974             case DW_LNS_fixed_advance_pc:
20975               {
20976                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20977                 line_ptr += 2;
20978
20979                 state_machine.handle_fixed_advance_pc (addr_adj);
20980               }
20981               break;
20982             default:
20983               {
20984                 /* Unknown standard opcode, ignore it.  */
20985                 int i;
20986
20987                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20988                   {
20989                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20990                     line_ptr += bytes_read;
20991                   }
20992               }
20993             }
20994         }
20995
20996       if (!end_sequence)
20997         dwarf2_debug_line_missing_end_sequence_complaint ();
20998
20999       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21000          in which case we still finish recording the last line).  */
21001       state_machine.record_line (true);
21002     }
21003 }
21004
21005 /* Decode the Line Number Program (LNP) for the given line_header
21006    structure and CU.  The actual information extracted and the type
21007    of structures created from the LNP depends on the value of PST.
21008
21009    1. If PST is NULL, then this procedure uses the data from the program
21010       to create all necessary symbol tables, and their linetables.
21011
21012    2. If PST is not NULL, this procedure reads the program to determine
21013       the list of files included by the unit represented by PST, and
21014       builds all the associated partial symbol tables.
21015
21016    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21017    It is used for relative paths in the line table.
21018    NOTE: When processing partial symtabs (pst != NULL),
21019    comp_dir == pst->dirname.
21020
21021    NOTE: It is important that psymtabs have the same file name (via strcmp)
21022    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21023    symtab we don't use it in the name of the psymtabs we create.
21024    E.g. expand_line_sal requires this when finding psymtabs to expand.
21025    A good testcase for this is mb-inline.exp.
21026
21027    LOWPC is the lowest address in CU (or 0 if not known).
21028
21029    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21030    for its PC<->lines mapping information.  Otherwise only the filename
21031    table is read in.  */
21032
21033 static void
21034 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21035                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21036                     CORE_ADDR lowpc, int decode_mapping)
21037 {
21038   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21039   const int decode_for_pst_p = (pst != NULL);
21040
21041   if (decode_mapping)
21042     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21043
21044   if (decode_for_pst_p)
21045     {
21046       int file_index;
21047
21048       /* Now that we're done scanning the Line Header Program, we can
21049          create the psymtab of each included file.  */
21050       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21051         if (lh->file_names[file_index].included_p == 1)
21052           {
21053             gdb::unique_xmalloc_ptr<char> name_holder;
21054             const char *include_name =
21055               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21056                                          &name_holder);
21057             if (include_name != NULL)
21058               dwarf2_create_include_psymtab (include_name, pst, objfile);
21059           }
21060     }
21061   else
21062     {
21063       /* Make sure a symtab is created for every file, even files
21064          which contain only variables (i.e. no code with associated
21065          line numbers).  */
21066       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21067       int i;
21068
21069       for (i = 0; i < lh->file_names.size (); i++)
21070         {
21071           file_entry &fe = lh->file_names[i];
21072
21073           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21074
21075           if (current_subfile->symtab == NULL)
21076             {
21077               current_subfile->symtab
21078                 = allocate_symtab (cust, current_subfile->name);
21079             }
21080           fe.symtab = current_subfile->symtab;
21081         }
21082     }
21083 }
21084
21085 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21086    DIRNAME the name of the source directory which contains FILENAME
21087    or NULL if not known.
21088    This routine tries to keep line numbers from identical absolute and
21089    relative file names in a common subfile.
21090
21091    Using the `list' example from the GDB testsuite, which resides in
21092    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21093    of /srcdir/list0.c yields the following debugging information for list0.c:
21094
21095    DW_AT_name:          /srcdir/list0.c
21096    DW_AT_comp_dir:      /compdir
21097    files.files[0].name: list0.h
21098    files.files[0].dir:  /srcdir
21099    files.files[1].name: list0.c
21100    files.files[1].dir:  /srcdir
21101
21102    The line number information for list0.c has to end up in a single
21103    subfile, so that `break /srcdir/list0.c:1' works as expected.
21104    start_subfile will ensure that this happens provided that we pass the
21105    concatenation of files.files[1].dir and files.files[1].name as the
21106    subfile's name.  */
21107
21108 static void
21109 dwarf2_start_subfile (const char *filename, const char *dirname)
21110 {
21111   char *copy = NULL;
21112
21113   /* In order not to lose the line information directory,
21114      we concatenate it to the filename when it makes sense.
21115      Note that the Dwarf3 standard says (speaking of filenames in line
21116      information): ``The directory index is ignored for file names
21117      that represent full path names''.  Thus ignoring dirname in the
21118      `else' branch below isn't an issue.  */
21119
21120   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21121     {
21122       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21123       filename = copy;
21124     }
21125
21126   start_subfile (filename);
21127
21128   if (copy != NULL)
21129     xfree (copy);
21130 }
21131
21132 /* Start a symtab for DWARF.
21133    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21134
21135 static struct compunit_symtab *
21136 dwarf2_start_symtab (struct dwarf2_cu *cu,
21137                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21138 {
21139   struct compunit_symtab *cust
21140     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21141                     low_pc, cu->language);
21142
21143   record_debugformat ("DWARF 2");
21144   record_producer (cu->producer);
21145
21146   /* We assume that we're processing GCC output.  */
21147   processing_gcc_compilation = 2;
21148
21149   cu->processing_has_namespace_info = 0;
21150
21151   return cust;
21152 }
21153
21154 static void
21155 var_decode_location (struct attribute *attr, struct symbol *sym,
21156                      struct dwarf2_cu *cu)
21157 {
21158   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21159   struct comp_unit_head *cu_header = &cu->header;
21160
21161   /* NOTE drow/2003-01-30: There used to be a comment and some special
21162      code here to turn a symbol with DW_AT_external and a
21163      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21164      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21165      with some versions of binutils) where shared libraries could have
21166      relocations against symbols in their debug information - the
21167      minimal symbol would have the right address, but the debug info
21168      would not.  It's no longer necessary, because we will explicitly
21169      apply relocations when we read in the debug information now.  */
21170
21171   /* A DW_AT_location attribute with no contents indicates that a
21172      variable has been optimized away.  */
21173   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21174     {
21175       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21176       return;
21177     }
21178
21179   /* Handle one degenerate form of location expression specially, to
21180      preserve GDB's previous behavior when section offsets are
21181      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21182      then mark this symbol as LOC_STATIC.  */
21183
21184   if (attr_form_is_block (attr)
21185       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21186            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21187           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21188               && (DW_BLOCK (attr)->size
21189                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21190     {
21191       unsigned int dummy;
21192
21193       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21194         SYMBOL_VALUE_ADDRESS (sym) =
21195           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21196       else
21197         SYMBOL_VALUE_ADDRESS (sym) =
21198           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21199       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21200       fixup_symbol_section (sym, objfile);
21201       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21202                                               SYMBOL_SECTION (sym));
21203       return;
21204     }
21205
21206   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21207      expression evaluator, and use LOC_COMPUTED only when necessary
21208      (i.e. when the value of a register or memory location is
21209      referenced, or a thread-local block, etc.).  Then again, it might
21210      not be worthwhile.  I'm assuming that it isn't unless performance
21211      or memory numbers show me otherwise.  */
21212
21213   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21214
21215   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21216     cu->has_loclist = 1;
21217 }
21218
21219 /* Given a pointer to a DWARF information entry, figure out if we need
21220    to make a symbol table entry for it, and if so, create a new entry
21221    and return a pointer to it.
21222    If TYPE is NULL, determine symbol type from the die, otherwise
21223    used the passed type.
21224    If SPACE is not NULL, use it to hold the new symbol.  If it is
21225    NULL, allocate a new symbol on the objfile's obstack.  */
21226
21227 static struct symbol *
21228 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21229             struct symbol *space)
21230 {
21231   struct dwarf2_per_objfile *dwarf2_per_objfile
21232     = cu->per_cu->dwarf2_per_objfile;
21233   struct objfile *objfile = dwarf2_per_objfile->objfile;
21234   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21235   struct symbol *sym = NULL;
21236   const char *name;
21237   struct attribute *attr = NULL;
21238   struct attribute *attr2 = NULL;
21239   CORE_ADDR baseaddr;
21240   struct pending **list_to_add = NULL;
21241
21242   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21243
21244   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21245
21246   name = dwarf2_name (die, cu);
21247   if (name)
21248     {
21249       const char *linkagename;
21250       int suppress_add = 0;
21251
21252       if (space)
21253         sym = space;
21254       else
21255         sym = allocate_symbol (objfile);
21256       OBJSTAT (objfile, n_syms++);
21257
21258       /* Cache this symbol's name and the name's demangled form (if any).  */
21259       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21260       linkagename = dwarf2_physname (name, die, cu);
21261       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21262
21263       /* Fortran does not have mangling standard and the mangling does differ
21264          between gfortran, iFort etc.  */
21265       if (cu->language == language_fortran
21266           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21267         symbol_set_demangled_name (&(sym->ginfo),
21268                                    dwarf2_full_name (name, die, cu),
21269                                    NULL);
21270
21271       /* Default assumptions.
21272          Use the passed type or decode it from the die.  */
21273       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21274       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21275       if (type != NULL)
21276         SYMBOL_TYPE (sym) = type;
21277       else
21278         SYMBOL_TYPE (sym) = die_type (die, cu);
21279       attr = dwarf2_attr (die,
21280                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21281                           cu);
21282       if (attr)
21283         {
21284           SYMBOL_LINE (sym) = DW_UNSND (attr);
21285         }
21286
21287       attr = dwarf2_attr (die,
21288                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21289                           cu);
21290       if (attr)
21291         {
21292           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21293           struct file_entry *fe;
21294
21295           if (cu->line_header != NULL)
21296             fe = cu->line_header->file_name_at (file_index);
21297           else
21298             fe = NULL;
21299
21300           if (fe == NULL)
21301             complaint (&symfile_complaints,
21302                        _("file index out of range"));
21303           else
21304             symbol_set_symtab (sym, fe->symtab);
21305         }
21306
21307       switch (die->tag)
21308         {
21309         case DW_TAG_label:
21310           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21311           if (attr)
21312             {
21313               CORE_ADDR addr;
21314
21315               addr = attr_value_as_address (attr);
21316               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21317               SYMBOL_VALUE_ADDRESS (sym) = addr;
21318             }
21319           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21320           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21321           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21322           add_symbol_to_list (sym, cu->list_in_scope);
21323           break;
21324         case DW_TAG_subprogram:
21325           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21326              finish_block.  */
21327           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21328           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21329           if ((attr2 && (DW_UNSND (attr2) != 0))
21330               || cu->language == language_ada)
21331             {
21332               /* Subprograms marked external are stored as a global symbol.
21333                  Ada subprograms, whether marked external or not, are always
21334                  stored as a global symbol, because we want to be able to
21335                  access them globally.  For instance, we want to be able
21336                  to break on a nested subprogram without having to
21337                  specify the context.  */
21338               list_to_add = &global_symbols;
21339             }
21340           else
21341             {
21342               list_to_add = cu->list_in_scope;
21343             }
21344           break;
21345         case DW_TAG_inlined_subroutine:
21346           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21347              finish_block.  */
21348           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21349           SYMBOL_INLINED (sym) = 1;
21350           list_to_add = cu->list_in_scope;
21351           break;
21352         case DW_TAG_template_value_param:
21353           suppress_add = 1;
21354           /* Fall through.  */
21355         case DW_TAG_constant:
21356         case DW_TAG_variable:
21357         case DW_TAG_member:
21358           /* Compilation with minimal debug info may result in
21359              variables with missing type entries.  Change the
21360              misleading `void' type to something sensible.  */
21361           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21362             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21363
21364           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21365           /* In the case of DW_TAG_member, we should only be called for
21366              static const members.  */
21367           if (die->tag == DW_TAG_member)
21368             {
21369               /* dwarf2_add_field uses die_is_declaration,
21370                  so we do the same.  */
21371               gdb_assert (die_is_declaration (die, cu));
21372               gdb_assert (attr);
21373             }
21374           if (attr)
21375             {
21376               dwarf2_const_value (attr, sym, cu);
21377               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21378               if (!suppress_add)
21379                 {
21380                   if (attr2 && (DW_UNSND (attr2) != 0))
21381                     list_to_add = &global_symbols;
21382                   else
21383                     list_to_add = cu->list_in_scope;
21384                 }
21385               break;
21386             }
21387           attr = dwarf2_attr (die, DW_AT_location, cu);
21388           if (attr)
21389             {
21390               var_decode_location (attr, sym, cu);
21391               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21392
21393               /* Fortran explicitly imports any global symbols to the local
21394                  scope by DW_TAG_common_block.  */
21395               if (cu->language == language_fortran && die->parent
21396                   && die->parent->tag == DW_TAG_common_block)
21397                 attr2 = NULL;
21398
21399               if (SYMBOL_CLASS (sym) == LOC_STATIC
21400                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21401                   && !dwarf2_per_objfile->has_section_at_zero)
21402                 {
21403                   /* When a static variable is eliminated by the linker,
21404                      the corresponding debug information is not stripped
21405                      out, but the variable address is set to null;
21406                      do not add such variables into symbol table.  */
21407                 }
21408               else if (attr2 && (DW_UNSND (attr2) != 0))
21409                 {
21410                   /* Workaround gfortran PR debug/40040 - it uses
21411                      DW_AT_location for variables in -fPIC libraries which may
21412                      get overriden by other libraries/executable and get
21413                      a different address.  Resolve it by the minimal symbol
21414                      which may come from inferior's executable using copy
21415                      relocation.  Make this workaround only for gfortran as for
21416                      other compilers GDB cannot guess the minimal symbol
21417                      Fortran mangling kind.  */
21418                   if (cu->language == language_fortran && die->parent
21419                       && die->parent->tag == DW_TAG_module
21420                       && cu->producer
21421                       && startswith (cu->producer, "GNU Fortran"))
21422                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21423
21424                   /* A variable with DW_AT_external is never static,
21425                      but it may be block-scoped.  */
21426                   list_to_add = (cu->list_in_scope == &file_symbols
21427                                  ? &global_symbols : cu->list_in_scope);
21428                 }
21429               else
21430                 list_to_add = cu->list_in_scope;
21431             }
21432           else
21433             {
21434               /* We do not know the address of this symbol.
21435                  If it is an external symbol and we have type information
21436                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21437                  The address of the variable will then be determined from
21438                  the minimal symbol table whenever the variable is
21439                  referenced.  */
21440               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21441
21442               /* Fortran explicitly imports any global symbols to the local
21443                  scope by DW_TAG_common_block.  */
21444               if (cu->language == language_fortran && die->parent
21445                   && die->parent->tag == DW_TAG_common_block)
21446                 {
21447                   /* SYMBOL_CLASS doesn't matter here because
21448                      read_common_block is going to reset it.  */
21449                   if (!suppress_add)
21450                     list_to_add = cu->list_in_scope;
21451                 }
21452               else if (attr2 && (DW_UNSND (attr2) != 0)
21453                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21454                 {
21455                   /* A variable with DW_AT_external is never static, but it
21456                      may be block-scoped.  */
21457                   list_to_add = (cu->list_in_scope == &file_symbols
21458                                  ? &global_symbols : cu->list_in_scope);
21459
21460                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21461                 }
21462               else if (!die_is_declaration (die, cu))
21463                 {
21464                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21465                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21466                   if (!suppress_add)
21467                     list_to_add = cu->list_in_scope;
21468                 }
21469             }
21470           break;
21471         case DW_TAG_formal_parameter:
21472           /* If we are inside a function, mark this as an argument.  If
21473              not, we might be looking at an argument to an inlined function
21474              when we do not have enough information to show inlined frames;
21475              pretend it's a local variable in that case so that the user can
21476              still see it.  */
21477           if (context_stack_depth > 0
21478               && context_stack[context_stack_depth - 1].name != NULL)
21479             SYMBOL_IS_ARGUMENT (sym) = 1;
21480           attr = dwarf2_attr (die, DW_AT_location, cu);
21481           if (attr)
21482             {
21483               var_decode_location (attr, sym, cu);
21484             }
21485           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21486           if (attr)
21487             {
21488               dwarf2_const_value (attr, sym, cu);
21489             }
21490
21491           list_to_add = cu->list_in_scope;
21492           break;
21493         case DW_TAG_unspecified_parameters:
21494           /* From varargs functions; gdb doesn't seem to have any
21495              interest in this information, so just ignore it for now.
21496              (FIXME?) */
21497           break;
21498         case DW_TAG_template_type_param:
21499           suppress_add = 1;
21500           /* Fall through.  */
21501         case DW_TAG_class_type:
21502         case DW_TAG_interface_type:
21503         case DW_TAG_structure_type:
21504         case DW_TAG_union_type:
21505         case DW_TAG_set_type:
21506         case DW_TAG_enumeration_type:
21507           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21508           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21509
21510           {
21511             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21512                really ever be static objects: otherwise, if you try
21513                to, say, break of a class's method and you're in a file
21514                which doesn't mention that class, it won't work unless
21515                the check for all static symbols in lookup_symbol_aux
21516                saves you.  See the OtherFileClass tests in
21517                gdb.c++/namespace.exp.  */
21518
21519             if (!suppress_add)
21520               {
21521                 list_to_add = (cu->list_in_scope == &file_symbols
21522                                && cu->language == language_cplus
21523                                ? &global_symbols : cu->list_in_scope);
21524
21525                 /* The semantics of C++ state that "struct foo {
21526                    ... }" also defines a typedef for "foo".  */
21527                 if (cu->language == language_cplus
21528                     || cu->language == language_ada
21529                     || cu->language == language_d
21530                     || cu->language == language_rust)
21531                   {
21532                     /* The symbol's name is already allocated along
21533                        with this objfile, so we don't need to
21534                        duplicate it for the type.  */
21535                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21536                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21537                   }
21538               }
21539           }
21540           break;
21541         case DW_TAG_typedef:
21542           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21543           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21544           list_to_add = cu->list_in_scope;
21545           break;
21546         case DW_TAG_base_type:
21547         case DW_TAG_subrange_type:
21548           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21549           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21550           list_to_add = cu->list_in_scope;
21551           break;
21552         case DW_TAG_enumerator:
21553           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21554           if (attr)
21555             {
21556               dwarf2_const_value (attr, sym, cu);
21557             }
21558           {
21559             /* NOTE: carlton/2003-11-10: See comment above in the
21560                DW_TAG_class_type, etc. block.  */
21561
21562             list_to_add = (cu->list_in_scope == &file_symbols
21563                            && cu->language == language_cplus
21564                            ? &global_symbols : cu->list_in_scope);
21565           }
21566           break;
21567         case DW_TAG_imported_declaration:
21568         case DW_TAG_namespace:
21569           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21570           list_to_add = &global_symbols;
21571           break;
21572         case DW_TAG_module:
21573           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21574           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21575           list_to_add = &global_symbols;
21576           break;
21577         case DW_TAG_common_block:
21578           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21579           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21580           add_symbol_to_list (sym, cu->list_in_scope);
21581           break;
21582         default:
21583           /* Not a tag we recognize.  Hopefully we aren't processing
21584              trash data, but since we must specifically ignore things
21585              we don't recognize, there is nothing else we should do at
21586              this point.  */
21587           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21588                      dwarf_tag_name (die->tag));
21589           break;
21590         }
21591
21592       if (suppress_add)
21593         {
21594           sym->hash_next = objfile->template_symbols;
21595           objfile->template_symbols = sym;
21596           list_to_add = NULL;
21597         }
21598
21599       if (list_to_add != NULL)
21600         add_symbol_to_list (sym, list_to_add);
21601
21602       /* For the benefit of old versions of GCC, check for anonymous
21603          namespaces based on the demangled name.  */
21604       if (!cu->processing_has_namespace_info
21605           && cu->language == language_cplus)
21606         cp_scan_for_anonymous_namespaces (sym, objfile);
21607     }
21608   return (sym);
21609 }
21610
21611 /* Given an attr with a DW_FORM_dataN value in host byte order,
21612    zero-extend it as appropriate for the symbol's type.  The DWARF
21613    standard (v4) is not entirely clear about the meaning of using
21614    DW_FORM_dataN for a constant with a signed type, where the type is
21615    wider than the data.  The conclusion of a discussion on the DWARF
21616    list was that this is unspecified.  We choose to always zero-extend
21617    because that is the interpretation long in use by GCC.  */
21618
21619 static gdb_byte *
21620 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21621                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21622 {
21623   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21624   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21625                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21626   LONGEST l = DW_UNSND (attr);
21627
21628   if (bits < sizeof (*value) * 8)
21629     {
21630       l &= ((LONGEST) 1 << bits) - 1;
21631       *value = l;
21632     }
21633   else if (bits == sizeof (*value) * 8)
21634     *value = l;
21635   else
21636     {
21637       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21638       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21639       return bytes;
21640     }
21641
21642   return NULL;
21643 }
21644
21645 /* Read a constant value from an attribute.  Either set *VALUE, or if
21646    the value does not fit in *VALUE, set *BYTES - either already
21647    allocated on the objfile obstack, or newly allocated on OBSTACK,
21648    or, set *BATON, if we translated the constant to a location
21649    expression.  */
21650
21651 static void
21652 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21653                          const char *name, struct obstack *obstack,
21654                          struct dwarf2_cu *cu,
21655                          LONGEST *value, const gdb_byte **bytes,
21656                          struct dwarf2_locexpr_baton **baton)
21657 {
21658   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21659   struct comp_unit_head *cu_header = &cu->header;
21660   struct dwarf_block *blk;
21661   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21662                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21663
21664   *value = 0;
21665   *bytes = NULL;
21666   *baton = NULL;
21667
21668   switch (attr->form)
21669     {
21670     case DW_FORM_addr:
21671     case DW_FORM_GNU_addr_index:
21672       {
21673         gdb_byte *data;
21674
21675         if (TYPE_LENGTH (type) != cu_header->addr_size)
21676           dwarf2_const_value_length_mismatch_complaint (name,
21677                                                         cu_header->addr_size,
21678                                                         TYPE_LENGTH (type));
21679         /* Symbols of this form are reasonably rare, so we just
21680            piggyback on the existing location code rather than writing
21681            a new implementation of symbol_computed_ops.  */
21682         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21683         (*baton)->per_cu = cu->per_cu;
21684         gdb_assert ((*baton)->per_cu);
21685
21686         (*baton)->size = 2 + cu_header->addr_size;
21687         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21688         (*baton)->data = data;
21689
21690         data[0] = DW_OP_addr;
21691         store_unsigned_integer (&data[1], cu_header->addr_size,
21692                                 byte_order, DW_ADDR (attr));
21693         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21694       }
21695       break;
21696     case DW_FORM_string:
21697     case DW_FORM_strp:
21698     case DW_FORM_GNU_str_index:
21699     case DW_FORM_GNU_strp_alt:
21700       /* DW_STRING is already allocated on the objfile obstack, point
21701          directly to it.  */
21702       *bytes = (const gdb_byte *) DW_STRING (attr);
21703       break;
21704     case DW_FORM_block1:
21705     case DW_FORM_block2:
21706     case DW_FORM_block4:
21707     case DW_FORM_block:
21708     case DW_FORM_exprloc:
21709     case DW_FORM_data16:
21710       blk = DW_BLOCK (attr);
21711       if (TYPE_LENGTH (type) != blk->size)
21712         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21713                                                       TYPE_LENGTH (type));
21714       *bytes = blk->data;
21715       break;
21716
21717       /* The DW_AT_const_value attributes are supposed to carry the
21718          symbol's value "represented as it would be on the target
21719          architecture."  By the time we get here, it's already been
21720          converted to host endianness, so we just need to sign- or
21721          zero-extend it as appropriate.  */
21722     case DW_FORM_data1:
21723       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21724       break;
21725     case DW_FORM_data2:
21726       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21727       break;
21728     case DW_FORM_data4:
21729       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21730       break;
21731     case DW_FORM_data8:
21732       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21733       break;
21734
21735     case DW_FORM_sdata:
21736     case DW_FORM_implicit_const:
21737       *value = DW_SND (attr);
21738       break;
21739
21740     case DW_FORM_udata:
21741       *value = DW_UNSND (attr);
21742       break;
21743
21744     default:
21745       complaint (&symfile_complaints,
21746                  _("unsupported const value attribute form: '%s'"),
21747                  dwarf_form_name (attr->form));
21748       *value = 0;
21749       break;
21750     }
21751 }
21752
21753
21754 /* Copy constant value from an attribute to a symbol.  */
21755
21756 static void
21757 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21758                     struct dwarf2_cu *cu)
21759 {
21760   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21761   LONGEST value;
21762   const gdb_byte *bytes;
21763   struct dwarf2_locexpr_baton *baton;
21764
21765   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21766                            SYMBOL_PRINT_NAME (sym),
21767                            &objfile->objfile_obstack, cu,
21768                            &value, &bytes, &baton);
21769
21770   if (baton != NULL)
21771     {
21772       SYMBOL_LOCATION_BATON (sym) = baton;
21773       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21774     }
21775   else if (bytes != NULL)
21776      {
21777       SYMBOL_VALUE_BYTES (sym) = bytes;
21778       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21779     }
21780   else
21781     {
21782       SYMBOL_VALUE (sym) = value;
21783       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21784     }
21785 }
21786
21787 /* Return the type of the die in question using its DW_AT_type attribute.  */
21788
21789 static struct type *
21790 die_type (struct die_info *die, struct dwarf2_cu *cu)
21791 {
21792   struct attribute *type_attr;
21793
21794   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21795   if (!type_attr)
21796     {
21797       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21798       /* A missing DW_AT_type represents a void type.  */
21799       return objfile_type (objfile)->builtin_void;
21800     }
21801
21802   return lookup_die_type (die, type_attr, cu);
21803 }
21804
21805 /* True iff CU's producer generates GNAT Ada auxiliary information
21806    that allows to find parallel types through that information instead
21807    of having to do expensive parallel lookups by type name.  */
21808
21809 static int
21810 need_gnat_info (struct dwarf2_cu *cu)
21811 {
21812   /* Assume that the Ada compiler was GNAT, which always produces
21813      the auxiliary information.  */
21814   return (cu->language == language_ada);
21815 }
21816
21817 /* Return the auxiliary type of the die in question using its
21818    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21819    attribute is not present.  */
21820
21821 static struct type *
21822 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21823 {
21824   struct attribute *type_attr;
21825
21826   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21827   if (!type_attr)
21828     return NULL;
21829
21830   return lookup_die_type (die, type_attr, cu);
21831 }
21832
21833 /* If DIE has a descriptive_type attribute, then set the TYPE's
21834    descriptive type accordingly.  */
21835
21836 static void
21837 set_descriptive_type (struct type *type, struct die_info *die,
21838                       struct dwarf2_cu *cu)
21839 {
21840   struct type *descriptive_type = die_descriptive_type (die, cu);
21841
21842   if (descriptive_type)
21843     {
21844       ALLOCATE_GNAT_AUX_TYPE (type);
21845       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21846     }
21847 }
21848
21849 /* Return the containing type of the die in question using its
21850    DW_AT_containing_type attribute.  */
21851
21852 static struct type *
21853 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21854 {
21855   struct attribute *type_attr;
21856   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21857
21858   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21859   if (!type_attr)
21860     error (_("Dwarf Error: Problem turning containing type into gdb type "
21861              "[in module %s]"), objfile_name (objfile));
21862
21863   return lookup_die_type (die, type_attr, cu);
21864 }
21865
21866 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21867
21868 static struct type *
21869 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21870 {
21871   struct dwarf2_per_objfile *dwarf2_per_objfile
21872     = cu->per_cu->dwarf2_per_objfile;
21873   struct objfile *objfile = dwarf2_per_objfile->objfile;
21874   char *message, *saved;
21875
21876   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21877                         objfile_name (objfile),
21878                         sect_offset_str (cu->header.sect_off),
21879                         sect_offset_str (die->sect_off));
21880   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21881                                   message, strlen (message));
21882   xfree (message);
21883
21884   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21885 }
21886
21887 /* Look up the type of DIE in CU using its type attribute ATTR.
21888    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21889    DW_AT_containing_type.
21890    If there is no type substitute an error marker.  */
21891
21892 static struct type *
21893 lookup_die_type (struct die_info *die, const struct attribute *attr,
21894                  struct dwarf2_cu *cu)
21895 {
21896   struct dwarf2_per_objfile *dwarf2_per_objfile
21897     = cu->per_cu->dwarf2_per_objfile;
21898   struct objfile *objfile = dwarf2_per_objfile->objfile;
21899   struct type *this_type;
21900
21901   gdb_assert (attr->name == DW_AT_type
21902               || attr->name == DW_AT_GNAT_descriptive_type
21903               || attr->name == DW_AT_containing_type);
21904
21905   /* First see if we have it cached.  */
21906
21907   if (attr->form == DW_FORM_GNU_ref_alt)
21908     {
21909       struct dwarf2_per_cu_data *per_cu;
21910       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21911
21912       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21913                                                  dwarf2_per_objfile);
21914       this_type = get_die_type_at_offset (sect_off, per_cu);
21915     }
21916   else if (attr_form_is_ref (attr))
21917     {
21918       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21919
21920       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21921     }
21922   else if (attr->form == DW_FORM_ref_sig8)
21923     {
21924       ULONGEST signature = DW_SIGNATURE (attr);
21925
21926       return get_signatured_type (die, signature, cu);
21927     }
21928   else
21929     {
21930       complaint (&symfile_complaints,
21931                  _("Dwarf Error: Bad type attribute %s in DIE"
21932                    " at %s [in module %s]"),
21933                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21934                  objfile_name (objfile));
21935       return build_error_marker_type (cu, die);
21936     }
21937
21938   /* If not cached we need to read it in.  */
21939
21940   if (this_type == NULL)
21941     {
21942       struct die_info *type_die = NULL;
21943       struct dwarf2_cu *type_cu = cu;
21944
21945       if (attr_form_is_ref (attr))
21946         type_die = follow_die_ref (die, attr, &type_cu);
21947       if (type_die == NULL)
21948         return build_error_marker_type (cu, die);
21949       /* If we find the type now, it's probably because the type came
21950          from an inter-CU reference and the type's CU got expanded before
21951          ours.  */
21952       this_type = read_type_die (type_die, type_cu);
21953     }
21954
21955   /* If we still don't have a type use an error marker.  */
21956
21957   if (this_type == NULL)
21958     return build_error_marker_type (cu, die);
21959
21960   return this_type;
21961 }
21962
21963 /* Return the type in DIE, CU.
21964    Returns NULL for invalid types.
21965
21966    This first does a lookup in die_type_hash,
21967    and only reads the die in if necessary.
21968
21969    NOTE: This can be called when reading in partial or full symbols.  */
21970
21971 static struct type *
21972 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21973 {
21974   struct type *this_type;
21975
21976   this_type = get_die_type (die, cu);
21977   if (this_type)
21978     return this_type;
21979
21980   return read_type_die_1 (die, cu);
21981 }
21982
21983 /* Read the type in DIE, CU.
21984    Returns NULL for invalid types.  */
21985
21986 static struct type *
21987 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21988 {
21989   struct type *this_type = NULL;
21990
21991   switch (die->tag)
21992     {
21993     case DW_TAG_class_type:
21994     case DW_TAG_interface_type:
21995     case DW_TAG_structure_type:
21996     case DW_TAG_union_type:
21997       this_type = read_structure_type (die, cu);
21998       break;
21999     case DW_TAG_enumeration_type:
22000       this_type = read_enumeration_type (die, cu);
22001       break;
22002     case DW_TAG_subprogram:
22003     case DW_TAG_subroutine_type:
22004     case DW_TAG_inlined_subroutine:
22005       this_type = read_subroutine_type (die, cu);
22006       break;
22007     case DW_TAG_array_type:
22008       this_type = read_array_type (die, cu);
22009       break;
22010     case DW_TAG_set_type:
22011       this_type = read_set_type (die, cu);
22012       break;
22013     case DW_TAG_pointer_type:
22014       this_type = read_tag_pointer_type (die, cu);
22015       break;
22016     case DW_TAG_ptr_to_member_type:
22017       this_type = read_tag_ptr_to_member_type (die, cu);
22018       break;
22019     case DW_TAG_reference_type:
22020       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22021       break;
22022     case DW_TAG_rvalue_reference_type:
22023       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22024       break;
22025     case DW_TAG_const_type:
22026       this_type = read_tag_const_type (die, cu);
22027       break;
22028     case DW_TAG_volatile_type:
22029       this_type = read_tag_volatile_type (die, cu);
22030       break;
22031     case DW_TAG_restrict_type:
22032       this_type = read_tag_restrict_type (die, cu);
22033       break;
22034     case DW_TAG_string_type:
22035       this_type = read_tag_string_type (die, cu);
22036       break;
22037     case DW_TAG_typedef:
22038       this_type = read_typedef (die, cu);
22039       break;
22040     case DW_TAG_subrange_type:
22041       this_type = read_subrange_type (die, cu);
22042       break;
22043     case DW_TAG_base_type:
22044       this_type = read_base_type (die, cu);
22045       break;
22046     case DW_TAG_unspecified_type:
22047       this_type = read_unspecified_type (die, cu);
22048       break;
22049     case DW_TAG_namespace:
22050       this_type = read_namespace_type (die, cu);
22051       break;
22052     case DW_TAG_module:
22053       this_type = read_module_type (die, cu);
22054       break;
22055     case DW_TAG_atomic_type:
22056       this_type = read_tag_atomic_type (die, cu);
22057       break;
22058     default:
22059       complaint (&symfile_complaints,
22060                  _("unexpected tag in read_type_die: '%s'"),
22061                  dwarf_tag_name (die->tag));
22062       break;
22063     }
22064
22065   return this_type;
22066 }
22067
22068 /* See if we can figure out if the class lives in a namespace.  We do
22069    this by looking for a member function; its demangled name will
22070    contain namespace info, if there is any.
22071    Return the computed name or NULL.
22072    Space for the result is allocated on the objfile's obstack.
22073    This is the full-die version of guess_partial_die_structure_name.
22074    In this case we know DIE has no useful parent.  */
22075
22076 static char *
22077 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22078 {
22079   struct die_info *spec_die;
22080   struct dwarf2_cu *spec_cu;
22081   struct die_info *child;
22082   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22083
22084   spec_cu = cu;
22085   spec_die = die_specification (die, &spec_cu);
22086   if (spec_die != NULL)
22087     {
22088       die = spec_die;
22089       cu = spec_cu;
22090     }
22091
22092   for (child = die->child;
22093        child != NULL;
22094        child = child->sibling)
22095     {
22096       if (child->tag == DW_TAG_subprogram)
22097         {
22098           const char *linkage_name = dw2_linkage_name (child, cu);
22099
22100           if (linkage_name != NULL)
22101             {
22102               char *actual_name
22103                 = language_class_name_from_physname (cu->language_defn,
22104                                                      linkage_name);
22105               char *name = NULL;
22106
22107               if (actual_name != NULL)
22108                 {
22109                   const char *die_name = dwarf2_name (die, cu);
22110
22111                   if (die_name != NULL
22112                       && strcmp (die_name, actual_name) != 0)
22113                     {
22114                       /* Strip off the class name from the full name.
22115                          We want the prefix.  */
22116                       int die_name_len = strlen (die_name);
22117                       int actual_name_len = strlen (actual_name);
22118
22119                       /* Test for '::' as a sanity check.  */
22120                       if (actual_name_len > die_name_len + 2
22121                           && actual_name[actual_name_len
22122                                          - die_name_len - 1] == ':')
22123                         name = (char *) obstack_copy0 (
22124                           &objfile->per_bfd->storage_obstack,
22125                           actual_name, actual_name_len - die_name_len - 2);
22126                     }
22127                 }
22128               xfree (actual_name);
22129               return name;
22130             }
22131         }
22132     }
22133
22134   return NULL;
22135 }
22136
22137 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22138    prefix part in such case.  See
22139    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22140
22141 static const char *
22142 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22143 {
22144   struct attribute *attr;
22145   const char *base;
22146
22147   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22148       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22149     return NULL;
22150
22151   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22152     return NULL;
22153
22154   attr = dw2_linkage_name_attr (die, cu);
22155   if (attr == NULL || DW_STRING (attr) == NULL)
22156     return NULL;
22157
22158   /* dwarf2_name had to be already called.  */
22159   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22160
22161   /* Strip the base name, keep any leading namespaces/classes.  */
22162   base = strrchr (DW_STRING (attr), ':');
22163   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22164     return "";
22165
22166   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22167   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22168                                  DW_STRING (attr),
22169                                  &base[-1] - DW_STRING (attr));
22170 }
22171
22172 /* Return the name of the namespace/class that DIE is defined within,
22173    or "" if we can't tell.  The caller should not xfree the result.
22174
22175    For example, if we're within the method foo() in the following
22176    code:
22177
22178    namespace N {
22179      class C {
22180        void foo () {
22181        }
22182      };
22183    }
22184
22185    then determine_prefix on foo's die will return "N::C".  */
22186
22187 static const char *
22188 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22189 {
22190   struct dwarf2_per_objfile *dwarf2_per_objfile
22191     = cu->per_cu->dwarf2_per_objfile;
22192   struct die_info *parent, *spec_die;
22193   struct dwarf2_cu *spec_cu;
22194   struct type *parent_type;
22195   const char *retval;
22196
22197   if (cu->language != language_cplus
22198       && cu->language != language_fortran && cu->language != language_d
22199       && cu->language != language_rust)
22200     return "";
22201
22202   retval = anonymous_struct_prefix (die, cu);
22203   if (retval)
22204     return retval;
22205
22206   /* We have to be careful in the presence of DW_AT_specification.
22207      For example, with GCC 3.4, given the code
22208
22209      namespace N {
22210        void foo() {
22211          // Definition of N::foo.
22212        }
22213      }
22214
22215      then we'll have a tree of DIEs like this:
22216
22217      1: DW_TAG_compile_unit
22218        2: DW_TAG_namespace        // N
22219          3: DW_TAG_subprogram     // declaration of N::foo
22220        4: DW_TAG_subprogram       // definition of N::foo
22221             DW_AT_specification   // refers to die #3
22222
22223      Thus, when processing die #4, we have to pretend that we're in
22224      the context of its DW_AT_specification, namely the contex of die
22225      #3.  */
22226   spec_cu = cu;
22227   spec_die = die_specification (die, &spec_cu);
22228   if (spec_die == NULL)
22229     parent = die->parent;
22230   else
22231     {
22232       parent = spec_die->parent;
22233       cu = spec_cu;
22234     }
22235
22236   if (parent == NULL)
22237     return "";
22238   else if (parent->building_fullname)
22239     {
22240       const char *name;
22241       const char *parent_name;
22242
22243       /* It has been seen on RealView 2.2 built binaries,
22244          DW_TAG_template_type_param types actually _defined_ as
22245          children of the parent class:
22246
22247          enum E {};
22248          template class <class Enum> Class{};
22249          Class<enum E> class_e;
22250
22251          1: DW_TAG_class_type (Class)
22252            2: DW_TAG_enumeration_type (E)
22253              3: DW_TAG_enumerator (enum1:0)
22254              3: DW_TAG_enumerator (enum2:1)
22255              ...
22256            2: DW_TAG_template_type_param
22257               DW_AT_type  DW_FORM_ref_udata (E)
22258
22259          Besides being broken debug info, it can put GDB into an
22260          infinite loop.  Consider:
22261
22262          When we're building the full name for Class<E>, we'll start
22263          at Class, and go look over its template type parameters,
22264          finding E.  We'll then try to build the full name of E, and
22265          reach here.  We're now trying to build the full name of E,
22266          and look over the parent DIE for containing scope.  In the
22267          broken case, if we followed the parent DIE of E, we'd again
22268          find Class, and once again go look at its template type
22269          arguments, etc., etc.  Simply don't consider such parent die
22270          as source-level parent of this die (it can't be, the language
22271          doesn't allow it), and break the loop here.  */
22272       name = dwarf2_name (die, cu);
22273       parent_name = dwarf2_name (parent, cu);
22274       complaint (&symfile_complaints,
22275                  _("template param type '%s' defined within parent '%s'"),
22276                  name ? name : "<unknown>",
22277                  parent_name ? parent_name : "<unknown>");
22278       return "";
22279     }
22280   else
22281     switch (parent->tag)
22282       {
22283       case DW_TAG_namespace:
22284         parent_type = read_type_die (parent, cu);
22285         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22286            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22287            Work around this problem here.  */
22288         if (cu->language == language_cplus
22289             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22290           return "";
22291         /* We give a name to even anonymous namespaces.  */
22292         return TYPE_TAG_NAME (parent_type);
22293       case DW_TAG_class_type:
22294       case DW_TAG_interface_type:
22295       case DW_TAG_structure_type:
22296       case DW_TAG_union_type:
22297       case DW_TAG_module:
22298         parent_type = read_type_die (parent, cu);
22299         if (TYPE_TAG_NAME (parent_type) != NULL)
22300           return TYPE_TAG_NAME (parent_type);
22301         else
22302           /* An anonymous structure is only allowed non-static data
22303              members; no typedefs, no member functions, et cetera.
22304              So it does not need a prefix.  */
22305           return "";
22306       case DW_TAG_compile_unit:
22307       case DW_TAG_partial_unit:
22308         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22309         if (cu->language == language_cplus
22310             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22311             && die->child != NULL
22312             && (die->tag == DW_TAG_class_type
22313                 || die->tag == DW_TAG_structure_type
22314                 || die->tag == DW_TAG_union_type))
22315           {
22316             char *name = guess_full_die_structure_name (die, cu);
22317             if (name != NULL)
22318               return name;
22319           }
22320         return "";
22321       case DW_TAG_enumeration_type:
22322         parent_type = read_type_die (parent, cu);
22323         if (TYPE_DECLARED_CLASS (parent_type))
22324           {
22325             if (TYPE_TAG_NAME (parent_type) != NULL)
22326               return TYPE_TAG_NAME (parent_type);
22327             return "";
22328           }
22329         /* Fall through.  */
22330       default:
22331         return determine_prefix (parent, cu);
22332       }
22333 }
22334
22335 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22336    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22337    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22338    an obconcat, otherwise allocate storage for the result.  The CU argument is
22339    used to determine the language and hence, the appropriate separator.  */
22340
22341 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22342
22343 static char *
22344 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22345                  int physname, struct dwarf2_cu *cu)
22346 {
22347   const char *lead = "";
22348   const char *sep;
22349
22350   if (suffix == NULL || suffix[0] == '\0'
22351       || prefix == NULL || prefix[0] == '\0')
22352     sep = "";
22353   else if (cu->language == language_d)
22354     {
22355       /* For D, the 'main' function could be defined in any module, but it
22356          should never be prefixed.  */
22357       if (strcmp (suffix, "D main") == 0)
22358         {
22359           prefix = "";
22360           sep = "";
22361         }
22362       else
22363         sep = ".";
22364     }
22365   else if (cu->language == language_fortran && physname)
22366     {
22367       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22368          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22369
22370       lead = "__";
22371       sep = "_MOD_";
22372     }
22373   else
22374     sep = "::";
22375
22376   if (prefix == NULL)
22377     prefix = "";
22378   if (suffix == NULL)
22379     suffix = "";
22380
22381   if (obs == NULL)
22382     {
22383       char *retval
22384         = ((char *)
22385            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22386
22387       strcpy (retval, lead);
22388       strcat (retval, prefix);
22389       strcat (retval, sep);
22390       strcat (retval, suffix);
22391       return retval;
22392     }
22393   else
22394     {
22395       /* We have an obstack.  */
22396       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22397     }
22398 }
22399
22400 /* Return sibling of die, NULL if no sibling.  */
22401
22402 static struct die_info *
22403 sibling_die (struct die_info *die)
22404 {
22405   return die->sibling;
22406 }
22407
22408 /* Get name of a die, return NULL if not found.  */
22409
22410 static const char *
22411 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22412                           struct obstack *obstack)
22413 {
22414   if (name && cu->language == language_cplus)
22415     {
22416       std::string canon_name = cp_canonicalize_string (name);
22417
22418       if (!canon_name.empty ())
22419         {
22420           if (canon_name != name)
22421             name = (const char *) obstack_copy0 (obstack,
22422                                                  canon_name.c_str (),
22423                                                  canon_name.length ());
22424         }
22425     }
22426
22427   return name;
22428 }
22429
22430 /* Get name of a die, return NULL if not found.
22431    Anonymous namespaces are converted to their magic string.  */
22432
22433 static const char *
22434 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22435 {
22436   struct attribute *attr;
22437   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22438
22439   attr = dwarf2_attr (die, DW_AT_name, cu);
22440   if ((!attr || !DW_STRING (attr))
22441       && die->tag != DW_TAG_namespace
22442       && die->tag != DW_TAG_class_type
22443       && die->tag != DW_TAG_interface_type
22444       && die->tag != DW_TAG_structure_type
22445       && die->tag != DW_TAG_union_type)
22446     return NULL;
22447
22448   switch (die->tag)
22449     {
22450     case DW_TAG_compile_unit:
22451     case DW_TAG_partial_unit:
22452       /* Compilation units have a DW_AT_name that is a filename, not
22453          a source language identifier.  */
22454     case DW_TAG_enumeration_type:
22455     case DW_TAG_enumerator:
22456       /* These tags always have simple identifiers already; no need
22457          to canonicalize them.  */
22458       return DW_STRING (attr);
22459
22460     case DW_TAG_namespace:
22461       if (attr != NULL && DW_STRING (attr) != NULL)
22462         return DW_STRING (attr);
22463       return CP_ANONYMOUS_NAMESPACE_STR;
22464
22465     case DW_TAG_class_type:
22466     case DW_TAG_interface_type:
22467     case DW_TAG_structure_type:
22468     case DW_TAG_union_type:
22469       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22470          structures or unions.  These were of the form "._%d" in GCC 4.1,
22471          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22472          and GCC 4.4.  We work around this problem by ignoring these.  */
22473       if (attr && DW_STRING (attr)
22474           && (startswith (DW_STRING (attr), "._")
22475               || startswith (DW_STRING (attr), "<anonymous")))
22476         return NULL;
22477
22478       /* GCC might emit a nameless typedef that has a linkage name.  See
22479          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22480       if (!attr || DW_STRING (attr) == NULL)
22481         {
22482           char *demangled = NULL;
22483
22484           attr = dw2_linkage_name_attr (die, cu);
22485           if (attr == NULL || DW_STRING (attr) == NULL)
22486             return NULL;
22487
22488           /* Avoid demangling DW_STRING (attr) the second time on a second
22489              call for the same DIE.  */
22490           if (!DW_STRING_IS_CANONICAL (attr))
22491             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22492
22493           if (demangled)
22494             {
22495               const char *base;
22496
22497               /* FIXME: we already did this for the partial symbol... */
22498               DW_STRING (attr)
22499                 = ((const char *)
22500                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22501                                   demangled, strlen (demangled)));
22502               DW_STRING_IS_CANONICAL (attr) = 1;
22503               xfree (demangled);
22504
22505               /* Strip any leading namespaces/classes, keep only the base name.
22506                  DW_AT_name for named DIEs does not contain the prefixes.  */
22507               base = strrchr (DW_STRING (attr), ':');
22508               if (base && base > DW_STRING (attr) && base[-1] == ':')
22509                 return &base[1];
22510               else
22511                 return DW_STRING (attr);
22512             }
22513         }
22514       break;
22515
22516     default:
22517       break;
22518     }
22519
22520   if (!DW_STRING_IS_CANONICAL (attr))
22521     {
22522       DW_STRING (attr)
22523         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22524                                     &objfile->per_bfd->storage_obstack);
22525       DW_STRING_IS_CANONICAL (attr) = 1;
22526     }
22527   return DW_STRING (attr);
22528 }
22529
22530 /* Return the die that this die in an extension of, or NULL if there
22531    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22532    containing the return value on output.  */
22533
22534 static struct die_info *
22535 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22536 {
22537   struct attribute *attr;
22538
22539   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22540   if (attr == NULL)
22541     return NULL;
22542
22543   return follow_die_ref (die, attr, ext_cu);
22544 }
22545
22546 /* Convert a DIE tag into its string name.  */
22547
22548 static const char *
22549 dwarf_tag_name (unsigned tag)
22550 {
22551   const char *name = get_DW_TAG_name (tag);
22552
22553   if (name == NULL)
22554     return "DW_TAG_<unknown>";
22555
22556   return name;
22557 }
22558
22559 /* Convert a DWARF attribute code into its string name.  */
22560
22561 static const char *
22562 dwarf_attr_name (unsigned attr)
22563 {
22564   const char *name;
22565
22566 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22567   if (attr == DW_AT_MIPS_fde)
22568     return "DW_AT_MIPS_fde";
22569 #else
22570   if (attr == DW_AT_HP_block_index)
22571     return "DW_AT_HP_block_index";
22572 #endif
22573
22574   name = get_DW_AT_name (attr);
22575
22576   if (name == NULL)
22577     return "DW_AT_<unknown>";
22578
22579   return name;
22580 }
22581
22582 /* Convert a DWARF value form code into its string name.  */
22583
22584 static const char *
22585 dwarf_form_name (unsigned form)
22586 {
22587   const char *name = get_DW_FORM_name (form);
22588
22589   if (name == NULL)
22590     return "DW_FORM_<unknown>";
22591
22592   return name;
22593 }
22594
22595 static const char *
22596 dwarf_bool_name (unsigned mybool)
22597 {
22598   if (mybool)
22599     return "TRUE";
22600   else
22601     return "FALSE";
22602 }
22603
22604 /* Convert a DWARF type code into its string name.  */
22605
22606 static const char *
22607 dwarf_type_encoding_name (unsigned enc)
22608 {
22609   const char *name = get_DW_ATE_name (enc);
22610
22611   if (name == NULL)
22612     return "DW_ATE_<unknown>";
22613
22614   return name;
22615 }
22616
22617 static void
22618 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22619 {
22620   unsigned int i;
22621
22622   print_spaces (indent, f);
22623   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22624                       dwarf_tag_name (die->tag), die->abbrev,
22625                       sect_offset_str (die->sect_off));
22626
22627   if (die->parent != NULL)
22628     {
22629       print_spaces (indent, f);
22630       fprintf_unfiltered (f, "  parent at offset: %s\n",
22631                           sect_offset_str (die->parent->sect_off));
22632     }
22633
22634   print_spaces (indent, f);
22635   fprintf_unfiltered (f, "  has children: %s\n",
22636            dwarf_bool_name (die->child != NULL));
22637
22638   print_spaces (indent, f);
22639   fprintf_unfiltered (f, "  attributes:\n");
22640
22641   for (i = 0; i < die->num_attrs; ++i)
22642     {
22643       print_spaces (indent, f);
22644       fprintf_unfiltered (f, "    %s (%s) ",
22645                dwarf_attr_name (die->attrs[i].name),
22646                dwarf_form_name (die->attrs[i].form));
22647
22648       switch (die->attrs[i].form)
22649         {
22650         case DW_FORM_addr:
22651         case DW_FORM_GNU_addr_index:
22652           fprintf_unfiltered (f, "address: ");
22653           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22654           break;
22655         case DW_FORM_block2:
22656         case DW_FORM_block4:
22657         case DW_FORM_block:
22658         case DW_FORM_block1:
22659           fprintf_unfiltered (f, "block: size %s",
22660                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22661           break;
22662         case DW_FORM_exprloc:
22663           fprintf_unfiltered (f, "expression: size %s",
22664                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22665           break;
22666         case DW_FORM_data16:
22667           fprintf_unfiltered (f, "constant of 16 bytes");
22668           break;
22669         case DW_FORM_ref_addr:
22670           fprintf_unfiltered (f, "ref address: ");
22671           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22672           break;
22673         case DW_FORM_GNU_ref_alt:
22674           fprintf_unfiltered (f, "alt ref address: ");
22675           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22676           break;
22677         case DW_FORM_ref1:
22678         case DW_FORM_ref2:
22679         case DW_FORM_ref4:
22680         case DW_FORM_ref8:
22681         case DW_FORM_ref_udata:
22682           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22683                               (long) (DW_UNSND (&die->attrs[i])));
22684           break;
22685         case DW_FORM_data1:
22686         case DW_FORM_data2:
22687         case DW_FORM_data4:
22688         case DW_FORM_data8:
22689         case DW_FORM_udata:
22690         case DW_FORM_sdata:
22691           fprintf_unfiltered (f, "constant: %s",
22692                               pulongest (DW_UNSND (&die->attrs[i])));
22693           break;
22694         case DW_FORM_sec_offset:
22695           fprintf_unfiltered (f, "section offset: %s",
22696                               pulongest (DW_UNSND (&die->attrs[i])));
22697           break;
22698         case DW_FORM_ref_sig8:
22699           fprintf_unfiltered (f, "signature: %s",
22700                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22701           break;
22702         case DW_FORM_string:
22703         case DW_FORM_strp:
22704         case DW_FORM_line_strp:
22705         case DW_FORM_GNU_str_index:
22706         case DW_FORM_GNU_strp_alt:
22707           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22708                    DW_STRING (&die->attrs[i])
22709                    ? DW_STRING (&die->attrs[i]) : "",
22710                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22711           break;
22712         case DW_FORM_flag:
22713           if (DW_UNSND (&die->attrs[i]))
22714             fprintf_unfiltered (f, "flag: TRUE");
22715           else
22716             fprintf_unfiltered (f, "flag: FALSE");
22717           break;
22718         case DW_FORM_flag_present:
22719           fprintf_unfiltered (f, "flag: TRUE");
22720           break;
22721         case DW_FORM_indirect:
22722           /* The reader will have reduced the indirect form to
22723              the "base form" so this form should not occur.  */
22724           fprintf_unfiltered (f, 
22725                               "unexpected attribute form: DW_FORM_indirect");
22726           break;
22727         case DW_FORM_implicit_const:
22728           fprintf_unfiltered (f, "constant: %s",
22729                               plongest (DW_SND (&die->attrs[i])));
22730           break;
22731         default:
22732           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22733                    die->attrs[i].form);
22734           break;
22735         }
22736       fprintf_unfiltered (f, "\n");
22737     }
22738 }
22739
22740 static void
22741 dump_die_for_error (struct die_info *die)
22742 {
22743   dump_die_shallow (gdb_stderr, 0, die);
22744 }
22745
22746 static void
22747 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22748 {
22749   int indent = level * 4;
22750
22751   gdb_assert (die != NULL);
22752
22753   if (level >= max_level)
22754     return;
22755
22756   dump_die_shallow (f, indent, die);
22757
22758   if (die->child != NULL)
22759     {
22760       print_spaces (indent, f);
22761       fprintf_unfiltered (f, "  Children:");
22762       if (level + 1 < max_level)
22763         {
22764           fprintf_unfiltered (f, "\n");
22765           dump_die_1 (f, level + 1, max_level, die->child);
22766         }
22767       else
22768         {
22769           fprintf_unfiltered (f,
22770                               " [not printed, max nesting level reached]\n");
22771         }
22772     }
22773
22774   if (die->sibling != NULL && level > 0)
22775     {
22776       dump_die_1 (f, level, max_level, die->sibling);
22777     }
22778 }
22779
22780 /* This is called from the pdie macro in gdbinit.in.
22781    It's not static so gcc will keep a copy callable from gdb.  */
22782
22783 void
22784 dump_die (struct die_info *die, int max_level)
22785 {
22786   dump_die_1 (gdb_stdlog, 0, max_level, die);
22787 }
22788
22789 static void
22790 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22791 {
22792   void **slot;
22793
22794   slot = htab_find_slot_with_hash (cu->die_hash, die,
22795                                    to_underlying (die->sect_off),
22796                                    INSERT);
22797
22798   *slot = die;
22799 }
22800
22801 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22802    required kind.  */
22803
22804 static sect_offset
22805 dwarf2_get_ref_die_offset (const struct attribute *attr)
22806 {
22807   if (attr_form_is_ref (attr))
22808     return (sect_offset) DW_UNSND (attr);
22809
22810   complaint (&symfile_complaints,
22811              _("unsupported die ref attribute form: '%s'"),
22812              dwarf_form_name (attr->form));
22813   return {};
22814 }
22815
22816 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22817  * the value held by the attribute is not constant.  */
22818
22819 static LONGEST
22820 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22821 {
22822   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22823     return DW_SND (attr);
22824   else if (attr->form == DW_FORM_udata
22825            || attr->form == DW_FORM_data1
22826            || attr->form == DW_FORM_data2
22827            || attr->form == DW_FORM_data4
22828            || attr->form == DW_FORM_data8)
22829     return DW_UNSND (attr);
22830   else
22831     {
22832       /* For DW_FORM_data16 see attr_form_is_constant.  */
22833       complaint (&symfile_complaints,
22834                  _("Attribute value is not a constant (%s)"),
22835                  dwarf_form_name (attr->form));
22836       return default_value;
22837     }
22838 }
22839
22840 /* Follow reference or signature attribute ATTR of SRC_DIE.
22841    On entry *REF_CU is the CU of SRC_DIE.
22842    On exit *REF_CU is the CU of the result.  */
22843
22844 static struct die_info *
22845 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22846                        struct dwarf2_cu **ref_cu)
22847 {
22848   struct die_info *die;
22849
22850   if (attr_form_is_ref (attr))
22851     die = follow_die_ref (src_die, attr, ref_cu);
22852   else if (attr->form == DW_FORM_ref_sig8)
22853     die = follow_die_sig (src_die, attr, ref_cu);
22854   else
22855     {
22856       dump_die_for_error (src_die);
22857       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22858              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22859     }
22860
22861   return die;
22862 }
22863
22864 /* Follow reference OFFSET.
22865    On entry *REF_CU is the CU of the source die referencing OFFSET.
22866    On exit *REF_CU is the CU of the result.
22867    Returns NULL if OFFSET is invalid.  */
22868
22869 static struct die_info *
22870 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22871                    struct dwarf2_cu **ref_cu)
22872 {
22873   struct die_info temp_die;
22874   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22875   struct dwarf2_per_objfile *dwarf2_per_objfile
22876     = cu->per_cu->dwarf2_per_objfile;
22877   struct objfile *objfile = dwarf2_per_objfile->objfile;
22878
22879   gdb_assert (cu->per_cu != NULL);
22880
22881   target_cu = cu;
22882
22883   if (cu->per_cu->is_debug_types)
22884     {
22885       /* .debug_types CUs cannot reference anything outside their CU.
22886          If they need to, they have to reference a signatured type via
22887          DW_FORM_ref_sig8.  */
22888       if (!offset_in_cu_p (&cu->header, sect_off))
22889         return NULL;
22890     }
22891   else if (offset_in_dwz != cu->per_cu->is_dwz
22892            || !offset_in_cu_p (&cu->header, sect_off))
22893     {
22894       struct dwarf2_per_cu_data *per_cu;
22895
22896       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22897                                                  dwarf2_per_objfile);
22898
22899       /* If necessary, add it to the queue and load its DIEs.  */
22900       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22901         load_full_comp_unit (per_cu, cu->language);
22902
22903       target_cu = per_cu->cu;
22904     }
22905   else if (cu->dies == NULL)
22906     {
22907       /* We're loading full DIEs during partial symbol reading.  */
22908       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22909       load_full_comp_unit (cu->per_cu, language_minimal);
22910     }
22911
22912   *ref_cu = target_cu;
22913   temp_die.sect_off = sect_off;
22914   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22915                                                   &temp_die,
22916                                                   to_underlying (sect_off));
22917 }
22918
22919 /* Follow reference attribute ATTR of SRC_DIE.
22920    On entry *REF_CU is the CU of SRC_DIE.
22921    On exit *REF_CU is the CU of the result.  */
22922
22923 static struct die_info *
22924 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22925                 struct dwarf2_cu **ref_cu)
22926 {
22927   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22928   struct dwarf2_cu *cu = *ref_cu;
22929   struct die_info *die;
22930
22931   die = follow_die_offset (sect_off,
22932                            (attr->form == DW_FORM_GNU_ref_alt
22933                             || cu->per_cu->is_dwz),
22934                            ref_cu);
22935   if (!die)
22936     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22937            "at %s [in module %s]"),
22938            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22939            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22940
22941   return die;
22942 }
22943
22944 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22945    Returned value is intended for DW_OP_call*.  Returned
22946    dwarf2_locexpr_baton->data has lifetime of
22947    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22948
22949 struct dwarf2_locexpr_baton
22950 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22951                                struct dwarf2_per_cu_data *per_cu,
22952                                CORE_ADDR (*get_frame_pc) (void *baton),
22953                                void *baton)
22954 {
22955   struct dwarf2_cu *cu;
22956   struct die_info *die;
22957   struct attribute *attr;
22958   struct dwarf2_locexpr_baton retval;
22959   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22960   struct dwarf2_per_objfile *dwarf2_per_objfile
22961     = get_dwarf2_per_objfile (objfile);
22962
22963   if (per_cu->cu == NULL)
22964     load_cu (per_cu);
22965   cu = per_cu->cu;
22966   if (cu == NULL)
22967     {
22968       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22969          Instead just throw an error, not much else we can do.  */
22970       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22971              sect_offset_str (sect_off), objfile_name (objfile));
22972     }
22973
22974   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22975   if (!die)
22976     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22977            sect_offset_str (sect_off), objfile_name (objfile));
22978
22979   attr = dwarf2_attr (die, DW_AT_location, cu);
22980   if (!attr)
22981     {
22982       /* DWARF: "If there is no such attribute, then there is no effect.".
22983          DATA is ignored if SIZE is 0.  */
22984
22985       retval.data = NULL;
22986       retval.size = 0;
22987     }
22988   else if (attr_form_is_section_offset (attr))
22989     {
22990       struct dwarf2_loclist_baton loclist_baton;
22991       CORE_ADDR pc = (*get_frame_pc) (baton);
22992       size_t size;
22993
22994       fill_in_loclist_baton (cu, &loclist_baton, attr);
22995
22996       retval.data = dwarf2_find_location_expression (&loclist_baton,
22997                                                      &size, pc);
22998       retval.size = size;
22999     }
23000   else
23001     {
23002       if (!attr_form_is_block (attr))
23003         error (_("Dwarf Error: DIE at %s referenced in module %s "
23004                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23005                sect_offset_str (sect_off), objfile_name (objfile));
23006
23007       retval.data = DW_BLOCK (attr)->data;
23008       retval.size = DW_BLOCK (attr)->size;
23009     }
23010   retval.per_cu = cu->per_cu;
23011
23012   age_cached_comp_units (dwarf2_per_objfile);
23013
23014   return retval;
23015 }
23016
23017 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23018    offset.  */
23019
23020 struct dwarf2_locexpr_baton
23021 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23022                              struct dwarf2_per_cu_data *per_cu,
23023                              CORE_ADDR (*get_frame_pc) (void *baton),
23024                              void *baton)
23025 {
23026   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23027
23028   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23029 }
23030
23031 /* Write a constant of a given type as target-ordered bytes into
23032    OBSTACK.  */
23033
23034 static const gdb_byte *
23035 write_constant_as_bytes (struct obstack *obstack,
23036                          enum bfd_endian byte_order,
23037                          struct type *type,
23038                          ULONGEST value,
23039                          LONGEST *len)
23040 {
23041   gdb_byte *result;
23042
23043   *len = TYPE_LENGTH (type);
23044   result = (gdb_byte *) obstack_alloc (obstack, *len);
23045   store_unsigned_integer (result, *len, byte_order, value);
23046
23047   return result;
23048 }
23049
23050 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23051    pointer to the constant bytes and set LEN to the length of the
23052    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23053    does not have a DW_AT_const_value, return NULL.  */
23054
23055 const gdb_byte *
23056 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23057                              struct dwarf2_per_cu_data *per_cu,
23058                              struct obstack *obstack,
23059                              LONGEST *len)
23060 {
23061   struct dwarf2_cu *cu;
23062   struct die_info *die;
23063   struct attribute *attr;
23064   const gdb_byte *result = NULL;
23065   struct type *type;
23066   LONGEST value;
23067   enum bfd_endian byte_order;
23068   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23069
23070   if (per_cu->cu == NULL)
23071     load_cu (per_cu);
23072   cu = per_cu->cu;
23073   if (cu == NULL)
23074     {
23075       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23076          Instead just throw an error, not much else we can do.  */
23077       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23078              sect_offset_str (sect_off), objfile_name (objfile));
23079     }
23080
23081   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23082   if (!die)
23083     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23084            sect_offset_str (sect_off), objfile_name (objfile));
23085
23086   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23087   if (attr == NULL)
23088     return NULL;
23089
23090   byte_order = (bfd_big_endian (objfile->obfd)
23091                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23092
23093   switch (attr->form)
23094     {
23095     case DW_FORM_addr:
23096     case DW_FORM_GNU_addr_index:
23097       {
23098         gdb_byte *tem;
23099
23100         *len = cu->header.addr_size;
23101         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23102         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23103         result = tem;
23104       }
23105       break;
23106     case DW_FORM_string:
23107     case DW_FORM_strp:
23108     case DW_FORM_GNU_str_index:
23109     case DW_FORM_GNU_strp_alt:
23110       /* DW_STRING is already allocated on the objfile obstack, point
23111          directly to it.  */
23112       result = (const gdb_byte *) DW_STRING (attr);
23113       *len = strlen (DW_STRING (attr));
23114       break;
23115     case DW_FORM_block1:
23116     case DW_FORM_block2:
23117     case DW_FORM_block4:
23118     case DW_FORM_block:
23119     case DW_FORM_exprloc:
23120     case DW_FORM_data16:
23121       result = DW_BLOCK (attr)->data;
23122       *len = DW_BLOCK (attr)->size;
23123       break;
23124
23125       /* The DW_AT_const_value attributes are supposed to carry the
23126          symbol's value "represented as it would be on the target
23127          architecture."  By the time we get here, it's already been
23128          converted to host endianness, so we just need to sign- or
23129          zero-extend it as appropriate.  */
23130     case DW_FORM_data1:
23131       type = die_type (die, cu);
23132       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23133       if (result == NULL)
23134         result = write_constant_as_bytes (obstack, byte_order,
23135                                           type, value, len);
23136       break;
23137     case DW_FORM_data2:
23138       type = die_type (die, cu);
23139       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23140       if (result == NULL)
23141         result = write_constant_as_bytes (obstack, byte_order,
23142                                           type, value, len);
23143       break;
23144     case DW_FORM_data4:
23145       type = die_type (die, cu);
23146       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23147       if (result == NULL)
23148         result = write_constant_as_bytes (obstack, byte_order,
23149                                           type, value, len);
23150       break;
23151     case DW_FORM_data8:
23152       type = die_type (die, cu);
23153       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23154       if (result == NULL)
23155         result = write_constant_as_bytes (obstack, byte_order,
23156                                           type, value, len);
23157       break;
23158
23159     case DW_FORM_sdata:
23160     case DW_FORM_implicit_const:
23161       type = die_type (die, cu);
23162       result = write_constant_as_bytes (obstack, byte_order,
23163                                         type, DW_SND (attr), len);
23164       break;
23165
23166     case DW_FORM_udata:
23167       type = die_type (die, cu);
23168       result = write_constant_as_bytes (obstack, byte_order,
23169                                         type, DW_UNSND (attr), len);
23170       break;
23171
23172     default:
23173       complaint (&symfile_complaints,
23174                  _("unsupported const value attribute form: '%s'"),
23175                  dwarf_form_name (attr->form));
23176       break;
23177     }
23178
23179   return result;
23180 }
23181
23182 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23183    valid type for this die is found.  */
23184
23185 struct type *
23186 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23187                                 struct dwarf2_per_cu_data *per_cu)
23188 {
23189   struct dwarf2_cu *cu;
23190   struct die_info *die;
23191
23192   if (per_cu->cu == NULL)
23193     load_cu (per_cu);
23194   cu = per_cu->cu;
23195   if (!cu)
23196     return NULL;
23197
23198   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23199   if (!die)
23200     return NULL;
23201
23202   return die_type (die, cu);
23203 }
23204
23205 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23206    PER_CU.  */
23207
23208 struct type *
23209 dwarf2_get_die_type (cu_offset die_offset,
23210                      struct dwarf2_per_cu_data *per_cu)
23211 {
23212   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23213   return get_die_type_at_offset (die_offset_sect, per_cu);
23214 }
23215
23216 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23217    On entry *REF_CU is the CU of SRC_DIE.
23218    On exit *REF_CU is the CU of the result.
23219    Returns NULL if the referenced DIE isn't found.  */
23220
23221 static struct die_info *
23222 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23223                   struct dwarf2_cu **ref_cu)
23224 {
23225   struct die_info temp_die;
23226   struct dwarf2_cu *sig_cu;
23227   struct die_info *die;
23228
23229   /* While it might be nice to assert sig_type->type == NULL here,
23230      we can get here for DW_AT_imported_declaration where we need
23231      the DIE not the type.  */
23232
23233   /* If necessary, add it to the queue and load its DIEs.  */
23234
23235   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23236     read_signatured_type (sig_type);
23237
23238   sig_cu = sig_type->per_cu.cu;
23239   gdb_assert (sig_cu != NULL);
23240   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23241   temp_die.sect_off = sig_type->type_offset_in_section;
23242   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23243                                                  to_underlying (temp_die.sect_off));
23244   if (die)
23245     {
23246       struct dwarf2_per_objfile *dwarf2_per_objfile
23247         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23248
23249       /* For .gdb_index version 7 keep track of included TUs.
23250          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23251       if (dwarf2_per_objfile->index_table != NULL
23252           && dwarf2_per_objfile->index_table->version <= 7)
23253         {
23254           VEC_safe_push (dwarf2_per_cu_ptr,
23255                          (*ref_cu)->per_cu->imported_symtabs,
23256                          sig_cu->per_cu);
23257         }
23258
23259       *ref_cu = sig_cu;
23260       return die;
23261     }
23262
23263   return NULL;
23264 }
23265
23266 /* Follow signatured type referenced by ATTR in SRC_DIE.
23267    On entry *REF_CU is the CU of SRC_DIE.
23268    On exit *REF_CU is the CU of the result.
23269    The result is the DIE of the type.
23270    If the referenced type cannot be found an error is thrown.  */
23271
23272 static struct die_info *
23273 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23274                 struct dwarf2_cu **ref_cu)
23275 {
23276   ULONGEST signature = DW_SIGNATURE (attr);
23277   struct signatured_type *sig_type;
23278   struct die_info *die;
23279
23280   gdb_assert (attr->form == DW_FORM_ref_sig8);
23281
23282   sig_type = lookup_signatured_type (*ref_cu, signature);
23283   /* sig_type will be NULL if the signatured type is missing from
23284      the debug info.  */
23285   if (sig_type == NULL)
23286     {
23287       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23288                " from DIE at %s [in module %s]"),
23289              hex_string (signature), sect_offset_str (src_die->sect_off),
23290              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23291     }
23292
23293   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23294   if (die == NULL)
23295     {
23296       dump_die_for_error (src_die);
23297       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23298                " from DIE at %s [in module %s]"),
23299              hex_string (signature), sect_offset_str (src_die->sect_off),
23300              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23301     }
23302
23303   return die;
23304 }
23305
23306 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23307    reading in and processing the type unit if necessary.  */
23308
23309 static struct type *
23310 get_signatured_type (struct die_info *die, ULONGEST signature,
23311                      struct dwarf2_cu *cu)
23312 {
23313   struct dwarf2_per_objfile *dwarf2_per_objfile
23314     = cu->per_cu->dwarf2_per_objfile;
23315   struct signatured_type *sig_type;
23316   struct dwarf2_cu *type_cu;
23317   struct die_info *type_die;
23318   struct type *type;
23319
23320   sig_type = lookup_signatured_type (cu, signature);
23321   /* sig_type will be NULL if the signatured type is missing from
23322      the debug info.  */
23323   if (sig_type == NULL)
23324     {
23325       complaint (&symfile_complaints,
23326                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23327                    " from DIE at %s [in module %s]"),
23328                  hex_string (signature), sect_offset_str (die->sect_off),
23329                  objfile_name (dwarf2_per_objfile->objfile));
23330       return build_error_marker_type (cu, die);
23331     }
23332
23333   /* If we already know the type we're done.  */
23334   if (sig_type->type != NULL)
23335     return sig_type->type;
23336
23337   type_cu = cu;
23338   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23339   if (type_die != NULL)
23340     {
23341       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23342          is created.  This is important, for example, because for c++ classes
23343          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23344       type = read_type_die (type_die, type_cu);
23345       if (type == NULL)
23346         {
23347           complaint (&symfile_complaints,
23348                      _("Dwarf Error: Cannot build signatured type %s"
23349                        " referenced from DIE at %s [in module %s]"),
23350                      hex_string (signature), sect_offset_str (die->sect_off),
23351                      objfile_name (dwarf2_per_objfile->objfile));
23352           type = build_error_marker_type (cu, die);
23353         }
23354     }
23355   else
23356     {
23357       complaint (&symfile_complaints,
23358                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23359                    " from DIE at %s [in module %s]"),
23360                  hex_string (signature), sect_offset_str (die->sect_off),
23361                  objfile_name (dwarf2_per_objfile->objfile));
23362       type = build_error_marker_type (cu, die);
23363     }
23364   sig_type->type = type;
23365
23366   return type;
23367 }
23368
23369 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23370    reading in and processing the type unit if necessary.  */
23371
23372 static struct type *
23373 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23374                           struct dwarf2_cu *cu) /* ARI: editCase function */
23375 {
23376   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23377   if (attr_form_is_ref (attr))
23378     {
23379       struct dwarf2_cu *type_cu = cu;
23380       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23381
23382       return read_type_die (type_die, type_cu);
23383     }
23384   else if (attr->form == DW_FORM_ref_sig8)
23385     {
23386       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23387     }
23388   else
23389     {
23390       struct dwarf2_per_objfile *dwarf2_per_objfile
23391         = cu->per_cu->dwarf2_per_objfile;
23392
23393       complaint (&symfile_complaints,
23394                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23395                    " at %s [in module %s]"),
23396                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23397                  objfile_name (dwarf2_per_objfile->objfile));
23398       return build_error_marker_type (cu, die);
23399     }
23400 }
23401
23402 /* Load the DIEs associated with type unit PER_CU into memory.  */
23403
23404 static void
23405 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23406 {
23407   struct signatured_type *sig_type;
23408
23409   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23410   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23411
23412   /* We have the per_cu, but we need the signatured_type.
23413      Fortunately this is an easy translation.  */
23414   gdb_assert (per_cu->is_debug_types);
23415   sig_type = (struct signatured_type *) per_cu;
23416
23417   gdb_assert (per_cu->cu == NULL);
23418
23419   read_signatured_type (sig_type);
23420
23421   gdb_assert (per_cu->cu != NULL);
23422 }
23423
23424 /* die_reader_func for read_signatured_type.
23425    This is identical to load_full_comp_unit_reader,
23426    but is kept separate for now.  */
23427
23428 static void
23429 read_signatured_type_reader (const struct die_reader_specs *reader,
23430                              const gdb_byte *info_ptr,
23431                              struct die_info *comp_unit_die,
23432                              int has_children,
23433                              void *data)
23434 {
23435   struct dwarf2_cu *cu = reader->cu;
23436
23437   gdb_assert (cu->die_hash == NULL);
23438   cu->die_hash =
23439     htab_create_alloc_ex (cu->header.length / 12,
23440                           die_hash,
23441                           die_eq,
23442                           NULL,
23443                           &cu->comp_unit_obstack,
23444                           hashtab_obstack_allocate,
23445                           dummy_obstack_deallocate);
23446
23447   if (has_children)
23448     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23449                                                   &info_ptr, comp_unit_die);
23450   cu->dies = comp_unit_die;
23451   /* comp_unit_die is not stored in die_hash, no need.  */
23452
23453   /* We try not to read any attributes in this function, because not
23454      all CUs needed for references have been loaded yet, and symbol
23455      table processing isn't initialized.  But we have to set the CU language,
23456      or we won't be able to build types correctly.
23457      Similarly, if we do not read the producer, we can not apply
23458      producer-specific interpretation.  */
23459   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23460 }
23461
23462 /* Read in a signatured type and build its CU and DIEs.
23463    If the type is a stub for the real type in a DWO file,
23464    read in the real type from the DWO file as well.  */
23465
23466 static void
23467 read_signatured_type (struct signatured_type *sig_type)
23468 {
23469   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23470
23471   gdb_assert (per_cu->is_debug_types);
23472   gdb_assert (per_cu->cu == NULL);
23473
23474   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23475                            read_signatured_type_reader, NULL);
23476   sig_type->per_cu.tu_read = 1;
23477 }
23478
23479 /* Decode simple location descriptions.
23480    Given a pointer to a dwarf block that defines a location, compute
23481    the location and return the value.
23482
23483    NOTE drow/2003-11-18: This function is called in two situations
23484    now: for the address of static or global variables (partial symbols
23485    only) and for offsets into structures which are expected to be
23486    (more or less) constant.  The partial symbol case should go away,
23487    and only the constant case should remain.  That will let this
23488    function complain more accurately.  A few special modes are allowed
23489    without complaint for global variables (for instance, global
23490    register values and thread-local values).
23491
23492    A location description containing no operations indicates that the
23493    object is optimized out.  The return value is 0 for that case.
23494    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23495    callers will only want a very basic result and this can become a
23496    complaint.
23497
23498    Note that stack[0] is unused except as a default error return.  */
23499
23500 static CORE_ADDR
23501 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23502 {
23503   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23504   size_t i;
23505   size_t size = blk->size;
23506   const gdb_byte *data = blk->data;
23507   CORE_ADDR stack[64];
23508   int stacki;
23509   unsigned int bytes_read, unsnd;
23510   gdb_byte op;
23511
23512   i = 0;
23513   stacki = 0;
23514   stack[stacki] = 0;
23515   stack[++stacki] = 0;
23516
23517   while (i < size)
23518     {
23519       op = data[i++];
23520       switch (op)
23521         {
23522         case DW_OP_lit0:
23523         case DW_OP_lit1:
23524         case DW_OP_lit2:
23525         case DW_OP_lit3:
23526         case DW_OP_lit4:
23527         case DW_OP_lit5:
23528         case DW_OP_lit6:
23529         case DW_OP_lit7:
23530         case DW_OP_lit8:
23531         case DW_OP_lit9:
23532         case DW_OP_lit10:
23533         case DW_OP_lit11:
23534         case DW_OP_lit12:
23535         case DW_OP_lit13:
23536         case DW_OP_lit14:
23537         case DW_OP_lit15:
23538         case DW_OP_lit16:
23539         case DW_OP_lit17:
23540         case DW_OP_lit18:
23541         case DW_OP_lit19:
23542         case DW_OP_lit20:
23543         case DW_OP_lit21:
23544         case DW_OP_lit22:
23545         case DW_OP_lit23:
23546         case DW_OP_lit24:
23547         case DW_OP_lit25:
23548         case DW_OP_lit26:
23549         case DW_OP_lit27:
23550         case DW_OP_lit28:
23551         case DW_OP_lit29:
23552         case DW_OP_lit30:
23553         case DW_OP_lit31:
23554           stack[++stacki] = op - DW_OP_lit0;
23555           break;
23556
23557         case DW_OP_reg0:
23558         case DW_OP_reg1:
23559         case DW_OP_reg2:
23560         case DW_OP_reg3:
23561         case DW_OP_reg4:
23562         case DW_OP_reg5:
23563         case DW_OP_reg6:
23564         case DW_OP_reg7:
23565         case DW_OP_reg8:
23566         case DW_OP_reg9:
23567         case DW_OP_reg10:
23568         case DW_OP_reg11:
23569         case DW_OP_reg12:
23570         case DW_OP_reg13:
23571         case DW_OP_reg14:
23572         case DW_OP_reg15:
23573         case DW_OP_reg16:
23574         case DW_OP_reg17:
23575         case DW_OP_reg18:
23576         case DW_OP_reg19:
23577         case DW_OP_reg20:
23578         case DW_OP_reg21:
23579         case DW_OP_reg22:
23580         case DW_OP_reg23:
23581         case DW_OP_reg24:
23582         case DW_OP_reg25:
23583         case DW_OP_reg26:
23584         case DW_OP_reg27:
23585         case DW_OP_reg28:
23586         case DW_OP_reg29:
23587         case DW_OP_reg30:
23588         case DW_OP_reg31:
23589           stack[++stacki] = op - DW_OP_reg0;
23590           if (i < size)
23591             dwarf2_complex_location_expr_complaint ();
23592           break;
23593
23594         case DW_OP_regx:
23595           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23596           i += bytes_read;
23597           stack[++stacki] = unsnd;
23598           if (i < size)
23599             dwarf2_complex_location_expr_complaint ();
23600           break;
23601
23602         case DW_OP_addr:
23603           stack[++stacki] = read_address (objfile->obfd, &data[i],
23604                                           cu, &bytes_read);
23605           i += bytes_read;
23606           break;
23607
23608         case DW_OP_const1u:
23609           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23610           i += 1;
23611           break;
23612
23613         case DW_OP_const1s:
23614           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23615           i += 1;
23616           break;
23617
23618         case DW_OP_const2u:
23619           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23620           i += 2;
23621           break;
23622
23623         case DW_OP_const2s:
23624           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23625           i += 2;
23626           break;
23627
23628         case DW_OP_const4u:
23629           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23630           i += 4;
23631           break;
23632
23633         case DW_OP_const4s:
23634           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23635           i += 4;
23636           break;
23637
23638         case DW_OP_const8u:
23639           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23640           i += 8;
23641           break;
23642
23643         case DW_OP_constu:
23644           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23645                                                   &bytes_read);
23646           i += bytes_read;
23647           break;
23648
23649         case DW_OP_consts:
23650           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23651           i += bytes_read;
23652           break;
23653
23654         case DW_OP_dup:
23655           stack[stacki + 1] = stack[stacki];
23656           stacki++;
23657           break;
23658
23659         case DW_OP_plus:
23660           stack[stacki - 1] += stack[stacki];
23661           stacki--;
23662           break;
23663
23664         case DW_OP_plus_uconst:
23665           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23666                                                  &bytes_read);
23667           i += bytes_read;
23668           break;
23669
23670         case DW_OP_minus:
23671           stack[stacki - 1] -= stack[stacki];
23672           stacki--;
23673           break;
23674
23675         case DW_OP_deref:
23676           /* If we're not the last op, then we definitely can't encode
23677              this using GDB's address_class enum.  This is valid for partial
23678              global symbols, although the variable's address will be bogus
23679              in the psymtab.  */
23680           if (i < size)
23681             dwarf2_complex_location_expr_complaint ();
23682           break;
23683
23684         case DW_OP_GNU_push_tls_address:
23685         case DW_OP_form_tls_address:
23686           /* The top of the stack has the offset from the beginning
23687              of the thread control block at which the variable is located.  */
23688           /* Nothing should follow this operator, so the top of stack would
23689              be returned.  */
23690           /* This is valid for partial global symbols, but the variable's
23691              address will be bogus in the psymtab.  Make it always at least
23692              non-zero to not look as a variable garbage collected by linker
23693              which have DW_OP_addr 0.  */
23694           if (i < size)
23695             dwarf2_complex_location_expr_complaint ();
23696           stack[stacki]++;
23697           break;
23698
23699         case DW_OP_GNU_uninit:
23700           break;
23701
23702         case DW_OP_GNU_addr_index:
23703         case DW_OP_GNU_const_index:
23704           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23705                                                          &bytes_read);
23706           i += bytes_read;
23707           break;
23708
23709         default:
23710           {
23711             const char *name = get_DW_OP_name (op);
23712
23713             if (name)
23714               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23715                          name);
23716             else
23717               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23718                          op);
23719           }
23720
23721           return (stack[stacki]);
23722         }
23723
23724       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23725          outside of the allocated space.  Also enforce minimum>0.  */
23726       if (stacki >= ARRAY_SIZE (stack) - 1)
23727         {
23728           complaint (&symfile_complaints,
23729                      _("location description stack overflow"));
23730           return 0;
23731         }
23732
23733       if (stacki <= 0)
23734         {
23735           complaint (&symfile_complaints,
23736                      _("location description stack underflow"));
23737           return 0;
23738         }
23739     }
23740   return (stack[stacki]);
23741 }
23742
23743 /* memory allocation interface */
23744
23745 static struct dwarf_block *
23746 dwarf_alloc_block (struct dwarf2_cu *cu)
23747 {
23748   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23749 }
23750
23751 static struct die_info *
23752 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23753 {
23754   struct die_info *die;
23755   size_t size = sizeof (struct die_info);
23756
23757   if (num_attrs > 1)
23758     size += (num_attrs - 1) * sizeof (struct attribute);
23759
23760   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23761   memset (die, 0, sizeof (struct die_info));
23762   return (die);
23763 }
23764
23765 \f
23766 /* Macro support.  */
23767
23768 /* Return file name relative to the compilation directory of file number I in
23769    *LH's file name table.  The result is allocated using xmalloc; the caller is
23770    responsible for freeing it.  */
23771
23772 static char *
23773 file_file_name (int file, struct line_header *lh)
23774 {
23775   /* Is the file number a valid index into the line header's file name
23776      table?  Remember that file numbers start with one, not zero.  */
23777   if (1 <= file && file <= lh->file_names.size ())
23778     {
23779       const file_entry &fe = lh->file_names[file - 1];
23780
23781       if (!IS_ABSOLUTE_PATH (fe.name))
23782         {
23783           const char *dir = fe.include_dir (lh);
23784           if (dir != NULL)
23785             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23786         }
23787       return xstrdup (fe.name);
23788     }
23789   else
23790     {
23791       /* The compiler produced a bogus file number.  We can at least
23792          record the macro definitions made in the file, even if we
23793          won't be able to find the file by name.  */
23794       char fake_name[80];
23795
23796       xsnprintf (fake_name, sizeof (fake_name),
23797                  "<bad macro file number %d>", file);
23798
23799       complaint (&symfile_complaints,
23800                  _("bad file number in macro information (%d)"),
23801                  file);
23802
23803       return xstrdup (fake_name);
23804     }
23805 }
23806
23807 /* Return the full name of file number I in *LH's file name table.
23808    Use COMP_DIR as the name of the current directory of the
23809    compilation.  The result is allocated using xmalloc; the caller is
23810    responsible for freeing it.  */
23811 static char *
23812 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23813 {
23814   /* Is the file number a valid index into the line header's file name
23815      table?  Remember that file numbers start with one, not zero.  */
23816   if (1 <= file && file <= lh->file_names.size ())
23817     {
23818       char *relative = file_file_name (file, lh);
23819
23820       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23821         return relative;
23822       return reconcat (relative, comp_dir, SLASH_STRING,
23823                        relative, (char *) NULL);
23824     }
23825   else
23826     return file_file_name (file, lh);
23827 }
23828
23829
23830 static struct macro_source_file *
23831 macro_start_file (int file, int line,
23832                   struct macro_source_file *current_file,
23833                   struct line_header *lh)
23834 {
23835   /* File name relative to the compilation directory of this source file.  */
23836   char *file_name = file_file_name (file, lh);
23837
23838   if (! current_file)
23839     {
23840       /* Note: We don't create a macro table for this compilation unit
23841          at all until we actually get a filename.  */
23842       struct macro_table *macro_table = get_macro_table ();
23843
23844       /* If we have no current file, then this must be the start_file
23845          directive for the compilation unit's main source file.  */
23846       current_file = macro_set_main (macro_table, file_name);
23847       macro_define_special (macro_table);
23848     }
23849   else
23850     current_file = macro_include (current_file, line, file_name);
23851
23852   xfree (file_name);
23853
23854   return current_file;
23855 }
23856
23857 static const char *
23858 consume_improper_spaces (const char *p, const char *body)
23859 {
23860   if (*p == ' ')
23861     {
23862       complaint (&symfile_complaints,
23863                  _("macro definition contains spaces "
23864                    "in formal argument list:\n`%s'"),
23865                  body);
23866
23867       while (*p == ' ')
23868         p++;
23869     }
23870
23871   return p;
23872 }
23873
23874
23875 static void
23876 parse_macro_definition (struct macro_source_file *file, int line,
23877                         const char *body)
23878 {
23879   const char *p;
23880
23881   /* The body string takes one of two forms.  For object-like macro
23882      definitions, it should be:
23883
23884         <macro name> " " <definition>
23885
23886      For function-like macro definitions, it should be:
23887
23888         <macro name> "() " <definition>
23889      or
23890         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23891
23892      Spaces may appear only where explicitly indicated, and in the
23893      <definition>.
23894
23895      The Dwarf 2 spec says that an object-like macro's name is always
23896      followed by a space, but versions of GCC around March 2002 omit
23897      the space when the macro's definition is the empty string.
23898
23899      The Dwarf 2 spec says that there should be no spaces between the
23900      formal arguments in a function-like macro's formal argument list,
23901      but versions of GCC around March 2002 include spaces after the
23902      commas.  */
23903
23904
23905   /* Find the extent of the macro name.  The macro name is terminated
23906      by either a space or null character (for an object-like macro) or
23907      an opening paren (for a function-like macro).  */
23908   for (p = body; *p; p++)
23909     if (*p == ' ' || *p == '(')
23910       break;
23911
23912   if (*p == ' ' || *p == '\0')
23913     {
23914       /* It's an object-like macro.  */
23915       int name_len = p - body;
23916       char *name = savestring (body, name_len);
23917       const char *replacement;
23918
23919       if (*p == ' ')
23920         replacement = body + name_len + 1;
23921       else
23922         {
23923           dwarf2_macro_malformed_definition_complaint (body);
23924           replacement = body + name_len;
23925         }
23926
23927       macro_define_object (file, line, name, replacement);
23928
23929       xfree (name);
23930     }
23931   else if (*p == '(')
23932     {
23933       /* It's a function-like macro.  */
23934       char *name = savestring (body, p - body);
23935       int argc = 0;
23936       int argv_size = 1;
23937       char **argv = XNEWVEC (char *, argv_size);
23938
23939       p++;
23940
23941       p = consume_improper_spaces (p, body);
23942
23943       /* Parse the formal argument list.  */
23944       while (*p && *p != ')')
23945         {
23946           /* Find the extent of the current argument name.  */
23947           const char *arg_start = p;
23948
23949           while (*p && *p != ',' && *p != ')' && *p != ' ')
23950             p++;
23951
23952           if (! *p || p == arg_start)
23953             dwarf2_macro_malformed_definition_complaint (body);
23954           else
23955             {
23956               /* Make sure argv has room for the new argument.  */
23957               if (argc >= argv_size)
23958                 {
23959                   argv_size *= 2;
23960                   argv = XRESIZEVEC (char *, argv, argv_size);
23961                 }
23962
23963               argv[argc++] = savestring (arg_start, p - arg_start);
23964             }
23965
23966           p = consume_improper_spaces (p, body);
23967
23968           /* Consume the comma, if present.  */
23969           if (*p == ',')
23970             {
23971               p++;
23972
23973               p = consume_improper_spaces (p, body);
23974             }
23975         }
23976
23977       if (*p == ')')
23978         {
23979           p++;
23980
23981           if (*p == ' ')
23982             /* Perfectly formed definition, no complaints.  */
23983             macro_define_function (file, line, name,
23984                                    argc, (const char **) argv,
23985                                    p + 1);
23986           else if (*p == '\0')
23987             {
23988               /* Complain, but do define it.  */
23989               dwarf2_macro_malformed_definition_complaint (body);
23990               macro_define_function (file, line, name,
23991                                      argc, (const char **) argv,
23992                                      p);
23993             }
23994           else
23995             /* Just complain.  */
23996             dwarf2_macro_malformed_definition_complaint (body);
23997         }
23998       else
23999         /* Just complain.  */
24000         dwarf2_macro_malformed_definition_complaint (body);
24001
24002       xfree (name);
24003       {
24004         int i;
24005
24006         for (i = 0; i < argc; i++)
24007           xfree (argv[i]);
24008       }
24009       xfree (argv);
24010     }
24011   else
24012     dwarf2_macro_malformed_definition_complaint (body);
24013 }
24014
24015 /* Skip some bytes from BYTES according to the form given in FORM.
24016    Returns the new pointer.  */
24017
24018 static const gdb_byte *
24019 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24020                  enum dwarf_form form,
24021                  unsigned int offset_size,
24022                  struct dwarf2_section_info *section)
24023 {
24024   unsigned int bytes_read;
24025
24026   switch (form)
24027     {
24028     case DW_FORM_data1:
24029     case DW_FORM_flag:
24030       ++bytes;
24031       break;
24032
24033     case DW_FORM_data2:
24034       bytes += 2;
24035       break;
24036
24037     case DW_FORM_data4:
24038       bytes += 4;
24039       break;
24040
24041     case DW_FORM_data8:
24042       bytes += 8;
24043       break;
24044
24045     case DW_FORM_data16:
24046       bytes += 16;
24047       break;
24048
24049     case DW_FORM_string:
24050       read_direct_string (abfd, bytes, &bytes_read);
24051       bytes += bytes_read;
24052       break;
24053
24054     case DW_FORM_sec_offset:
24055     case DW_FORM_strp:
24056     case DW_FORM_GNU_strp_alt:
24057       bytes += offset_size;
24058       break;
24059
24060     case DW_FORM_block:
24061       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24062       bytes += bytes_read;
24063       break;
24064
24065     case DW_FORM_block1:
24066       bytes += 1 + read_1_byte (abfd, bytes);
24067       break;
24068     case DW_FORM_block2:
24069       bytes += 2 + read_2_bytes (abfd, bytes);
24070       break;
24071     case DW_FORM_block4:
24072       bytes += 4 + read_4_bytes (abfd, bytes);
24073       break;
24074
24075     case DW_FORM_sdata:
24076     case DW_FORM_udata:
24077     case DW_FORM_GNU_addr_index:
24078     case DW_FORM_GNU_str_index:
24079       bytes = gdb_skip_leb128 (bytes, buffer_end);
24080       if (bytes == NULL)
24081         {
24082           dwarf2_section_buffer_overflow_complaint (section);
24083           return NULL;
24084         }
24085       break;
24086
24087     case DW_FORM_implicit_const:
24088       break;
24089
24090     default:
24091       {
24092         complaint (&symfile_complaints,
24093                    _("invalid form 0x%x in `%s'"),
24094                    form, get_section_name (section));
24095         return NULL;
24096       }
24097     }
24098
24099   return bytes;
24100 }
24101
24102 /* A helper for dwarf_decode_macros that handles skipping an unknown
24103    opcode.  Returns an updated pointer to the macro data buffer; or,
24104    on error, issues a complaint and returns NULL.  */
24105
24106 static const gdb_byte *
24107 skip_unknown_opcode (unsigned int opcode,
24108                      const gdb_byte **opcode_definitions,
24109                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24110                      bfd *abfd,
24111                      unsigned int offset_size,
24112                      struct dwarf2_section_info *section)
24113 {
24114   unsigned int bytes_read, i;
24115   unsigned long arg;
24116   const gdb_byte *defn;
24117
24118   if (opcode_definitions[opcode] == NULL)
24119     {
24120       complaint (&symfile_complaints,
24121                  _("unrecognized DW_MACFINO opcode 0x%x"),
24122                  opcode);
24123       return NULL;
24124     }
24125
24126   defn = opcode_definitions[opcode];
24127   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24128   defn += bytes_read;
24129
24130   for (i = 0; i < arg; ++i)
24131     {
24132       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24133                                  (enum dwarf_form) defn[i], offset_size,
24134                                  section);
24135       if (mac_ptr == NULL)
24136         {
24137           /* skip_form_bytes already issued the complaint.  */
24138           return NULL;
24139         }
24140     }
24141
24142   return mac_ptr;
24143 }
24144
24145 /* A helper function which parses the header of a macro section.
24146    If the macro section is the extended (for now called "GNU") type,
24147    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24148    the header, or issues a complaint and returns NULL on error.  */
24149
24150 static const gdb_byte *
24151 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24152                           bfd *abfd,
24153                           const gdb_byte *mac_ptr,
24154                           unsigned int *offset_size,
24155                           int section_is_gnu)
24156 {
24157   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24158
24159   if (section_is_gnu)
24160     {
24161       unsigned int version, flags;
24162
24163       version = read_2_bytes (abfd, mac_ptr);
24164       if (version != 4 && version != 5)
24165         {
24166           complaint (&symfile_complaints,
24167                      _("unrecognized version `%d' in .debug_macro section"),
24168                      version);
24169           return NULL;
24170         }
24171       mac_ptr += 2;
24172
24173       flags = read_1_byte (abfd, mac_ptr);
24174       ++mac_ptr;
24175       *offset_size = (flags & 1) ? 8 : 4;
24176
24177       if ((flags & 2) != 0)
24178         /* We don't need the line table offset.  */
24179         mac_ptr += *offset_size;
24180
24181       /* Vendor opcode descriptions.  */
24182       if ((flags & 4) != 0)
24183         {
24184           unsigned int i, count;
24185
24186           count = read_1_byte (abfd, mac_ptr);
24187           ++mac_ptr;
24188           for (i = 0; i < count; ++i)
24189             {
24190               unsigned int opcode, bytes_read;
24191               unsigned long arg;
24192
24193               opcode = read_1_byte (abfd, mac_ptr);
24194               ++mac_ptr;
24195               opcode_definitions[opcode] = mac_ptr;
24196               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24197               mac_ptr += bytes_read;
24198               mac_ptr += arg;
24199             }
24200         }
24201     }
24202
24203   return mac_ptr;
24204 }
24205
24206 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24207    including DW_MACRO_import.  */
24208
24209 static void
24210 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24211                           bfd *abfd,
24212                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24213                           struct macro_source_file *current_file,
24214                           struct line_header *lh,
24215                           struct dwarf2_section_info *section,
24216                           int section_is_gnu, int section_is_dwz,
24217                           unsigned int offset_size,
24218                           htab_t include_hash)
24219 {
24220   struct objfile *objfile = dwarf2_per_objfile->objfile;
24221   enum dwarf_macro_record_type macinfo_type;
24222   int at_commandline;
24223   const gdb_byte *opcode_definitions[256];
24224
24225   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24226                                       &offset_size, section_is_gnu);
24227   if (mac_ptr == NULL)
24228     {
24229       /* We already issued a complaint.  */
24230       return;
24231     }
24232
24233   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24234      GDB is still reading the definitions from command line.  First
24235      DW_MACINFO_start_file will need to be ignored as it was already executed
24236      to create CURRENT_FILE for the main source holding also the command line
24237      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24238      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24239
24240   at_commandline = 1;
24241
24242   do
24243     {
24244       /* Do we at least have room for a macinfo type byte?  */
24245       if (mac_ptr >= mac_end)
24246         {
24247           dwarf2_section_buffer_overflow_complaint (section);
24248           break;
24249         }
24250
24251       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24252       mac_ptr++;
24253
24254       /* Note that we rely on the fact that the corresponding GNU and
24255          DWARF constants are the same.  */
24256       DIAGNOSTIC_PUSH
24257       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24258       switch (macinfo_type)
24259         {
24260           /* A zero macinfo type indicates the end of the macro
24261              information.  */
24262         case 0:
24263           break;
24264
24265         case DW_MACRO_define:
24266         case DW_MACRO_undef:
24267         case DW_MACRO_define_strp:
24268         case DW_MACRO_undef_strp:
24269         case DW_MACRO_define_sup:
24270         case DW_MACRO_undef_sup:
24271           {
24272             unsigned int bytes_read;
24273             int line;
24274             const char *body;
24275             int is_define;
24276
24277             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24278             mac_ptr += bytes_read;
24279
24280             if (macinfo_type == DW_MACRO_define
24281                 || macinfo_type == DW_MACRO_undef)
24282               {
24283                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24284                 mac_ptr += bytes_read;
24285               }
24286             else
24287               {
24288                 LONGEST str_offset;
24289
24290                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24291                 mac_ptr += offset_size;
24292
24293                 if (macinfo_type == DW_MACRO_define_sup
24294                     || macinfo_type == DW_MACRO_undef_sup
24295                     || section_is_dwz)
24296                   {
24297                     struct dwz_file *dwz
24298                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24299
24300                     body = read_indirect_string_from_dwz (objfile,
24301                                                           dwz, str_offset);
24302                   }
24303                 else
24304                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24305                                                          abfd, str_offset);
24306               }
24307
24308             is_define = (macinfo_type == DW_MACRO_define
24309                          || macinfo_type == DW_MACRO_define_strp
24310                          || macinfo_type == DW_MACRO_define_sup);
24311             if (! current_file)
24312               {
24313                 /* DWARF violation as no main source is present.  */
24314                 complaint (&symfile_complaints,
24315                            _("debug info with no main source gives macro %s "
24316                              "on line %d: %s"),
24317                            is_define ? _("definition") : _("undefinition"),
24318                            line, body);
24319                 break;
24320               }
24321             if ((line == 0 && !at_commandline)
24322                 || (line != 0 && at_commandline))
24323               complaint (&symfile_complaints,
24324                          _("debug info gives %s macro %s with %s line %d: %s"),
24325                          at_commandline ? _("command-line") : _("in-file"),
24326                          is_define ? _("definition") : _("undefinition"),
24327                          line == 0 ? _("zero") : _("non-zero"), line, body);
24328
24329             if (is_define)
24330               parse_macro_definition (current_file, line, body);
24331             else
24332               {
24333                 gdb_assert (macinfo_type == DW_MACRO_undef
24334                             || macinfo_type == DW_MACRO_undef_strp
24335                             || macinfo_type == DW_MACRO_undef_sup);
24336                 macro_undef (current_file, line, body);
24337               }
24338           }
24339           break;
24340
24341         case DW_MACRO_start_file:
24342           {
24343             unsigned int bytes_read;
24344             int line, file;
24345
24346             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24347             mac_ptr += bytes_read;
24348             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24349             mac_ptr += bytes_read;
24350
24351             if ((line == 0 && !at_commandline)
24352                 || (line != 0 && at_commandline))
24353               complaint (&symfile_complaints,
24354                          _("debug info gives source %d included "
24355                            "from %s at %s line %d"),
24356                          file, at_commandline ? _("command-line") : _("file"),
24357                          line == 0 ? _("zero") : _("non-zero"), line);
24358
24359             if (at_commandline)
24360               {
24361                 /* This DW_MACRO_start_file was executed in the
24362                    pass one.  */
24363                 at_commandline = 0;
24364               }
24365             else
24366               current_file = macro_start_file (file, line, current_file, lh);
24367           }
24368           break;
24369
24370         case DW_MACRO_end_file:
24371           if (! current_file)
24372             complaint (&symfile_complaints,
24373                        _("macro debug info has an unmatched "
24374                          "`close_file' directive"));
24375           else
24376             {
24377               current_file = current_file->included_by;
24378               if (! current_file)
24379                 {
24380                   enum dwarf_macro_record_type next_type;
24381
24382                   /* GCC circa March 2002 doesn't produce the zero
24383                      type byte marking the end of the compilation
24384                      unit.  Complain if it's not there, but exit no
24385                      matter what.  */
24386
24387                   /* Do we at least have room for a macinfo type byte?  */
24388                   if (mac_ptr >= mac_end)
24389                     {
24390                       dwarf2_section_buffer_overflow_complaint (section);
24391                       return;
24392                     }
24393
24394                   /* We don't increment mac_ptr here, so this is just
24395                      a look-ahead.  */
24396                   next_type
24397                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24398                                                                   mac_ptr);
24399                   if (next_type != 0)
24400                     complaint (&symfile_complaints,
24401                                _("no terminating 0-type entry for "
24402                                  "macros in `.debug_macinfo' section"));
24403
24404                   return;
24405                 }
24406             }
24407           break;
24408
24409         case DW_MACRO_import:
24410         case DW_MACRO_import_sup:
24411           {
24412             LONGEST offset;
24413             void **slot;
24414             bfd *include_bfd = abfd;
24415             struct dwarf2_section_info *include_section = section;
24416             const gdb_byte *include_mac_end = mac_end;
24417             int is_dwz = section_is_dwz;
24418             const gdb_byte *new_mac_ptr;
24419
24420             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24421             mac_ptr += offset_size;
24422
24423             if (macinfo_type == DW_MACRO_import_sup)
24424               {
24425                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24426
24427                 dwarf2_read_section (objfile, &dwz->macro);
24428
24429                 include_section = &dwz->macro;
24430                 include_bfd = get_section_bfd_owner (include_section);
24431                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24432                 is_dwz = 1;
24433               }
24434
24435             new_mac_ptr = include_section->buffer + offset;
24436             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24437
24438             if (*slot != NULL)
24439               {
24440                 /* This has actually happened; see
24441                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24442                 complaint (&symfile_complaints,
24443                            _("recursive DW_MACRO_import in "
24444                              ".debug_macro section"));
24445               }
24446             else
24447               {
24448                 *slot = (void *) new_mac_ptr;
24449
24450                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24451                                           include_bfd, new_mac_ptr,
24452                                           include_mac_end, current_file, lh,
24453                                           section, section_is_gnu, is_dwz,
24454                                           offset_size, include_hash);
24455
24456                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24457               }
24458           }
24459           break;
24460
24461         case DW_MACINFO_vendor_ext:
24462           if (!section_is_gnu)
24463             {
24464               unsigned int bytes_read;
24465
24466               /* This reads the constant, but since we don't recognize
24467                  any vendor extensions, we ignore it.  */
24468               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24469               mac_ptr += bytes_read;
24470               read_direct_string (abfd, mac_ptr, &bytes_read);
24471               mac_ptr += bytes_read;
24472
24473               /* We don't recognize any vendor extensions.  */
24474               break;
24475             }
24476           /* FALLTHROUGH */
24477
24478         default:
24479           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24480                                          mac_ptr, mac_end, abfd, offset_size,
24481                                          section);
24482           if (mac_ptr == NULL)
24483             return;
24484           break;
24485         }
24486       DIAGNOSTIC_POP
24487     } while (macinfo_type != 0);
24488 }
24489
24490 static void
24491 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24492                      int section_is_gnu)
24493 {
24494   struct dwarf2_per_objfile *dwarf2_per_objfile
24495     = cu->per_cu->dwarf2_per_objfile;
24496   struct objfile *objfile = dwarf2_per_objfile->objfile;
24497   struct line_header *lh = cu->line_header;
24498   bfd *abfd;
24499   const gdb_byte *mac_ptr, *mac_end;
24500   struct macro_source_file *current_file = 0;
24501   enum dwarf_macro_record_type macinfo_type;
24502   unsigned int offset_size = cu->header.offset_size;
24503   const gdb_byte *opcode_definitions[256];
24504   void **slot;
24505   struct dwarf2_section_info *section;
24506   const char *section_name;
24507
24508   if (cu->dwo_unit != NULL)
24509     {
24510       if (section_is_gnu)
24511         {
24512           section = &cu->dwo_unit->dwo_file->sections.macro;
24513           section_name = ".debug_macro.dwo";
24514         }
24515       else
24516         {
24517           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24518           section_name = ".debug_macinfo.dwo";
24519         }
24520     }
24521   else
24522     {
24523       if (section_is_gnu)
24524         {
24525           section = &dwarf2_per_objfile->macro;
24526           section_name = ".debug_macro";
24527         }
24528       else
24529         {
24530           section = &dwarf2_per_objfile->macinfo;
24531           section_name = ".debug_macinfo";
24532         }
24533     }
24534
24535   dwarf2_read_section (objfile, section);
24536   if (section->buffer == NULL)
24537     {
24538       complaint (&symfile_complaints, _("missing %s section"), section_name);
24539       return;
24540     }
24541   abfd = get_section_bfd_owner (section);
24542
24543   /* First pass: Find the name of the base filename.
24544      This filename is needed in order to process all macros whose definition
24545      (or undefinition) comes from the command line.  These macros are defined
24546      before the first DW_MACINFO_start_file entry, and yet still need to be
24547      associated to the base file.
24548
24549      To determine the base file name, we scan the macro definitions until we
24550      reach the first DW_MACINFO_start_file entry.  We then initialize
24551      CURRENT_FILE accordingly so that any macro definition found before the
24552      first DW_MACINFO_start_file can still be associated to the base file.  */
24553
24554   mac_ptr = section->buffer + offset;
24555   mac_end = section->buffer + section->size;
24556
24557   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24558                                       &offset_size, section_is_gnu);
24559   if (mac_ptr == NULL)
24560     {
24561       /* We already issued a complaint.  */
24562       return;
24563     }
24564
24565   do
24566     {
24567       /* Do we at least have room for a macinfo type byte?  */
24568       if (mac_ptr >= mac_end)
24569         {
24570           /* Complaint is printed during the second pass as GDB will probably
24571              stop the first pass earlier upon finding
24572              DW_MACINFO_start_file.  */
24573           break;
24574         }
24575
24576       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24577       mac_ptr++;
24578
24579       /* Note that we rely on the fact that the corresponding GNU and
24580          DWARF constants are the same.  */
24581       DIAGNOSTIC_PUSH
24582       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24583       switch (macinfo_type)
24584         {
24585           /* A zero macinfo type indicates the end of the macro
24586              information.  */
24587         case 0:
24588           break;
24589
24590         case DW_MACRO_define:
24591         case DW_MACRO_undef:
24592           /* Only skip the data by MAC_PTR.  */
24593           {
24594             unsigned int bytes_read;
24595
24596             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24597             mac_ptr += bytes_read;
24598             read_direct_string (abfd, mac_ptr, &bytes_read);
24599             mac_ptr += bytes_read;
24600           }
24601           break;
24602
24603         case DW_MACRO_start_file:
24604           {
24605             unsigned int bytes_read;
24606             int line, file;
24607
24608             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24609             mac_ptr += bytes_read;
24610             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24611             mac_ptr += bytes_read;
24612
24613             current_file = macro_start_file (file, line, current_file, lh);
24614           }
24615           break;
24616
24617         case DW_MACRO_end_file:
24618           /* No data to skip by MAC_PTR.  */
24619           break;
24620
24621         case DW_MACRO_define_strp:
24622         case DW_MACRO_undef_strp:
24623         case DW_MACRO_define_sup:
24624         case DW_MACRO_undef_sup:
24625           {
24626             unsigned int bytes_read;
24627
24628             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24629             mac_ptr += bytes_read;
24630             mac_ptr += offset_size;
24631           }
24632           break;
24633
24634         case DW_MACRO_import:
24635         case DW_MACRO_import_sup:
24636           /* Note that, according to the spec, a transparent include
24637              chain cannot call DW_MACRO_start_file.  So, we can just
24638              skip this opcode.  */
24639           mac_ptr += offset_size;
24640           break;
24641
24642         case DW_MACINFO_vendor_ext:
24643           /* Only skip the data by MAC_PTR.  */
24644           if (!section_is_gnu)
24645             {
24646               unsigned int bytes_read;
24647
24648               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24649               mac_ptr += bytes_read;
24650               read_direct_string (abfd, mac_ptr, &bytes_read);
24651               mac_ptr += bytes_read;
24652             }
24653           /* FALLTHROUGH */
24654
24655         default:
24656           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24657                                          mac_ptr, mac_end, abfd, offset_size,
24658                                          section);
24659           if (mac_ptr == NULL)
24660             return;
24661           break;
24662         }
24663       DIAGNOSTIC_POP
24664     } while (macinfo_type != 0 && current_file == NULL);
24665
24666   /* Second pass: Process all entries.
24667
24668      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24669      command-line macro definitions/undefinitions.  This flag is unset when we
24670      reach the first DW_MACINFO_start_file entry.  */
24671
24672   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24673                                            htab_eq_pointer,
24674                                            NULL, xcalloc, xfree));
24675   mac_ptr = section->buffer + offset;
24676   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24677   *slot = (void *) mac_ptr;
24678   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24679                             abfd, mac_ptr, mac_end,
24680                             current_file, lh, section,
24681                             section_is_gnu, 0, offset_size,
24682                             include_hash.get ());
24683 }
24684
24685 /* Check if the attribute's form is a DW_FORM_block*
24686    if so return true else false.  */
24687
24688 static int
24689 attr_form_is_block (const struct attribute *attr)
24690 {
24691   return (attr == NULL ? 0 :
24692       attr->form == DW_FORM_block1
24693       || attr->form == DW_FORM_block2
24694       || attr->form == DW_FORM_block4
24695       || attr->form == DW_FORM_block
24696       || attr->form == DW_FORM_exprloc);
24697 }
24698
24699 /* Return non-zero if ATTR's value is a section offset --- classes
24700    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24701    You may use DW_UNSND (attr) to retrieve such offsets.
24702
24703    Section 7.5.4, "Attribute Encodings", explains that no attribute
24704    may have a value that belongs to more than one of these classes; it
24705    would be ambiguous if we did, because we use the same forms for all
24706    of them.  */
24707
24708 static int
24709 attr_form_is_section_offset (const struct attribute *attr)
24710 {
24711   return (attr->form == DW_FORM_data4
24712           || attr->form == DW_FORM_data8
24713           || attr->form == DW_FORM_sec_offset);
24714 }
24715
24716 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24717    zero otherwise.  When this function returns true, you can apply
24718    dwarf2_get_attr_constant_value to it.
24719
24720    However, note that for some attributes you must check
24721    attr_form_is_section_offset before using this test.  DW_FORM_data4
24722    and DW_FORM_data8 are members of both the constant class, and of
24723    the classes that contain offsets into other debug sections
24724    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24725    that, if an attribute's can be either a constant or one of the
24726    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24727    taken as section offsets, not constants.
24728
24729    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24730    cannot handle that.  */
24731
24732 static int
24733 attr_form_is_constant (const struct attribute *attr)
24734 {
24735   switch (attr->form)
24736     {
24737     case DW_FORM_sdata:
24738     case DW_FORM_udata:
24739     case DW_FORM_data1:
24740     case DW_FORM_data2:
24741     case DW_FORM_data4:
24742     case DW_FORM_data8:
24743     case DW_FORM_implicit_const:
24744       return 1;
24745     default:
24746       return 0;
24747     }
24748 }
24749
24750
24751 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24752    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24753
24754 static int
24755 attr_form_is_ref (const struct attribute *attr)
24756 {
24757   switch (attr->form)
24758     {
24759     case DW_FORM_ref_addr:
24760     case DW_FORM_ref1:
24761     case DW_FORM_ref2:
24762     case DW_FORM_ref4:
24763     case DW_FORM_ref8:
24764     case DW_FORM_ref_udata:
24765     case DW_FORM_GNU_ref_alt:
24766       return 1;
24767     default:
24768       return 0;
24769     }
24770 }
24771
24772 /* Return the .debug_loc section to use for CU.
24773    For DWO files use .debug_loc.dwo.  */
24774
24775 static struct dwarf2_section_info *
24776 cu_debug_loc_section (struct dwarf2_cu *cu)
24777 {
24778   struct dwarf2_per_objfile *dwarf2_per_objfile
24779     = cu->per_cu->dwarf2_per_objfile;
24780
24781   if (cu->dwo_unit)
24782     {
24783       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24784       
24785       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24786     }
24787   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24788                                   : &dwarf2_per_objfile->loc);
24789 }
24790
24791 /* A helper function that fills in a dwarf2_loclist_baton.  */
24792
24793 static void
24794 fill_in_loclist_baton (struct dwarf2_cu *cu,
24795                        struct dwarf2_loclist_baton *baton,
24796                        const struct attribute *attr)
24797 {
24798   struct dwarf2_per_objfile *dwarf2_per_objfile
24799     = cu->per_cu->dwarf2_per_objfile;
24800   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24801
24802   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24803
24804   baton->per_cu = cu->per_cu;
24805   gdb_assert (baton->per_cu);
24806   /* We don't know how long the location list is, but make sure we
24807      don't run off the edge of the section.  */
24808   baton->size = section->size - DW_UNSND (attr);
24809   baton->data = section->buffer + DW_UNSND (attr);
24810   baton->base_address = cu->base_address;
24811   baton->from_dwo = cu->dwo_unit != NULL;
24812 }
24813
24814 static void
24815 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24816                              struct dwarf2_cu *cu, int is_block)
24817 {
24818   struct dwarf2_per_objfile *dwarf2_per_objfile
24819     = cu->per_cu->dwarf2_per_objfile;
24820   struct objfile *objfile = dwarf2_per_objfile->objfile;
24821   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24822
24823   if (attr_form_is_section_offset (attr)
24824       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24825          the section.  If so, fall through to the complaint in the
24826          other branch.  */
24827       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24828     {
24829       struct dwarf2_loclist_baton *baton;
24830
24831       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24832
24833       fill_in_loclist_baton (cu, baton, attr);
24834
24835       if (cu->base_known == 0)
24836         complaint (&symfile_complaints,
24837                    _("Location list used without "
24838                      "specifying the CU base address."));
24839
24840       SYMBOL_ACLASS_INDEX (sym) = (is_block
24841                                    ? dwarf2_loclist_block_index
24842                                    : dwarf2_loclist_index);
24843       SYMBOL_LOCATION_BATON (sym) = baton;
24844     }
24845   else
24846     {
24847       struct dwarf2_locexpr_baton *baton;
24848
24849       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24850       baton->per_cu = cu->per_cu;
24851       gdb_assert (baton->per_cu);
24852
24853       if (attr_form_is_block (attr))
24854         {
24855           /* Note that we're just copying the block's data pointer
24856              here, not the actual data.  We're still pointing into the
24857              info_buffer for SYM's objfile; right now we never release
24858              that buffer, but when we do clean up properly this may
24859              need to change.  */
24860           baton->size = DW_BLOCK (attr)->size;
24861           baton->data = DW_BLOCK (attr)->data;
24862         }
24863       else
24864         {
24865           dwarf2_invalid_attrib_class_complaint ("location description",
24866                                                  SYMBOL_NATURAL_NAME (sym));
24867           baton->size = 0;
24868         }
24869
24870       SYMBOL_ACLASS_INDEX (sym) = (is_block
24871                                    ? dwarf2_locexpr_block_index
24872                                    : dwarf2_locexpr_index);
24873       SYMBOL_LOCATION_BATON (sym) = baton;
24874     }
24875 }
24876
24877 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24878    came from a separate debuginfo file, then the master objfile is
24879    returned.  */
24880
24881 struct objfile *
24882 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24883 {
24884   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24885
24886   /* Return the master objfile, so that we can report and look up the
24887      correct file containing this variable.  */
24888   if (objfile->separate_debug_objfile_backlink)
24889     objfile = objfile->separate_debug_objfile_backlink;
24890
24891   return objfile;
24892 }
24893
24894 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24895    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24896    CU_HEADERP first.  */
24897
24898 static const struct comp_unit_head *
24899 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24900                        struct dwarf2_per_cu_data *per_cu)
24901 {
24902   const gdb_byte *info_ptr;
24903
24904   if (per_cu->cu)
24905     return &per_cu->cu->header;
24906
24907   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24908
24909   memset (cu_headerp, 0, sizeof (*cu_headerp));
24910   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24911                        rcuh_kind::COMPILE);
24912
24913   return cu_headerp;
24914 }
24915
24916 /* Return the address size given in the compilation unit header for CU.  */
24917
24918 int
24919 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24920 {
24921   struct comp_unit_head cu_header_local;
24922   const struct comp_unit_head *cu_headerp;
24923
24924   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24925
24926   return cu_headerp->addr_size;
24927 }
24928
24929 /* Return the offset size given in the compilation unit header for CU.  */
24930
24931 int
24932 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24933 {
24934   struct comp_unit_head cu_header_local;
24935   const struct comp_unit_head *cu_headerp;
24936
24937   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24938
24939   return cu_headerp->offset_size;
24940 }
24941
24942 /* See its dwarf2loc.h declaration.  */
24943
24944 int
24945 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24946 {
24947   struct comp_unit_head cu_header_local;
24948   const struct comp_unit_head *cu_headerp;
24949
24950   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24951
24952   if (cu_headerp->version == 2)
24953     return cu_headerp->addr_size;
24954   else
24955     return cu_headerp->offset_size;
24956 }
24957
24958 /* Return the text offset of the CU.  The returned offset comes from
24959    this CU's objfile.  If this objfile came from a separate debuginfo
24960    file, then the offset may be different from the corresponding
24961    offset in the parent objfile.  */
24962
24963 CORE_ADDR
24964 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24965 {
24966   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24967
24968   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24969 }
24970
24971 /* Return DWARF version number of PER_CU.  */
24972
24973 short
24974 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24975 {
24976   return per_cu->dwarf_version;
24977 }
24978
24979 /* Locate the .debug_info compilation unit from CU's objfile which contains
24980    the DIE at OFFSET.  Raises an error on failure.  */
24981
24982 static struct dwarf2_per_cu_data *
24983 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24984                                   unsigned int offset_in_dwz,
24985                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24986 {
24987   struct dwarf2_per_cu_data *this_cu;
24988   int low, high;
24989   const sect_offset *cu_off;
24990
24991   low = 0;
24992   high = dwarf2_per_objfile->n_comp_units - 1;
24993   while (high > low)
24994     {
24995       struct dwarf2_per_cu_data *mid_cu;
24996       int mid = low + (high - low) / 2;
24997
24998       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24999       cu_off = &mid_cu->sect_off;
25000       if (mid_cu->is_dwz > offset_in_dwz
25001           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25002         high = mid;
25003       else
25004         low = mid + 1;
25005     }
25006   gdb_assert (low == high);
25007   this_cu = dwarf2_per_objfile->all_comp_units[low];
25008   cu_off = &this_cu->sect_off;
25009   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25010     {
25011       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25012         error (_("Dwarf Error: could not find partial DIE containing "
25013                "offset %s [in module %s]"),
25014                sect_offset_str (sect_off),
25015                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25016
25017       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25018                   <= sect_off);
25019       return dwarf2_per_objfile->all_comp_units[low-1];
25020     }
25021   else
25022     {
25023       this_cu = dwarf2_per_objfile->all_comp_units[low];
25024       if (low == dwarf2_per_objfile->n_comp_units - 1
25025           && sect_off >= this_cu->sect_off + this_cu->length)
25026         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25027       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25028       return this_cu;
25029     }
25030 }
25031
25032 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25033
25034 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25035   : per_cu (per_cu_),
25036     mark (0),
25037     has_loclist (0),
25038     checked_producer (0),
25039     producer_is_gxx_lt_4_6 (0),
25040     producer_is_gcc_lt_4_3 (0),
25041     producer_is_icc_lt_14 (0),
25042     processing_has_namespace_info (0)
25043 {
25044   per_cu->cu = this;
25045 }
25046
25047 /* Destroy a dwarf2_cu.  */
25048
25049 dwarf2_cu::~dwarf2_cu ()
25050 {
25051   per_cu->cu = NULL;
25052 }
25053
25054 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25055
25056 static void
25057 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25058                        enum language pretend_language)
25059 {
25060   struct attribute *attr;
25061
25062   /* Set the language we're debugging.  */
25063   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25064   if (attr)
25065     set_cu_language (DW_UNSND (attr), cu);
25066   else
25067     {
25068       cu->language = pretend_language;
25069       cu->language_defn = language_def (cu->language);
25070     }
25071
25072   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25073 }
25074
25075 /* Free all cached compilation units.  */
25076
25077 static void
25078 free_cached_comp_units (void *data)
25079 {
25080   struct dwarf2_per_objfile *dwarf2_per_objfile
25081     = (struct dwarf2_per_objfile *) data;
25082
25083   dwarf2_per_objfile->free_cached_comp_units ();
25084 }
25085
25086 /* Increase the age counter on each cached compilation unit, and free
25087    any that are too old.  */
25088
25089 static void
25090 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25091 {
25092   struct dwarf2_per_cu_data *per_cu, **last_chain;
25093
25094   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25095   per_cu = dwarf2_per_objfile->read_in_chain;
25096   while (per_cu != NULL)
25097     {
25098       per_cu->cu->last_used ++;
25099       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25100         dwarf2_mark (per_cu->cu);
25101       per_cu = per_cu->cu->read_in_chain;
25102     }
25103
25104   per_cu = dwarf2_per_objfile->read_in_chain;
25105   last_chain = &dwarf2_per_objfile->read_in_chain;
25106   while (per_cu != NULL)
25107     {
25108       struct dwarf2_per_cu_data *next_cu;
25109
25110       next_cu = per_cu->cu->read_in_chain;
25111
25112       if (!per_cu->cu->mark)
25113         {
25114           delete per_cu->cu;
25115           *last_chain = next_cu;
25116         }
25117       else
25118         last_chain = &per_cu->cu->read_in_chain;
25119
25120       per_cu = next_cu;
25121     }
25122 }
25123
25124 /* Remove a single compilation unit from the cache.  */
25125
25126 static void
25127 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25128 {
25129   struct dwarf2_per_cu_data *per_cu, **last_chain;
25130   struct dwarf2_per_objfile *dwarf2_per_objfile
25131     = target_per_cu->dwarf2_per_objfile;
25132
25133   per_cu = dwarf2_per_objfile->read_in_chain;
25134   last_chain = &dwarf2_per_objfile->read_in_chain;
25135   while (per_cu != NULL)
25136     {
25137       struct dwarf2_per_cu_data *next_cu;
25138
25139       next_cu = per_cu->cu->read_in_chain;
25140
25141       if (per_cu == target_per_cu)
25142         {
25143           delete per_cu->cu;
25144           per_cu->cu = NULL;
25145           *last_chain = next_cu;
25146           break;
25147         }
25148       else
25149         last_chain = &per_cu->cu->read_in_chain;
25150
25151       per_cu = next_cu;
25152     }
25153 }
25154
25155 /* Release all extra memory associated with OBJFILE.  */
25156
25157 void
25158 dwarf2_free_objfile (struct objfile *objfile)
25159 {
25160   struct dwarf2_per_objfile *dwarf2_per_objfile
25161     = get_dwarf2_per_objfile (objfile);
25162
25163   delete dwarf2_per_objfile;
25164 }
25165
25166 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25167    We store these in a hash table separate from the DIEs, and preserve them
25168    when the DIEs are flushed out of cache.
25169
25170    The CU "per_cu" pointer is needed because offset alone is not enough to
25171    uniquely identify the type.  A file may have multiple .debug_types sections,
25172    or the type may come from a DWO file.  Furthermore, while it's more logical
25173    to use per_cu->section+offset, with Fission the section with the data is in
25174    the DWO file but we don't know that section at the point we need it.
25175    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25176    because we can enter the lookup routine, get_die_type_at_offset, from
25177    outside this file, and thus won't necessarily have PER_CU->cu.
25178    Fortunately, PER_CU is stable for the life of the objfile.  */
25179
25180 struct dwarf2_per_cu_offset_and_type
25181 {
25182   const struct dwarf2_per_cu_data *per_cu;
25183   sect_offset sect_off;
25184   struct type *type;
25185 };
25186
25187 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25188
25189 static hashval_t
25190 per_cu_offset_and_type_hash (const void *item)
25191 {
25192   const struct dwarf2_per_cu_offset_and_type *ofs
25193     = (const struct dwarf2_per_cu_offset_and_type *) item;
25194
25195   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25196 }
25197
25198 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25199
25200 static int
25201 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25202 {
25203   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25204     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25205   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25206     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25207
25208   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25209           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25210 }
25211
25212 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25213    table if necessary.  For convenience, return TYPE.
25214
25215    The DIEs reading must have careful ordering to:
25216     * Not cause infite loops trying to read in DIEs as a prerequisite for
25217       reading current DIE.
25218     * Not trying to dereference contents of still incompletely read in types
25219       while reading in other DIEs.
25220     * Enable referencing still incompletely read in types just by a pointer to
25221       the type without accessing its fields.
25222
25223    Therefore caller should follow these rules:
25224      * Try to fetch any prerequisite types we may need to build this DIE type
25225        before building the type and calling set_die_type.
25226      * After building type call set_die_type for current DIE as soon as
25227        possible before fetching more types to complete the current type.
25228      * Make the type as complete as possible before fetching more types.  */
25229
25230 static struct type *
25231 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25232 {
25233   struct dwarf2_per_objfile *dwarf2_per_objfile
25234     = cu->per_cu->dwarf2_per_objfile;
25235   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25236   struct objfile *objfile = dwarf2_per_objfile->objfile;
25237   struct attribute *attr;
25238   struct dynamic_prop prop;
25239
25240   /* For Ada types, make sure that the gnat-specific data is always
25241      initialized (if not already set).  There are a few types where
25242      we should not be doing so, because the type-specific area is
25243      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25244      where the type-specific area is used to store the floatformat).
25245      But this is not a problem, because the gnat-specific information
25246      is actually not needed for these types.  */
25247   if (need_gnat_info (cu)
25248       && TYPE_CODE (type) != TYPE_CODE_FUNC
25249       && TYPE_CODE (type) != TYPE_CODE_FLT
25250       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25251       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25252       && TYPE_CODE (type) != TYPE_CODE_METHOD
25253       && !HAVE_GNAT_AUX_INFO (type))
25254     INIT_GNAT_SPECIFIC (type);
25255
25256   /* Read DW_AT_allocated and set in type.  */
25257   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25258   if (attr_form_is_block (attr))
25259     {
25260       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25261         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25262     }
25263   else if (attr != NULL)
25264     {
25265       complaint (&symfile_complaints,
25266                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25267                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25268                  sect_offset_str (die->sect_off));
25269     }
25270
25271   /* Read DW_AT_associated and set in type.  */
25272   attr = dwarf2_attr (die, DW_AT_associated, cu);
25273   if (attr_form_is_block (attr))
25274     {
25275       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25276         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25277     }
25278   else if (attr != NULL)
25279     {
25280       complaint (&symfile_complaints,
25281                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25282                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25283                  sect_offset_str (die->sect_off));
25284     }
25285
25286   /* Read DW_AT_data_location and set in type.  */
25287   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25288   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25289     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25290
25291   if (dwarf2_per_objfile->die_type_hash == NULL)
25292     {
25293       dwarf2_per_objfile->die_type_hash =
25294         htab_create_alloc_ex (127,
25295                               per_cu_offset_and_type_hash,
25296                               per_cu_offset_and_type_eq,
25297                               NULL,
25298                               &objfile->objfile_obstack,
25299                               hashtab_obstack_allocate,
25300                               dummy_obstack_deallocate);
25301     }
25302
25303   ofs.per_cu = cu->per_cu;
25304   ofs.sect_off = die->sect_off;
25305   ofs.type = type;
25306   slot = (struct dwarf2_per_cu_offset_and_type **)
25307     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25308   if (*slot)
25309     complaint (&symfile_complaints,
25310                _("A problem internal to GDB: DIE %s has type already set"),
25311                sect_offset_str (die->sect_off));
25312   *slot = XOBNEW (&objfile->objfile_obstack,
25313                   struct dwarf2_per_cu_offset_and_type);
25314   **slot = ofs;
25315   return type;
25316 }
25317
25318 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25319    or return NULL if the die does not have a saved type.  */
25320
25321 static struct type *
25322 get_die_type_at_offset (sect_offset sect_off,
25323                         struct dwarf2_per_cu_data *per_cu)
25324 {
25325   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25326   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25327
25328   if (dwarf2_per_objfile->die_type_hash == NULL)
25329     return NULL;
25330
25331   ofs.per_cu = per_cu;
25332   ofs.sect_off = sect_off;
25333   slot = ((struct dwarf2_per_cu_offset_and_type *)
25334           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25335   if (slot)
25336     return slot->type;
25337   else
25338     return NULL;
25339 }
25340
25341 /* Look up the type for DIE in CU in die_type_hash,
25342    or return NULL if DIE does not have a saved type.  */
25343
25344 static struct type *
25345 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25346 {
25347   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25348 }
25349
25350 /* Add a dependence relationship from CU to REF_PER_CU.  */
25351
25352 static void
25353 dwarf2_add_dependence (struct dwarf2_cu *cu,
25354                        struct dwarf2_per_cu_data *ref_per_cu)
25355 {
25356   void **slot;
25357
25358   if (cu->dependencies == NULL)
25359     cu->dependencies
25360       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25361                               NULL, &cu->comp_unit_obstack,
25362                               hashtab_obstack_allocate,
25363                               dummy_obstack_deallocate);
25364
25365   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25366   if (*slot == NULL)
25367     *slot = ref_per_cu;
25368 }
25369
25370 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25371    Set the mark field in every compilation unit in the
25372    cache that we must keep because we are keeping CU.  */
25373
25374 static int
25375 dwarf2_mark_helper (void **slot, void *data)
25376 {
25377   struct dwarf2_per_cu_data *per_cu;
25378
25379   per_cu = (struct dwarf2_per_cu_data *) *slot;
25380
25381   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25382      reading of the chain.  As such dependencies remain valid it is not much
25383      useful to track and undo them during QUIT cleanups.  */
25384   if (per_cu->cu == NULL)
25385     return 1;
25386
25387   if (per_cu->cu->mark)
25388     return 1;
25389   per_cu->cu->mark = 1;
25390
25391   if (per_cu->cu->dependencies != NULL)
25392     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25393
25394   return 1;
25395 }
25396
25397 /* Set the mark field in CU and in every other compilation unit in the
25398    cache that we must keep because we are keeping CU.  */
25399
25400 static void
25401 dwarf2_mark (struct dwarf2_cu *cu)
25402 {
25403   if (cu->mark)
25404     return;
25405   cu->mark = 1;
25406   if (cu->dependencies != NULL)
25407     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25408 }
25409
25410 static void
25411 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25412 {
25413   while (per_cu)
25414     {
25415       per_cu->cu->mark = 0;
25416       per_cu = per_cu->cu->read_in_chain;
25417     }
25418 }
25419
25420 /* Trivial hash function for partial_die_info: the hash value of a DIE
25421    is its offset in .debug_info for this objfile.  */
25422
25423 static hashval_t
25424 partial_die_hash (const void *item)
25425 {
25426   const struct partial_die_info *part_die
25427     = (const struct partial_die_info *) item;
25428
25429   return to_underlying (part_die->sect_off);
25430 }
25431
25432 /* Trivial comparison function for partial_die_info structures: two DIEs
25433    are equal if they have the same offset.  */
25434
25435 static int
25436 partial_die_eq (const void *item_lhs, const void *item_rhs)
25437 {
25438   const struct partial_die_info *part_die_lhs
25439     = (const struct partial_die_info *) item_lhs;
25440   const struct partial_die_info *part_die_rhs
25441     = (const struct partial_die_info *) item_rhs;
25442
25443   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25444 }
25445
25446 static struct cmd_list_element *set_dwarf_cmdlist;
25447 static struct cmd_list_element *show_dwarf_cmdlist;
25448
25449 static void
25450 set_dwarf_cmd (const char *args, int from_tty)
25451 {
25452   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25453              gdb_stdout);
25454 }
25455
25456 static void
25457 show_dwarf_cmd (const char *args, int from_tty)
25458 {
25459   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25460 }
25461
25462 int dwarf_always_disassemble;
25463
25464 static void
25465 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25466                                struct cmd_list_element *c, const char *value)
25467 {
25468   fprintf_filtered (file,
25469                     _("Whether to always disassemble "
25470                       "DWARF expressions is %s.\n"),
25471                     value);
25472 }
25473
25474 static void
25475 show_check_physname (struct ui_file *file, int from_tty,
25476                      struct cmd_list_element *c, const char *value)
25477 {
25478   fprintf_filtered (file,
25479                     _("Whether to check \"physname\" is %s.\n"),
25480                     value);
25481 }
25482
25483 void
25484 _initialize_dwarf2_read (void)
25485 {
25486
25487   dwarf2_objfile_data_key = register_objfile_data ();
25488
25489   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25490 Set DWARF specific variables.\n\
25491 Configure DWARF variables such as the cache size"),
25492                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25493                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25494
25495   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25496 Show DWARF specific variables\n\
25497 Show DWARF variables such as the cache size"),
25498                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25499                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25500
25501   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25502                             &dwarf_max_cache_age, _("\
25503 Set the upper bound on the age of cached DWARF compilation units."), _("\
25504 Show the upper bound on the age of cached DWARF compilation units."), _("\
25505 A higher limit means that cached compilation units will be stored\n\
25506 in memory longer, and more total memory will be used.  Zero disables\n\
25507 caching, which can slow down startup."),
25508                             NULL,
25509                             show_dwarf_max_cache_age,
25510                             &set_dwarf_cmdlist,
25511                             &show_dwarf_cmdlist);
25512
25513   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25514                            &dwarf_always_disassemble, _("\
25515 Set whether `info address' always disassembles DWARF expressions."), _("\
25516 Show whether `info address' always disassembles DWARF expressions."), _("\
25517 When enabled, DWARF expressions are always printed in an assembly-like\n\
25518 syntax.  When disabled, expressions will be printed in a more\n\
25519 conversational style, when possible."),
25520                            NULL,
25521                            show_dwarf_always_disassemble,
25522                            &set_dwarf_cmdlist,
25523                            &show_dwarf_cmdlist);
25524
25525   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25526 Set debugging of the DWARF reader."), _("\
25527 Show debugging of the DWARF reader."), _("\
25528 When enabled (non-zero), debugging messages are printed during DWARF\n\
25529 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25530 information.  A value greater than 1 provides more verbose information."),
25531                             NULL,
25532                             NULL,
25533                             &setdebuglist, &showdebuglist);
25534
25535   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25536 Set debugging of the DWARF DIE reader."), _("\
25537 Show debugging of the DWARF DIE reader."), _("\
25538 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25539 The value is the maximum depth to print."),
25540                              NULL,
25541                              NULL,
25542                              &setdebuglist, &showdebuglist);
25543
25544   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25545 Set debugging of the dwarf line reader."), _("\
25546 Show debugging of the dwarf line reader."), _("\
25547 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25548 A value of 1 (one) provides basic information.\n\
25549 A value greater than 1 provides more verbose information."),
25550                              NULL,
25551                              NULL,
25552                              &setdebuglist, &showdebuglist);
25553
25554   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25555 Set cross-checking of \"physname\" code against demangler."), _("\
25556 Show cross-checking of \"physname\" code against demangler."), _("\
25557 When enabled, GDB's internal \"physname\" code is checked against\n\
25558 the demangler."),
25559                            NULL, show_check_physname,
25560                            &setdebuglist, &showdebuglist);
25561
25562   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25563                            no_class, &use_deprecated_index_sections, _("\
25564 Set whether to use deprecated gdb_index sections."), _("\
25565 Show whether to use deprecated gdb_index sections."), _("\
25566 When enabled, deprecated .gdb_index sections are used anyway.\n\
25567 Normally they are ignored either because of a missing feature or\n\
25568 performance issue.\n\
25569 Warning: This option must be enabled before gdb reads the file."),
25570                            NULL,
25571                            NULL,
25572                            &setlist, &showlist);
25573
25574   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25575                                                         &dwarf2_locexpr_funcs);
25576   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25577                                                         &dwarf2_loclist_funcs);
25578
25579   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25580                                         &dwarf2_block_frame_base_locexpr_funcs);
25581   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25582                                         &dwarf2_block_frame_base_loclist_funcs);
25583
25584 #if GDB_SELF_TEST
25585   selftests::register_test ("dw2_expand_symtabs_matching",
25586                             selftests::dw2_expand_symtabs_matching::run_test);
25587 #endif
25588 }