Simplify calls to init_psymbol_list
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2019 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-cache.h"
34 #include "dwarf-index-common.h"
35 #include "bfd.h"
36 #include "elf-bfd.h"
37 #include "symtab.h"
38 #include "gdbtypes.h"
39 #include "objfiles.h"
40 #include "dwarf2.h"
41 #include "buildsym.h"
42 #include "demangle.h"
43 #include "gdb-demangle.h"
44 #include "expression.h"
45 #include "filenames.h"  /* for DOSish file names */
46 #include "macrotab.h"
47 #include "language.h"
48 #include "complaints.h"
49 #include "bcache.h"
50 #include "dwarf2expr.h"
51 #include "dwarf2loc.h"
52 #include "cp-support.h"
53 #include "hashtab.h"
54 #include "command.h"
55 #include "gdbcmd.h"
56 #include "block.h"
57 #include "addrmap.h"
58 #include "typeprint.h"
59 #include "psympriv.h"
60 #include <sys/stat.h>
61 #include "completer.h"
62 #include "vec.h"
63 #include "c-lang.h"
64 #include "go-lang.h"
65 #include "valprint.h"
66 #include "gdbcore.h" /* for gnutarget */
67 #include "gdb/gdb-index.h"
68 #include <ctype.h>
69 #include "gdb_bfd.h"
70 #include "f-lang.h"
71 #include "source.h"
72 #include "filestuff.h"
73 #include "build-id.h"
74 #include "namespace.h"
75 #include "common/gdb_unlinker.h"
76 #include "common/function-view.h"
77 #include "common/gdb_optional.h"
78 #include "common/underlying.h"
79 #include "common/byte-vector.h"
80 #include "common/hash_enum.h"
81 #include "filename-seen-cache.h"
82 #include "producer.h"
83 #include <fcntl.h>
84 #include <sys/types.h>
85 #include <algorithm>
86 #include <unordered_set>
87 #include <unordered_map>
88 #include "selftest.h"
89 #include <cmath>
90 #include <set>
91 #include <forward_list>
92 #include "rust-lang.h"
93 #include "common/pathstuff.h"
94
95 /* When == 1, print basic high level tracing messages.
96    When > 1, be more verbose.
97    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
98 static unsigned int dwarf_read_debug = 0;
99
100 /* When non-zero, dump DIEs after they are read in.  */
101 static unsigned int dwarf_die_debug = 0;
102
103 /* When non-zero, dump line number entries as they are read in.  */
104 static unsigned int dwarf_line_debug = 0;
105
106 /* When non-zero, cross-check physname against demangler.  */
107 static int check_physname = 0;
108
109 /* When non-zero, do not reject deprecated .gdb_index sections.  */
110 static int use_deprecated_index_sections = 0;
111
112 static const struct objfile_data *dwarf2_objfile_data_key;
113
114 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
115
116 static int dwarf2_locexpr_index;
117 static int dwarf2_loclist_index;
118 static int dwarf2_locexpr_block_index;
119 static int dwarf2_loclist_block_index;
120
121 /* An index into a (C++) symbol name component in a symbol name as
122    recorded in the mapped_index's symbol table.  For each C++ symbol
123    in the symbol table, we record one entry for the start of each
124    component in the symbol in a table of name components, and then
125    sort the table, in order to be able to binary search symbol names,
126    ignoring leading namespaces, both completion and regular look up.
127    For example, for symbol "A::B::C", we'll have an entry that points
128    to "A::B::C", another that points to "B::C", and another for "C".
129    Note that function symbols in GDB index have no parameter
130    information, just the function/method names.  You can convert a
131    name_component to a "const char *" using the
132    'mapped_index::symbol_name_at(offset_type)' method.  */
133
134 struct name_component
135 {
136   /* Offset in the symbol name where the component starts.  Stored as
137      a (32-bit) offset instead of a pointer to save memory and improve
138      locality on 64-bit architectures.  */
139   offset_type name_offset;
140
141   /* The symbol's index in the symbol and constant pool tables of a
142      mapped_index.  */
143   offset_type idx;
144 };
145
146 /* Base class containing bits shared by both .gdb_index and
147    .debug_name indexes.  */
148
149 struct mapped_index_base
150 {
151   mapped_index_base () = default;
152   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
153
154   /* The name_component table (a sorted vector).  See name_component's
155      description above.  */
156   std::vector<name_component> name_components;
157
158   /* How NAME_COMPONENTS is sorted.  */
159   enum case_sensitivity name_components_casing;
160
161   /* Return the number of names in the symbol table.  */
162   virtual size_t symbol_name_count () const = 0;
163
164   /* Get the name of the symbol at IDX in the symbol table.  */
165   virtual const char *symbol_name_at (offset_type idx) const = 0;
166
167   /* Return whether the name at IDX in the symbol table should be
168      ignored.  */
169   virtual bool symbol_name_slot_invalid (offset_type idx) const
170   {
171     return false;
172   }
173
174   /* Build the symbol name component sorted vector, if we haven't
175      yet.  */
176   void build_name_components ();
177
178   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
179      possible matches for LN_NO_PARAMS in the name component
180      vector.  */
181   std::pair<std::vector<name_component>::const_iterator,
182             std::vector<name_component>::const_iterator>
183     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
184
185   /* Prevent deleting/destroying via a base class pointer.  */
186 protected:
187   ~mapped_index_base() = default;
188 };
189
190 /* A description of the mapped index.  The file format is described in
191    a comment by the code that writes the index.  */
192 struct mapped_index final : public mapped_index_base
193 {
194   /* A slot/bucket in the symbol table hash.  */
195   struct symbol_table_slot
196   {
197     const offset_type name;
198     const offset_type vec;
199   };
200
201   /* Index data format version.  */
202   int version = 0;
203
204   /* The address table data.  */
205   gdb::array_view<const gdb_byte> address_table;
206
207   /* The symbol table, implemented as a hash table.  */
208   gdb::array_view<symbol_table_slot> symbol_table;
209
210   /* A pointer to the constant pool.  */
211   const char *constant_pool = nullptr;
212
213   bool symbol_name_slot_invalid (offset_type idx) const override
214   {
215     const auto &bucket = this->symbol_table[idx];
216     return bucket.name == 0 && bucket.vec;
217   }
218
219   /* Convenience method to get at the name of the symbol at IDX in the
220      symbol table.  */
221   const char *symbol_name_at (offset_type idx) const override
222   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
223
224   size_t symbol_name_count () const override
225   { return this->symbol_table.size (); }
226 };
227
228 /* A description of the mapped .debug_names.
229    Uninitialized map has CU_COUNT 0.  */
230 struct mapped_debug_names final : public mapped_index_base
231 {
232   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
233   : dwarf2_per_objfile (dwarf2_per_objfile_)
234   {}
235
236   struct dwarf2_per_objfile *dwarf2_per_objfile;
237   bfd_endian dwarf5_byte_order;
238   bool dwarf5_is_dwarf64;
239   bool augmentation_is_gdb;
240   uint8_t offset_size;
241   uint32_t cu_count = 0;
242   uint32_t tu_count, bucket_count, name_count;
243   const gdb_byte *cu_table_reordered, *tu_table_reordered;
244   const uint32_t *bucket_table_reordered, *hash_table_reordered;
245   const gdb_byte *name_table_string_offs_reordered;
246   const gdb_byte *name_table_entry_offs_reordered;
247   const gdb_byte *entry_pool;
248
249   struct index_val
250   {
251     ULONGEST dwarf_tag;
252     struct attr
253     {
254       /* Attribute name DW_IDX_*.  */
255       ULONGEST dw_idx;
256
257       /* Attribute form DW_FORM_*.  */
258       ULONGEST form;
259
260       /* Value if FORM is DW_FORM_implicit_const.  */
261       LONGEST implicit_const;
262     };
263     std::vector<attr> attr_vec;
264   };
265
266   std::unordered_map<ULONGEST, index_val> abbrev_map;
267
268   const char *namei_to_name (uint32_t namei) const;
269
270   /* Implementation of the mapped_index_base virtual interface, for
271      the name_components cache.  */
272
273   const char *symbol_name_at (offset_type idx) const override
274   { return namei_to_name (idx); }
275
276   size_t symbol_name_count () const override
277   { return this->name_count; }
278 };
279
280 /* See dwarf2read.h.  */
281
282 dwarf2_per_objfile *
283 get_dwarf2_per_objfile (struct objfile *objfile)
284 {
285   return ((struct dwarf2_per_objfile *)
286           objfile_data (objfile, dwarf2_objfile_data_key));
287 }
288
289 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
290
291 void
292 set_dwarf2_per_objfile (struct objfile *objfile,
293                         struct dwarf2_per_objfile *dwarf2_per_objfile)
294 {
295   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
296   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
297 }
298
299 /* Default names of the debugging sections.  */
300
301 /* Note that if the debugging section has been compressed, it might
302    have a name like .zdebug_info.  */
303
304 static const struct dwarf2_debug_sections dwarf2_elf_names =
305 {
306   { ".debug_info", ".zdebug_info" },
307   { ".debug_abbrev", ".zdebug_abbrev" },
308   { ".debug_line", ".zdebug_line" },
309   { ".debug_loc", ".zdebug_loc" },
310   { ".debug_loclists", ".zdebug_loclists" },
311   { ".debug_macinfo", ".zdebug_macinfo" },
312   { ".debug_macro", ".zdebug_macro" },
313   { ".debug_str", ".zdebug_str" },
314   { ".debug_line_str", ".zdebug_line_str" },
315   { ".debug_ranges", ".zdebug_ranges" },
316   { ".debug_rnglists", ".zdebug_rnglists" },
317   { ".debug_types", ".zdebug_types" },
318   { ".debug_addr", ".zdebug_addr" },
319   { ".debug_frame", ".zdebug_frame" },
320   { ".eh_frame", NULL },
321   { ".gdb_index", ".zgdb_index" },
322   { ".debug_names", ".zdebug_names" },
323   { ".debug_aranges", ".zdebug_aranges" },
324   23
325 };
326
327 /* List of DWO/DWP sections.  */
328
329 static const struct dwop_section_names
330 {
331   struct dwarf2_section_names abbrev_dwo;
332   struct dwarf2_section_names info_dwo;
333   struct dwarf2_section_names line_dwo;
334   struct dwarf2_section_names loc_dwo;
335   struct dwarf2_section_names loclists_dwo;
336   struct dwarf2_section_names macinfo_dwo;
337   struct dwarf2_section_names macro_dwo;
338   struct dwarf2_section_names str_dwo;
339   struct dwarf2_section_names str_offsets_dwo;
340   struct dwarf2_section_names types_dwo;
341   struct dwarf2_section_names cu_index;
342   struct dwarf2_section_names tu_index;
343 }
344 dwop_section_names =
345 {
346   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
347   { ".debug_info.dwo", ".zdebug_info.dwo" },
348   { ".debug_line.dwo", ".zdebug_line.dwo" },
349   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
350   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
351   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
352   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
353   { ".debug_str.dwo", ".zdebug_str.dwo" },
354   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
355   { ".debug_types.dwo", ".zdebug_types.dwo" },
356   { ".debug_cu_index", ".zdebug_cu_index" },
357   { ".debug_tu_index", ".zdebug_tu_index" },
358 };
359
360 /* local data types */
361
362 /* The data in a compilation unit header, after target2host
363    translation, looks like this.  */
364 struct comp_unit_head
365 {
366   unsigned int length;
367   short version;
368   unsigned char addr_size;
369   unsigned char signed_addr_p;
370   sect_offset abbrev_sect_off;
371
372   /* Size of file offsets; either 4 or 8.  */
373   unsigned int offset_size;
374
375   /* Size of the length field; either 4 or 12.  */
376   unsigned int initial_length_size;
377
378   enum dwarf_unit_type unit_type;
379
380   /* Offset to the first byte of this compilation unit header in the
381      .debug_info section, for resolving relative reference dies.  */
382   sect_offset sect_off;
383
384   /* Offset to first die in this cu from the start of the cu.
385      This will be the first byte following the compilation unit header.  */
386   cu_offset first_die_cu_offset;
387
388   /* 64-bit signature of this type unit - it is valid only for
389      UNIT_TYPE DW_UT_type.  */
390   ULONGEST signature;
391
392   /* For types, offset in the type's DIE of the type defined by this TU.  */
393   cu_offset type_cu_offset_in_tu;
394 };
395
396 /* Type used for delaying computation of method physnames.
397    See comments for compute_delayed_physnames.  */
398 struct delayed_method_info
399 {
400   /* The type to which the method is attached, i.e., its parent class.  */
401   struct type *type;
402
403   /* The index of the method in the type's function fieldlists.  */
404   int fnfield_index;
405
406   /* The index of the method in the fieldlist.  */
407   int index;
408
409   /* The name of the DIE.  */
410   const char *name;
411
412   /*  The DIE associated with this method.  */
413   struct die_info *die;
414 };
415
416 /* Internal state when decoding a particular compilation unit.  */
417 struct dwarf2_cu
418 {
419   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
420   ~dwarf2_cu ();
421
422   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
423
424   /* The header of the compilation unit.  */
425   struct comp_unit_head header {};
426
427   /* Base address of this compilation unit.  */
428   CORE_ADDR base_address = 0;
429
430   /* Non-zero if base_address has been set.  */
431   int base_known = 0;
432
433   /* The language we are debugging.  */
434   enum language language = language_unknown;
435   const struct language_defn *language_defn = nullptr;
436
437   const char *producer = nullptr;
438
439   /* The symtab builder for this CU.  This is only non-NULL when full
440      symbols are being read.  */
441   std::unique_ptr<buildsym_compunit> builder;
442
443   /* The generic symbol table building routines have separate lists for
444      file scope symbols and all all other scopes (local scopes).  So
445      we need to select the right one to pass to add_symbol_to_list().
446      We do it by keeping a pointer to the correct list in list_in_scope.
447
448      FIXME: The original dwarf code just treated the file scope as the
449      first local scope, and all other local scopes as nested local
450      scopes, and worked fine.  Check to see if we really need to
451      distinguish these in buildsym.c.  */
452   struct pending **list_in_scope = nullptr;
453
454   /* Hash table holding all the loaded partial DIEs
455      with partial_die->offset.SECT_OFF as hash.  */
456   htab_t partial_dies = nullptr;
457
458   /* Storage for things with the same lifetime as this read-in compilation
459      unit, including partial DIEs.  */
460   auto_obstack comp_unit_obstack;
461
462   /* When multiple dwarf2_cu structures are living in memory, this field
463      chains them all together, so that they can be released efficiently.
464      We will probably also want a generation counter so that most-recently-used
465      compilation units are cached...  */
466   struct dwarf2_per_cu_data *read_in_chain = nullptr;
467
468   /* Backlink to our per_cu entry.  */
469   struct dwarf2_per_cu_data *per_cu;
470
471   /* How many compilation units ago was this CU last referenced?  */
472   int last_used = 0;
473
474   /* A hash table of DIE cu_offset for following references with
475      die_info->offset.sect_off as hash.  */
476   htab_t die_hash = nullptr;
477
478   /* Full DIEs if read in.  */
479   struct die_info *dies = nullptr;
480
481   /* A set of pointers to dwarf2_per_cu_data objects for compilation
482      units referenced by this one.  Only set during full symbol processing;
483      partial symbol tables do not have dependencies.  */
484   htab_t dependencies = nullptr;
485
486   /* Header data from the line table, during full symbol processing.  */
487   struct line_header *line_header = nullptr;
488   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
489      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
490      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
491      to the line header as long as this DIE is being processed.  See
492      process_die_scope.  */
493   die_info *line_header_die_owner = nullptr;
494
495   /* A list of methods which need to have physnames computed
496      after all type information has been read.  */
497   std::vector<delayed_method_info> method_list;
498
499   /* To be copied to symtab->call_site_htab.  */
500   htab_t call_site_htab = nullptr;
501
502   /* Non-NULL if this CU came from a DWO file.
503      There is an invariant here that is important to remember:
504      Except for attributes copied from the top level DIE in the "main"
505      (or "stub") file in preparation for reading the DWO file
506      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
507      Either there isn't a DWO file (in which case this is NULL and the point
508      is moot), or there is and either we're not going to read it (in which
509      case this is NULL) or there is and we are reading it (in which case this
510      is non-NULL).  */
511   struct dwo_unit *dwo_unit = nullptr;
512
513   /* The DW_AT_addr_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   ULONGEST addr_base = 0;
517
518   /* The DW_AT_ranges_base attribute if present, zero otherwise
519      (zero is a valid value though).
520      Note this value comes from the Fission stub CU/TU's DIE.
521      Also note that the value is zero in the non-DWO case so this value can
522      be used without needing to know whether DWO files are in use or not.
523      N.B. This does not apply to DW_AT_ranges appearing in
524      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
525      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
526      DW_AT_ranges_base *would* have to be applied, and we'd have to care
527      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
528   ULONGEST ranges_base = 0;
529
530   /* When reading debug info generated by older versions of rustc, we
531      have to rewrite some union types to be struct types with a
532      variant part.  This rewriting must be done after the CU is fully
533      read in, because otherwise at the point of rewriting some struct
534      type might not have been fully processed.  So, we keep a list of
535      all such types here and process them after expansion.  */
536   std::vector<struct type *> rust_unions;
537
538   /* Mark used when releasing cached dies.  */
539   bool mark : 1;
540
541   /* This CU references .debug_loc.  See the symtab->locations_valid field.
542      This test is imperfect as there may exist optimized debug code not using
543      any location list and still facing inlining issues if handled as
544      unoptimized code.  For a future better test see GCC PR other/32998.  */
545   bool has_loclist : 1;
546
547   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is true
548      if all the producer_is_* fields are valid.  This information is cached
549      because profiling CU expansion showed excessive time spent in
550      producer_is_gxx_lt_4_6.  */
551   bool checked_producer : 1;
552   bool producer_is_gxx_lt_4_6 : 1;
553   bool producer_is_gcc_lt_4_3 : 1;
554   bool producer_is_icc : 1;
555   bool producer_is_icc_lt_14 : 1;
556   bool producer_is_codewarrior : 1;
557
558   /* When true, the file that we're processing is known to have
559      debugging info for C++ namespaces.  GCC 3.3.x did not produce
560      this information, but later versions do.  */
561
562   bool processing_has_namespace_info : 1;
563
564   struct partial_die_info *find_partial_die (sect_offset sect_off);
565 };
566
567 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
568    This includes type_unit_group and quick_file_names.  */
569
570 struct stmt_list_hash
571 {
572   /* The DWO unit this table is from or NULL if there is none.  */
573   struct dwo_unit *dwo_unit;
574
575   /* Offset in .debug_line or .debug_line.dwo.  */
576   sect_offset line_sect_off;
577 };
578
579 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
580    an object of this type.  */
581
582 struct type_unit_group
583 {
584   /* dwarf2read.c's main "handle" on a TU symtab.
585      To simplify things we create an artificial CU that "includes" all the
586      type units using this stmt_list so that the rest of the code still has
587      a "per_cu" handle on the symtab.
588      This PER_CU is recognized by having no section.  */
589 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
590   struct dwarf2_per_cu_data per_cu;
591
592   /* The TUs that share this DW_AT_stmt_list entry.
593      This is added to while parsing type units to build partial symtabs,
594      and is deleted afterwards and not used again.  */
595   VEC (sig_type_ptr) *tus;
596
597   /* The compunit symtab.
598      Type units in a group needn't all be defined in the same source file,
599      so we create an essentially anonymous symtab as the compunit symtab.  */
600   struct compunit_symtab *compunit_symtab;
601
602   /* The data used to construct the hash key.  */
603   struct stmt_list_hash hash;
604
605   /* The number of symtabs from the line header.
606      The value here must match line_header.num_file_names.  */
607   unsigned int num_symtabs;
608
609   /* The symbol tables for this TU (obtained from the files listed in
610      DW_AT_stmt_list).
611      WARNING: The order of entries here must match the order of entries
612      in the line header.  After the first TU using this type_unit_group, the
613      line header for the subsequent TUs is recreated from this.  This is done
614      because we need to use the same symtabs for each TU using the same
615      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
616      there's no guarantee the line header doesn't have duplicate entries.  */
617   struct symtab **symtabs;
618 };
619
620 /* These sections are what may appear in a (real or virtual) DWO file.  */
621
622 struct dwo_sections
623 {
624   struct dwarf2_section_info abbrev;
625   struct dwarf2_section_info line;
626   struct dwarf2_section_info loc;
627   struct dwarf2_section_info loclists;
628   struct dwarf2_section_info macinfo;
629   struct dwarf2_section_info macro;
630   struct dwarf2_section_info str;
631   struct dwarf2_section_info str_offsets;
632   /* In the case of a virtual DWO file, these two are unused.  */
633   struct dwarf2_section_info info;
634   VEC (dwarf2_section_info_def) *types;
635 };
636
637 /* CUs/TUs in DWP/DWO files.  */
638
639 struct dwo_unit
640 {
641   /* Backlink to the containing struct dwo_file.  */
642   struct dwo_file *dwo_file;
643
644   /* The "id" that distinguishes this CU/TU.
645      .debug_info calls this "dwo_id", .debug_types calls this "signature".
646      Since signatures came first, we stick with it for consistency.  */
647   ULONGEST signature;
648
649   /* The section this CU/TU lives in, in the DWO file.  */
650   struct dwarf2_section_info *section;
651
652   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
653   sect_offset sect_off;
654   unsigned int length;
655
656   /* For types, offset in the type's DIE of the type defined by this TU.  */
657   cu_offset type_offset_in_tu;
658 };
659
660 /* include/dwarf2.h defines the DWP section codes.
661    It defines a max value but it doesn't define a min value, which we
662    use for error checking, so provide one.  */
663
664 enum dwp_v2_section_ids
665 {
666   DW_SECT_MIN = 1
667 };
668
669 /* Data for one DWO file.
670
671    This includes virtual DWO files (a virtual DWO file is a DWO file as it
672    appears in a DWP file).  DWP files don't really have DWO files per se -
673    comdat folding of types "loses" the DWO file they came from, and from
674    a high level view DWP files appear to contain a mass of random types.
675    However, to maintain consistency with the non-DWP case we pretend DWP
676    files contain virtual DWO files, and we assign each TU with one virtual
677    DWO file (generally based on the line and abbrev section offsets -
678    a heuristic that seems to work in practice).  */
679
680 struct dwo_file
681 {
682   /* The DW_AT_GNU_dwo_name attribute.
683      For virtual DWO files the name is constructed from the section offsets
684      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
685      from related CU+TUs.  */
686   const char *dwo_name;
687
688   /* The DW_AT_comp_dir attribute.  */
689   const char *comp_dir;
690
691   /* The bfd, when the file is open.  Otherwise this is NULL.
692      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
693   bfd *dbfd;
694
695   /* The sections that make up this DWO file.
696      Remember that for virtual DWO files in DWP V2, these are virtual
697      sections (for lack of a better name).  */
698   struct dwo_sections sections;
699
700   /* The CUs in the file.
701      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
702      an extension to handle LLVM's Link Time Optimization output (where
703      multiple source files may be compiled into a single object/dwo pair). */
704   htab_t cus;
705
706   /* Table of TUs in the file.
707      Each element is a struct dwo_unit.  */
708   htab_t tus;
709 };
710
711 /* These sections are what may appear in a DWP file.  */
712
713 struct dwp_sections
714 {
715   /* These are used by both DWP version 1 and 2.  */
716   struct dwarf2_section_info str;
717   struct dwarf2_section_info cu_index;
718   struct dwarf2_section_info tu_index;
719
720   /* These are only used by DWP version 2 files.
721      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
722      sections are referenced by section number, and are not recorded here.
723      In DWP version 2 there is at most one copy of all these sections, each
724      section being (effectively) comprised of the concatenation of all of the
725      individual sections that exist in the version 1 format.
726      To keep the code simple we treat each of these concatenated pieces as a
727      section itself (a virtual section?).  */
728   struct dwarf2_section_info abbrev;
729   struct dwarf2_section_info info;
730   struct dwarf2_section_info line;
731   struct dwarf2_section_info loc;
732   struct dwarf2_section_info macinfo;
733   struct dwarf2_section_info macro;
734   struct dwarf2_section_info str_offsets;
735   struct dwarf2_section_info types;
736 };
737
738 /* These sections are what may appear in a virtual DWO file in DWP version 1.
739    A virtual DWO file is a DWO file as it appears in a DWP file.  */
740
741 struct virtual_v1_dwo_sections
742 {
743   struct dwarf2_section_info abbrev;
744   struct dwarf2_section_info line;
745   struct dwarf2_section_info loc;
746   struct dwarf2_section_info macinfo;
747   struct dwarf2_section_info macro;
748   struct dwarf2_section_info str_offsets;
749   /* Each DWP hash table entry records one CU or one TU.
750      That is recorded here, and copied to dwo_unit.section.  */
751   struct dwarf2_section_info info_or_types;
752 };
753
754 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
755    In version 2, the sections of the DWO files are concatenated together
756    and stored in one section of that name.  Thus each ELF section contains
757    several "virtual" sections.  */
758
759 struct virtual_v2_dwo_sections
760 {
761   bfd_size_type abbrev_offset;
762   bfd_size_type abbrev_size;
763
764   bfd_size_type line_offset;
765   bfd_size_type line_size;
766
767   bfd_size_type loc_offset;
768   bfd_size_type loc_size;
769
770   bfd_size_type macinfo_offset;
771   bfd_size_type macinfo_size;
772
773   bfd_size_type macro_offset;
774   bfd_size_type macro_size;
775
776   bfd_size_type str_offsets_offset;
777   bfd_size_type str_offsets_size;
778
779   /* Each DWP hash table entry records one CU or one TU.
780      That is recorded here, and copied to dwo_unit.section.  */
781   bfd_size_type info_or_types_offset;
782   bfd_size_type info_or_types_size;
783 };
784
785 /* Contents of DWP hash tables.  */
786
787 struct dwp_hash_table
788 {
789   uint32_t version, nr_columns;
790   uint32_t nr_units, nr_slots;
791   const gdb_byte *hash_table, *unit_table;
792   union
793   {
794     struct
795     {
796       const gdb_byte *indices;
797     } v1;
798     struct
799     {
800       /* This is indexed by column number and gives the id of the section
801          in that column.  */
802 #define MAX_NR_V2_DWO_SECTIONS \
803   (1 /* .debug_info or .debug_types */ \
804    + 1 /* .debug_abbrev */ \
805    + 1 /* .debug_line */ \
806    + 1 /* .debug_loc */ \
807    + 1 /* .debug_str_offsets */ \
808    + 1 /* .debug_macro or .debug_macinfo */)
809       int section_ids[MAX_NR_V2_DWO_SECTIONS];
810       const gdb_byte *offsets;
811       const gdb_byte *sizes;
812     } v2;
813   } section_pool;
814 };
815
816 /* Data for one DWP file.  */
817
818 struct dwp_file
819 {
820   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
821     : name (name_),
822       dbfd (std::move (abfd))
823   {
824   }
825
826   /* Name of the file.  */
827   const char *name;
828
829   /* File format version.  */
830   int version = 0;
831
832   /* The bfd.  */
833   gdb_bfd_ref_ptr dbfd;
834
835   /* Section info for this file.  */
836   struct dwp_sections sections {};
837
838   /* Table of CUs in the file.  */
839   const struct dwp_hash_table *cus = nullptr;
840
841   /* Table of TUs in the file.  */
842   const struct dwp_hash_table *tus = nullptr;
843
844   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
845   htab_t loaded_cus {};
846   htab_t loaded_tus {};
847
848   /* Table to map ELF section numbers to their sections.
849      This is only needed for the DWP V1 file format.  */
850   unsigned int num_sections = 0;
851   asection **elf_sections = nullptr;
852 };
853
854 /* This represents a '.dwz' file.  */
855
856 struct dwz_file
857 {
858   dwz_file (gdb_bfd_ref_ptr &&bfd)
859     : dwz_bfd (std::move (bfd))
860   {
861   }
862
863   /* A dwz file can only contain a few sections.  */
864   struct dwarf2_section_info abbrev {};
865   struct dwarf2_section_info info {};
866   struct dwarf2_section_info str {};
867   struct dwarf2_section_info line {};
868   struct dwarf2_section_info macro {};
869   struct dwarf2_section_info gdb_index {};
870   struct dwarf2_section_info debug_names {};
871
872   /* The dwz's BFD.  */
873   gdb_bfd_ref_ptr dwz_bfd;
874
875   /* If we loaded the index from an external file, this contains the
876      resources associated to the open file, memory mapping, etc.  */
877   std::unique_ptr<index_cache_resource> index_cache_res;
878 };
879
880 /* Struct used to pass misc. parameters to read_die_and_children, et
881    al.  which are used for both .debug_info and .debug_types dies.
882    All parameters here are unchanging for the life of the call.  This
883    struct exists to abstract away the constant parameters of die reading.  */
884
885 struct die_reader_specs
886 {
887   /* The bfd of die_section.  */
888   bfd* abfd;
889
890   /* The CU of the DIE we are parsing.  */
891   struct dwarf2_cu *cu;
892
893   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
894   struct dwo_file *dwo_file;
895
896   /* The section the die comes from.
897      This is either .debug_info or .debug_types, or the .dwo variants.  */
898   struct dwarf2_section_info *die_section;
899
900   /* die_section->buffer.  */
901   const gdb_byte *buffer;
902
903   /* The end of the buffer.  */
904   const gdb_byte *buffer_end;
905
906   /* The value of the DW_AT_comp_dir attribute.  */
907   const char *comp_dir;
908
909   /* The abbreviation table to use when reading the DIEs.  */
910   struct abbrev_table *abbrev_table;
911 };
912
913 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
914 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
915                                       const gdb_byte *info_ptr,
916                                       struct die_info *comp_unit_die,
917                                       int has_children,
918                                       void *data);
919
920 /* A 1-based directory index.  This is a strong typedef to prevent
921    accidentally using a directory index as a 0-based index into an
922    array/vector.  */
923 enum class dir_index : unsigned int {};
924
925 /* Likewise, a 1-based file name index.  */
926 enum class file_name_index : unsigned int {};
927
928 struct file_entry
929 {
930   file_entry () = default;
931
932   file_entry (const char *name_, dir_index d_index_,
933               unsigned int mod_time_, unsigned int length_)
934     : name (name_),
935       d_index (d_index_),
936       mod_time (mod_time_),
937       length (length_)
938   {}
939
940   /* Return the include directory at D_INDEX stored in LH.  Returns
941      NULL if D_INDEX is out of bounds.  */
942   const char *include_dir (const line_header *lh) const;
943
944   /* The file name.  Note this is an observing pointer.  The memory is
945      owned by debug_line_buffer.  */
946   const char *name {};
947
948   /* The directory index (1-based).  */
949   dir_index d_index {};
950
951   unsigned int mod_time {};
952
953   unsigned int length {};
954
955   /* True if referenced by the Line Number Program.  */
956   bool included_p {};
957
958   /* The associated symbol table, if any.  */
959   struct symtab *symtab {};
960 };
961
962 /* The line number information for a compilation unit (found in the
963    .debug_line section) begins with a "statement program header",
964    which contains the following information.  */
965 struct line_header
966 {
967   line_header ()
968     : offset_in_dwz {}
969   {}
970
971   /* Add an entry to the include directory table.  */
972   void add_include_dir (const char *include_dir);
973
974   /* Add an entry to the file name table.  */
975   void add_file_name (const char *name, dir_index d_index,
976                       unsigned int mod_time, unsigned int length);
977
978   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
979      is out of bounds.  */
980   const char *include_dir_at (dir_index index) const
981   {
982     /* Convert directory index number (1-based) to vector index
983        (0-based).  */
984     size_t vec_index = to_underlying (index) - 1;
985
986     if (vec_index >= include_dirs.size ())
987       return NULL;
988     return include_dirs[vec_index];
989   }
990
991   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
992      is out of bounds.  */
993   file_entry *file_name_at (file_name_index index)
994   {
995     /* Convert file name index number (1-based) to vector index
996        (0-based).  */
997     size_t vec_index = to_underlying (index) - 1;
998
999     if (vec_index >= file_names.size ())
1000       return NULL;
1001     return &file_names[vec_index];
1002   }
1003
1004   /* Const version of the above.  */
1005   const file_entry *file_name_at (unsigned int index) const
1006   {
1007     if (index >= file_names.size ())
1008       return NULL;
1009     return &file_names[index];
1010   }
1011
1012   /* Offset of line number information in .debug_line section.  */
1013   sect_offset sect_off {};
1014
1015   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1016   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1017
1018   unsigned int total_length {};
1019   unsigned short version {};
1020   unsigned int header_length {};
1021   unsigned char minimum_instruction_length {};
1022   unsigned char maximum_ops_per_instruction {};
1023   unsigned char default_is_stmt {};
1024   int line_base {};
1025   unsigned char line_range {};
1026   unsigned char opcode_base {};
1027
1028   /* standard_opcode_lengths[i] is the number of operands for the
1029      standard opcode whose value is i.  This means that
1030      standard_opcode_lengths[0] is unused, and the last meaningful
1031      element is standard_opcode_lengths[opcode_base - 1].  */
1032   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1033
1034   /* The include_directories table.  Note these are observing
1035      pointers.  The memory is owned by debug_line_buffer.  */
1036   std::vector<const char *> include_dirs;
1037
1038   /* The file_names table.  */
1039   std::vector<file_entry> file_names;
1040
1041   /* The start and end of the statement program following this
1042      header.  These point into dwarf2_per_objfile->line_buffer.  */
1043   const gdb_byte *statement_program_start {}, *statement_program_end {};
1044 };
1045
1046 typedef std::unique_ptr<line_header> line_header_up;
1047
1048 const char *
1049 file_entry::include_dir (const line_header *lh) const
1050 {
1051   return lh->include_dir_at (d_index);
1052 }
1053
1054 /* When we construct a partial symbol table entry we only
1055    need this much information.  */
1056 struct partial_die_info : public allocate_on_obstack
1057   {
1058     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1059
1060     /* Disable assign but still keep copy ctor, which is needed
1061        load_partial_dies.   */
1062     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1063
1064     /* Adjust the partial die before generating a symbol for it.  This
1065        function may set the is_external flag or change the DIE's
1066        name.  */
1067     void fixup (struct dwarf2_cu *cu);
1068
1069     /* Read a minimal amount of information into the minimal die
1070        structure.  */
1071     const gdb_byte *read (const struct die_reader_specs *reader,
1072                           const struct abbrev_info &abbrev,
1073                           const gdb_byte *info_ptr);
1074
1075     /* Offset of this DIE.  */
1076     const sect_offset sect_off;
1077
1078     /* DWARF-2 tag for this DIE.  */
1079     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1080
1081     /* Assorted flags describing the data found in this DIE.  */
1082     const unsigned int has_children : 1;
1083
1084     unsigned int is_external : 1;
1085     unsigned int is_declaration : 1;
1086     unsigned int has_type : 1;
1087     unsigned int has_specification : 1;
1088     unsigned int has_pc_info : 1;
1089     unsigned int may_be_inlined : 1;
1090
1091     /* This DIE has been marked DW_AT_main_subprogram.  */
1092     unsigned int main_subprogram : 1;
1093
1094     /* Flag set if the SCOPE field of this structure has been
1095        computed.  */
1096     unsigned int scope_set : 1;
1097
1098     /* Flag set if the DIE has a byte_size attribute.  */
1099     unsigned int has_byte_size : 1;
1100
1101     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1102     unsigned int has_const_value : 1;
1103
1104     /* Flag set if any of the DIE's children are template arguments.  */
1105     unsigned int has_template_arguments : 1;
1106
1107     /* Flag set if fixup has been called on this die.  */
1108     unsigned int fixup_called : 1;
1109
1110     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1111     unsigned int is_dwz : 1;
1112
1113     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1114     unsigned int spec_is_dwz : 1;
1115
1116     /* The name of this DIE.  Normally the value of DW_AT_name, but
1117        sometimes a default name for unnamed DIEs.  */
1118     const char *name = nullptr;
1119
1120     /* The linkage name, if present.  */
1121     const char *linkage_name = nullptr;
1122
1123     /* The scope to prepend to our children.  This is generally
1124        allocated on the comp_unit_obstack, so will disappear
1125        when this compilation unit leaves the cache.  */
1126     const char *scope = nullptr;
1127
1128     /* Some data associated with the partial DIE.  The tag determines
1129        which field is live.  */
1130     union
1131     {
1132       /* The location description associated with this DIE, if any.  */
1133       struct dwarf_block *locdesc;
1134       /* The offset of an import, for DW_TAG_imported_unit.  */
1135       sect_offset sect_off;
1136     } d {};
1137
1138     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1139     CORE_ADDR lowpc = 0;
1140     CORE_ADDR highpc = 0;
1141
1142     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1143        DW_AT_sibling, if any.  */
1144     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1145        could return DW_AT_sibling values to its caller load_partial_dies.  */
1146     const gdb_byte *sibling = nullptr;
1147
1148     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1149        DW_AT_specification (or DW_AT_abstract_origin or
1150        DW_AT_extension).  */
1151     sect_offset spec_offset {};
1152
1153     /* Pointers to this DIE's parent, first child, and next sibling,
1154        if any.  */
1155     struct partial_die_info *die_parent = nullptr;
1156     struct partial_die_info *die_child = nullptr;
1157     struct partial_die_info *die_sibling = nullptr;
1158
1159     friend struct partial_die_info *
1160     dwarf2_cu::find_partial_die (sect_offset sect_off);
1161
1162   private:
1163     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1164     partial_die_info (sect_offset sect_off)
1165       : partial_die_info (sect_off, DW_TAG_padding, 0)
1166     {
1167     }
1168
1169     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1170                       int has_children_)
1171       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1172     {
1173       is_external = 0;
1174       is_declaration = 0;
1175       has_type = 0;
1176       has_specification = 0;
1177       has_pc_info = 0;
1178       may_be_inlined = 0;
1179       main_subprogram = 0;
1180       scope_set = 0;
1181       has_byte_size = 0;
1182       has_const_value = 0;
1183       has_template_arguments = 0;
1184       fixup_called = 0;
1185       is_dwz = 0;
1186       spec_is_dwz = 0;
1187     }
1188   };
1189
1190 /* This data structure holds the information of an abbrev.  */
1191 struct abbrev_info
1192   {
1193     unsigned int number;        /* number identifying abbrev */
1194     enum dwarf_tag tag;         /* dwarf tag */
1195     unsigned short has_children;                /* boolean */
1196     unsigned short num_attrs;   /* number of attributes */
1197     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1198     struct abbrev_info *next;   /* next in chain */
1199   };
1200
1201 struct attr_abbrev
1202   {
1203     ENUM_BITFIELD(dwarf_attribute) name : 16;
1204     ENUM_BITFIELD(dwarf_form) form : 16;
1205
1206     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1207     LONGEST implicit_const;
1208   };
1209
1210 /* Size of abbrev_table.abbrev_hash_table.  */
1211 #define ABBREV_HASH_SIZE 121
1212
1213 /* Top level data structure to contain an abbreviation table.  */
1214
1215 struct abbrev_table
1216 {
1217   explicit abbrev_table (sect_offset off)
1218     : sect_off (off)
1219   {
1220     m_abbrevs =
1221       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1222     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1223   }
1224
1225   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1226
1227   /* Allocate space for a struct abbrev_info object in
1228      ABBREV_TABLE.  */
1229   struct abbrev_info *alloc_abbrev ();
1230
1231   /* Add an abbreviation to the table.  */
1232   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1233
1234   /* Look up an abbrev in the table.
1235      Returns NULL if the abbrev is not found.  */
1236
1237   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1238
1239
1240   /* Where the abbrev table came from.
1241      This is used as a sanity check when the table is used.  */
1242   const sect_offset sect_off;
1243
1244   /* Storage for the abbrev table.  */
1245   auto_obstack abbrev_obstack;
1246
1247 private:
1248
1249   /* Hash table of abbrevs.
1250      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1251      It could be statically allocated, but the previous code didn't so we
1252      don't either.  */
1253   struct abbrev_info **m_abbrevs;
1254 };
1255
1256 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1257
1258 /* Attributes have a name and a value.  */
1259 struct attribute
1260   {
1261     ENUM_BITFIELD(dwarf_attribute) name : 16;
1262     ENUM_BITFIELD(dwarf_form) form : 15;
1263
1264     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1265        field should be in u.str (existing only for DW_STRING) but it is kept
1266        here for better struct attribute alignment.  */
1267     unsigned int string_is_canonical : 1;
1268
1269     union
1270       {
1271         const char *str;
1272         struct dwarf_block *blk;
1273         ULONGEST unsnd;
1274         LONGEST snd;
1275         CORE_ADDR addr;
1276         ULONGEST signature;
1277       }
1278     u;
1279   };
1280
1281 /* This data structure holds a complete die structure.  */
1282 struct die_info
1283   {
1284     /* DWARF-2 tag for this DIE.  */
1285     ENUM_BITFIELD(dwarf_tag) tag : 16;
1286
1287     /* Number of attributes */
1288     unsigned char num_attrs;
1289
1290     /* True if we're presently building the full type name for the
1291        type derived from this DIE.  */
1292     unsigned char building_fullname : 1;
1293
1294     /* True if this die is in process.  PR 16581.  */
1295     unsigned char in_process : 1;
1296
1297     /* Abbrev number */
1298     unsigned int abbrev;
1299
1300     /* Offset in .debug_info or .debug_types section.  */
1301     sect_offset sect_off;
1302
1303     /* The dies in a compilation unit form an n-ary tree.  PARENT
1304        points to this die's parent; CHILD points to the first child of
1305        this node; and all the children of a given node are chained
1306        together via their SIBLING fields.  */
1307     struct die_info *child;     /* Its first child, if any.  */
1308     struct die_info *sibling;   /* Its next sibling, if any.  */
1309     struct die_info *parent;    /* Its parent, if any.  */
1310
1311     /* An array of attributes, with NUM_ATTRS elements.  There may be
1312        zero, but it's not common and zero-sized arrays are not
1313        sufficiently portable C.  */
1314     struct attribute attrs[1];
1315   };
1316
1317 /* Get at parts of an attribute structure.  */
1318
1319 #define DW_STRING(attr)    ((attr)->u.str)
1320 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1321 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1322 #define DW_BLOCK(attr)     ((attr)->u.blk)
1323 #define DW_SND(attr)       ((attr)->u.snd)
1324 #define DW_ADDR(attr)      ((attr)->u.addr)
1325 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1326
1327 /* Blocks are a bunch of untyped bytes.  */
1328 struct dwarf_block
1329   {
1330     size_t size;
1331
1332     /* Valid only if SIZE is not zero.  */
1333     const gdb_byte *data;
1334   };
1335
1336 #ifndef ATTR_ALLOC_CHUNK
1337 #define ATTR_ALLOC_CHUNK 4
1338 #endif
1339
1340 /* Allocate fields for structs, unions and enums in this size.  */
1341 #ifndef DW_FIELD_ALLOC_CHUNK
1342 #define DW_FIELD_ALLOC_CHUNK 4
1343 #endif
1344
1345 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1346    but this would require a corresponding change in unpack_field_as_long
1347    and friends.  */
1348 static int bits_per_byte = 8;
1349
1350 /* When reading a variant or variant part, we track a bit more
1351    information about the field, and store it in an object of this
1352    type.  */
1353
1354 struct variant_field
1355 {
1356   /* If we see a DW_TAG_variant, then this will be the discriminant
1357      value.  */
1358   ULONGEST discriminant_value;
1359   /* If we see a DW_TAG_variant, then this will be set if this is the
1360      default branch.  */
1361   bool default_branch;
1362   /* While reading a DW_TAG_variant_part, this will be set if this
1363      field is the discriminant.  */
1364   bool is_discriminant;
1365 };
1366
1367 struct nextfield
1368 {
1369   int accessibility = 0;
1370   int virtuality = 0;
1371   /* Extra information to describe a variant or variant part.  */
1372   struct variant_field variant {};
1373   struct field field {};
1374 };
1375
1376 struct fnfieldlist
1377 {
1378   const char *name = nullptr;
1379   std::vector<struct fn_field> fnfields;
1380 };
1381
1382 /* The routines that read and process dies for a C struct or C++ class
1383    pass lists of data member fields and lists of member function fields
1384    in an instance of a field_info structure, as defined below.  */
1385 struct field_info
1386   {
1387     /* List of data member and baseclasses fields.  */
1388     std::vector<struct nextfield> fields;
1389     std::vector<struct nextfield> baseclasses;
1390
1391     /* Number of fields (including baseclasses).  */
1392     int nfields = 0;
1393
1394     /* Set if the accesibility of one of the fields is not public.  */
1395     int non_public_fields = 0;
1396
1397     /* Member function fieldlist array, contains name of possibly overloaded
1398        member function, number of overloaded member functions and a pointer
1399        to the head of the member function field chain.  */
1400     std::vector<struct fnfieldlist> fnfieldlists;
1401
1402     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1403        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1404     std::vector<struct decl_field> typedef_field_list;
1405
1406     /* Nested types defined by this class and the number of elements in this
1407        list.  */
1408     std::vector<struct decl_field> nested_types_list;
1409   };
1410
1411 /* One item on the queue of compilation units to read in full symbols
1412    for.  */
1413 struct dwarf2_queue_item
1414 {
1415   struct dwarf2_per_cu_data *per_cu;
1416   enum language pretend_language;
1417   struct dwarf2_queue_item *next;
1418 };
1419
1420 /* The current queue.  */
1421 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1422
1423 /* Loaded secondary compilation units are kept in memory until they
1424    have not been referenced for the processing of this many
1425    compilation units.  Set this to zero to disable caching.  Cache
1426    sizes of up to at least twenty will improve startup time for
1427    typical inter-CU-reference binaries, at an obvious memory cost.  */
1428 static int dwarf_max_cache_age = 5;
1429 static void
1430 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1431                           struct cmd_list_element *c, const char *value)
1432 {
1433   fprintf_filtered (file, _("The upper bound on the age of cached "
1434                             "DWARF compilation units is %s.\n"),
1435                     value);
1436 }
1437 \f
1438 /* local function prototypes */
1439
1440 static const char *get_section_name (const struct dwarf2_section_info *);
1441
1442 static const char *get_section_file_name (const struct dwarf2_section_info *);
1443
1444 static void dwarf2_find_base_address (struct die_info *die,
1445                                       struct dwarf2_cu *cu);
1446
1447 static struct partial_symtab *create_partial_symtab
1448   (struct dwarf2_per_cu_data *per_cu, const char *name);
1449
1450 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1451                                         const gdb_byte *info_ptr,
1452                                         struct die_info *type_unit_die,
1453                                         int has_children, void *data);
1454
1455 static void dwarf2_build_psymtabs_hard
1456   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1457
1458 static void scan_partial_symbols (struct partial_die_info *,
1459                                   CORE_ADDR *, CORE_ADDR *,
1460                                   int, struct dwarf2_cu *);
1461
1462 static void add_partial_symbol (struct partial_die_info *,
1463                                 struct dwarf2_cu *);
1464
1465 static void add_partial_namespace (struct partial_die_info *pdi,
1466                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1467                                    int set_addrmap, struct dwarf2_cu *cu);
1468
1469 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1470                                 CORE_ADDR *highpc, int set_addrmap,
1471                                 struct dwarf2_cu *cu);
1472
1473 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1474                                      struct dwarf2_cu *cu);
1475
1476 static void add_partial_subprogram (struct partial_die_info *pdi,
1477                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1478                                     int need_pc, struct dwarf2_cu *cu);
1479
1480 static void dwarf2_read_symtab (struct partial_symtab *,
1481                                 struct objfile *);
1482
1483 static void psymtab_to_symtab_1 (struct partial_symtab *);
1484
1485 static abbrev_table_up abbrev_table_read_table
1486   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1487    sect_offset);
1488
1489 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1490
1491 static struct partial_die_info *load_partial_dies
1492   (const struct die_reader_specs *, const gdb_byte *, int);
1493
1494 static struct partial_die_info *find_partial_die (sect_offset, int,
1495                                                   struct dwarf2_cu *);
1496
1497 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1498                                        struct attribute *, struct attr_abbrev *,
1499                                        const gdb_byte *);
1500
1501 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1502
1503 static int read_1_signed_byte (bfd *, const gdb_byte *);
1504
1505 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1506
1507 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1508
1509 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1510
1511 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1512                                unsigned int *);
1513
1514 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1515
1516 static LONGEST read_checked_initial_length_and_offset
1517   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1518    unsigned int *, unsigned int *);
1519
1520 static LONGEST read_offset (bfd *, const gdb_byte *,
1521                             const struct comp_unit_head *,
1522                             unsigned int *);
1523
1524 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1525
1526 static sect_offset read_abbrev_offset
1527   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1528    struct dwarf2_section_info *, sect_offset);
1529
1530 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1531
1532 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1533
1534 static const char *read_indirect_string
1535   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1536    const struct comp_unit_head *, unsigned int *);
1537
1538 static const char *read_indirect_line_string
1539   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1540    const struct comp_unit_head *, unsigned int *);
1541
1542 static const char *read_indirect_string_at_offset
1543   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1544    LONGEST str_offset);
1545
1546 static const char *read_indirect_string_from_dwz
1547   (struct objfile *objfile, struct dwz_file *, LONGEST);
1548
1549 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1550
1551 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1552                                               const gdb_byte *,
1553                                               unsigned int *);
1554
1555 static const char *read_str_index (const struct die_reader_specs *reader,
1556                                    ULONGEST str_index);
1557
1558 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1559
1560 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1561                                       struct dwarf2_cu *);
1562
1563 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1564                                                 unsigned int);
1565
1566 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1567                                        struct dwarf2_cu *cu);
1568
1569 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1570                                struct dwarf2_cu *cu);
1571
1572 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1573
1574 static struct die_info *die_specification (struct die_info *die,
1575                                            struct dwarf2_cu **);
1576
1577 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1578                                                 struct dwarf2_cu *cu);
1579
1580 static void dwarf_decode_lines (struct line_header *, const char *,
1581                                 struct dwarf2_cu *, struct partial_symtab *,
1582                                 CORE_ADDR, int decode_mapping);
1583
1584 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1585                                   const char *);
1586
1587 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1588                                                     const char *, const char *,
1589                                                     CORE_ADDR);
1590
1591 static struct symbol *new_symbol (struct die_info *, struct type *,
1592                                   struct dwarf2_cu *, struct symbol * = NULL);
1593
1594 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1595                                 struct dwarf2_cu *);
1596
1597 static void dwarf2_const_value_attr (const struct attribute *attr,
1598                                      struct type *type,
1599                                      const char *name,
1600                                      struct obstack *obstack,
1601                                      struct dwarf2_cu *cu, LONGEST *value,
1602                                      const gdb_byte **bytes,
1603                                      struct dwarf2_locexpr_baton **baton);
1604
1605 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1606
1607 static int need_gnat_info (struct dwarf2_cu *);
1608
1609 static struct type *die_descriptive_type (struct die_info *,
1610                                           struct dwarf2_cu *);
1611
1612 static void set_descriptive_type (struct type *, struct die_info *,
1613                                   struct dwarf2_cu *);
1614
1615 static struct type *die_containing_type (struct die_info *,
1616                                          struct dwarf2_cu *);
1617
1618 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1619                                      struct dwarf2_cu *);
1620
1621 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1622
1623 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1624
1625 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1626
1627 static char *typename_concat (struct obstack *obs, const char *prefix,
1628                               const char *suffix, int physname,
1629                               struct dwarf2_cu *cu);
1630
1631 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1632
1633 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1634
1635 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1636
1637 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1638
1639 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1640
1641 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1642
1643 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1644                                struct dwarf2_cu *, struct partial_symtab *);
1645
1646 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1647    values.  Keep the items ordered with increasing constraints compliance.  */
1648 enum pc_bounds_kind
1649 {
1650   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1651   PC_BOUNDS_NOT_PRESENT,
1652
1653   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1654      were present but they do not form a valid range of PC addresses.  */
1655   PC_BOUNDS_INVALID,
1656
1657   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1658   PC_BOUNDS_RANGES,
1659
1660   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1661   PC_BOUNDS_HIGH_LOW,
1662 };
1663
1664 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1665                                                  CORE_ADDR *, CORE_ADDR *,
1666                                                  struct dwarf2_cu *,
1667                                                  struct partial_symtab *);
1668
1669 static void get_scope_pc_bounds (struct die_info *,
1670                                  CORE_ADDR *, CORE_ADDR *,
1671                                  struct dwarf2_cu *);
1672
1673 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1674                                         CORE_ADDR, struct dwarf2_cu *);
1675
1676 static void dwarf2_add_field (struct field_info *, struct die_info *,
1677                               struct dwarf2_cu *);
1678
1679 static void dwarf2_attach_fields_to_type (struct field_info *,
1680                                           struct type *, struct dwarf2_cu *);
1681
1682 static void dwarf2_add_member_fn (struct field_info *,
1683                                   struct die_info *, struct type *,
1684                                   struct dwarf2_cu *);
1685
1686 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1687                                              struct type *,
1688                                              struct dwarf2_cu *);
1689
1690 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1691
1692 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1693
1694 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1695
1696 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1697
1698 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1699
1700 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1701
1702 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1703
1704 static struct type *read_module_type (struct die_info *die,
1705                                       struct dwarf2_cu *cu);
1706
1707 static const char *namespace_name (struct die_info *die,
1708                                    int *is_anonymous, struct dwarf2_cu *);
1709
1710 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1711
1712 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1713
1714 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1715                                                        struct dwarf2_cu *);
1716
1717 static struct die_info *read_die_and_siblings_1
1718   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1719    struct die_info *);
1720
1721 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1722                                                const gdb_byte *info_ptr,
1723                                                const gdb_byte **new_info_ptr,
1724                                                struct die_info *parent);
1725
1726 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1727                                         struct die_info **, const gdb_byte *,
1728                                         int *, int);
1729
1730 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1731                                       struct die_info **, const gdb_byte *,
1732                                       int *);
1733
1734 static void process_die (struct die_info *, struct dwarf2_cu *);
1735
1736 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1737                                              struct obstack *);
1738
1739 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1740
1741 static const char *dwarf2_full_name (const char *name,
1742                                      struct die_info *die,
1743                                      struct dwarf2_cu *cu);
1744
1745 static const char *dwarf2_physname (const char *name, struct die_info *die,
1746                                     struct dwarf2_cu *cu);
1747
1748 static struct die_info *dwarf2_extension (struct die_info *die,
1749                                           struct dwarf2_cu **);
1750
1751 static const char *dwarf_tag_name (unsigned int);
1752
1753 static const char *dwarf_attr_name (unsigned int);
1754
1755 static const char *dwarf_form_name (unsigned int);
1756
1757 static const char *dwarf_bool_name (unsigned int);
1758
1759 static const char *dwarf_type_encoding_name (unsigned int);
1760
1761 static struct die_info *sibling_die (struct die_info *);
1762
1763 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1764
1765 static void dump_die_for_error (struct die_info *);
1766
1767 static void dump_die_1 (struct ui_file *, int level, int max_level,
1768                         struct die_info *);
1769
1770 /*static*/ void dump_die (struct die_info *, int max_level);
1771
1772 static void store_in_ref_table (struct die_info *,
1773                                 struct dwarf2_cu *);
1774
1775 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1776
1777 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1778
1779 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1780                                                const struct attribute *,
1781                                                struct dwarf2_cu **);
1782
1783 static struct die_info *follow_die_ref (struct die_info *,
1784                                         const struct attribute *,
1785                                         struct dwarf2_cu **);
1786
1787 static struct die_info *follow_die_sig (struct die_info *,
1788                                         const struct attribute *,
1789                                         struct dwarf2_cu **);
1790
1791 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1792                                          struct dwarf2_cu *);
1793
1794 static struct type *get_DW_AT_signature_type (struct die_info *,
1795                                               const struct attribute *,
1796                                               struct dwarf2_cu *);
1797
1798 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1799
1800 static void read_signatured_type (struct signatured_type *);
1801
1802 static int attr_to_dynamic_prop (const struct attribute *attr,
1803                                  struct die_info *die, struct dwarf2_cu *cu,
1804                                  struct dynamic_prop *prop);
1805
1806 /* memory allocation interface */
1807
1808 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1809
1810 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1811
1812 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1813
1814 static int attr_form_is_block (const struct attribute *);
1815
1816 static int attr_form_is_section_offset (const struct attribute *);
1817
1818 static int attr_form_is_constant (const struct attribute *);
1819
1820 static int attr_form_is_ref (const struct attribute *);
1821
1822 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1823                                    struct dwarf2_loclist_baton *baton,
1824                                    const struct attribute *attr);
1825
1826 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1827                                          struct symbol *sym,
1828                                          struct dwarf2_cu *cu,
1829                                          int is_block);
1830
1831 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1832                                      const gdb_byte *info_ptr,
1833                                      struct abbrev_info *abbrev);
1834
1835 static hashval_t partial_die_hash (const void *item);
1836
1837 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1838
1839 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1840   (sect_offset sect_off, unsigned int offset_in_dwz,
1841    struct dwarf2_per_objfile *dwarf2_per_objfile);
1842
1843 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1844                                    struct die_info *comp_unit_die,
1845                                    enum language pretend_language);
1846
1847 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1848
1849 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1850
1851 static struct type *set_die_type (struct die_info *, struct type *,
1852                                   struct dwarf2_cu *);
1853
1854 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1855
1856 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1857
1858 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1859                                  enum language);
1860
1861 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1862                                     enum language);
1863
1864 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1865                                     enum language);
1866
1867 static void dwarf2_add_dependence (struct dwarf2_cu *,
1868                                    struct dwarf2_per_cu_data *);
1869
1870 static void dwarf2_mark (struct dwarf2_cu *);
1871
1872 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1873
1874 static struct type *get_die_type_at_offset (sect_offset,
1875                                             struct dwarf2_per_cu_data *);
1876
1877 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1878
1879 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1880                              enum language pretend_language);
1881
1882 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1883
1884 /* Class, the destructor of which frees all allocated queue entries.  This
1885    will only have work to do if an error was thrown while processing the
1886    dwarf.  If no error was thrown then the queue entries should have all
1887    been processed, and freed, as we went along.  */
1888
1889 class dwarf2_queue_guard
1890 {
1891 public:
1892   dwarf2_queue_guard () = default;
1893
1894   /* Free any entries remaining on the queue.  There should only be
1895      entries left if we hit an error while processing the dwarf.  */
1896   ~dwarf2_queue_guard ()
1897   {
1898     struct dwarf2_queue_item *item, *last;
1899
1900     item = dwarf2_queue;
1901     while (item)
1902       {
1903         /* Anything still marked queued is likely to be in an
1904            inconsistent state, so discard it.  */
1905         if (item->per_cu->queued)
1906           {
1907             if (item->per_cu->cu != NULL)
1908               free_one_cached_comp_unit (item->per_cu);
1909             item->per_cu->queued = 0;
1910           }
1911
1912         last = item;
1913         item = item->next;
1914         xfree (last);
1915       }
1916
1917     dwarf2_queue = dwarf2_queue_tail = NULL;
1918   }
1919 };
1920
1921 /* The return type of find_file_and_directory.  Note, the enclosed
1922    string pointers are only valid while this object is valid.  */
1923
1924 struct file_and_directory
1925 {
1926   /* The filename.  This is never NULL.  */
1927   const char *name;
1928
1929   /* The compilation directory.  NULL if not known.  If we needed to
1930      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1931      points directly to the DW_AT_comp_dir string attribute owned by
1932      the obstack that owns the DIE.  */
1933   const char *comp_dir;
1934
1935   /* If we needed to build a new string for comp_dir, this is what
1936      owns the storage.  */
1937   std::string comp_dir_storage;
1938 };
1939
1940 static file_and_directory find_file_and_directory (struct die_info *die,
1941                                                    struct dwarf2_cu *cu);
1942
1943 static char *file_full_name (int file, struct line_header *lh,
1944                              const char *comp_dir);
1945
1946 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1947 enum class rcuh_kind { COMPILE, TYPE };
1948
1949 static const gdb_byte *read_and_check_comp_unit_head
1950   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1951    struct comp_unit_head *header,
1952    struct dwarf2_section_info *section,
1953    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1954    rcuh_kind section_kind);
1955
1956 static void init_cutu_and_read_dies
1957   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1958    int use_existing_cu, int keep, bool skip_partial,
1959    die_reader_func_ftype *die_reader_func, void *data);
1960
1961 static void init_cutu_and_read_dies_simple
1962   (struct dwarf2_per_cu_data *this_cu,
1963    die_reader_func_ftype *die_reader_func, void *data);
1964
1965 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1966
1967 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1968
1969 static struct dwo_unit *lookup_dwo_unit_in_dwp
1970   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1971    struct dwp_file *dwp_file, const char *comp_dir,
1972    ULONGEST signature, int is_debug_types);
1973
1974 static struct dwp_file *get_dwp_file
1975   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1976
1977 static struct dwo_unit *lookup_dwo_comp_unit
1978   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1979
1980 static struct dwo_unit *lookup_dwo_type_unit
1981   (struct signatured_type *, const char *, const char *);
1982
1983 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1984
1985 static void free_dwo_file (struct dwo_file *);
1986
1987 /* A unique_ptr helper to free a dwo_file.  */
1988
1989 struct dwo_file_deleter
1990 {
1991   void operator() (struct dwo_file *df) const
1992   {
1993     free_dwo_file (df);
1994   }
1995 };
1996
1997 /* A unique pointer to a dwo_file.  */
1998
1999 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
2000
2001 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2002
2003 static void check_producer (struct dwarf2_cu *cu);
2004
2005 static void free_line_header_voidp (void *arg);
2006 \f
2007 /* Various complaints about symbol reading that don't abort the process.  */
2008
2009 static void
2010 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2011 {
2012   complaint (_("statement list doesn't fit in .debug_line section"));
2013 }
2014
2015 static void
2016 dwarf2_debug_line_missing_file_complaint (void)
2017 {
2018   complaint (_(".debug_line section has line data without a file"));
2019 }
2020
2021 static void
2022 dwarf2_debug_line_missing_end_sequence_complaint (void)
2023 {
2024   complaint (_(".debug_line section has line "
2025                "program sequence without an end"));
2026 }
2027
2028 static void
2029 dwarf2_complex_location_expr_complaint (void)
2030 {
2031   complaint (_("location expression too complex"));
2032 }
2033
2034 static void
2035 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2036                                               int arg3)
2037 {
2038   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2039              arg1, arg2, arg3);
2040 }
2041
2042 static void
2043 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2044 {
2045   complaint (_("debug info runs off end of %s section"
2046                " [in module %s]"),
2047              get_section_name (section),
2048              get_section_file_name (section));
2049 }
2050
2051 static void
2052 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2053 {
2054   complaint (_("macro debug info contains a "
2055                "malformed macro definition:\n`%s'"),
2056              arg1);
2057 }
2058
2059 static void
2060 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2061 {
2062   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2063              arg1, arg2);
2064 }
2065
2066 /* Hash function for line_header_hash.  */
2067
2068 static hashval_t
2069 line_header_hash (const struct line_header *ofs)
2070 {
2071   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2072 }
2073
2074 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2075
2076 static hashval_t
2077 line_header_hash_voidp (const void *item)
2078 {
2079   const struct line_header *ofs = (const struct line_header *) item;
2080
2081   return line_header_hash (ofs);
2082 }
2083
2084 /* Equality function for line_header_hash.  */
2085
2086 static int
2087 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2088 {
2089   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2090   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2091
2092   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2093           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2094 }
2095
2096 \f
2097
2098 /* Read the given attribute value as an address, taking the attribute's
2099    form into account.  */
2100
2101 static CORE_ADDR
2102 attr_value_as_address (struct attribute *attr)
2103 {
2104   CORE_ADDR addr;
2105
2106   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2107     {
2108       /* Aside from a few clearly defined exceptions, attributes that
2109          contain an address must always be in DW_FORM_addr form.
2110          Unfortunately, some compilers happen to be violating this
2111          requirement by encoding addresses using other forms, such
2112          as DW_FORM_data4 for example.  For those broken compilers,
2113          we try to do our best, without any guarantee of success,
2114          to interpret the address correctly.  It would also be nice
2115          to generate a complaint, but that would require us to maintain
2116          a list of legitimate cases where a non-address form is allowed,
2117          as well as update callers to pass in at least the CU's DWARF
2118          version.  This is more overhead than what we're willing to
2119          expand for a pretty rare case.  */
2120       addr = DW_UNSND (attr);
2121     }
2122   else
2123     addr = DW_ADDR (attr);
2124
2125   return addr;
2126 }
2127
2128 /* See declaration.  */
2129
2130 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2131                                         const dwarf2_debug_sections *names)
2132   : objfile (objfile_)
2133 {
2134   if (names == NULL)
2135     names = &dwarf2_elf_names;
2136
2137   bfd *obfd = objfile->obfd;
2138
2139   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2140     locate_sections (obfd, sec, *names);
2141 }
2142
2143 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2144
2145 dwarf2_per_objfile::~dwarf2_per_objfile ()
2146 {
2147   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2148   free_cached_comp_units ();
2149
2150   if (quick_file_names_table)
2151     htab_delete (quick_file_names_table);
2152
2153   if (line_header_hash)
2154     htab_delete (line_header_hash);
2155
2156   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2157     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2158
2159   for (signatured_type *sig_type : all_type_units)
2160     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2161
2162   VEC_free (dwarf2_section_info_def, types);
2163
2164   if (dwo_files != NULL)
2165     free_dwo_files (dwo_files, objfile);
2166
2167   /* Everything else should be on the objfile obstack.  */
2168 }
2169
2170 /* See declaration.  */
2171
2172 void
2173 dwarf2_per_objfile::free_cached_comp_units ()
2174 {
2175   dwarf2_per_cu_data *per_cu = read_in_chain;
2176   dwarf2_per_cu_data **last_chain = &read_in_chain;
2177   while (per_cu != NULL)
2178     {
2179       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2180
2181       delete per_cu->cu;
2182       *last_chain = next_cu;
2183       per_cu = next_cu;
2184     }
2185 }
2186
2187 /* A helper class that calls free_cached_comp_units on
2188    destruction.  */
2189
2190 class free_cached_comp_units
2191 {
2192 public:
2193
2194   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2195     : m_per_objfile (per_objfile)
2196   {
2197   }
2198
2199   ~free_cached_comp_units ()
2200   {
2201     m_per_objfile->free_cached_comp_units ();
2202   }
2203
2204   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2205
2206 private:
2207
2208   dwarf2_per_objfile *m_per_objfile;
2209 };
2210
2211 /* Try to locate the sections we need for DWARF 2 debugging
2212    information and return true if we have enough to do something.
2213    NAMES points to the dwarf2 section names, or is NULL if the standard
2214    ELF names are used.  */
2215
2216 int
2217 dwarf2_has_info (struct objfile *objfile,
2218                  const struct dwarf2_debug_sections *names)
2219 {
2220   if (objfile->flags & OBJF_READNEVER)
2221     return 0;
2222
2223   struct dwarf2_per_objfile *dwarf2_per_objfile
2224     = get_dwarf2_per_objfile (objfile);
2225
2226   if (dwarf2_per_objfile == NULL)
2227     {
2228       /* Initialize per-objfile state.  */
2229       dwarf2_per_objfile
2230         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2231                                                                      names);
2232       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2233     }
2234   return (!dwarf2_per_objfile->info.is_virtual
2235           && dwarf2_per_objfile->info.s.section != NULL
2236           && !dwarf2_per_objfile->abbrev.is_virtual
2237           && dwarf2_per_objfile->abbrev.s.section != NULL);
2238 }
2239
2240 /* Return the containing section of virtual section SECTION.  */
2241
2242 static struct dwarf2_section_info *
2243 get_containing_section (const struct dwarf2_section_info *section)
2244 {
2245   gdb_assert (section->is_virtual);
2246   return section->s.containing_section;
2247 }
2248
2249 /* Return the bfd owner of SECTION.  */
2250
2251 static struct bfd *
2252 get_section_bfd_owner (const struct dwarf2_section_info *section)
2253 {
2254   if (section->is_virtual)
2255     {
2256       section = get_containing_section (section);
2257       gdb_assert (!section->is_virtual);
2258     }
2259   return section->s.section->owner;
2260 }
2261
2262 /* Return the bfd section of SECTION.
2263    Returns NULL if the section is not present.  */
2264
2265 static asection *
2266 get_section_bfd_section (const struct dwarf2_section_info *section)
2267 {
2268   if (section->is_virtual)
2269     {
2270       section = get_containing_section (section);
2271       gdb_assert (!section->is_virtual);
2272     }
2273   return section->s.section;
2274 }
2275
2276 /* Return the name of SECTION.  */
2277
2278 static const char *
2279 get_section_name (const struct dwarf2_section_info *section)
2280 {
2281   asection *sectp = get_section_bfd_section (section);
2282
2283   gdb_assert (sectp != NULL);
2284   return bfd_section_name (get_section_bfd_owner (section), sectp);
2285 }
2286
2287 /* Return the name of the file SECTION is in.  */
2288
2289 static const char *
2290 get_section_file_name (const struct dwarf2_section_info *section)
2291 {
2292   bfd *abfd = get_section_bfd_owner (section);
2293
2294   return bfd_get_filename (abfd);
2295 }
2296
2297 /* Return the id of SECTION.
2298    Returns 0 if SECTION doesn't exist.  */
2299
2300 static int
2301 get_section_id (const struct dwarf2_section_info *section)
2302 {
2303   asection *sectp = get_section_bfd_section (section);
2304
2305   if (sectp == NULL)
2306     return 0;
2307   return sectp->id;
2308 }
2309
2310 /* Return the flags of SECTION.
2311    SECTION (or containing section if this is a virtual section) must exist.  */
2312
2313 static int
2314 get_section_flags (const struct dwarf2_section_info *section)
2315 {
2316   asection *sectp = get_section_bfd_section (section);
2317
2318   gdb_assert (sectp != NULL);
2319   return bfd_get_section_flags (sectp->owner, sectp);
2320 }
2321
2322 /* When loading sections, we look either for uncompressed section or for
2323    compressed section names.  */
2324
2325 static int
2326 section_is_p (const char *section_name,
2327               const struct dwarf2_section_names *names)
2328 {
2329   if (names->normal != NULL
2330       && strcmp (section_name, names->normal) == 0)
2331     return 1;
2332   if (names->compressed != NULL
2333       && strcmp (section_name, names->compressed) == 0)
2334     return 1;
2335   return 0;
2336 }
2337
2338 /* See declaration.  */
2339
2340 void
2341 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2342                                      const dwarf2_debug_sections &names)
2343 {
2344   flagword aflag = bfd_get_section_flags (abfd, sectp);
2345
2346   if ((aflag & SEC_HAS_CONTENTS) == 0)
2347     {
2348     }
2349   else if (section_is_p (sectp->name, &names.info))
2350     {
2351       this->info.s.section = sectp;
2352       this->info.size = bfd_get_section_size (sectp);
2353     }
2354   else if (section_is_p (sectp->name, &names.abbrev))
2355     {
2356       this->abbrev.s.section = sectp;
2357       this->abbrev.size = bfd_get_section_size (sectp);
2358     }
2359   else if (section_is_p (sectp->name, &names.line))
2360     {
2361       this->line.s.section = sectp;
2362       this->line.size = bfd_get_section_size (sectp);
2363     }
2364   else if (section_is_p (sectp->name, &names.loc))
2365     {
2366       this->loc.s.section = sectp;
2367       this->loc.size = bfd_get_section_size (sectp);
2368     }
2369   else if (section_is_p (sectp->name, &names.loclists))
2370     {
2371       this->loclists.s.section = sectp;
2372       this->loclists.size = bfd_get_section_size (sectp);
2373     }
2374   else if (section_is_p (sectp->name, &names.macinfo))
2375     {
2376       this->macinfo.s.section = sectp;
2377       this->macinfo.size = bfd_get_section_size (sectp);
2378     }
2379   else if (section_is_p (sectp->name, &names.macro))
2380     {
2381       this->macro.s.section = sectp;
2382       this->macro.size = bfd_get_section_size (sectp);
2383     }
2384   else if (section_is_p (sectp->name, &names.str))
2385     {
2386       this->str.s.section = sectp;
2387       this->str.size = bfd_get_section_size (sectp);
2388     }
2389   else if (section_is_p (sectp->name, &names.line_str))
2390     {
2391       this->line_str.s.section = sectp;
2392       this->line_str.size = bfd_get_section_size (sectp);
2393     }
2394   else if (section_is_p (sectp->name, &names.addr))
2395     {
2396       this->addr.s.section = sectp;
2397       this->addr.size = bfd_get_section_size (sectp);
2398     }
2399   else if (section_is_p (sectp->name, &names.frame))
2400     {
2401       this->frame.s.section = sectp;
2402       this->frame.size = bfd_get_section_size (sectp);
2403     }
2404   else if (section_is_p (sectp->name, &names.eh_frame))
2405     {
2406       this->eh_frame.s.section = sectp;
2407       this->eh_frame.size = bfd_get_section_size (sectp);
2408     }
2409   else if (section_is_p (sectp->name, &names.ranges))
2410     {
2411       this->ranges.s.section = sectp;
2412       this->ranges.size = bfd_get_section_size (sectp);
2413     }
2414   else if (section_is_p (sectp->name, &names.rnglists))
2415     {
2416       this->rnglists.s.section = sectp;
2417       this->rnglists.size = bfd_get_section_size (sectp);
2418     }
2419   else if (section_is_p (sectp->name, &names.types))
2420     {
2421       struct dwarf2_section_info type_section;
2422
2423       memset (&type_section, 0, sizeof (type_section));
2424       type_section.s.section = sectp;
2425       type_section.size = bfd_get_section_size (sectp);
2426
2427       VEC_safe_push (dwarf2_section_info_def, this->types,
2428                      &type_section);
2429     }
2430   else if (section_is_p (sectp->name, &names.gdb_index))
2431     {
2432       this->gdb_index.s.section = sectp;
2433       this->gdb_index.size = bfd_get_section_size (sectp);
2434     }
2435   else if (section_is_p (sectp->name, &names.debug_names))
2436     {
2437       this->debug_names.s.section = sectp;
2438       this->debug_names.size = bfd_get_section_size (sectp);
2439     }
2440   else if (section_is_p (sectp->name, &names.debug_aranges))
2441     {
2442       this->debug_aranges.s.section = sectp;
2443       this->debug_aranges.size = bfd_get_section_size (sectp);
2444     }
2445
2446   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2447       && bfd_section_vma (abfd, sectp) == 0)
2448     this->has_section_at_zero = true;
2449 }
2450
2451 /* A helper function that decides whether a section is empty,
2452    or not present.  */
2453
2454 static int
2455 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2456 {
2457   if (section->is_virtual)
2458     return section->size == 0;
2459   return section->s.section == NULL || section->size == 0;
2460 }
2461
2462 /* See dwarf2read.h.  */
2463
2464 void
2465 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2466 {
2467   asection *sectp;
2468   bfd *abfd;
2469   gdb_byte *buf, *retbuf;
2470
2471   if (info->readin)
2472     return;
2473   info->buffer = NULL;
2474   info->readin = 1;
2475
2476   if (dwarf2_section_empty_p (info))
2477     return;
2478
2479   sectp = get_section_bfd_section (info);
2480
2481   /* If this is a virtual section we need to read in the real one first.  */
2482   if (info->is_virtual)
2483     {
2484       struct dwarf2_section_info *containing_section =
2485         get_containing_section (info);
2486
2487       gdb_assert (sectp != NULL);
2488       if ((sectp->flags & SEC_RELOC) != 0)
2489         {
2490           error (_("Dwarf Error: DWP format V2 with relocations is not"
2491                    " supported in section %s [in module %s]"),
2492                  get_section_name (info), get_section_file_name (info));
2493         }
2494       dwarf2_read_section (objfile, containing_section);
2495       /* Other code should have already caught virtual sections that don't
2496          fit.  */
2497       gdb_assert (info->virtual_offset + info->size
2498                   <= containing_section->size);
2499       /* If the real section is empty or there was a problem reading the
2500          section we shouldn't get here.  */
2501       gdb_assert (containing_section->buffer != NULL);
2502       info->buffer = containing_section->buffer + info->virtual_offset;
2503       return;
2504     }
2505
2506   /* If the section has relocations, we must read it ourselves.
2507      Otherwise we attach it to the BFD.  */
2508   if ((sectp->flags & SEC_RELOC) == 0)
2509     {
2510       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2511       return;
2512     }
2513
2514   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2515   info->buffer = buf;
2516
2517   /* When debugging .o files, we may need to apply relocations; see
2518      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2519      We never compress sections in .o files, so we only need to
2520      try this when the section is not compressed.  */
2521   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2522   if (retbuf != NULL)
2523     {
2524       info->buffer = retbuf;
2525       return;
2526     }
2527
2528   abfd = get_section_bfd_owner (info);
2529   gdb_assert (abfd != NULL);
2530
2531   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2532       || bfd_bread (buf, info->size, abfd) != info->size)
2533     {
2534       error (_("Dwarf Error: Can't read DWARF data"
2535                " in section %s [in module %s]"),
2536              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2537     }
2538 }
2539
2540 /* A helper function that returns the size of a section in a safe way.
2541    If you are positive that the section has been read before using the
2542    size, then it is safe to refer to the dwarf2_section_info object's
2543    "size" field directly.  In other cases, you must call this
2544    function, because for compressed sections the size field is not set
2545    correctly until the section has been read.  */
2546
2547 static bfd_size_type
2548 dwarf2_section_size (struct objfile *objfile,
2549                      struct dwarf2_section_info *info)
2550 {
2551   if (!info->readin)
2552     dwarf2_read_section (objfile, info);
2553   return info->size;
2554 }
2555
2556 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2557    SECTION_NAME.  */
2558
2559 void
2560 dwarf2_get_section_info (struct objfile *objfile,
2561                          enum dwarf2_section_enum sect,
2562                          asection **sectp, const gdb_byte **bufp,
2563                          bfd_size_type *sizep)
2564 {
2565   struct dwarf2_per_objfile *data
2566     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2567                                                   dwarf2_objfile_data_key);
2568   struct dwarf2_section_info *info;
2569
2570   /* We may see an objfile without any DWARF, in which case we just
2571      return nothing.  */
2572   if (data == NULL)
2573     {
2574       *sectp = NULL;
2575       *bufp = NULL;
2576       *sizep = 0;
2577       return;
2578     }
2579   switch (sect)
2580     {
2581     case DWARF2_DEBUG_FRAME:
2582       info = &data->frame;
2583       break;
2584     case DWARF2_EH_FRAME:
2585       info = &data->eh_frame;
2586       break;
2587     default:
2588       gdb_assert_not_reached ("unexpected section");
2589     }
2590
2591   dwarf2_read_section (objfile, info);
2592
2593   *sectp = get_section_bfd_section (info);
2594   *bufp = info->buffer;
2595   *sizep = info->size;
2596 }
2597
2598 /* A helper function to find the sections for a .dwz file.  */
2599
2600 static void
2601 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2602 {
2603   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2604
2605   /* Note that we only support the standard ELF names, because .dwz
2606      is ELF-only (at the time of writing).  */
2607   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2608     {
2609       dwz_file->abbrev.s.section = sectp;
2610       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2611     }
2612   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2613     {
2614       dwz_file->info.s.section = sectp;
2615       dwz_file->info.size = bfd_get_section_size (sectp);
2616     }
2617   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2618     {
2619       dwz_file->str.s.section = sectp;
2620       dwz_file->str.size = bfd_get_section_size (sectp);
2621     }
2622   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2623     {
2624       dwz_file->line.s.section = sectp;
2625       dwz_file->line.size = bfd_get_section_size (sectp);
2626     }
2627   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2628     {
2629       dwz_file->macro.s.section = sectp;
2630       dwz_file->macro.size = bfd_get_section_size (sectp);
2631     }
2632   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2633     {
2634       dwz_file->gdb_index.s.section = sectp;
2635       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2636     }
2637   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2638     {
2639       dwz_file->debug_names.s.section = sectp;
2640       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2641     }
2642 }
2643
2644 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2645    there is no .gnu_debugaltlink section in the file.  Error if there
2646    is such a section but the file cannot be found.  */
2647
2648 static struct dwz_file *
2649 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2650 {
2651   const char *filename;
2652   bfd_size_type buildid_len_arg;
2653   size_t buildid_len;
2654   bfd_byte *buildid;
2655
2656   if (dwarf2_per_objfile->dwz_file != NULL)
2657     return dwarf2_per_objfile->dwz_file.get ();
2658
2659   bfd_set_error (bfd_error_no_error);
2660   gdb::unique_xmalloc_ptr<char> data
2661     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2662                                   &buildid_len_arg, &buildid));
2663   if (data == NULL)
2664     {
2665       if (bfd_get_error () == bfd_error_no_error)
2666         return NULL;
2667       error (_("could not read '.gnu_debugaltlink' section: %s"),
2668              bfd_errmsg (bfd_get_error ()));
2669     }
2670
2671   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2672
2673   buildid_len = (size_t) buildid_len_arg;
2674
2675   filename = data.get ();
2676
2677   std::string abs_storage;
2678   if (!IS_ABSOLUTE_PATH (filename))
2679     {
2680       gdb::unique_xmalloc_ptr<char> abs
2681         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2682
2683       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2684       filename = abs_storage.c_str ();
2685     }
2686
2687   /* First try the file name given in the section.  If that doesn't
2688      work, try to use the build-id instead.  */
2689   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2690   if (dwz_bfd != NULL)
2691     {
2692       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2693         dwz_bfd.release ();
2694     }
2695
2696   if (dwz_bfd == NULL)
2697     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2698
2699   if (dwz_bfd == NULL)
2700     error (_("could not find '.gnu_debugaltlink' file for %s"),
2701            objfile_name (dwarf2_per_objfile->objfile));
2702
2703   std::unique_ptr<struct dwz_file> result
2704     (new struct dwz_file (std::move (dwz_bfd)));
2705
2706   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2707                          result.get ());
2708
2709   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2710                             result->dwz_bfd.get ());
2711   dwarf2_per_objfile->dwz_file = std::move (result);
2712   return dwarf2_per_objfile->dwz_file.get ();
2713 }
2714 \f
2715 /* DWARF quick_symbols_functions support.  */
2716
2717 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2718    unique line tables, so we maintain a separate table of all .debug_line
2719    derived entries to support the sharing.
2720    All the quick functions need is the list of file names.  We discard the
2721    line_header when we're done and don't need to record it here.  */
2722 struct quick_file_names
2723 {
2724   /* The data used to construct the hash key.  */
2725   struct stmt_list_hash hash;
2726
2727   /* The number of entries in file_names, real_names.  */
2728   unsigned int num_file_names;
2729
2730   /* The file names from the line table, after being run through
2731      file_full_name.  */
2732   const char **file_names;
2733
2734   /* The file names from the line table after being run through
2735      gdb_realpath.  These are computed lazily.  */
2736   const char **real_names;
2737 };
2738
2739 /* When using the index (and thus not using psymtabs), each CU has an
2740    object of this type.  This is used to hold information needed by
2741    the various "quick" methods.  */
2742 struct dwarf2_per_cu_quick_data
2743 {
2744   /* The file table.  This can be NULL if there was no file table
2745      or it's currently not read in.
2746      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2747   struct quick_file_names *file_names;
2748
2749   /* The corresponding symbol table.  This is NULL if symbols for this
2750      CU have not yet been read.  */
2751   struct compunit_symtab *compunit_symtab;
2752
2753   /* A temporary mark bit used when iterating over all CUs in
2754      expand_symtabs_matching.  */
2755   unsigned int mark : 1;
2756
2757   /* True if we've tried to read the file table and found there isn't one.
2758      There will be no point in trying to read it again next time.  */
2759   unsigned int no_file_data : 1;
2760 };
2761
2762 /* Utility hash function for a stmt_list_hash.  */
2763
2764 static hashval_t
2765 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2766 {
2767   hashval_t v = 0;
2768
2769   if (stmt_list_hash->dwo_unit != NULL)
2770     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2771   v += to_underlying (stmt_list_hash->line_sect_off);
2772   return v;
2773 }
2774
2775 /* Utility equality function for a stmt_list_hash.  */
2776
2777 static int
2778 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2779                     const struct stmt_list_hash *rhs)
2780 {
2781   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2782     return 0;
2783   if (lhs->dwo_unit != NULL
2784       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2785     return 0;
2786
2787   return lhs->line_sect_off == rhs->line_sect_off;
2788 }
2789
2790 /* Hash function for a quick_file_names.  */
2791
2792 static hashval_t
2793 hash_file_name_entry (const void *e)
2794 {
2795   const struct quick_file_names *file_data
2796     = (const struct quick_file_names *) e;
2797
2798   return hash_stmt_list_entry (&file_data->hash);
2799 }
2800
2801 /* Equality function for a quick_file_names.  */
2802
2803 static int
2804 eq_file_name_entry (const void *a, const void *b)
2805 {
2806   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2807   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2808
2809   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2810 }
2811
2812 /* Delete function for a quick_file_names.  */
2813
2814 static void
2815 delete_file_name_entry (void *e)
2816 {
2817   struct quick_file_names *file_data = (struct quick_file_names *) e;
2818   int i;
2819
2820   for (i = 0; i < file_data->num_file_names; ++i)
2821     {
2822       xfree ((void*) file_data->file_names[i]);
2823       if (file_data->real_names)
2824         xfree ((void*) file_data->real_names[i]);
2825     }
2826
2827   /* The space for the struct itself lives on objfile_obstack,
2828      so we don't free it here.  */
2829 }
2830
2831 /* Create a quick_file_names hash table.  */
2832
2833 static htab_t
2834 create_quick_file_names_table (unsigned int nr_initial_entries)
2835 {
2836   return htab_create_alloc (nr_initial_entries,
2837                             hash_file_name_entry, eq_file_name_entry,
2838                             delete_file_name_entry, xcalloc, xfree);
2839 }
2840
2841 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2842    have to be created afterwards.  You should call age_cached_comp_units after
2843    processing PER_CU->CU.  dw2_setup must have been already called.  */
2844
2845 static void
2846 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2847 {
2848   if (per_cu->is_debug_types)
2849     load_full_type_unit (per_cu);
2850   else
2851     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2852
2853   if (per_cu->cu == NULL)
2854     return;  /* Dummy CU.  */
2855
2856   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2857 }
2858
2859 /* Read in the symbols for PER_CU.  */
2860
2861 static void
2862 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2863 {
2864   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2865
2866   /* Skip type_unit_groups, reading the type units they contain
2867      is handled elsewhere.  */
2868   if (IS_TYPE_UNIT_GROUP (per_cu))
2869     return;
2870
2871   /* The destructor of dwarf2_queue_guard frees any entries left on
2872      the queue.  After this point we're guaranteed to leave this function
2873      with the dwarf queue empty.  */
2874   dwarf2_queue_guard q_guard;
2875
2876   if (dwarf2_per_objfile->using_index
2877       ? per_cu->v.quick->compunit_symtab == NULL
2878       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2879     {
2880       queue_comp_unit (per_cu, language_minimal);
2881       load_cu (per_cu, skip_partial);
2882
2883       /* If we just loaded a CU from a DWO, and we're working with an index
2884          that may badly handle TUs, load all the TUs in that DWO as well.
2885          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2886       if (!per_cu->is_debug_types
2887           && per_cu->cu != NULL
2888           && per_cu->cu->dwo_unit != NULL
2889           && dwarf2_per_objfile->index_table != NULL
2890           && dwarf2_per_objfile->index_table->version <= 7
2891           /* DWP files aren't supported yet.  */
2892           && get_dwp_file (dwarf2_per_objfile) == NULL)
2893         queue_and_load_all_dwo_tus (per_cu);
2894     }
2895
2896   process_queue (dwarf2_per_objfile);
2897
2898   /* Age the cache, releasing compilation units that have not
2899      been used recently.  */
2900   age_cached_comp_units (dwarf2_per_objfile);
2901 }
2902
2903 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2904    the objfile from which this CU came.  Returns the resulting symbol
2905    table.  */
2906
2907 static struct compunit_symtab *
2908 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2909 {
2910   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2911
2912   gdb_assert (dwarf2_per_objfile->using_index);
2913   if (!per_cu->v.quick->compunit_symtab)
2914     {
2915       free_cached_comp_units freer (dwarf2_per_objfile);
2916       scoped_restore decrementer = increment_reading_symtab ();
2917       dw2_do_instantiate_symtab (per_cu, skip_partial);
2918       process_cu_includes (dwarf2_per_objfile);
2919     }
2920
2921   return per_cu->v.quick->compunit_symtab;
2922 }
2923
2924 /* See declaration.  */
2925
2926 dwarf2_per_cu_data *
2927 dwarf2_per_objfile::get_cutu (int index)
2928 {
2929   if (index >= this->all_comp_units.size ())
2930     {
2931       index -= this->all_comp_units.size ();
2932       gdb_assert (index < this->all_type_units.size ());
2933       return &this->all_type_units[index]->per_cu;
2934     }
2935
2936   return this->all_comp_units[index];
2937 }
2938
2939 /* See declaration.  */
2940
2941 dwarf2_per_cu_data *
2942 dwarf2_per_objfile::get_cu (int index)
2943 {
2944   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2945
2946   return this->all_comp_units[index];
2947 }
2948
2949 /* See declaration.  */
2950
2951 signatured_type *
2952 dwarf2_per_objfile::get_tu (int index)
2953 {
2954   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2955
2956   return this->all_type_units[index];
2957 }
2958
2959 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2960    objfile_obstack, and constructed with the specified field
2961    values.  */
2962
2963 static dwarf2_per_cu_data *
2964 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2965                           struct dwarf2_section_info *section,
2966                           int is_dwz,
2967                           sect_offset sect_off, ULONGEST length)
2968 {
2969   struct objfile *objfile = dwarf2_per_objfile->objfile;
2970   dwarf2_per_cu_data *the_cu
2971     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2972                      struct dwarf2_per_cu_data);
2973   the_cu->sect_off = sect_off;
2974   the_cu->length = length;
2975   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2976   the_cu->section = section;
2977   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2978                                    struct dwarf2_per_cu_quick_data);
2979   the_cu->is_dwz = is_dwz;
2980   return the_cu;
2981 }
2982
2983 /* A helper for create_cus_from_index that handles a given list of
2984    CUs.  */
2985
2986 static void
2987 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2988                             const gdb_byte *cu_list, offset_type n_elements,
2989                             struct dwarf2_section_info *section,
2990                             int is_dwz)
2991 {
2992   for (offset_type i = 0; i < n_elements; i += 2)
2993     {
2994       gdb_static_assert (sizeof (ULONGEST) >= 8);
2995
2996       sect_offset sect_off
2997         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2998       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2999       cu_list += 2 * 8;
3000
3001       dwarf2_per_cu_data *per_cu
3002         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3003                                      sect_off, length);
3004       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
3005     }
3006 }
3007
3008 /* Read the CU list from the mapped index, and use it to create all
3009    the CU objects for this objfile.  */
3010
3011 static void
3012 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3013                        const gdb_byte *cu_list, offset_type cu_list_elements,
3014                        const gdb_byte *dwz_list, offset_type dwz_elements)
3015 {
3016   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3017   dwarf2_per_objfile->all_comp_units.reserve
3018     ((cu_list_elements + dwz_elements) / 2);
3019
3020   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3021                               &dwarf2_per_objfile->info, 0);
3022
3023   if (dwz_elements == 0)
3024     return;
3025
3026   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3027   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3028                               &dwz->info, 1);
3029 }
3030
3031 /* Create the signatured type hash table from the index.  */
3032
3033 static void
3034 create_signatured_type_table_from_index
3035   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3036    struct dwarf2_section_info *section,
3037    const gdb_byte *bytes,
3038    offset_type elements)
3039 {
3040   struct objfile *objfile = dwarf2_per_objfile->objfile;
3041
3042   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3043   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3044
3045   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3046
3047   for (offset_type i = 0; i < elements; i += 3)
3048     {
3049       struct signatured_type *sig_type;
3050       ULONGEST signature;
3051       void **slot;
3052       cu_offset type_offset_in_tu;
3053
3054       gdb_static_assert (sizeof (ULONGEST) >= 8);
3055       sect_offset sect_off
3056         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3057       type_offset_in_tu
3058         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3059                                                 BFD_ENDIAN_LITTLE);
3060       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3061       bytes += 3 * 8;
3062
3063       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3064                                  struct signatured_type);
3065       sig_type->signature = signature;
3066       sig_type->type_offset_in_tu = type_offset_in_tu;
3067       sig_type->per_cu.is_debug_types = 1;
3068       sig_type->per_cu.section = section;
3069       sig_type->per_cu.sect_off = sect_off;
3070       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3071       sig_type->per_cu.v.quick
3072         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3073                           struct dwarf2_per_cu_quick_data);
3074
3075       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3076       *slot = sig_type;
3077
3078       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3079     }
3080
3081   dwarf2_per_objfile->signatured_types = sig_types_hash;
3082 }
3083
3084 /* Create the signatured type hash table from .debug_names.  */
3085
3086 static void
3087 create_signatured_type_table_from_debug_names
3088   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3089    const mapped_debug_names &map,
3090    struct dwarf2_section_info *section,
3091    struct dwarf2_section_info *abbrev_section)
3092 {
3093   struct objfile *objfile = dwarf2_per_objfile->objfile;
3094
3095   dwarf2_read_section (objfile, section);
3096   dwarf2_read_section (objfile, abbrev_section);
3097
3098   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3099   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3100
3101   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3102
3103   for (uint32_t i = 0; i < map.tu_count; ++i)
3104     {
3105       struct signatured_type *sig_type;
3106       void **slot;
3107
3108       sect_offset sect_off
3109         = (sect_offset) (extract_unsigned_integer
3110                          (map.tu_table_reordered + i * map.offset_size,
3111                           map.offset_size,
3112                           map.dwarf5_byte_order));
3113
3114       comp_unit_head cu_header;
3115       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3116                                      abbrev_section,
3117                                      section->buffer + to_underlying (sect_off),
3118                                      rcuh_kind::TYPE);
3119
3120       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3121                                  struct signatured_type);
3122       sig_type->signature = cu_header.signature;
3123       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3124       sig_type->per_cu.is_debug_types = 1;
3125       sig_type->per_cu.section = section;
3126       sig_type->per_cu.sect_off = sect_off;
3127       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3128       sig_type->per_cu.v.quick
3129         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3130                           struct dwarf2_per_cu_quick_data);
3131
3132       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3133       *slot = sig_type;
3134
3135       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3136     }
3137
3138   dwarf2_per_objfile->signatured_types = sig_types_hash;
3139 }
3140
3141 /* Read the address map data from the mapped index, and use it to
3142    populate the objfile's psymtabs_addrmap.  */
3143
3144 static void
3145 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3146                            struct mapped_index *index)
3147 {
3148   struct objfile *objfile = dwarf2_per_objfile->objfile;
3149   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3150   const gdb_byte *iter, *end;
3151   struct addrmap *mutable_map;
3152   CORE_ADDR baseaddr;
3153
3154   auto_obstack temp_obstack;
3155
3156   mutable_map = addrmap_create_mutable (&temp_obstack);
3157
3158   iter = index->address_table.data ();
3159   end = iter + index->address_table.size ();
3160
3161   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3162
3163   while (iter < end)
3164     {
3165       ULONGEST hi, lo, cu_index;
3166       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3167       iter += 8;
3168       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3169       iter += 8;
3170       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3171       iter += 4;
3172
3173       if (lo > hi)
3174         {
3175           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3176                      hex_string (lo), hex_string (hi));
3177           continue;
3178         }
3179
3180       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3181         {
3182           complaint (_(".gdb_index address table has invalid CU number %u"),
3183                      (unsigned) cu_index);
3184           continue;
3185         }
3186
3187       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
3188       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
3189       addrmap_set_empty (mutable_map, lo, hi - 1,
3190                          dwarf2_per_objfile->get_cu (cu_index));
3191     }
3192
3193   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3194                                                     &objfile->objfile_obstack);
3195 }
3196
3197 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3198    populate the objfile's psymtabs_addrmap.  */
3199
3200 static void
3201 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3202                              struct dwarf2_section_info *section)
3203 {
3204   struct objfile *objfile = dwarf2_per_objfile->objfile;
3205   bfd *abfd = objfile->obfd;
3206   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3207   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3208                                        SECT_OFF_TEXT (objfile));
3209
3210   auto_obstack temp_obstack;
3211   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3212
3213   std::unordered_map<sect_offset,
3214                      dwarf2_per_cu_data *,
3215                      gdb::hash_enum<sect_offset>>
3216     debug_info_offset_to_per_cu;
3217   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3218     {
3219       const auto insertpair
3220         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3221       if (!insertpair.second)
3222         {
3223           warning (_("Section .debug_aranges in %s has duplicate "
3224                      "debug_info_offset %s, ignoring .debug_aranges."),
3225                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3226           return;
3227         }
3228     }
3229
3230   dwarf2_read_section (objfile, section);
3231
3232   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3233
3234   const gdb_byte *addr = section->buffer;
3235
3236   while (addr < section->buffer + section->size)
3237     {
3238       const gdb_byte *const entry_addr = addr;
3239       unsigned int bytes_read;
3240
3241       const LONGEST entry_length = read_initial_length (abfd, addr,
3242                                                         &bytes_read);
3243       addr += bytes_read;
3244
3245       const gdb_byte *const entry_end = addr + entry_length;
3246       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3247       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3248       if (addr + entry_length > section->buffer + section->size)
3249         {
3250           warning (_("Section .debug_aranges in %s entry at offset %zu "
3251                      "length %s exceeds section length %s, "
3252                      "ignoring .debug_aranges."),
3253                    objfile_name (objfile), entry_addr - section->buffer,
3254                    plongest (bytes_read + entry_length),
3255                    pulongest (section->size));
3256           return;
3257         }
3258
3259       /* The version number.  */
3260       const uint16_t version = read_2_bytes (abfd, addr);
3261       addr += 2;
3262       if (version != 2)
3263         {
3264           warning (_("Section .debug_aranges in %s entry at offset %zu "
3265                      "has unsupported version %d, ignoring .debug_aranges."),
3266                    objfile_name (objfile), entry_addr - section->buffer,
3267                    version);
3268           return;
3269         }
3270
3271       const uint64_t debug_info_offset
3272         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3273       addr += offset_size;
3274       const auto per_cu_it
3275         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3276       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3277         {
3278           warning (_("Section .debug_aranges in %s entry at offset %zu "
3279                      "debug_info_offset %s does not exists, "
3280                      "ignoring .debug_aranges."),
3281                    objfile_name (objfile), entry_addr - section->buffer,
3282                    pulongest (debug_info_offset));
3283           return;
3284         }
3285       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3286
3287       const uint8_t address_size = *addr++;
3288       if (address_size < 1 || address_size > 8)
3289         {
3290           warning (_("Section .debug_aranges in %s entry at offset %zu "
3291                      "address_size %u is invalid, ignoring .debug_aranges."),
3292                    objfile_name (objfile), entry_addr - section->buffer,
3293                    address_size);
3294           return;
3295         }
3296
3297       const uint8_t segment_selector_size = *addr++;
3298       if (segment_selector_size != 0)
3299         {
3300           warning (_("Section .debug_aranges in %s entry at offset %zu "
3301                      "segment_selector_size %u is not supported, "
3302                      "ignoring .debug_aranges."),
3303                    objfile_name (objfile), entry_addr - section->buffer,
3304                    segment_selector_size);
3305           return;
3306         }
3307
3308       /* Must pad to an alignment boundary that is twice the address
3309          size.  It is undocumented by the DWARF standard but GCC does
3310          use it.  */
3311       for (size_t padding = ((-(addr - section->buffer))
3312                              & (2 * address_size - 1));
3313            padding > 0; padding--)
3314         if (*addr++ != 0)
3315           {
3316             warning (_("Section .debug_aranges in %s entry at offset %zu "
3317                        "padding is not zero, ignoring .debug_aranges."),
3318                      objfile_name (objfile), entry_addr - section->buffer);
3319             return;
3320           }
3321
3322       for (;;)
3323         {
3324           if (addr + 2 * address_size > entry_end)
3325             {
3326               warning (_("Section .debug_aranges in %s entry at offset %zu "
3327                          "address list is not properly terminated, "
3328                          "ignoring .debug_aranges."),
3329                        objfile_name (objfile), entry_addr - section->buffer);
3330               return;
3331             }
3332           ULONGEST start = extract_unsigned_integer (addr, address_size,
3333                                                      dwarf5_byte_order);
3334           addr += address_size;
3335           ULONGEST length = extract_unsigned_integer (addr, address_size,
3336                                                       dwarf5_byte_order);
3337           addr += address_size;
3338           if (start == 0 && length == 0)
3339             break;
3340           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3341             {
3342               /* Symbol was eliminated due to a COMDAT group.  */
3343               continue;
3344             }
3345           ULONGEST end = start + length;
3346           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3347                    - baseaddr);
3348           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3349                  - baseaddr);
3350           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3351         }
3352     }
3353
3354   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3355                                                     &objfile->objfile_obstack);
3356 }
3357
3358 /* Find a slot in the mapped index INDEX for the object named NAME.
3359    If NAME is found, set *VEC_OUT to point to the CU vector in the
3360    constant pool and return true.  If NAME cannot be found, return
3361    false.  */
3362
3363 static bool
3364 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3365                           offset_type **vec_out)
3366 {
3367   offset_type hash;
3368   offset_type slot, step;
3369   int (*cmp) (const char *, const char *);
3370
3371   gdb::unique_xmalloc_ptr<char> without_params;
3372   if (current_language->la_language == language_cplus
3373       || current_language->la_language == language_fortran
3374       || current_language->la_language == language_d)
3375     {
3376       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3377          not contain any.  */
3378
3379       if (strchr (name, '(') != NULL)
3380         {
3381           without_params = cp_remove_params (name);
3382
3383           if (without_params != NULL)
3384             name = without_params.get ();
3385         }
3386     }
3387
3388   /* Index version 4 did not support case insensitive searches.  But the
3389      indices for case insensitive languages are built in lowercase, therefore
3390      simulate our NAME being searched is also lowercased.  */
3391   hash = mapped_index_string_hash ((index->version == 4
3392                                     && case_sensitivity == case_sensitive_off
3393                                     ? 5 : index->version),
3394                                    name);
3395
3396   slot = hash & (index->symbol_table.size () - 1);
3397   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3398   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3399
3400   for (;;)
3401     {
3402       const char *str;
3403
3404       const auto &bucket = index->symbol_table[slot];
3405       if (bucket.name == 0 && bucket.vec == 0)
3406         return false;
3407
3408       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3409       if (!cmp (name, str))
3410         {
3411           *vec_out = (offset_type *) (index->constant_pool
3412                                       + MAYBE_SWAP (bucket.vec));
3413           return true;
3414         }
3415
3416       slot = (slot + step) & (index->symbol_table.size () - 1);
3417     }
3418 }
3419
3420 /* A helper function that reads the .gdb_index from BUFFER and fills
3421    in MAP.  FILENAME is the name of the file containing the data;
3422    it is used for error reporting.  DEPRECATED_OK is true if it is
3423    ok to use deprecated sections.
3424
3425    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3426    out parameters that are filled in with information about the CU and
3427    TU lists in the section.
3428
3429    Returns true if all went well, false otherwise.  */
3430
3431 static bool
3432 read_gdb_index_from_buffer (struct objfile *objfile,
3433                             const char *filename,
3434                             bool deprecated_ok,
3435                             gdb::array_view<const gdb_byte> buffer,
3436                             struct mapped_index *map,
3437                             const gdb_byte **cu_list,
3438                             offset_type *cu_list_elements,
3439                             const gdb_byte **types_list,
3440                             offset_type *types_list_elements)
3441 {
3442   const gdb_byte *addr = &buffer[0];
3443
3444   /* Version check.  */
3445   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3446   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3447      causes the index to behave very poorly for certain requests.  Version 3
3448      contained incomplete addrmap.  So, it seems better to just ignore such
3449      indices.  */
3450   if (version < 4)
3451     {
3452       static int warning_printed = 0;
3453       if (!warning_printed)
3454         {
3455           warning (_("Skipping obsolete .gdb_index section in %s."),
3456                    filename);
3457           warning_printed = 1;
3458         }
3459       return 0;
3460     }
3461   /* Index version 4 uses a different hash function than index version
3462      5 and later.
3463
3464      Versions earlier than 6 did not emit psymbols for inlined
3465      functions.  Using these files will cause GDB not to be able to
3466      set breakpoints on inlined functions by name, so we ignore these
3467      indices unless the user has done
3468      "set use-deprecated-index-sections on".  */
3469   if (version < 6 && !deprecated_ok)
3470     {
3471       static int warning_printed = 0;
3472       if (!warning_printed)
3473         {
3474           warning (_("\
3475 Skipping deprecated .gdb_index section in %s.\n\
3476 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3477 to use the section anyway."),
3478                    filename);
3479           warning_printed = 1;
3480         }
3481       return 0;
3482     }
3483   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3484      of the TU (for symbols coming from TUs),
3485      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3486      Plus gold-generated indices can have duplicate entries for global symbols,
3487      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3488      These are just performance bugs, and we can't distinguish gdb-generated
3489      indices from gold-generated ones, so issue no warning here.  */
3490
3491   /* Indexes with higher version than the one supported by GDB may be no
3492      longer backward compatible.  */
3493   if (version > 8)
3494     return 0;
3495
3496   map->version = version;
3497
3498   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3499
3500   int i = 0;
3501   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3502   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3503                        / 8);
3504   ++i;
3505
3506   *types_list = addr + MAYBE_SWAP (metadata[i]);
3507   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3508                            - MAYBE_SWAP (metadata[i]))
3509                           / 8);
3510   ++i;
3511
3512   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3513   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3514   map->address_table
3515     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3516   ++i;
3517
3518   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3519   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3520   map->symbol_table
3521     = gdb::array_view<mapped_index::symbol_table_slot>
3522        ((mapped_index::symbol_table_slot *) symbol_table,
3523         (mapped_index::symbol_table_slot *) symbol_table_end);
3524
3525   ++i;
3526   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3527
3528   return 1;
3529 }
3530
3531 /* Callback types for dwarf2_read_gdb_index.  */
3532
3533 typedef gdb::function_view
3534     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3535     get_gdb_index_contents_ftype;
3536 typedef gdb::function_view
3537     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3538     get_gdb_index_contents_dwz_ftype;
3539
3540 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3541    elements of all the CUs and return 1.  Otherwise, return 0.  */
3542
3543 static int
3544 dwarf2_read_gdb_index
3545   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3546    get_gdb_index_contents_ftype get_gdb_index_contents,
3547    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3548 {
3549   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3550   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3551   struct dwz_file *dwz;
3552   struct objfile *objfile = dwarf2_per_objfile->objfile;
3553
3554   gdb::array_view<const gdb_byte> main_index_contents
3555     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3556
3557   if (main_index_contents.empty ())
3558     return 0;
3559
3560   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3561   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3562                                    use_deprecated_index_sections,
3563                                    main_index_contents, map.get (), &cu_list,
3564                                    &cu_list_elements, &types_list,
3565                                    &types_list_elements))
3566     return 0;
3567
3568   /* Don't use the index if it's empty.  */
3569   if (map->symbol_table.empty ())
3570     return 0;
3571
3572   /* If there is a .dwz file, read it so we can get its CU list as
3573      well.  */
3574   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3575   if (dwz != NULL)
3576     {
3577       struct mapped_index dwz_map;
3578       const gdb_byte *dwz_types_ignore;
3579       offset_type dwz_types_elements_ignore;
3580
3581       gdb::array_view<const gdb_byte> dwz_index_content
3582         = get_gdb_index_contents_dwz (objfile, dwz);
3583
3584       if (dwz_index_content.empty ())
3585         return 0;
3586
3587       if (!read_gdb_index_from_buffer (objfile,
3588                                        bfd_get_filename (dwz->dwz_bfd), 1,
3589                                        dwz_index_content, &dwz_map,
3590                                        &dwz_list, &dwz_list_elements,
3591                                        &dwz_types_ignore,
3592                                        &dwz_types_elements_ignore))
3593         {
3594           warning (_("could not read '.gdb_index' section from %s; skipping"),
3595                    bfd_get_filename (dwz->dwz_bfd));
3596           return 0;
3597         }
3598     }
3599
3600   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3601                          dwz_list, dwz_list_elements);
3602
3603   if (types_list_elements)
3604     {
3605       struct dwarf2_section_info *section;
3606
3607       /* We can only handle a single .debug_types when we have an
3608          index.  */
3609       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3610         return 0;
3611
3612       section = VEC_index (dwarf2_section_info_def,
3613                            dwarf2_per_objfile->types, 0);
3614
3615       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3616                                                types_list, types_list_elements);
3617     }
3618
3619   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3620
3621   dwarf2_per_objfile->index_table = std::move (map);
3622   dwarf2_per_objfile->using_index = 1;
3623   dwarf2_per_objfile->quick_file_names_table =
3624     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3625
3626   return 1;
3627 }
3628
3629 /* die_reader_func for dw2_get_file_names.  */
3630
3631 static void
3632 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3633                            const gdb_byte *info_ptr,
3634                            struct die_info *comp_unit_die,
3635                            int has_children,
3636                            void *data)
3637 {
3638   struct dwarf2_cu *cu = reader->cu;
3639   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3640   struct dwarf2_per_objfile *dwarf2_per_objfile
3641     = cu->per_cu->dwarf2_per_objfile;
3642   struct objfile *objfile = dwarf2_per_objfile->objfile;
3643   struct dwarf2_per_cu_data *lh_cu;
3644   struct attribute *attr;
3645   int i;
3646   void **slot;
3647   struct quick_file_names *qfn;
3648
3649   gdb_assert (! this_cu->is_debug_types);
3650
3651   /* Our callers never want to match partial units -- instead they
3652      will match the enclosing full CU.  */
3653   if (comp_unit_die->tag == DW_TAG_partial_unit)
3654     {
3655       this_cu->v.quick->no_file_data = 1;
3656       return;
3657     }
3658
3659   lh_cu = this_cu;
3660   slot = NULL;
3661
3662   line_header_up lh;
3663   sect_offset line_offset {};
3664
3665   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3666   if (attr)
3667     {
3668       struct quick_file_names find_entry;
3669
3670       line_offset = (sect_offset) DW_UNSND (attr);
3671
3672       /* We may have already read in this line header (TU line header sharing).
3673          If we have we're done.  */
3674       find_entry.hash.dwo_unit = cu->dwo_unit;
3675       find_entry.hash.line_sect_off = line_offset;
3676       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3677                              &find_entry, INSERT);
3678       if (*slot != NULL)
3679         {
3680           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3681           return;
3682         }
3683
3684       lh = dwarf_decode_line_header (line_offset, cu);
3685     }
3686   if (lh == NULL)
3687     {
3688       lh_cu->v.quick->no_file_data = 1;
3689       return;
3690     }
3691
3692   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3693   qfn->hash.dwo_unit = cu->dwo_unit;
3694   qfn->hash.line_sect_off = line_offset;
3695   gdb_assert (slot != NULL);
3696   *slot = qfn;
3697
3698   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3699
3700   qfn->num_file_names = lh->file_names.size ();
3701   qfn->file_names =
3702     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3703   for (i = 0; i < lh->file_names.size (); ++i)
3704     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3705   qfn->real_names = NULL;
3706
3707   lh_cu->v.quick->file_names = qfn;
3708 }
3709
3710 /* A helper for the "quick" functions which attempts to read the line
3711    table for THIS_CU.  */
3712
3713 static struct quick_file_names *
3714 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3715 {
3716   /* This should never be called for TUs.  */
3717   gdb_assert (! this_cu->is_debug_types);
3718   /* Nor type unit groups.  */
3719   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3720
3721   if (this_cu->v.quick->file_names != NULL)
3722     return this_cu->v.quick->file_names;
3723   /* If we know there is no line data, no point in looking again.  */
3724   if (this_cu->v.quick->no_file_data)
3725     return NULL;
3726
3727   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3728
3729   if (this_cu->v.quick->no_file_data)
3730     return NULL;
3731   return this_cu->v.quick->file_names;
3732 }
3733
3734 /* A helper for the "quick" functions which computes and caches the
3735    real path for a given file name from the line table.  */
3736
3737 static const char *
3738 dw2_get_real_path (struct objfile *objfile,
3739                    struct quick_file_names *qfn, int index)
3740 {
3741   if (qfn->real_names == NULL)
3742     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3743                                       qfn->num_file_names, const char *);
3744
3745   if (qfn->real_names[index] == NULL)
3746     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3747
3748   return qfn->real_names[index];
3749 }
3750
3751 static struct symtab *
3752 dw2_find_last_source_symtab (struct objfile *objfile)
3753 {
3754   struct dwarf2_per_objfile *dwarf2_per_objfile
3755     = get_dwarf2_per_objfile (objfile);
3756   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3757   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3758
3759   if (cust == NULL)
3760     return NULL;
3761
3762   return compunit_primary_filetab (cust);
3763 }
3764
3765 /* Traversal function for dw2_forget_cached_source_info.  */
3766
3767 static int
3768 dw2_free_cached_file_names (void **slot, void *info)
3769 {
3770   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3771
3772   if (file_data->real_names)
3773     {
3774       int i;
3775
3776       for (i = 0; i < file_data->num_file_names; ++i)
3777         {
3778           xfree ((void*) file_data->real_names[i]);
3779           file_data->real_names[i] = NULL;
3780         }
3781     }
3782
3783   return 1;
3784 }
3785
3786 static void
3787 dw2_forget_cached_source_info (struct objfile *objfile)
3788 {
3789   struct dwarf2_per_objfile *dwarf2_per_objfile
3790     = get_dwarf2_per_objfile (objfile);
3791
3792   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3793                           dw2_free_cached_file_names, NULL);
3794 }
3795
3796 /* Helper function for dw2_map_symtabs_matching_filename that expands
3797    the symtabs and calls the iterator.  */
3798
3799 static int
3800 dw2_map_expand_apply (struct objfile *objfile,
3801                       struct dwarf2_per_cu_data *per_cu,
3802                       const char *name, const char *real_path,
3803                       gdb::function_view<bool (symtab *)> callback)
3804 {
3805   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3806
3807   /* Don't visit already-expanded CUs.  */
3808   if (per_cu->v.quick->compunit_symtab)
3809     return 0;
3810
3811   /* This may expand more than one symtab, and we want to iterate over
3812      all of them.  */
3813   dw2_instantiate_symtab (per_cu, false);
3814
3815   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3816                                     last_made, callback);
3817 }
3818
3819 /* Implementation of the map_symtabs_matching_filename method.  */
3820
3821 static bool
3822 dw2_map_symtabs_matching_filename
3823   (struct objfile *objfile, const char *name, const char *real_path,
3824    gdb::function_view<bool (symtab *)> callback)
3825 {
3826   const char *name_basename = lbasename (name);
3827   struct dwarf2_per_objfile *dwarf2_per_objfile
3828     = get_dwarf2_per_objfile (objfile);
3829
3830   /* The rule is CUs specify all the files, including those used by
3831      any TU, so there's no need to scan TUs here.  */
3832
3833   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3834     {
3835       /* We only need to look at symtabs not already expanded.  */
3836       if (per_cu->v.quick->compunit_symtab)
3837         continue;
3838
3839       quick_file_names *file_data = dw2_get_file_names (per_cu);
3840       if (file_data == NULL)
3841         continue;
3842
3843       for (int j = 0; j < file_data->num_file_names; ++j)
3844         {
3845           const char *this_name = file_data->file_names[j];
3846           const char *this_real_name;
3847
3848           if (compare_filenames_for_search (this_name, name))
3849             {
3850               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3851                                         callback))
3852                 return true;
3853               continue;
3854             }
3855
3856           /* Before we invoke realpath, which can get expensive when many
3857              files are involved, do a quick comparison of the basenames.  */
3858           if (! basenames_may_differ
3859               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3860             continue;
3861
3862           this_real_name = dw2_get_real_path (objfile, file_data, j);
3863           if (compare_filenames_for_search (this_real_name, name))
3864             {
3865               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3866                                         callback))
3867                 return true;
3868               continue;
3869             }
3870
3871           if (real_path != NULL)
3872             {
3873               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3874               gdb_assert (IS_ABSOLUTE_PATH (name));
3875               if (this_real_name != NULL
3876                   && FILENAME_CMP (real_path, this_real_name) == 0)
3877                 {
3878                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3879                                             callback))
3880                     return true;
3881                   continue;
3882                 }
3883             }
3884         }
3885     }
3886
3887   return false;
3888 }
3889
3890 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3891
3892 struct dw2_symtab_iterator
3893 {
3894   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3895   struct dwarf2_per_objfile *dwarf2_per_objfile;
3896   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3897   int want_specific_block;
3898   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3899      Unused if !WANT_SPECIFIC_BLOCK.  */
3900   int block_index;
3901   /* The kind of symbol we're looking for.  */
3902   domain_enum domain;
3903   /* The list of CUs from the index entry of the symbol,
3904      or NULL if not found.  */
3905   offset_type *vec;
3906   /* The next element in VEC to look at.  */
3907   int next;
3908   /* The number of elements in VEC, or zero if there is no match.  */
3909   int length;
3910   /* Have we seen a global version of the symbol?
3911      If so we can ignore all further global instances.
3912      This is to work around gold/15646, inefficient gold-generated
3913      indices.  */
3914   int global_seen;
3915 };
3916
3917 /* Initialize the index symtab iterator ITER.
3918    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3919    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3920
3921 static void
3922 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3923                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3924                       int want_specific_block,
3925                       int block_index,
3926                       domain_enum domain,
3927                       const char *name)
3928 {
3929   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3930   iter->want_specific_block = want_specific_block;
3931   iter->block_index = block_index;
3932   iter->domain = domain;
3933   iter->next = 0;
3934   iter->global_seen = 0;
3935
3936   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3937
3938   /* index is NULL if OBJF_READNOW.  */
3939   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3940     iter->length = MAYBE_SWAP (*iter->vec);
3941   else
3942     {
3943       iter->vec = NULL;
3944       iter->length = 0;
3945     }
3946 }
3947
3948 /* Return the next matching CU or NULL if there are no more.  */
3949
3950 static struct dwarf2_per_cu_data *
3951 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3952 {
3953   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3954
3955   for ( ; iter->next < iter->length; ++iter->next)
3956     {
3957       offset_type cu_index_and_attrs =
3958         MAYBE_SWAP (iter->vec[iter->next + 1]);
3959       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3960       int want_static = iter->block_index != GLOBAL_BLOCK;
3961       /* This value is only valid for index versions >= 7.  */
3962       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3963       gdb_index_symbol_kind symbol_kind =
3964         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3965       /* Only check the symbol attributes if they're present.
3966          Indices prior to version 7 don't record them,
3967          and indices >= 7 may elide them for certain symbols
3968          (gold does this).  */
3969       int attrs_valid =
3970         (dwarf2_per_objfile->index_table->version >= 7
3971          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3972
3973       /* Don't crash on bad data.  */
3974       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3975                        + dwarf2_per_objfile->all_type_units.size ()))
3976         {
3977           complaint (_(".gdb_index entry has bad CU index"
3978                        " [in module %s]"),
3979                      objfile_name (dwarf2_per_objfile->objfile));
3980           continue;
3981         }
3982
3983       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3984
3985       /* Skip if already read in.  */
3986       if (per_cu->v.quick->compunit_symtab)
3987         continue;
3988
3989       /* Check static vs global.  */
3990       if (attrs_valid)
3991         {
3992           if (iter->want_specific_block
3993               && want_static != is_static)
3994             continue;
3995           /* Work around gold/15646.  */
3996           if (!is_static && iter->global_seen)
3997             continue;
3998           if (!is_static)
3999             iter->global_seen = 1;
4000         }
4001
4002       /* Only check the symbol's kind if it has one.  */
4003       if (attrs_valid)
4004         {
4005           switch (iter->domain)
4006             {
4007             case VAR_DOMAIN:
4008               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4009                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4010                   /* Some types are also in VAR_DOMAIN.  */
4011                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4012                 continue;
4013               break;
4014             case STRUCT_DOMAIN:
4015               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4016                 continue;
4017               break;
4018             case LABEL_DOMAIN:
4019               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4020                 continue;
4021               break;
4022             default:
4023               break;
4024             }
4025         }
4026
4027       ++iter->next;
4028       return per_cu;
4029     }
4030
4031   return NULL;
4032 }
4033
4034 static struct compunit_symtab *
4035 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4036                    const char *name, domain_enum domain)
4037 {
4038   struct compunit_symtab *stab_best = NULL;
4039   struct dwarf2_per_objfile *dwarf2_per_objfile
4040     = get_dwarf2_per_objfile (objfile);
4041
4042   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4043
4044   struct dw2_symtab_iterator iter;
4045   struct dwarf2_per_cu_data *per_cu;
4046
4047   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4048
4049   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4050     {
4051       struct symbol *sym, *with_opaque = NULL;
4052       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4053       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4054       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4055
4056       sym = block_find_symbol (block, name, domain,
4057                                block_find_non_opaque_type_preferred,
4058                                &with_opaque);
4059
4060       /* Some caution must be observed with overloaded functions
4061          and methods, since the index will not contain any overload
4062          information (but NAME might contain it).  */
4063
4064       if (sym != NULL
4065           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4066         return stab;
4067       if (with_opaque != NULL
4068           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4069         stab_best = stab;
4070
4071       /* Keep looking through other CUs.  */
4072     }
4073
4074   return stab_best;
4075 }
4076
4077 static void
4078 dw2_print_stats (struct objfile *objfile)
4079 {
4080   struct dwarf2_per_objfile *dwarf2_per_objfile
4081     = get_dwarf2_per_objfile (objfile);
4082   int total = (dwarf2_per_objfile->all_comp_units.size ()
4083                + dwarf2_per_objfile->all_type_units.size ());
4084   int count = 0;
4085
4086   for (int i = 0; i < total; ++i)
4087     {
4088       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4089
4090       if (!per_cu->v.quick->compunit_symtab)
4091         ++count;
4092     }
4093   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4094   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4095 }
4096
4097 /* This dumps minimal information about the index.
4098    It is called via "mt print objfiles".
4099    One use is to verify .gdb_index has been loaded by the
4100    gdb.dwarf2/gdb-index.exp testcase.  */
4101
4102 static void
4103 dw2_dump (struct objfile *objfile)
4104 {
4105   struct dwarf2_per_objfile *dwarf2_per_objfile
4106     = get_dwarf2_per_objfile (objfile);
4107
4108   gdb_assert (dwarf2_per_objfile->using_index);
4109   printf_filtered (".gdb_index:");
4110   if (dwarf2_per_objfile->index_table != NULL)
4111     {
4112       printf_filtered (" version %d\n",
4113                        dwarf2_per_objfile->index_table->version);
4114     }
4115   else
4116     printf_filtered (" faked for \"readnow\"\n");
4117   printf_filtered ("\n");
4118 }
4119
4120 static void
4121 dw2_expand_symtabs_for_function (struct objfile *objfile,
4122                                  const char *func_name)
4123 {
4124   struct dwarf2_per_objfile *dwarf2_per_objfile
4125     = get_dwarf2_per_objfile (objfile);
4126
4127   struct dw2_symtab_iterator iter;
4128   struct dwarf2_per_cu_data *per_cu;
4129
4130   /* Note: It doesn't matter what we pass for block_index here.  */
4131   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4132                         func_name);
4133
4134   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4135     dw2_instantiate_symtab (per_cu, false);
4136
4137 }
4138
4139 static void
4140 dw2_expand_all_symtabs (struct objfile *objfile)
4141 {
4142   struct dwarf2_per_objfile *dwarf2_per_objfile
4143     = get_dwarf2_per_objfile (objfile);
4144   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4145                      + dwarf2_per_objfile->all_type_units.size ());
4146
4147   for (int i = 0; i < total_units; ++i)
4148     {
4149       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4150
4151       /* We don't want to directly expand a partial CU, because if we
4152          read it with the wrong language, then assertion failures can
4153          be triggered later on.  See PR symtab/23010.  So, tell
4154          dw2_instantiate_symtab to skip partial CUs -- any important
4155          partial CU will be read via DW_TAG_imported_unit anyway.  */
4156       dw2_instantiate_symtab (per_cu, true);
4157     }
4158 }
4159
4160 static void
4161 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4162                                   const char *fullname)
4163 {
4164   struct dwarf2_per_objfile *dwarf2_per_objfile
4165     = get_dwarf2_per_objfile (objfile);
4166
4167   /* We don't need to consider type units here.
4168      This is only called for examining code, e.g. expand_line_sal.
4169      There can be an order of magnitude (or more) more type units
4170      than comp units, and we avoid them if we can.  */
4171
4172   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4173     {
4174       /* We only need to look at symtabs not already expanded.  */
4175       if (per_cu->v.quick->compunit_symtab)
4176         continue;
4177
4178       quick_file_names *file_data = dw2_get_file_names (per_cu);
4179       if (file_data == NULL)
4180         continue;
4181
4182       for (int j = 0; j < file_data->num_file_names; ++j)
4183         {
4184           const char *this_fullname = file_data->file_names[j];
4185
4186           if (filename_cmp (this_fullname, fullname) == 0)
4187             {
4188               dw2_instantiate_symtab (per_cu, false);
4189               break;
4190             }
4191         }
4192     }
4193 }
4194
4195 static void
4196 dw2_map_matching_symbols (struct objfile *objfile,
4197                           const char * name, domain_enum domain,
4198                           int global,
4199                           int (*callback) (struct block *,
4200                                            struct symbol *, void *),
4201                           void *data, symbol_name_match_type match,
4202                           symbol_compare_ftype *ordered_compare)
4203 {
4204   /* Currently unimplemented; used for Ada.  The function can be called if the
4205      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4206      does not look for non-Ada symbols this function should just return.  */
4207 }
4208
4209 /* Symbol name matcher for .gdb_index names.
4210
4211    Symbol names in .gdb_index have a few particularities:
4212
4213    - There's no indication of which is the language of each symbol.
4214
4215      Since each language has its own symbol name matching algorithm,
4216      and we don't know which language is the right one, we must match
4217      each symbol against all languages.  This would be a potential
4218      performance problem if it were not mitigated by the
4219      mapped_index::name_components lookup table, which significantly
4220      reduces the number of times we need to call into this matcher,
4221      making it a non-issue.
4222
4223    - Symbol names in the index have no overload (parameter)
4224      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4225      appear as "foo" in the index, for example.
4226
4227      This means that the lookup names passed to the symbol name
4228      matcher functions must have no parameter information either
4229      because (e.g.) symbol search name "foo" does not match
4230      lookup-name "foo(int)" [while swapping search name for lookup
4231      name would match].
4232 */
4233 class gdb_index_symbol_name_matcher
4234 {
4235 public:
4236   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4237   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4238
4239   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4240      Returns true if any matcher matches.  */
4241   bool matches (const char *symbol_name);
4242
4243 private:
4244   /* A reference to the lookup name we're matching against.  */
4245   const lookup_name_info &m_lookup_name;
4246
4247   /* A vector holding all the different symbol name matchers, for all
4248      languages.  */
4249   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4250 };
4251
4252 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4253   (const lookup_name_info &lookup_name)
4254     : m_lookup_name (lookup_name)
4255 {
4256   /* Prepare the vector of comparison functions upfront, to avoid
4257      doing the same work for each symbol.  Care is taken to avoid
4258      matching with the same matcher more than once if/when multiple
4259      languages use the same matcher function.  */
4260   auto &matchers = m_symbol_name_matcher_funcs;
4261   matchers.reserve (nr_languages);
4262
4263   matchers.push_back (default_symbol_name_matcher);
4264
4265   for (int i = 0; i < nr_languages; i++)
4266     {
4267       const language_defn *lang = language_def ((enum language) i);
4268       symbol_name_matcher_ftype *name_matcher
4269         = get_symbol_name_matcher (lang, m_lookup_name);
4270
4271       /* Don't insert the same comparison routine more than once.
4272          Note that we do this linear walk instead of a seemingly
4273          cheaper sorted insert, or use a std::set or something like
4274          that, because relative order of function addresses is not
4275          stable.  This is not a problem in practice because the number
4276          of supported languages is low, and the cost here is tiny
4277          compared to the number of searches we'll do afterwards using
4278          this object.  */
4279       if (name_matcher != default_symbol_name_matcher
4280           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4281               == matchers.end ()))
4282         matchers.push_back (name_matcher);
4283     }
4284 }
4285
4286 bool
4287 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4288 {
4289   for (auto matches_name : m_symbol_name_matcher_funcs)
4290     if (matches_name (symbol_name, m_lookup_name, NULL))
4291       return true;
4292
4293   return false;
4294 }
4295
4296 /* Starting from a search name, return the string that finds the upper
4297    bound of all strings that start with SEARCH_NAME in a sorted name
4298    list.  Returns the empty string to indicate that the upper bound is
4299    the end of the list.  */
4300
4301 static std::string
4302 make_sort_after_prefix_name (const char *search_name)
4303 {
4304   /* When looking to complete "func", we find the upper bound of all
4305      symbols that start with "func" by looking for where we'd insert
4306      the closest string that would follow "func" in lexicographical
4307      order.  Usually, that's "func"-with-last-character-incremented,
4308      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4309      will be UTF-8 multi-byte sequences, but we can't be certain.
4310      Especially mind the 0xff character, which is a valid character in
4311      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4312      rule out compilers allowing it in identifiers.  Note that
4313      conveniently, strcmp/strcasecmp are specified to compare
4314      characters interpreted as unsigned char.  So what we do is treat
4315      the whole string as a base 256 number composed of a sequence of
4316      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4317      to 0, and carries 1 to the following more-significant position.
4318      If the very first character in SEARCH_NAME ends up incremented
4319      and carries/overflows, then the upper bound is the end of the
4320      list.  The string after the empty string is also the empty
4321      string.
4322
4323      Some examples of this operation:
4324
4325        SEARCH_NAME  => "+1" RESULT
4326
4327        "abc"              => "abd"
4328        "ab\xff"           => "ac"
4329        "\xff" "a" "\xff"  => "\xff" "b"
4330        "\xff"             => ""
4331        "\xff\xff"         => ""
4332        ""                 => ""
4333
4334      Then, with these symbols for example:
4335
4336       func
4337       func1
4338       fund
4339
4340      completing "func" looks for symbols between "func" and
4341      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4342      which finds "func" and "func1", but not "fund".
4343
4344      And with:
4345
4346       funcÿ     (Latin1 'ÿ' [0xff])
4347       funcÿ1
4348       fund
4349
4350      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4351      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4352
4353      And with:
4354
4355       ÿÿ        (Latin1 'ÿ' [0xff])
4356       ÿÿ1
4357
4358      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4359      the end of the list.
4360   */
4361   std::string after = search_name;
4362   while (!after.empty () && (unsigned char) after.back () == 0xff)
4363     after.pop_back ();
4364   if (!after.empty ())
4365     after.back () = (unsigned char) after.back () + 1;
4366   return after;
4367 }
4368
4369 /* See declaration.  */
4370
4371 std::pair<std::vector<name_component>::const_iterator,
4372           std::vector<name_component>::const_iterator>
4373 mapped_index_base::find_name_components_bounds
4374   (const lookup_name_info &lookup_name_without_params) const
4375 {
4376   auto *name_cmp
4377     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4378
4379   const char *cplus
4380     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4381
4382   /* Comparison function object for lower_bound that matches against a
4383      given symbol name.  */
4384   auto lookup_compare_lower = [&] (const name_component &elem,
4385                                    const char *name)
4386     {
4387       const char *elem_qualified = this->symbol_name_at (elem.idx);
4388       const char *elem_name = elem_qualified + elem.name_offset;
4389       return name_cmp (elem_name, name) < 0;
4390     };
4391
4392   /* Comparison function object for upper_bound that matches against a
4393      given symbol name.  */
4394   auto lookup_compare_upper = [&] (const char *name,
4395                                    const name_component &elem)
4396     {
4397       const char *elem_qualified = this->symbol_name_at (elem.idx);
4398       const char *elem_name = elem_qualified + elem.name_offset;
4399       return name_cmp (name, elem_name) < 0;
4400     };
4401
4402   auto begin = this->name_components.begin ();
4403   auto end = this->name_components.end ();
4404
4405   /* Find the lower bound.  */
4406   auto lower = [&] ()
4407     {
4408       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4409         return begin;
4410       else
4411         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4412     } ();
4413
4414   /* Find the upper bound.  */
4415   auto upper = [&] ()
4416     {
4417       if (lookup_name_without_params.completion_mode ())
4418         {
4419           /* In completion mode, we want UPPER to point past all
4420              symbols names that have the same prefix.  I.e., with
4421              these symbols, and completing "func":
4422
4423               function        << lower bound
4424               function1
4425               other_function  << upper bound
4426
4427              We find the upper bound by looking for the insertion
4428              point of "func"-with-last-character-incremented,
4429              i.e. "fund".  */
4430           std::string after = make_sort_after_prefix_name (cplus);
4431           if (after.empty ())
4432             return end;
4433           return std::lower_bound (lower, end, after.c_str (),
4434                                    lookup_compare_lower);
4435         }
4436       else
4437         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4438     } ();
4439
4440   return {lower, upper};
4441 }
4442
4443 /* See declaration.  */
4444
4445 void
4446 mapped_index_base::build_name_components ()
4447 {
4448   if (!this->name_components.empty ())
4449     return;
4450
4451   this->name_components_casing = case_sensitivity;
4452   auto *name_cmp
4453     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4454
4455   /* The code below only knows how to break apart components of C++
4456      symbol names (and other languages that use '::' as
4457      namespace/module separator).  If we add support for wild matching
4458      to some language that uses some other operator (E.g., Ada, Go and
4459      D use '.'), then we'll need to try splitting the symbol name
4460      according to that language too.  Note that Ada does support wild
4461      matching, but doesn't currently support .gdb_index.  */
4462   auto count = this->symbol_name_count ();
4463   for (offset_type idx = 0; idx < count; idx++)
4464     {
4465       if (this->symbol_name_slot_invalid (idx))
4466         continue;
4467
4468       const char *name = this->symbol_name_at (idx);
4469
4470       /* Add each name component to the name component table.  */
4471       unsigned int previous_len = 0;
4472       for (unsigned int current_len = cp_find_first_component (name);
4473            name[current_len] != '\0';
4474            current_len += cp_find_first_component (name + current_len))
4475         {
4476           gdb_assert (name[current_len] == ':');
4477           this->name_components.push_back ({previous_len, idx});
4478           /* Skip the '::'.  */
4479           current_len += 2;
4480           previous_len = current_len;
4481         }
4482       this->name_components.push_back ({previous_len, idx});
4483     }
4484
4485   /* Sort name_components elements by name.  */
4486   auto name_comp_compare = [&] (const name_component &left,
4487                                 const name_component &right)
4488     {
4489       const char *left_qualified = this->symbol_name_at (left.idx);
4490       const char *right_qualified = this->symbol_name_at (right.idx);
4491
4492       const char *left_name = left_qualified + left.name_offset;
4493       const char *right_name = right_qualified + right.name_offset;
4494
4495       return name_cmp (left_name, right_name) < 0;
4496     };
4497
4498   std::sort (this->name_components.begin (),
4499              this->name_components.end (),
4500              name_comp_compare);
4501 }
4502
4503 /* Helper for dw2_expand_symtabs_matching that works with a
4504    mapped_index_base instead of the containing objfile.  This is split
4505    to a separate function in order to be able to unit test the
4506    name_components matching using a mock mapped_index_base.  For each
4507    symbol name that matches, calls MATCH_CALLBACK, passing it the
4508    symbol's index in the mapped_index_base symbol table.  */
4509
4510 static void
4511 dw2_expand_symtabs_matching_symbol
4512   (mapped_index_base &index,
4513    const lookup_name_info &lookup_name_in,
4514    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4515    enum search_domain kind,
4516    gdb::function_view<void (offset_type)> match_callback)
4517 {
4518   lookup_name_info lookup_name_without_params
4519     = lookup_name_in.make_ignore_params ();
4520   gdb_index_symbol_name_matcher lookup_name_matcher
4521     (lookup_name_without_params);
4522
4523   /* Build the symbol name component sorted vector, if we haven't
4524      yet.  */
4525   index.build_name_components ();
4526
4527   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4528
4529   /* Now for each symbol name in range, check to see if we have a name
4530      match, and if so, call the MATCH_CALLBACK callback.  */
4531
4532   /* The same symbol may appear more than once in the range though.
4533      E.g., if we're looking for symbols that complete "w", and we have
4534      a symbol named "w1::w2", we'll find the two name components for
4535      that same symbol in the range.  To be sure we only call the
4536      callback once per symbol, we first collect the symbol name
4537      indexes that matched in a temporary vector and ignore
4538      duplicates.  */
4539   std::vector<offset_type> matches;
4540   matches.reserve (std::distance (bounds.first, bounds.second));
4541
4542   for (; bounds.first != bounds.second; ++bounds.first)
4543     {
4544       const char *qualified = index.symbol_name_at (bounds.first->idx);
4545
4546       if (!lookup_name_matcher.matches (qualified)
4547           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4548         continue;
4549
4550       matches.push_back (bounds.first->idx);
4551     }
4552
4553   std::sort (matches.begin (), matches.end ());
4554
4555   /* Finally call the callback, once per match.  */
4556   ULONGEST prev = -1;
4557   for (offset_type idx : matches)
4558     {
4559       if (prev != idx)
4560         {
4561           match_callback (idx);
4562           prev = idx;
4563         }
4564     }
4565
4566   /* Above we use a type wider than idx's for 'prev', since 0 and
4567      (offset_type)-1 are both possible values.  */
4568   static_assert (sizeof (prev) > sizeof (offset_type), "");
4569 }
4570
4571 #if GDB_SELF_TEST
4572
4573 namespace selftests { namespace dw2_expand_symtabs_matching {
4574
4575 /* A mock .gdb_index/.debug_names-like name index table, enough to
4576    exercise dw2_expand_symtabs_matching_symbol, which works with the
4577    mapped_index_base interface.  Builds an index from the symbol list
4578    passed as parameter to the constructor.  */
4579 class mock_mapped_index : public mapped_index_base
4580 {
4581 public:
4582   mock_mapped_index (gdb::array_view<const char *> symbols)
4583     : m_symbol_table (symbols)
4584   {}
4585
4586   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4587
4588   /* Return the number of names in the symbol table.  */
4589   size_t symbol_name_count () const override
4590   {
4591     return m_symbol_table.size ();
4592   }
4593
4594   /* Get the name of the symbol at IDX in the symbol table.  */
4595   const char *symbol_name_at (offset_type idx) const override
4596   {
4597     return m_symbol_table[idx];
4598   }
4599
4600 private:
4601   gdb::array_view<const char *> m_symbol_table;
4602 };
4603
4604 /* Convenience function that converts a NULL pointer to a "<null>"
4605    string, to pass to print routines.  */
4606
4607 static const char *
4608 string_or_null (const char *str)
4609 {
4610   return str != NULL ? str : "<null>";
4611 }
4612
4613 /* Check if a lookup_name_info built from
4614    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4615    index.  EXPECTED_LIST is the list of expected matches, in expected
4616    matching order.  If no match expected, then an empty list is
4617    specified.  Returns true on success.  On failure prints a warning
4618    indicating the file:line that failed, and returns false.  */
4619
4620 static bool
4621 check_match (const char *file, int line,
4622              mock_mapped_index &mock_index,
4623              const char *name, symbol_name_match_type match_type,
4624              bool completion_mode,
4625              std::initializer_list<const char *> expected_list)
4626 {
4627   lookup_name_info lookup_name (name, match_type, completion_mode);
4628
4629   bool matched = true;
4630
4631   auto mismatch = [&] (const char *expected_str,
4632                        const char *got)
4633   {
4634     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4635                "expected=\"%s\", got=\"%s\"\n"),
4636              file, line,
4637              (match_type == symbol_name_match_type::FULL
4638               ? "FULL" : "WILD"),
4639              name, string_or_null (expected_str), string_or_null (got));
4640     matched = false;
4641   };
4642
4643   auto expected_it = expected_list.begin ();
4644   auto expected_end = expected_list.end ();
4645
4646   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4647                                       NULL, ALL_DOMAIN,
4648                                       [&] (offset_type idx)
4649   {
4650     const char *matched_name = mock_index.symbol_name_at (idx);
4651     const char *expected_str
4652       = expected_it == expected_end ? NULL : *expected_it++;
4653
4654     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4655       mismatch (expected_str, matched_name);
4656   });
4657
4658   const char *expected_str
4659   = expected_it == expected_end ? NULL : *expected_it++;
4660   if (expected_str != NULL)
4661     mismatch (expected_str, NULL);
4662
4663   return matched;
4664 }
4665
4666 /* The symbols added to the mock mapped_index for testing (in
4667    canonical form).  */
4668 static const char *test_symbols[] = {
4669   "function",
4670   "std::bar",
4671   "std::zfunction",
4672   "std::zfunction2",
4673   "w1::w2",
4674   "ns::foo<char*>",
4675   "ns::foo<int>",
4676   "ns::foo<long>",
4677   "ns2::tmpl<int>::foo2",
4678   "(anonymous namespace)::A::B::C",
4679
4680   /* These are used to check that the increment-last-char in the
4681      matching algorithm for completion doesn't match "t1_fund" when
4682      completing "t1_func".  */
4683   "t1_func",
4684   "t1_func1",
4685   "t1_fund",
4686   "t1_fund1",
4687
4688   /* A UTF-8 name with multi-byte sequences to make sure that
4689      cp-name-parser understands this as a single identifier ("função"
4690      is "function" in PT).  */
4691   u8"u8função",
4692
4693   /* \377 (0xff) is Latin1 'ÿ'.  */
4694   "yfunc\377",
4695
4696   /* \377 (0xff) is Latin1 'ÿ'.  */
4697   "\377",
4698   "\377\377123",
4699
4700   /* A name with all sorts of complications.  Starts with "z" to make
4701      it easier for the completion tests below.  */
4702 #define Z_SYM_NAME \
4703   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4704     "::tuple<(anonymous namespace)::ui*, " \
4705     "std::default_delete<(anonymous namespace)::ui>, void>"
4706
4707   Z_SYM_NAME
4708 };
4709
4710 /* Returns true if the mapped_index_base::find_name_component_bounds
4711    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4712    in completion mode.  */
4713
4714 static bool
4715 check_find_bounds_finds (mapped_index_base &index,
4716                          const char *search_name,
4717                          gdb::array_view<const char *> expected_syms)
4718 {
4719   lookup_name_info lookup_name (search_name,
4720                                 symbol_name_match_type::FULL, true);
4721
4722   auto bounds = index.find_name_components_bounds (lookup_name);
4723
4724   size_t distance = std::distance (bounds.first, bounds.second);
4725   if (distance != expected_syms.size ())
4726     return false;
4727
4728   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4729     {
4730       auto nc_elem = bounds.first + exp_elem;
4731       const char *qualified = index.symbol_name_at (nc_elem->idx);
4732       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4733         return false;
4734     }
4735
4736   return true;
4737 }
4738
4739 /* Test the lower-level mapped_index::find_name_component_bounds
4740    method.  */
4741
4742 static void
4743 test_mapped_index_find_name_component_bounds ()
4744 {
4745   mock_mapped_index mock_index (test_symbols);
4746
4747   mock_index.build_name_components ();
4748
4749   /* Test the lower-level mapped_index::find_name_component_bounds
4750      method in completion mode.  */
4751   {
4752     static const char *expected_syms[] = {
4753       "t1_func",
4754       "t1_func1",
4755     };
4756
4757     SELF_CHECK (check_find_bounds_finds (mock_index,
4758                                          "t1_func", expected_syms));
4759   }
4760
4761   /* Check that the increment-last-char in the name matching algorithm
4762      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4763   {
4764     static const char *expected_syms1[] = {
4765       "\377",
4766       "\377\377123",
4767     };
4768     SELF_CHECK (check_find_bounds_finds (mock_index,
4769                                          "\377", expected_syms1));
4770
4771     static const char *expected_syms2[] = {
4772       "\377\377123",
4773     };
4774     SELF_CHECK (check_find_bounds_finds (mock_index,
4775                                          "\377\377", expected_syms2));
4776   }
4777 }
4778
4779 /* Test dw2_expand_symtabs_matching_symbol.  */
4780
4781 static void
4782 test_dw2_expand_symtabs_matching_symbol ()
4783 {
4784   mock_mapped_index mock_index (test_symbols);
4785
4786   /* We let all tests run until the end even if some fails, for debug
4787      convenience.  */
4788   bool any_mismatch = false;
4789
4790   /* Create the expected symbols list (an initializer_list).  Needed
4791      because lists have commas, and we need to pass them to CHECK,
4792      which is a macro.  */
4793 #define EXPECT(...) { __VA_ARGS__ }
4794
4795   /* Wrapper for check_match that passes down the current
4796      __FILE__/__LINE__.  */
4797 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4798   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4799                                 mock_index,                             \
4800                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4801                                 EXPECTED_LIST)
4802
4803   /* Identity checks.  */
4804   for (const char *sym : test_symbols)
4805     {
4806       /* Should be able to match all existing symbols.  */
4807       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4808                    EXPECT (sym));
4809
4810       /* Should be able to match all existing symbols with
4811          parameters.  */
4812       std::string with_params = std::string (sym) + "(int)";
4813       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4814                    EXPECT (sym));
4815
4816       /* Should be able to match all existing symbols with
4817          parameters and qualifiers.  */
4818       with_params = std::string (sym) + " ( int ) const";
4819       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4820                    EXPECT (sym));
4821
4822       /* This should really find sym, but cp-name-parser.y doesn't
4823          know about lvalue/rvalue qualifiers yet.  */
4824       with_params = std::string (sym) + " ( int ) &&";
4825       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4826                    {});
4827     }
4828
4829   /* Check that the name matching algorithm for completion doesn't get
4830      confused with Latin1 'ÿ' / 0xff.  */
4831   {
4832     static const char str[] = "\377";
4833     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4834                  EXPECT ("\377", "\377\377123"));
4835   }
4836
4837   /* Check that the increment-last-char in the matching algorithm for
4838      completion doesn't match "t1_fund" when completing "t1_func".  */
4839   {
4840     static const char str[] = "t1_func";
4841     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4842                  EXPECT ("t1_func", "t1_func1"));
4843   }
4844
4845   /* Check that completion mode works at each prefix of the expected
4846      symbol name.  */
4847   {
4848     static const char str[] = "function(int)";
4849     size_t len = strlen (str);
4850     std::string lookup;
4851
4852     for (size_t i = 1; i < len; i++)
4853       {
4854         lookup.assign (str, i);
4855         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4856                      EXPECT ("function"));
4857       }
4858   }
4859
4860   /* While "w" is a prefix of both components, the match function
4861      should still only be called once.  */
4862   {
4863     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4864                  EXPECT ("w1::w2"));
4865     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4866                  EXPECT ("w1::w2"));
4867   }
4868
4869   /* Same, with a "complicated" symbol.  */
4870   {
4871     static const char str[] = Z_SYM_NAME;
4872     size_t len = strlen (str);
4873     std::string lookup;
4874
4875     for (size_t i = 1; i < len; i++)
4876       {
4877         lookup.assign (str, i);
4878         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4879                      EXPECT (Z_SYM_NAME));
4880       }
4881   }
4882
4883   /* In FULL mode, an incomplete symbol doesn't match.  */
4884   {
4885     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4886                  {});
4887   }
4888
4889   /* A complete symbol with parameters matches any overload, since the
4890      index has no overload info.  */
4891   {
4892     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4893                  EXPECT ("std::zfunction", "std::zfunction2"));
4894     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4895                  EXPECT ("std::zfunction", "std::zfunction2"));
4896     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4897                  EXPECT ("std::zfunction", "std::zfunction2"));
4898   }
4899
4900   /* Check that whitespace is ignored appropriately.  A symbol with a
4901      template argument list. */
4902   {
4903     static const char expected[] = "ns::foo<int>";
4904     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4905                  EXPECT (expected));
4906     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4907                  EXPECT (expected));
4908   }
4909
4910   /* Check that whitespace is ignored appropriately.  A symbol with a
4911      template argument list that includes a pointer.  */
4912   {
4913     static const char expected[] = "ns::foo<char*>";
4914     /* Try both completion and non-completion modes.  */
4915     static const bool completion_mode[2] = {false, true};
4916     for (size_t i = 0; i < 2; i++)
4917       {
4918         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4919                      completion_mode[i], EXPECT (expected));
4920         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4921                      completion_mode[i], EXPECT (expected));
4922
4923         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4924                      completion_mode[i], EXPECT (expected));
4925         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4926                      completion_mode[i], EXPECT (expected));
4927       }
4928   }
4929
4930   {
4931     /* Check method qualifiers are ignored.  */
4932     static const char expected[] = "ns::foo<char*>";
4933     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4934                  symbol_name_match_type::FULL, true, EXPECT (expected));
4935     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4936                  symbol_name_match_type::FULL, true, EXPECT (expected));
4937     CHECK_MATCH ("foo < char * >  ( int ) const",
4938                  symbol_name_match_type::WILD, true, EXPECT (expected));
4939     CHECK_MATCH ("foo < char * >  ( int ) &&",
4940                  symbol_name_match_type::WILD, true, EXPECT (expected));
4941   }
4942
4943   /* Test lookup names that don't match anything.  */
4944   {
4945     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4946                  {});
4947
4948     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4949                  {});
4950   }
4951
4952   /* Some wild matching tests, exercising "(anonymous namespace)",
4953      which should not be confused with a parameter list.  */
4954   {
4955     static const char *syms[] = {
4956       "A::B::C",
4957       "B::C",
4958       "C",
4959       "A :: B :: C ( int )",
4960       "B :: C ( int )",
4961       "C ( int )",
4962     };
4963
4964     for (const char *s : syms)
4965       {
4966         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4967                      EXPECT ("(anonymous namespace)::A::B::C"));
4968       }
4969   }
4970
4971   {
4972     static const char expected[] = "ns2::tmpl<int>::foo2";
4973     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4974                  EXPECT (expected));
4975     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4976                  EXPECT (expected));
4977   }
4978
4979   SELF_CHECK (!any_mismatch);
4980
4981 #undef EXPECT
4982 #undef CHECK_MATCH
4983 }
4984
4985 static void
4986 run_test ()
4987 {
4988   test_mapped_index_find_name_component_bounds ();
4989   test_dw2_expand_symtabs_matching_symbol ();
4990 }
4991
4992 }} // namespace selftests::dw2_expand_symtabs_matching
4993
4994 #endif /* GDB_SELF_TEST */
4995
4996 /* If FILE_MATCHER is NULL or if PER_CU has
4997    dwarf2_per_cu_quick_data::MARK set (see
4998    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4999    EXPANSION_NOTIFY on it.  */
5000
5001 static void
5002 dw2_expand_symtabs_matching_one
5003   (struct dwarf2_per_cu_data *per_cu,
5004    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5005    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5006 {
5007   if (file_matcher == NULL || per_cu->v.quick->mark)
5008     {
5009       bool symtab_was_null
5010         = (per_cu->v.quick->compunit_symtab == NULL);
5011
5012       dw2_instantiate_symtab (per_cu, false);
5013
5014       if (expansion_notify != NULL
5015           && symtab_was_null
5016           && per_cu->v.quick->compunit_symtab != NULL)
5017         expansion_notify (per_cu->v.quick->compunit_symtab);
5018     }
5019 }
5020
5021 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5022    matched, to expand corresponding CUs that were marked.  IDX is the
5023    index of the symbol name that matched.  */
5024
5025 static void
5026 dw2_expand_marked_cus
5027   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5028    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5029    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5030    search_domain kind)
5031 {
5032   offset_type *vec, vec_len, vec_idx;
5033   bool global_seen = false;
5034   mapped_index &index = *dwarf2_per_objfile->index_table;
5035
5036   vec = (offset_type *) (index.constant_pool
5037                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5038   vec_len = MAYBE_SWAP (vec[0]);
5039   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5040     {
5041       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5042       /* This value is only valid for index versions >= 7.  */
5043       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5044       gdb_index_symbol_kind symbol_kind =
5045         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5046       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5047       /* Only check the symbol attributes if they're present.
5048          Indices prior to version 7 don't record them,
5049          and indices >= 7 may elide them for certain symbols
5050          (gold does this).  */
5051       int attrs_valid =
5052         (index.version >= 7
5053          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5054
5055       /* Work around gold/15646.  */
5056       if (attrs_valid)
5057         {
5058           if (!is_static && global_seen)
5059             continue;
5060           if (!is_static)
5061             global_seen = true;
5062         }
5063
5064       /* Only check the symbol's kind if it has one.  */
5065       if (attrs_valid)
5066         {
5067           switch (kind)
5068             {
5069             case VARIABLES_DOMAIN:
5070               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5071                 continue;
5072               break;
5073             case FUNCTIONS_DOMAIN:
5074               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5075                 continue;
5076               break;
5077             case TYPES_DOMAIN:
5078               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5079                 continue;
5080               break;
5081             default:
5082               break;
5083             }
5084         }
5085
5086       /* Don't crash on bad data.  */
5087       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5088                        + dwarf2_per_objfile->all_type_units.size ()))
5089         {
5090           complaint (_(".gdb_index entry has bad CU index"
5091                        " [in module %s]"),
5092                        objfile_name (dwarf2_per_objfile->objfile));
5093           continue;
5094         }
5095
5096       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5097       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5098                                        expansion_notify);
5099     }
5100 }
5101
5102 /* If FILE_MATCHER is non-NULL, set all the
5103    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5104    that match FILE_MATCHER.  */
5105
5106 static void
5107 dw_expand_symtabs_matching_file_matcher
5108   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5109    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5110 {
5111   if (file_matcher == NULL)
5112     return;
5113
5114   objfile *const objfile = dwarf2_per_objfile->objfile;
5115
5116   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5117                                             htab_eq_pointer,
5118                                             NULL, xcalloc, xfree));
5119   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5120                                                 htab_eq_pointer,
5121                                                 NULL, xcalloc, xfree));
5122
5123   /* The rule is CUs specify all the files, including those used by
5124      any TU, so there's no need to scan TUs here.  */
5125
5126   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5127     {
5128       QUIT;
5129
5130       per_cu->v.quick->mark = 0;
5131
5132       /* We only need to look at symtabs not already expanded.  */
5133       if (per_cu->v.quick->compunit_symtab)
5134         continue;
5135
5136       quick_file_names *file_data = dw2_get_file_names (per_cu);
5137       if (file_data == NULL)
5138         continue;
5139
5140       if (htab_find (visited_not_found.get (), file_data) != NULL)
5141         continue;
5142       else if (htab_find (visited_found.get (), file_data) != NULL)
5143         {
5144           per_cu->v.quick->mark = 1;
5145           continue;
5146         }
5147
5148       for (int j = 0; j < file_data->num_file_names; ++j)
5149         {
5150           const char *this_real_name;
5151
5152           if (file_matcher (file_data->file_names[j], false))
5153             {
5154               per_cu->v.quick->mark = 1;
5155               break;
5156             }
5157
5158           /* Before we invoke realpath, which can get expensive when many
5159              files are involved, do a quick comparison of the basenames.  */
5160           if (!basenames_may_differ
5161               && !file_matcher (lbasename (file_data->file_names[j]),
5162                                 true))
5163             continue;
5164
5165           this_real_name = dw2_get_real_path (objfile, file_data, j);
5166           if (file_matcher (this_real_name, false))
5167             {
5168               per_cu->v.quick->mark = 1;
5169               break;
5170             }
5171         }
5172
5173       void **slot = htab_find_slot (per_cu->v.quick->mark
5174                                     ? visited_found.get ()
5175                                     : visited_not_found.get (),
5176                                     file_data, INSERT);
5177       *slot = file_data;
5178     }
5179 }
5180
5181 static void
5182 dw2_expand_symtabs_matching
5183   (struct objfile *objfile,
5184    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5185    const lookup_name_info &lookup_name,
5186    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5187    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5188    enum search_domain kind)
5189 {
5190   struct dwarf2_per_objfile *dwarf2_per_objfile
5191     = get_dwarf2_per_objfile (objfile);
5192
5193   /* index_table is NULL if OBJF_READNOW.  */
5194   if (!dwarf2_per_objfile->index_table)
5195     return;
5196
5197   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5198
5199   mapped_index &index = *dwarf2_per_objfile->index_table;
5200
5201   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5202                                       symbol_matcher,
5203                                       kind, [&] (offset_type idx)
5204     {
5205       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5206                              expansion_notify, kind);
5207     });
5208 }
5209
5210 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5211    symtab.  */
5212
5213 static struct compunit_symtab *
5214 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5215                                           CORE_ADDR pc)
5216 {
5217   int i;
5218
5219   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5220       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5221     return cust;
5222
5223   if (cust->includes == NULL)
5224     return NULL;
5225
5226   for (i = 0; cust->includes[i]; ++i)
5227     {
5228       struct compunit_symtab *s = cust->includes[i];
5229
5230       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5231       if (s != NULL)
5232         return s;
5233     }
5234
5235   return NULL;
5236 }
5237
5238 static struct compunit_symtab *
5239 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5240                                   struct bound_minimal_symbol msymbol,
5241                                   CORE_ADDR pc,
5242                                   struct obj_section *section,
5243                                   int warn_if_readin)
5244 {
5245   struct dwarf2_per_cu_data *data;
5246   struct compunit_symtab *result;
5247
5248   if (!objfile->psymtabs_addrmap)
5249     return NULL;
5250
5251   CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
5252                                  SECT_OFF_TEXT (objfile));
5253   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5254                                                      pc - baseaddr);
5255   if (!data)
5256     return NULL;
5257
5258   if (warn_if_readin && data->v.quick->compunit_symtab)
5259     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5260              paddress (get_objfile_arch (objfile), pc));
5261
5262   result
5263     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5264                                                                         false),
5265                                                 pc);
5266   gdb_assert (result != NULL);
5267   return result;
5268 }
5269
5270 static void
5271 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5272                           void *data, int need_fullname)
5273 {
5274   struct dwarf2_per_objfile *dwarf2_per_objfile
5275     = get_dwarf2_per_objfile (objfile);
5276
5277   if (!dwarf2_per_objfile->filenames_cache)
5278     {
5279       dwarf2_per_objfile->filenames_cache.emplace ();
5280
5281       htab_up visited (htab_create_alloc (10,
5282                                           htab_hash_pointer, htab_eq_pointer,
5283                                           NULL, xcalloc, xfree));
5284
5285       /* The rule is CUs specify all the files, including those used
5286          by any TU, so there's no need to scan TUs here.  We can
5287          ignore file names coming from already-expanded CUs.  */
5288
5289       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5290         {
5291           if (per_cu->v.quick->compunit_symtab)
5292             {
5293               void **slot = htab_find_slot (visited.get (),
5294                                             per_cu->v.quick->file_names,
5295                                             INSERT);
5296
5297               *slot = per_cu->v.quick->file_names;
5298             }
5299         }
5300
5301       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5302         {
5303           /* We only need to look at symtabs not already expanded.  */
5304           if (per_cu->v.quick->compunit_symtab)
5305             continue;
5306
5307           quick_file_names *file_data = dw2_get_file_names (per_cu);
5308           if (file_data == NULL)
5309             continue;
5310
5311           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5312           if (*slot)
5313             {
5314               /* Already visited.  */
5315               continue;
5316             }
5317           *slot = file_data;
5318
5319           for (int j = 0; j < file_data->num_file_names; ++j)
5320             {
5321               const char *filename = file_data->file_names[j];
5322               dwarf2_per_objfile->filenames_cache->seen (filename);
5323             }
5324         }
5325     }
5326
5327   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5328     {
5329       gdb::unique_xmalloc_ptr<char> this_real_name;
5330
5331       if (need_fullname)
5332         this_real_name = gdb_realpath (filename);
5333       (*fun) (filename, this_real_name.get (), data);
5334     });
5335 }
5336
5337 static int
5338 dw2_has_symbols (struct objfile *objfile)
5339 {
5340   return 1;
5341 }
5342
5343 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5344 {
5345   dw2_has_symbols,
5346   dw2_find_last_source_symtab,
5347   dw2_forget_cached_source_info,
5348   dw2_map_symtabs_matching_filename,
5349   dw2_lookup_symbol,
5350   dw2_print_stats,
5351   dw2_dump,
5352   dw2_expand_symtabs_for_function,
5353   dw2_expand_all_symtabs,
5354   dw2_expand_symtabs_with_fullname,
5355   dw2_map_matching_symbols,
5356   dw2_expand_symtabs_matching,
5357   dw2_find_pc_sect_compunit_symtab,
5358   NULL,
5359   dw2_map_symbol_filenames
5360 };
5361
5362 /* DWARF-5 debug_names reader.  */
5363
5364 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5365 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5366
5367 /* A helper function that reads the .debug_names section in SECTION
5368    and fills in MAP.  FILENAME is the name of the file containing the
5369    section; it is used for error reporting.
5370
5371    Returns true if all went well, false otherwise.  */
5372
5373 static bool
5374 read_debug_names_from_section (struct objfile *objfile,
5375                                const char *filename,
5376                                struct dwarf2_section_info *section,
5377                                mapped_debug_names &map)
5378 {
5379   if (dwarf2_section_empty_p (section))
5380     return false;
5381
5382   /* Older elfutils strip versions could keep the section in the main
5383      executable while splitting it for the separate debug info file.  */
5384   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5385     return false;
5386
5387   dwarf2_read_section (objfile, section);
5388
5389   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5390
5391   const gdb_byte *addr = section->buffer;
5392
5393   bfd *const abfd = get_section_bfd_owner (section);
5394
5395   unsigned int bytes_read;
5396   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5397   addr += bytes_read;
5398
5399   map.dwarf5_is_dwarf64 = bytes_read != 4;
5400   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5401   if (bytes_read + length != section->size)
5402     {
5403       /* There may be multiple per-CU indices.  */
5404       warning (_("Section .debug_names in %s length %s does not match "
5405                  "section length %s, ignoring .debug_names."),
5406                filename, plongest (bytes_read + length),
5407                pulongest (section->size));
5408       return false;
5409     }
5410
5411   /* The version number.  */
5412   uint16_t version = read_2_bytes (abfd, addr);
5413   addr += 2;
5414   if (version != 5)
5415     {
5416       warning (_("Section .debug_names in %s has unsupported version %d, "
5417                  "ignoring .debug_names."),
5418                filename, version);
5419       return false;
5420     }
5421
5422   /* Padding.  */
5423   uint16_t padding = read_2_bytes (abfd, addr);
5424   addr += 2;
5425   if (padding != 0)
5426     {
5427       warning (_("Section .debug_names in %s has unsupported padding %d, "
5428                  "ignoring .debug_names."),
5429                filename, padding);
5430       return false;
5431     }
5432
5433   /* comp_unit_count - The number of CUs in the CU list.  */
5434   map.cu_count = read_4_bytes (abfd, addr);
5435   addr += 4;
5436
5437   /* local_type_unit_count - The number of TUs in the local TU
5438      list.  */
5439   map.tu_count = read_4_bytes (abfd, addr);
5440   addr += 4;
5441
5442   /* foreign_type_unit_count - The number of TUs in the foreign TU
5443      list.  */
5444   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5445   addr += 4;
5446   if (foreign_tu_count != 0)
5447     {
5448       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5449                  "ignoring .debug_names."),
5450                filename, static_cast<unsigned long> (foreign_tu_count));
5451       return false;
5452     }
5453
5454   /* bucket_count - The number of hash buckets in the hash lookup
5455      table.  */
5456   map.bucket_count = read_4_bytes (abfd, addr);
5457   addr += 4;
5458
5459   /* name_count - The number of unique names in the index.  */
5460   map.name_count = read_4_bytes (abfd, addr);
5461   addr += 4;
5462
5463   /* abbrev_table_size - The size in bytes of the abbreviations
5464      table.  */
5465   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5466   addr += 4;
5467
5468   /* augmentation_string_size - The size in bytes of the augmentation
5469      string.  This value is rounded up to a multiple of 4.  */
5470   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5471   addr += 4;
5472   map.augmentation_is_gdb = ((augmentation_string_size
5473                               == sizeof (dwarf5_augmentation))
5474                              && memcmp (addr, dwarf5_augmentation,
5475                                         sizeof (dwarf5_augmentation)) == 0);
5476   augmentation_string_size += (-augmentation_string_size) & 3;
5477   addr += augmentation_string_size;
5478
5479   /* List of CUs */
5480   map.cu_table_reordered = addr;
5481   addr += map.cu_count * map.offset_size;
5482
5483   /* List of Local TUs */
5484   map.tu_table_reordered = addr;
5485   addr += map.tu_count * map.offset_size;
5486
5487   /* Hash Lookup Table */
5488   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5489   addr += map.bucket_count * 4;
5490   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5491   addr += map.name_count * 4;
5492
5493   /* Name Table */
5494   map.name_table_string_offs_reordered = addr;
5495   addr += map.name_count * map.offset_size;
5496   map.name_table_entry_offs_reordered = addr;
5497   addr += map.name_count * map.offset_size;
5498
5499   const gdb_byte *abbrev_table_start = addr;
5500   for (;;)
5501     {
5502       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5503       addr += bytes_read;
5504       if (index_num == 0)
5505         break;
5506
5507       const auto insertpair
5508         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5509       if (!insertpair.second)
5510         {
5511           warning (_("Section .debug_names in %s has duplicate index %s, "
5512                      "ignoring .debug_names."),
5513                    filename, pulongest (index_num));
5514           return false;
5515         }
5516       mapped_debug_names::index_val &indexval = insertpair.first->second;
5517       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5518       addr += bytes_read;
5519
5520       for (;;)
5521         {
5522           mapped_debug_names::index_val::attr attr;
5523           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5524           addr += bytes_read;
5525           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5526           addr += bytes_read;
5527           if (attr.form == DW_FORM_implicit_const)
5528             {
5529               attr.implicit_const = read_signed_leb128 (abfd, addr,
5530                                                         &bytes_read);
5531               addr += bytes_read;
5532             }
5533           if (attr.dw_idx == 0 && attr.form == 0)
5534             break;
5535           indexval.attr_vec.push_back (std::move (attr));
5536         }
5537     }
5538   if (addr != abbrev_table_start + abbrev_table_size)
5539     {
5540       warning (_("Section .debug_names in %s has abbreviation_table "
5541                  "of size %zu vs. written as %u, ignoring .debug_names."),
5542                filename, addr - abbrev_table_start, abbrev_table_size);
5543       return false;
5544     }
5545   map.entry_pool = addr;
5546
5547   return true;
5548 }
5549
5550 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5551    list.  */
5552
5553 static void
5554 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5555                                   const mapped_debug_names &map,
5556                                   dwarf2_section_info &section,
5557                                   bool is_dwz)
5558 {
5559   sect_offset sect_off_prev;
5560   for (uint32_t i = 0; i <= map.cu_count; ++i)
5561     {
5562       sect_offset sect_off_next;
5563       if (i < map.cu_count)
5564         {
5565           sect_off_next
5566             = (sect_offset) (extract_unsigned_integer
5567                              (map.cu_table_reordered + i * map.offset_size,
5568                               map.offset_size,
5569                               map.dwarf5_byte_order));
5570         }
5571       else
5572         sect_off_next = (sect_offset) section.size;
5573       if (i >= 1)
5574         {
5575           const ULONGEST length = sect_off_next - sect_off_prev;
5576           dwarf2_per_cu_data *per_cu
5577             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5578                                          sect_off_prev, length);
5579           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5580         }
5581       sect_off_prev = sect_off_next;
5582     }
5583 }
5584
5585 /* Read the CU list from the mapped index, and use it to create all
5586    the CU objects for this dwarf2_per_objfile.  */
5587
5588 static void
5589 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5590                              const mapped_debug_names &map,
5591                              const mapped_debug_names &dwz_map)
5592 {
5593   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5594   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5595
5596   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5597                                     dwarf2_per_objfile->info,
5598                                     false /* is_dwz */);
5599
5600   if (dwz_map.cu_count == 0)
5601     return;
5602
5603   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5604   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5605                                     true /* is_dwz */);
5606 }
5607
5608 /* Read .debug_names.  If everything went ok, initialize the "quick"
5609    elements of all the CUs and return true.  Otherwise, return false.  */
5610
5611 static bool
5612 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5613 {
5614   std::unique_ptr<mapped_debug_names> map
5615     (new mapped_debug_names (dwarf2_per_objfile));
5616   mapped_debug_names dwz_map (dwarf2_per_objfile);
5617   struct objfile *objfile = dwarf2_per_objfile->objfile;
5618
5619   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5620                                       &dwarf2_per_objfile->debug_names,
5621                                       *map))
5622     return false;
5623
5624   /* Don't use the index if it's empty.  */
5625   if (map->name_count == 0)
5626     return false;
5627
5628   /* If there is a .dwz file, read it so we can get its CU list as
5629      well.  */
5630   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5631   if (dwz != NULL)
5632     {
5633       if (!read_debug_names_from_section (objfile,
5634                                           bfd_get_filename (dwz->dwz_bfd),
5635                                           &dwz->debug_names, dwz_map))
5636         {
5637           warning (_("could not read '.debug_names' section from %s; skipping"),
5638                    bfd_get_filename (dwz->dwz_bfd));
5639           return false;
5640         }
5641     }
5642
5643   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5644
5645   if (map->tu_count != 0)
5646     {
5647       /* We can only handle a single .debug_types when we have an
5648          index.  */
5649       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5650         return false;
5651
5652       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5653                                                 dwarf2_per_objfile->types, 0);
5654
5655       create_signatured_type_table_from_debug_names
5656         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5657     }
5658
5659   create_addrmap_from_aranges (dwarf2_per_objfile,
5660                                &dwarf2_per_objfile->debug_aranges);
5661
5662   dwarf2_per_objfile->debug_names_table = std::move (map);
5663   dwarf2_per_objfile->using_index = 1;
5664   dwarf2_per_objfile->quick_file_names_table =
5665     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5666
5667   return true;
5668 }
5669
5670 /* Type used to manage iterating over all CUs looking for a symbol for
5671    .debug_names.  */
5672
5673 class dw2_debug_names_iterator
5674 {
5675 public:
5676   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5677      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5678   dw2_debug_names_iterator (const mapped_debug_names &map,
5679                             bool want_specific_block,
5680                             block_enum block_index, domain_enum domain,
5681                             const char *name)
5682     : m_map (map), m_want_specific_block (want_specific_block),
5683       m_block_index (block_index), m_domain (domain),
5684       m_addr (find_vec_in_debug_names (map, name))
5685   {}
5686
5687   dw2_debug_names_iterator (const mapped_debug_names &map,
5688                             search_domain search, uint32_t namei)
5689     : m_map (map),
5690       m_search (search),
5691       m_addr (find_vec_in_debug_names (map, namei))
5692   {}
5693
5694   /* Return the next matching CU or NULL if there are no more.  */
5695   dwarf2_per_cu_data *next ();
5696
5697 private:
5698   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5699                                                   const char *name);
5700   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5701                                                   uint32_t namei);
5702
5703   /* The internalized form of .debug_names.  */
5704   const mapped_debug_names &m_map;
5705
5706   /* If true, only look for symbols that match BLOCK_INDEX.  */
5707   const bool m_want_specific_block = false;
5708
5709   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5710      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5711      value.  */
5712   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5713
5714   /* The kind of symbol we're looking for.  */
5715   const domain_enum m_domain = UNDEF_DOMAIN;
5716   const search_domain m_search = ALL_DOMAIN;
5717
5718   /* The list of CUs from the index entry of the symbol, or NULL if
5719      not found.  */
5720   const gdb_byte *m_addr;
5721 };
5722
5723 const char *
5724 mapped_debug_names::namei_to_name (uint32_t namei) const
5725 {
5726   const ULONGEST namei_string_offs
5727     = extract_unsigned_integer ((name_table_string_offs_reordered
5728                                  + namei * offset_size),
5729                                 offset_size,
5730                                 dwarf5_byte_order);
5731   return read_indirect_string_at_offset
5732     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5733 }
5734
5735 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5736    found, return pointer to its pool data.  If NAME cannot be found,
5737    return NULL.  */
5738
5739 const gdb_byte *
5740 dw2_debug_names_iterator::find_vec_in_debug_names
5741   (const mapped_debug_names &map, const char *name)
5742 {
5743   int (*cmp) (const char *, const char *);
5744
5745   if (current_language->la_language == language_cplus
5746       || current_language->la_language == language_fortran
5747       || current_language->la_language == language_d)
5748     {
5749       /* NAME is already canonical.  Drop any qualifiers as
5750          .debug_names does not contain any.  */
5751
5752       if (strchr (name, '(') != NULL)
5753         {
5754           gdb::unique_xmalloc_ptr<char> without_params
5755             = cp_remove_params (name);
5756
5757           if (without_params != NULL)
5758             {
5759               name = without_params.get();
5760             }
5761         }
5762     }
5763
5764   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5765
5766   const uint32_t full_hash = dwarf5_djb_hash (name);
5767   uint32_t namei
5768     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5769                                 (map.bucket_table_reordered
5770                                  + (full_hash % map.bucket_count)), 4,
5771                                 map.dwarf5_byte_order);
5772   if (namei == 0)
5773     return NULL;
5774   --namei;
5775   if (namei >= map.name_count)
5776     {
5777       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5778                    "[in module %s]"),
5779                  namei, map.name_count,
5780                  objfile_name (map.dwarf2_per_objfile->objfile));
5781       return NULL;
5782     }
5783
5784   for (;;)
5785     {
5786       const uint32_t namei_full_hash
5787         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5788                                     (map.hash_table_reordered + namei), 4,
5789                                     map.dwarf5_byte_order);
5790       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5791         return NULL;
5792
5793       if (full_hash == namei_full_hash)
5794         {
5795           const char *const namei_string = map.namei_to_name (namei);
5796
5797 #if 0 /* An expensive sanity check.  */
5798           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5799             {
5800               complaint (_("Wrong .debug_names hash for string at index %u "
5801                            "[in module %s]"),
5802                          namei, objfile_name (dwarf2_per_objfile->objfile));
5803               return NULL;
5804             }
5805 #endif
5806
5807           if (cmp (namei_string, name) == 0)
5808             {
5809               const ULONGEST namei_entry_offs
5810                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5811                                              + namei * map.offset_size),
5812                                             map.offset_size, map.dwarf5_byte_order);
5813               return map.entry_pool + namei_entry_offs;
5814             }
5815         }
5816
5817       ++namei;
5818       if (namei >= map.name_count)
5819         return NULL;
5820     }
5821 }
5822
5823 const gdb_byte *
5824 dw2_debug_names_iterator::find_vec_in_debug_names
5825   (const mapped_debug_names &map, uint32_t namei)
5826 {
5827   if (namei >= map.name_count)
5828     {
5829       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5830                    "[in module %s]"),
5831                  namei, map.name_count,
5832                  objfile_name (map.dwarf2_per_objfile->objfile));
5833       return NULL;
5834     }
5835
5836   const ULONGEST namei_entry_offs
5837     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5838                                  + namei * map.offset_size),
5839                                 map.offset_size, map.dwarf5_byte_order);
5840   return map.entry_pool + namei_entry_offs;
5841 }
5842
5843 /* See dw2_debug_names_iterator.  */
5844
5845 dwarf2_per_cu_data *
5846 dw2_debug_names_iterator::next ()
5847 {
5848   if (m_addr == NULL)
5849     return NULL;
5850
5851   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5852   struct objfile *objfile = dwarf2_per_objfile->objfile;
5853   bfd *const abfd = objfile->obfd;
5854
5855  again:
5856
5857   unsigned int bytes_read;
5858   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5859   m_addr += bytes_read;
5860   if (abbrev == 0)
5861     return NULL;
5862
5863   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5864   if (indexval_it == m_map.abbrev_map.cend ())
5865     {
5866       complaint (_("Wrong .debug_names undefined abbrev code %s "
5867                    "[in module %s]"),
5868                  pulongest (abbrev), objfile_name (objfile));
5869       return NULL;
5870     }
5871   const mapped_debug_names::index_val &indexval = indexval_it->second;
5872   bool have_is_static = false;
5873   bool is_static;
5874   dwarf2_per_cu_data *per_cu = NULL;
5875   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5876     {
5877       ULONGEST ull;
5878       switch (attr.form)
5879         {
5880         case DW_FORM_implicit_const:
5881           ull = attr.implicit_const;
5882           break;
5883         case DW_FORM_flag_present:
5884           ull = 1;
5885           break;
5886         case DW_FORM_udata:
5887           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5888           m_addr += bytes_read;
5889           break;
5890         default:
5891           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5892                      dwarf_form_name (attr.form),
5893                      objfile_name (objfile));
5894           return NULL;
5895         }
5896       switch (attr.dw_idx)
5897         {
5898         case DW_IDX_compile_unit:
5899           /* Don't crash on bad data.  */
5900           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5901             {
5902               complaint (_(".debug_names entry has bad CU index %s"
5903                            " [in module %s]"),
5904                          pulongest (ull),
5905                          objfile_name (dwarf2_per_objfile->objfile));
5906               continue;
5907             }
5908           per_cu = dwarf2_per_objfile->get_cutu (ull);
5909           break;
5910         case DW_IDX_type_unit:
5911           /* Don't crash on bad data.  */
5912           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5913             {
5914               complaint (_(".debug_names entry has bad TU index %s"
5915                            " [in module %s]"),
5916                          pulongest (ull),
5917                          objfile_name (dwarf2_per_objfile->objfile));
5918               continue;
5919             }
5920           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5921           break;
5922         case DW_IDX_GNU_internal:
5923           if (!m_map.augmentation_is_gdb)
5924             break;
5925           have_is_static = true;
5926           is_static = true;
5927           break;
5928         case DW_IDX_GNU_external:
5929           if (!m_map.augmentation_is_gdb)
5930             break;
5931           have_is_static = true;
5932           is_static = false;
5933           break;
5934         }
5935     }
5936
5937   /* Skip if already read in.  */
5938   if (per_cu->v.quick->compunit_symtab)
5939     goto again;
5940
5941   /* Check static vs global.  */
5942   if (have_is_static)
5943     {
5944       const bool want_static = m_block_index != GLOBAL_BLOCK;
5945       if (m_want_specific_block && want_static != is_static)
5946         goto again;
5947     }
5948
5949   /* Match dw2_symtab_iter_next, symbol_kind
5950      and debug_names::psymbol_tag.  */
5951   switch (m_domain)
5952     {
5953     case VAR_DOMAIN:
5954       switch (indexval.dwarf_tag)
5955         {
5956         case DW_TAG_variable:
5957         case DW_TAG_subprogram:
5958         /* Some types are also in VAR_DOMAIN.  */
5959         case DW_TAG_typedef:
5960         case DW_TAG_structure_type:
5961           break;
5962         default:
5963           goto again;
5964         }
5965       break;
5966     case STRUCT_DOMAIN:
5967       switch (indexval.dwarf_tag)
5968         {
5969         case DW_TAG_typedef:
5970         case DW_TAG_structure_type:
5971           break;
5972         default:
5973           goto again;
5974         }
5975       break;
5976     case LABEL_DOMAIN:
5977       switch (indexval.dwarf_tag)
5978         {
5979         case 0:
5980         case DW_TAG_variable:
5981           break;
5982         default:
5983           goto again;
5984         }
5985       break;
5986     default:
5987       break;
5988     }
5989
5990   /* Match dw2_expand_symtabs_matching, symbol_kind and
5991      debug_names::psymbol_tag.  */
5992   switch (m_search)
5993     {
5994     case VARIABLES_DOMAIN:
5995       switch (indexval.dwarf_tag)
5996         {
5997         case DW_TAG_variable:
5998           break;
5999         default:
6000           goto again;
6001         }
6002       break;
6003     case FUNCTIONS_DOMAIN:
6004       switch (indexval.dwarf_tag)
6005         {
6006         case DW_TAG_subprogram:
6007           break;
6008         default:
6009           goto again;
6010         }
6011       break;
6012     case TYPES_DOMAIN:
6013       switch (indexval.dwarf_tag)
6014         {
6015         case DW_TAG_typedef:
6016         case DW_TAG_structure_type:
6017           break;
6018         default:
6019           goto again;
6020         }
6021       break;
6022     default:
6023       break;
6024     }
6025
6026   return per_cu;
6027 }
6028
6029 static struct compunit_symtab *
6030 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6031                                const char *name, domain_enum domain)
6032 {
6033   const block_enum block_index = static_cast<block_enum> (block_index_int);
6034   struct dwarf2_per_objfile *dwarf2_per_objfile
6035     = get_dwarf2_per_objfile (objfile);
6036
6037   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6038   if (!mapp)
6039     {
6040       /* index is NULL if OBJF_READNOW.  */
6041       return NULL;
6042     }
6043   const auto &map = *mapp;
6044
6045   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6046                                  block_index, domain, name);
6047
6048   struct compunit_symtab *stab_best = NULL;
6049   struct dwarf2_per_cu_data *per_cu;
6050   while ((per_cu = iter.next ()) != NULL)
6051     {
6052       struct symbol *sym, *with_opaque = NULL;
6053       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6054       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6055       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6056
6057       sym = block_find_symbol (block, name, domain,
6058                                block_find_non_opaque_type_preferred,
6059                                &with_opaque);
6060
6061       /* Some caution must be observed with overloaded functions and
6062          methods, since the index will not contain any overload
6063          information (but NAME might contain it).  */
6064
6065       if (sym != NULL
6066           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6067         return stab;
6068       if (with_opaque != NULL
6069           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6070         stab_best = stab;
6071
6072       /* Keep looking through other CUs.  */
6073     }
6074
6075   return stab_best;
6076 }
6077
6078 /* This dumps minimal information about .debug_names.  It is called
6079    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6080    uses this to verify that .debug_names has been loaded.  */
6081
6082 static void
6083 dw2_debug_names_dump (struct objfile *objfile)
6084 {
6085   struct dwarf2_per_objfile *dwarf2_per_objfile
6086     = get_dwarf2_per_objfile (objfile);
6087
6088   gdb_assert (dwarf2_per_objfile->using_index);
6089   printf_filtered (".debug_names:");
6090   if (dwarf2_per_objfile->debug_names_table)
6091     printf_filtered (" exists\n");
6092   else
6093     printf_filtered (" faked for \"readnow\"\n");
6094   printf_filtered ("\n");
6095 }
6096
6097 static void
6098 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6099                                              const char *func_name)
6100 {
6101   struct dwarf2_per_objfile *dwarf2_per_objfile
6102     = get_dwarf2_per_objfile (objfile);
6103
6104   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6105   if (dwarf2_per_objfile->debug_names_table)
6106     {
6107       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6108
6109       /* Note: It doesn't matter what we pass for block_index here.  */
6110       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6111                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6112
6113       struct dwarf2_per_cu_data *per_cu;
6114       while ((per_cu = iter.next ()) != NULL)
6115         dw2_instantiate_symtab (per_cu, false);
6116     }
6117 }
6118
6119 static void
6120 dw2_debug_names_expand_symtabs_matching
6121   (struct objfile *objfile,
6122    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6123    const lookup_name_info &lookup_name,
6124    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6125    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6126    enum search_domain kind)
6127 {
6128   struct dwarf2_per_objfile *dwarf2_per_objfile
6129     = get_dwarf2_per_objfile (objfile);
6130
6131   /* debug_names_table is NULL if OBJF_READNOW.  */
6132   if (!dwarf2_per_objfile->debug_names_table)
6133     return;
6134
6135   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6136
6137   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6138
6139   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6140                                       symbol_matcher,
6141                                       kind, [&] (offset_type namei)
6142     {
6143       /* The name was matched, now expand corresponding CUs that were
6144          marked.  */
6145       dw2_debug_names_iterator iter (map, kind, namei);
6146
6147       struct dwarf2_per_cu_data *per_cu;
6148       while ((per_cu = iter.next ()) != NULL)
6149         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6150                                          expansion_notify);
6151     });
6152 }
6153
6154 const struct quick_symbol_functions dwarf2_debug_names_functions =
6155 {
6156   dw2_has_symbols,
6157   dw2_find_last_source_symtab,
6158   dw2_forget_cached_source_info,
6159   dw2_map_symtabs_matching_filename,
6160   dw2_debug_names_lookup_symbol,
6161   dw2_print_stats,
6162   dw2_debug_names_dump,
6163   dw2_debug_names_expand_symtabs_for_function,
6164   dw2_expand_all_symtabs,
6165   dw2_expand_symtabs_with_fullname,
6166   dw2_map_matching_symbols,
6167   dw2_debug_names_expand_symtabs_matching,
6168   dw2_find_pc_sect_compunit_symtab,
6169   NULL,
6170   dw2_map_symbol_filenames
6171 };
6172
6173 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
6174    to either a dwarf2_per_objfile or dwz_file object.  */
6175
6176 template <typename T>
6177 static gdb::array_view<const gdb_byte>
6178 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
6179 {
6180   dwarf2_section_info *section = &section_owner->gdb_index;
6181
6182   if (dwarf2_section_empty_p (section))
6183     return {};
6184
6185   /* Older elfutils strip versions could keep the section in the main
6186      executable while splitting it for the separate debug info file.  */
6187   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
6188     return {};
6189
6190   dwarf2_read_section (obj, section);
6191
6192   /* dwarf2_section_info::size is a bfd_size_type, while
6193      gdb::array_view works with size_t.  On 32-bit hosts, with
6194      --enable-64-bit-bfd, bfd_size_type is a 64-bit type, while size_t
6195      is 32-bit.  So we need an explicit narrowing conversion here.
6196      This is fine, because it's impossible to allocate or mmap an
6197      array/buffer larger than what size_t can represent.  */
6198   return gdb::make_array_view (section->buffer, section->size);
6199 }
6200
6201 /* Lookup the index cache for the contents of the index associated to
6202    DWARF2_OBJ.  */
6203
6204 static gdb::array_view<const gdb_byte>
6205 get_gdb_index_contents_from_cache (objfile *obj, dwarf2_per_objfile *dwarf2_obj)
6206 {
6207   const bfd_build_id *build_id = build_id_bfd_get (obj->obfd);
6208   if (build_id == nullptr)
6209     return {};
6210
6211   return global_index_cache.lookup_gdb_index (build_id,
6212                                               &dwarf2_obj->index_cache_res);
6213 }
6214
6215 /* Same as the above, but for DWZ.  */
6216
6217 static gdb::array_view<const gdb_byte>
6218 get_gdb_index_contents_from_cache_dwz (objfile *obj, dwz_file *dwz)
6219 {
6220   const bfd_build_id *build_id = build_id_bfd_get (dwz->dwz_bfd.get ());
6221   if (build_id == nullptr)
6222     return {};
6223
6224   return global_index_cache.lookup_gdb_index (build_id, &dwz->index_cache_res);
6225 }
6226
6227 /* See symfile.h.  */
6228
6229 bool
6230 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6231 {
6232   struct dwarf2_per_objfile *dwarf2_per_objfile
6233     = get_dwarf2_per_objfile (objfile);
6234
6235   /* If we're about to read full symbols, don't bother with the
6236      indices.  In this case we also don't care if some other debug
6237      format is making psymtabs, because they are all about to be
6238      expanded anyway.  */
6239   if ((objfile->flags & OBJF_READNOW))
6240     {
6241       dwarf2_per_objfile->using_index = 1;
6242       create_all_comp_units (dwarf2_per_objfile);
6243       create_all_type_units (dwarf2_per_objfile);
6244       dwarf2_per_objfile->quick_file_names_table
6245         = create_quick_file_names_table
6246             (dwarf2_per_objfile->all_comp_units.size ());
6247
6248       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6249                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6250         {
6251           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6252
6253           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6254                                             struct dwarf2_per_cu_quick_data);
6255         }
6256
6257       /* Return 1 so that gdb sees the "quick" functions.  However,
6258          these functions will be no-ops because we will have expanded
6259          all symtabs.  */
6260       *index_kind = dw_index_kind::GDB_INDEX;
6261       return true;
6262     }
6263
6264   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6265     {
6266       *index_kind = dw_index_kind::DEBUG_NAMES;
6267       return true;
6268     }
6269
6270   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6271                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6272                              get_gdb_index_contents_from_section<dwz_file>))
6273     {
6274       *index_kind = dw_index_kind::GDB_INDEX;
6275       return true;
6276     }
6277
6278   /* ... otherwise, try to find the index in the index cache.  */
6279   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6280                              get_gdb_index_contents_from_cache,
6281                              get_gdb_index_contents_from_cache_dwz))
6282     {
6283       global_index_cache.hit ();
6284       *index_kind = dw_index_kind::GDB_INDEX;
6285       return true;
6286     }
6287
6288   global_index_cache.miss ();
6289   return false;
6290 }
6291
6292 \f
6293
6294 /* Build a partial symbol table.  */
6295
6296 void
6297 dwarf2_build_psymtabs (struct objfile *objfile)
6298 {
6299   struct dwarf2_per_objfile *dwarf2_per_objfile
6300     = get_dwarf2_per_objfile (objfile);
6301
6302   init_psymbol_list (objfile, 1024);
6303
6304   TRY
6305     {
6306       /* This isn't really ideal: all the data we allocate on the
6307          objfile's obstack is still uselessly kept around.  However,
6308          freeing it seems unsafe.  */
6309       psymtab_discarder psymtabs (objfile);
6310       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6311       psymtabs.keep ();
6312
6313       /* (maybe) store an index in the cache.  */
6314       global_index_cache.store (dwarf2_per_objfile);
6315     }
6316   CATCH (except, RETURN_MASK_ERROR)
6317     {
6318       exception_print (gdb_stderr, except);
6319     }
6320   END_CATCH
6321 }
6322
6323 /* Return the total length of the CU described by HEADER.  */
6324
6325 static unsigned int
6326 get_cu_length (const struct comp_unit_head *header)
6327 {
6328   return header->initial_length_size + header->length;
6329 }
6330
6331 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6332
6333 static inline bool
6334 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6335 {
6336   sect_offset bottom = cu_header->sect_off;
6337   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6338
6339   return sect_off >= bottom && sect_off < top;
6340 }
6341
6342 /* Find the base address of the compilation unit for range lists and
6343    location lists.  It will normally be specified by DW_AT_low_pc.
6344    In DWARF-3 draft 4, the base address could be overridden by
6345    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6346    compilation units with discontinuous ranges.  */
6347
6348 static void
6349 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6350 {
6351   struct attribute *attr;
6352
6353   cu->base_known = 0;
6354   cu->base_address = 0;
6355
6356   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6357   if (attr)
6358     {
6359       cu->base_address = attr_value_as_address (attr);
6360       cu->base_known = 1;
6361     }
6362   else
6363     {
6364       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6365       if (attr)
6366         {
6367           cu->base_address = attr_value_as_address (attr);
6368           cu->base_known = 1;
6369         }
6370     }
6371 }
6372
6373 /* Read in the comp unit header information from the debug_info at info_ptr.
6374    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6375    NOTE: This leaves members offset, first_die_offset to be filled in
6376    by the caller.  */
6377
6378 static const gdb_byte *
6379 read_comp_unit_head (struct comp_unit_head *cu_header,
6380                      const gdb_byte *info_ptr,
6381                      struct dwarf2_section_info *section,
6382                      rcuh_kind section_kind)
6383 {
6384   int signed_addr;
6385   unsigned int bytes_read;
6386   const char *filename = get_section_file_name (section);
6387   bfd *abfd = get_section_bfd_owner (section);
6388
6389   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6390   cu_header->initial_length_size = bytes_read;
6391   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6392   info_ptr += bytes_read;
6393   cu_header->version = read_2_bytes (abfd, info_ptr);
6394   if (cu_header->version < 2 || cu_header->version > 5)
6395     error (_("Dwarf Error: wrong version in compilation unit header "
6396            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6397            cu_header->version, filename);
6398   info_ptr += 2;
6399   if (cu_header->version < 5)
6400     switch (section_kind)
6401       {
6402       case rcuh_kind::COMPILE:
6403         cu_header->unit_type = DW_UT_compile;
6404         break;
6405       case rcuh_kind::TYPE:
6406         cu_header->unit_type = DW_UT_type;
6407         break;
6408       default:
6409         internal_error (__FILE__, __LINE__,
6410                         _("read_comp_unit_head: invalid section_kind"));
6411       }
6412   else
6413     {
6414       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6415                                                  (read_1_byte (abfd, info_ptr));
6416       info_ptr += 1;
6417       switch (cu_header->unit_type)
6418         {
6419         case DW_UT_compile:
6420           if (section_kind != rcuh_kind::COMPILE)
6421             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6422                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6423                    filename);
6424           break;
6425         case DW_UT_type:
6426           section_kind = rcuh_kind::TYPE;
6427           break;
6428         default:
6429           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6430                  "(is %d, should be %d or %d) [in module %s]"),
6431                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6432         }
6433
6434       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6435       info_ptr += 1;
6436     }
6437   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6438                                                           cu_header,
6439                                                           &bytes_read);
6440   info_ptr += bytes_read;
6441   if (cu_header->version < 5)
6442     {
6443       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6444       info_ptr += 1;
6445     }
6446   signed_addr = bfd_get_sign_extend_vma (abfd);
6447   if (signed_addr < 0)
6448     internal_error (__FILE__, __LINE__,
6449                     _("read_comp_unit_head: dwarf from non elf file"));
6450   cu_header->signed_addr_p = signed_addr;
6451
6452   if (section_kind == rcuh_kind::TYPE)
6453     {
6454       LONGEST type_offset;
6455
6456       cu_header->signature = read_8_bytes (abfd, info_ptr);
6457       info_ptr += 8;
6458
6459       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6460       info_ptr += bytes_read;
6461       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6462       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6463         error (_("Dwarf Error: Too big type_offset in compilation unit "
6464                "header (is %s) [in module %s]"), plongest (type_offset),
6465                filename);
6466     }
6467
6468   return info_ptr;
6469 }
6470
6471 /* Helper function that returns the proper abbrev section for
6472    THIS_CU.  */
6473
6474 static struct dwarf2_section_info *
6475 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6476 {
6477   struct dwarf2_section_info *abbrev;
6478   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6479
6480   if (this_cu->is_dwz)
6481     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6482   else
6483     abbrev = &dwarf2_per_objfile->abbrev;
6484
6485   return abbrev;
6486 }
6487
6488 /* Subroutine of read_and_check_comp_unit_head and
6489    read_and_check_type_unit_head to simplify them.
6490    Perform various error checking on the header.  */
6491
6492 static void
6493 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6494                             struct comp_unit_head *header,
6495                             struct dwarf2_section_info *section,
6496                             struct dwarf2_section_info *abbrev_section)
6497 {
6498   const char *filename = get_section_file_name (section);
6499
6500   if (to_underlying (header->abbrev_sect_off)
6501       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6502     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6503            "(offset %s + 6) [in module %s]"),
6504            sect_offset_str (header->abbrev_sect_off),
6505            sect_offset_str (header->sect_off),
6506            filename);
6507
6508   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6509      avoid potential 32-bit overflow.  */
6510   if (((ULONGEST) header->sect_off + get_cu_length (header))
6511       > section->size)
6512     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6513            "(offset %s + 0) [in module %s]"),
6514            header->length, sect_offset_str (header->sect_off),
6515            filename);
6516 }
6517
6518 /* Read in a CU/TU header and perform some basic error checking.
6519    The contents of the header are stored in HEADER.
6520    The result is a pointer to the start of the first DIE.  */
6521
6522 static const gdb_byte *
6523 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6524                                struct comp_unit_head *header,
6525                                struct dwarf2_section_info *section,
6526                                struct dwarf2_section_info *abbrev_section,
6527                                const gdb_byte *info_ptr,
6528                                rcuh_kind section_kind)
6529 {
6530   const gdb_byte *beg_of_comp_unit = info_ptr;
6531
6532   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6533
6534   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6535
6536   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6537
6538   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6539                               abbrev_section);
6540
6541   return info_ptr;
6542 }
6543
6544 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6545
6546 static sect_offset
6547 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6548                     struct dwarf2_section_info *section,
6549                     sect_offset sect_off)
6550 {
6551   bfd *abfd = get_section_bfd_owner (section);
6552   const gdb_byte *info_ptr;
6553   unsigned int initial_length_size, offset_size;
6554   uint16_t version;
6555
6556   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6557   info_ptr = section->buffer + to_underlying (sect_off);
6558   read_initial_length (abfd, info_ptr, &initial_length_size);
6559   offset_size = initial_length_size == 4 ? 4 : 8;
6560   info_ptr += initial_length_size;
6561
6562   version = read_2_bytes (abfd, info_ptr);
6563   info_ptr += 2;
6564   if (version >= 5)
6565     {
6566       /* Skip unit type and address size.  */
6567       info_ptr += 2;
6568     }
6569
6570   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6571 }
6572
6573 /* Allocate a new partial symtab for file named NAME and mark this new
6574    partial symtab as being an include of PST.  */
6575
6576 static void
6577 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6578                                struct objfile *objfile)
6579 {
6580   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6581
6582   if (!IS_ABSOLUTE_PATH (subpst->filename))
6583     {
6584       /* It shares objfile->objfile_obstack.  */
6585       subpst->dirname = pst->dirname;
6586     }
6587
6588   subpst->dependencies
6589     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6590   subpst->dependencies[0] = pst;
6591   subpst->number_of_dependencies = 1;
6592
6593   subpst->read_symtab = pst->read_symtab;
6594
6595   /* No private part is necessary for include psymtabs.  This property
6596      can be used to differentiate between such include psymtabs and
6597      the regular ones.  */
6598   subpst->read_symtab_private = NULL;
6599 }
6600
6601 /* Read the Line Number Program data and extract the list of files
6602    included by the source file represented by PST.  Build an include
6603    partial symtab for each of these included files.  */
6604
6605 static void
6606 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6607                                struct die_info *die,
6608                                struct partial_symtab *pst)
6609 {
6610   line_header_up lh;
6611   struct attribute *attr;
6612
6613   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6614   if (attr)
6615     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6616   if (lh == NULL)
6617     return;  /* No linetable, so no includes.  */
6618
6619   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6620      that we pass in the raw text_low here; that is ok because we're
6621      only decoding the line table to make include partial symtabs, and
6622      so the addresses aren't really used.  */
6623   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6624                       pst->raw_text_low (), 1);
6625 }
6626
6627 static hashval_t
6628 hash_signatured_type (const void *item)
6629 {
6630   const struct signatured_type *sig_type
6631     = (const struct signatured_type *) item;
6632
6633   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6634   return sig_type->signature;
6635 }
6636
6637 static int
6638 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6639 {
6640   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6641   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6642
6643   return lhs->signature == rhs->signature;
6644 }
6645
6646 /* Allocate a hash table for signatured types.  */
6647
6648 static htab_t
6649 allocate_signatured_type_table (struct objfile *objfile)
6650 {
6651   return htab_create_alloc_ex (41,
6652                                hash_signatured_type,
6653                                eq_signatured_type,
6654                                NULL,
6655                                &objfile->objfile_obstack,
6656                                hashtab_obstack_allocate,
6657                                dummy_obstack_deallocate);
6658 }
6659
6660 /* A helper function to add a signatured type CU to a table.  */
6661
6662 static int
6663 add_signatured_type_cu_to_table (void **slot, void *datum)
6664 {
6665   struct signatured_type *sigt = (struct signatured_type *) *slot;
6666   std::vector<signatured_type *> *all_type_units
6667     = (std::vector<signatured_type *> *) datum;
6668
6669   all_type_units->push_back (sigt);
6670
6671   return 1;
6672 }
6673
6674 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6675    and fill them into TYPES_HTAB.  It will process only type units,
6676    therefore DW_UT_type.  */
6677
6678 static void
6679 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6680                               struct dwo_file *dwo_file,
6681                               dwarf2_section_info *section, htab_t &types_htab,
6682                               rcuh_kind section_kind)
6683 {
6684   struct objfile *objfile = dwarf2_per_objfile->objfile;
6685   struct dwarf2_section_info *abbrev_section;
6686   bfd *abfd;
6687   const gdb_byte *info_ptr, *end_ptr;
6688
6689   abbrev_section = (dwo_file != NULL
6690                     ? &dwo_file->sections.abbrev
6691                     : &dwarf2_per_objfile->abbrev);
6692
6693   if (dwarf_read_debug)
6694     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6695                         get_section_name (section),
6696                         get_section_file_name (abbrev_section));
6697
6698   dwarf2_read_section (objfile, section);
6699   info_ptr = section->buffer;
6700
6701   if (info_ptr == NULL)
6702     return;
6703
6704   /* We can't set abfd until now because the section may be empty or
6705      not present, in which case the bfd is unknown.  */
6706   abfd = get_section_bfd_owner (section);
6707
6708   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6709      because we don't need to read any dies: the signature is in the
6710      header.  */
6711
6712   end_ptr = info_ptr + section->size;
6713   while (info_ptr < end_ptr)
6714     {
6715       struct signatured_type *sig_type;
6716       struct dwo_unit *dwo_tu;
6717       void **slot;
6718       const gdb_byte *ptr = info_ptr;
6719       struct comp_unit_head header;
6720       unsigned int length;
6721
6722       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6723
6724       /* Initialize it due to a false compiler warning.  */
6725       header.signature = -1;
6726       header.type_cu_offset_in_tu = (cu_offset) -1;
6727
6728       /* We need to read the type's signature in order to build the hash
6729          table, but we don't need anything else just yet.  */
6730
6731       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6732                                            abbrev_section, ptr, section_kind);
6733
6734       length = get_cu_length (&header);
6735
6736       /* Skip dummy type units.  */
6737       if (ptr >= info_ptr + length
6738           || peek_abbrev_code (abfd, ptr) == 0
6739           || header.unit_type != DW_UT_type)
6740         {
6741           info_ptr += length;
6742           continue;
6743         }
6744
6745       if (types_htab == NULL)
6746         {
6747           if (dwo_file)
6748             types_htab = allocate_dwo_unit_table (objfile);
6749           else
6750             types_htab = allocate_signatured_type_table (objfile);
6751         }
6752
6753       if (dwo_file)
6754         {
6755           sig_type = NULL;
6756           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6757                                    struct dwo_unit);
6758           dwo_tu->dwo_file = dwo_file;
6759           dwo_tu->signature = header.signature;
6760           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6761           dwo_tu->section = section;
6762           dwo_tu->sect_off = sect_off;
6763           dwo_tu->length = length;
6764         }
6765       else
6766         {
6767           /* N.B.: type_offset is not usable if this type uses a DWO file.
6768              The real type_offset is in the DWO file.  */
6769           dwo_tu = NULL;
6770           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6771                                      struct signatured_type);
6772           sig_type->signature = header.signature;
6773           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6774           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6775           sig_type->per_cu.is_debug_types = 1;
6776           sig_type->per_cu.section = section;
6777           sig_type->per_cu.sect_off = sect_off;
6778           sig_type->per_cu.length = length;
6779         }
6780
6781       slot = htab_find_slot (types_htab,
6782                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6783                              INSERT);
6784       gdb_assert (slot != NULL);
6785       if (*slot != NULL)
6786         {
6787           sect_offset dup_sect_off;
6788
6789           if (dwo_file)
6790             {
6791               const struct dwo_unit *dup_tu
6792                 = (const struct dwo_unit *) *slot;
6793
6794               dup_sect_off = dup_tu->sect_off;
6795             }
6796           else
6797             {
6798               const struct signatured_type *dup_tu
6799                 = (const struct signatured_type *) *slot;
6800
6801               dup_sect_off = dup_tu->per_cu.sect_off;
6802             }
6803
6804           complaint (_("debug type entry at offset %s is duplicate to"
6805                        " the entry at offset %s, signature %s"),
6806                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6807                      hex_string (header.signature));
6808         }
6809       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6810
6811       if (dwarf_read_debug > 1)
6812         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6813                             sect_offset_str (sect_off),
6814                             hex_string (header.signature));
6815
6816       info_ptr += length;
6817     }
6818 }
6819
6820 /* Create the hash table of all entries in the .debug_types
6821    (or .debug_types.dwo) section(s).
6822    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6823    otherwise it is NULL.
6824
6825    The result is a pointer to the hash table or NULL if there are no types.
6826
6827    Note: This function processes DWO files only, not DWP files.  */
6828
6829 static void
6830 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6831                                struct dwo_file *dwo_file,
6832                                VEC (dwarf2_section_info_def) *types,
6833                                htab_t &types_htab)
6834 {
6835   int ix;
6836   struct dwarf2_section_info *section;
6837
6838   if (VEC_empty (dwarf2_section_info_def, types))
6839     return;
6840
6841   for (ix = 0;
6842        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6843        ++ix)
6844     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6845                                   types_htab, rcuh_kind::TYPE);
6846 }
6847
6848 /* Create the hash table of all entries in the .debug_types section,
6849    and initialize all_type_units.
6850    The result is zero if there is an error (e.g. missing .debug_types section),
6851    otherwise non-zero.  */
6852
6853 static int
6854 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6855 {
6856   htab_t types_htab = NULL;
6857
6858   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6859                                 &dwarf2_per_objfile->info, types_htab,
6860                                 rcuh_kind::COMPILE);
6861   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6862                                  dwarf2_per_objfile->types, types_htab);
6863   if (types_htab == NULL)
6864     {
6865       dwarf2_per_objfile->signatured_types = NULL;
6866       return 0;
6867     }
6868
6869   dwarf2_per_objfile->signatured_types = types_htab;
6870
6871   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6872   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6873
6874   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6875                           &dwarf2_per_objfile->all_type_units);
6876
6877   return 1;
6878 }
6879
6880 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6881    If SLOT is non-NULL, it is the entry to use in the hash table.
6882    Otherwise we find one.  */
6883
6884 static struct signatured_type *
6885 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6886                void **slot)
6887 {
6888   struct objfile *objfile = dwarf2_per_objfile->objfile;
6889
6890   if (dwarf2_per_objfile->all_type_units.size ()
6891       == dwarf2_per_objfile->all_type_units.capacity ())
6892     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6893
6894   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6895                                               struct signatured_type);
6896
6897   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6898   sig_type->signature = sig;
6899   sig_type->per_cu.is_debug_types = 1;
6900   if (dwarf2_per_objfile->using_index)
6901     {
6902       sig_type->per_cu.v.quick =
6903         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6904                         struct dwarf2_per_cu_quick_data);
6905     }
6906
6907   if (slot == NULL)
6908     {
6909       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6910                              sig_type, INSERT);
6911     }
6912   gdb_assert (*slot == NULL);
6913   *slot = sig_type;
6914   /* The rest of sig_type must be filled in by the caller.  */
6915   return sig_type;
6916 }
6917
6918 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6919    Fill in SIG_ENTRY with DWO_ENTRY.  */
6920
6921 static void
6922 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6923                                   struct signatured_type *sig_entry,
6924                                   struct dwo_unit *dwo_entry)
6925 {
6926   /* Make sure we're not clobbering something we don't expect to.  */
6927   gdb_assert (! sig_entry->per_cu.queued);
6928   gdb_assert (sig_entry->per_cu.cu == NULL);
6929   if (dwarf2_per_objfile->using_index)
6930     {
6931       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6932       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6933     }
6934   else
6935       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6936   gdb_assert (sig_entry->signature == dwo_entry->signature);
6937   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6938   gdb_assert (sig_entry->type_unit_group == NULL);
6939   gdb_assert (sig_entry->dwo_unit == NULL);
6940
6941   sig_entry->per_cu.section = dwo_entry->section;
6942   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6943   sig_entry->per_cu.length = dwo_entry->length;
6944   sig_entry->per_cu.reading_dwo_directly = 1;
6945   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6946   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6947   sig_entry->dwo_unit = dwo_entry;
6948 }
6949
6950 /* Subroutine of lookup_signatured_type.
6951    If we haven't read the TU yet, create the signatured_type data structure
6952    for a TU to be read in directly from a DWO file, bypassing the stub.
6953    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6954    using .gdb_index, then when reading a CU we want to stay in the DWO file
6955    containing that CU.  Otherwise we could end up reading several other DWO
6956    files (due to comdat folding) to process the transitive closure of all the
6957    mentioned TUs, and that can be slow.  The current DWO file will have every
6958    type signature that it needs.
6959    We only do this for .gdb_index because in the psymtab case we already have
6960    to read all the DWOs to build the type unit groups.  */
6961
6962 static struct signatured_type *
6963 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6964 {
6965   struct dwarf2_per_objfile *dwarf2_per_objfile
6966     = cu->per_cu->dwarf2_per_objfile;
6967   struct objfile *objfile = dwarf2_per_objfile->objfile;
6968   struct dwo_file *dwo_file;
6969   struct dwo_unit find_dwo_entry, *dwo_entry;
6970   struct signatured_type find_sig_entry, *sig_entry;
6971   void **slot;
6972
6973   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6974
6975   /* If TU skeletons have been removed then we may not have read in any
6976      TUs yet.  */
6977   if (dwarf2_per_objfile->signatured_types == NULL)
6978     {
6979       dwarf2_per_objfile->signatured_types
6980         = allocate_signatured_type_table (objfile);
6981     }
6982
6983   /* We only ever need to read in one copy of a signatured type.
6984      Use the global signatured_types array to do our own comdat-folding
6985      of types.  If this is the first time we're reading this TU, and
6986      the TU has an entry in .gdb_index, replace the recorded data from
6987      .gdb_index with this TU.  */
6988
6989   find_sig_entry.signature = sig;
6990   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6991                          &find_sig_entry, INSERT);
6992   sig_entry = (struct signatured_type *) *slot;
6993
6994   /* We can get here with the TU already read, *or* in the process of being
6995      read.  Don't reassign the global entry to point to this DWO if that's
6996      the case.  Also note that if the TU is already being read, it may not
6997      have come from a DWO, the program may be a mix of Fission-compiled
6998      code and non-Fission-compiled code.  */
6999
7000   /* Have we already tried to read this TU?
7001      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7002      needn't exist in the global table yet).  */
7003   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7004     return sig_entry;
7005
7006   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7007      dwo_unit of the TU itself.  */
7008   dwo_file = cu->dwo_unit->dwo_file;
7009
7010   /* Ok, this is the first time we're reading this TU.  */
7011   if (dwo_file->tus == NULL)
7012     return NULL;
7013   find_dwo_entry.signature = sig;
7014   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7015   if (dwo_entry == NULL)
7016     return NULL;
7017
7018   /* If the global table doesn't have an entry for this TU, add one.  */
7019   if (sig_entry == NULL)
7020     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7021
7022   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7023   sig_entry->per_cu.tu_read = 1;
7024   return sig_entry;
7025 }
7026
7027 /* Subroutine of lookup_signatured_type.
7028    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7029    then try the DWP file.  If the TU stub (skeleton) has been removed then
7030    it won't be in .gdb_index.  */
7031
7032 static struct signatured_type *
7033 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7034 {
7035   struct dwarf2_per_objfile *dwarf2_per_objfile
7036     = cu->per_cu->dwarf2_per_objfile;
7037   struct objfile *objfile = dwarf2_per_objfile->objfile;
7038   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7039   struct dwo_unit *dwo_entry;
7040   struct signatured_type find_sig_entry, *sig_entry;
7041   void **slot;
7042
7043   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7044   gdb_assert (dwp_file != NULL);
7045
7046   /* If TU skeletons have been removed then we may not have read in any
7047      TUs yet.  */
7048   if (dwarf2_per_objfile->signatured_types == NULL)
7049     {
7050       dwarf2_per_objfile->signatured_types
7051         = allocate_signatured_type_table (objfile);
7052     }
7053
7054   find_sig_entry.signature = sig;
7055   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7056                          &find_sig_entry, INSERT);
7057   sig_entry = (struct signatured_type *) *slot;
7058
7059   /* Have we already tried to read this TU?
7060      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7061      needn't exist in the global table yet).  */
7062   if (sig_entry != NULL)
7063     return sig_entry;
7064
7065   if (dwp_file->tus == NULL)
7066     return NULL;
7067   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7068                                       sig, 1 /* is_debug_types */);
7069   if (dwo_entry == NULL)
7070     return NULL;
7071
7072   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7073   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7074
7075   return sig_entry;
7076 }
7077
7078 /* Lookup a signature based type for DW_FORM_ref_sig8.
7079    Returns NULL if signature SIG is not present in the table.
7080    It is up to the caller to complain about this.  */
7081
7082 static struct signatured_type *
7083 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7084 {
7085   struct dwarf2_per_objfile *dwarf2_per_objfile
7086     = cu->per_cu->dwarf2_per_objfile;
7087
7088   if (cu->dwo_unit
7089       && dwarf2_per_objfile->using_index)
7090     {
7091       /* We're in a DWO/DWP file, and we're using .gdb_index.
7092          These cases require special processing.  */
7093       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7094         return lookup_dwo_signatured_type (cu, sig);
7095       else
7096         return lookup_dwp_signatured_type (cu, sig);
7097     }
7098   else
7099     {
7100       struct signatured_type find_entry, *entry;
7101
7102       if (dwarf2_per_objfile->signatured_types == NULL)
7103         return NULL;
7104       find_entry.signature = sig;
7105       entry = ((struct signatured_type *)
7106                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7107       return entry;
7108     }
7109 }
7110 \f
7111 /* Low level DIE reading support.  */
7112
7113 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7114
7115 static void
7116 init_cu_die_reader (struct die_reader_specs *reader,
7117                     struct dwarf2_cu *cu,
7118                     struct dwarf2_section_info *section,
7119                     struct dwo_file *dwo_file,
7120                     struct abbrev_table *abbrev_table)
7121 {
7122   gdb_assert (section->readin && section->buffer != NULL);
7123   reader->abfd = get_section_bfd_owner (section);
7124   reader->cu = cu;
7125   reader->dwo_file = dwo_file;
7126   reader->die_section = section;
7127   reader->buffer = section->buffer;
7128   reader->buffer_end = section->buffer + section->size;
7129   reader->comp_dir = NULL;
7130   reader->abbrev_table = abbrev_table;
7131 }
7132
7133 /* Subroutine of init_cutu_and_read_dies to simplify it.
7134    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7135    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7136    already.
7137
7138    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7139    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7140    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7141    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7142    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7143    STUB_COMP_DIR may be non-NULL.
7144    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7145    are filled in with the info of the DIE from the DWO file.
7146    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7147    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7148    kept around for at least as long as *RESULT_READER.
7149
7150    The result is non-zero if a valid (non-dummy) DIE was found.  */
7151
7152 static int
7153 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7154                         struct dwo_unit *dwo_unit,
7155                         struct die_info *stub_comp_unit_die,
7156                         const char *stub_comp_dir,
7157                         struct die_reader_specs *result_reader,
7158                         const gdb_byte **result_info_ptr,
7159                         struct die_info **result_comp_unit_die,
7160                         int *result_has_children,
7161                         abbrev_table_up *result_dwo_abbrev_table)
7162 {
7163   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7164   struct objfile *objfile = dwarf2_per_objfile->objfile;
7165   struct dwarf2_cu *cu = this_cu->cu;
7166   bfd *abfd;
7167   const gdb_byte *begin_info_ptr, *info_ptr;
7168   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7169   int i,num_extra_attrs;
7170   struct dwarf2_section_info *dwo_abbrev_section;
7171   struct attribute *attr;
7172   struct die_info *comp_unit_die;
7173
7174   /* At most one of these may be provided.  */
7175   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7176
7177   /* These attributes aren't processed until later:
7178      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7179      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7180      referenced later.  However, these attributes are found in the stub
7181      which we won't have later.  In order to not impose this complication
7182      on the rest of the code, we read them here and copy them to the
7183      DWO CU/TU die.  */
7184
7185   stmt_list = NULL;
7186   low_pc = NULL;
7187   high_pc = NULL;
7188   ranges = NULL;
7189   comp_dir = NULL;
7190
7191   if (stub_comp_unit_die != NULL)
7192     {
7193       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7194          DWO file.  */
7195       if (! this_cu->is_debug_types)
7196         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7197       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7198       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7199       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7200       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7201
7202       /* There should be a DW_AT_addr_base attribute here (if needed).
7203          We need the value before we can process DW_FORM_GNU_addr_index.  */
7204       cu->addr_base = 0;
7205       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7206       if (attr)
7207         cu->addr_base = DW_UNSND (attr);
7208
7209       /* There should be a DW_AT_ranges_base attribute here (if needed).
7210          We need the value before we can process DW_AT_ranges.  */
7211       cu->ranges_base = 0;
7212       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7213       if (attr)
7214         cu->ranges_base = DW_UNSND (attr);
7215     }
7216   else if (stub_comp_dir != NULL)
7217     {
7218       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7219       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7220       comp_dir->name = DW_AT_comp_dir;
7221       comp_dir->form = DW_FORM_string;
7222       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7223       DW_STRING (comp_dir) = stub_comp_dir;
7224     }
7225
7226   /* Set up for reading the DWO CU/TU.  */
7227   cu->dwo_unit = dwo_unit;
7228   dwarf2_section_info *section = dwo_unit->section;
7229   dwarf2_read_section (objfile, section);
7230   abfd = get_section_bfd_owner (section);
7231   begin_info_ptr = info_ptr = (section->buffer
7232                                + to_underlying (dwo_unit->sect_off));
7233   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7234
7235   if (this_cu->is_debug_types)
7236     {
7237       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7238
7239       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7240                                                 &cu->header, section,
7241                                                 dwo_abbrev_section,
7242                                                 info_ptr, rcuh_kind::TYPE);
7243       /* This is not an assert because it can be caused by bad debug info.  */
7244       if (sig_type->signature != cu->header.signature)
7245         {
7246           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7247                    " TU at offset %s [in module %s]"),
7248                  hex_string (sig_type->signature),
7249                  hex_string (cu->header.signature),
7250                  sect_offset_str (dwo_unit->sect_off),
7251                  bfd_get_filename (abfd));
7252         }
7253       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7254       /* For DWOs coming from DWP files, we don't know the CU length
7255          nor the type's offset in the TU until now.  */
7256       dwo_unit->length = get_cu_length (&cu->header);
7257       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7258
7259       /* Establish the type offset that can be used to lookup the type.
7260          For DWO files, we don't know it until now.  */
7261       sig_type->type_offset_in_section
7262         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7263     }
7264   else
7265     {
7266       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7267                                                 &cu->header, section,
7268                                                 dwo_abbrev_section,
7269                                                 info_ptr, rcuh_kind::COMPILE);
7270       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7271       /* For DWOs coming from DWP files, we don't know the CU length
7272          until now.  */
7273       dwo_unit->length = get_cu_length (&cu->header);
7274     }
7275
7276   *result_dwo_abbrev_table
7277     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7278                                cu->header.abbrev_sect_off);
7279   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7280                       result_dwo_abbrev_table->get ());
7281
7282   /* Read in the die, but leave space to copy over the attributes
7283      from the stub.  This has the benefit of simplifying the rest of
7284      the code - all the work to maintain the illusion of a single
7285      DW_TAG_{compile,type}_unit DIE is done here.  */
7286   num_extra_attrs = ((stmt_list != NULL)
7287                      + (low_pc != NULL)
7288                      + (high_pc != NULL)
7289                      + (ranges != NULL)
7290                      + (comp_dir != NULL));
7291   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7292                               result_has_children, num_extra_attrs);
7293
7294   /* Copy over the attributes from the stub to the DIE we just read in.  */
7295   comp_unit_die = *result_comp_unit_die;
7296   i = comp_unit_die->num_attrs;
7297   if (stmt_list != NULL)
7298     comp_unit_die->attrs[i++] = *stmt_list;
7299   if (low_pc != NULL)
7300     comp_unit_die->attrs[i++] = *low_pc;
7301   if (high_pc != NULL)
7302     comp_unit_die->attrs[i++] = *high_pc;
7303   if (ranges != NULL)
7304     comp_unit_die->attrs[i++] = *ranges;
7305   if (comp_dir != NULL)
7306     comp_unit_die->attrs[i++] = *comp_dir;
7307   comp_unit_die->num_attrs += num_extra_attrs;
7308
7309   if (dwarf_die_debug)
7310     {
7311       fprintf_unfiltered (gdb_stdlog,
7312                           "Read die from %s@0x%x of %s:\n",
7313                           get_section_name (section),
7314                           (unsigned) (begin_info_ptr - section->buffer),
7315                           bfd_get_filename (abfd));
7316       dump_die (comp_unit_die, dwarf_die_debug);
7317     }
7318
7319   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7320      TUs by skipping the stub and going directly to the entry in the DWO file.
7321      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7322      to get it via circuitous means.  Blech.  */
7323   if (comp_dir != NULL)
7324     result_reader->comp_dir = DW_STRING (comp_dir);
7325
7326   /* Skip dummy compilation units.  */
7327   if (info_ptr >= begin_info_ptr + dwo_unit->length
7328       || peek_abbrev_code (abfd, info_ptr) == 0)
7329     return 0;
7330
7331   *result_info_ptr = info_ptr;
7332   return 1;
7333 }
7334
7335 /* Subroutine of init_cutu_and_read_dies to simplify it.
7336    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7337    Returns NULL if the specified DWO unit cannot be found.  */
7338
7339 static struct dwo_unit *
7340 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7341                  struct die_info *comp_unit_die)
7342 {
7343   struct dwarf2_cu *cu = this_cu->cu;
7344   ULONGEST signature;
7345   struct dwo_unit *dwo_unit;
7346   const char *comp_dir, *dwo_name;
7347
7348   gdb_assert (cu != NULL);
7349
7350   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7351   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7352   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7353
7354   if (this_cu->is_debug_types)
7355     {
7356       struct signatured_type *sig_type;
7357
7358       /* Since this_cu is the first member of struct signatured_type,
7359          we can go from a pointer to one to a pointer to the other.  */
7360       sig_type = (struct signatured_type *) this_cu;
7361       signature = sig_type->signature;
7362       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7363     }
7364   else
7365     {
7366       struct attribute *attr;
7367
7368       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7369       if (! attr)
7370         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7371                  " [in module %s]"),
7372                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7373       signature = DW_UNSND (attr);
7374       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7375                                        signature);
7376     }
7377
7378   return dwo_unit;
7379 }
7380
7381 /* Subroutine of init_cutu_and_read_dies to simplify it.
7382    See it for a description of the parameters.
7383    Read a TU directly from a DWO file, bypassing the stub.  */
7384
7385 static void
7386 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7387                            int use_existing_cu, int keep,
7388                            die_reader_func_ftype *die_reader_func,
7389                            void *data)
7390 {
7391   std::unique_ptr<dwarf2_cu> new_cu;
7392   struct signatured_type *sig_type;
7393   struct die_reader_specs reader;
7394   const gdb_byte *info_ptr;
7395   struct die_info *comp_unit_die;
7396   int has_children;
7397   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7398
7399   /* Verify we can do the following downcast, and that we have the
7400      data we need.  */
7401   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7402   sig_type = (struct signatured_type *) this_cu;
7403   gdb_assert (sig_type->dwo_unit != NULL);
7404
7405   if (use_existing_cu && this_cu->cu != NULL)
7406     {
7407       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7408       /* There's no need to do the rereading_dwo_cu handling that
7409          init_cutu_and_read_dies does since we don't read the stub.  */
7410     }
7411   else
7412     {
7413       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7414       gdb_assert (this_cu->cu == NULL);
7415       new_cu.reset (new dwarf2_cu (this_cu));
7416     }
7417
7418   /* A future optimization, if needed, would be to use an existing
7419      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7420      could share abbrev tables.  */
7421
7422   /* The abbreviation table used by READER, this must live at least as long as
7423      READER.  */
7424   abbrev_table_up dwo_abbrev_table;
7425
7426   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7427                               NULL /* stub_comp_unit_die */,
7428                               sig_type->dwo_unit->dwo_file->comp_dir,
7429                               &reader, &info_ptr,
7430                               &comp_unit_die, &has_children,
7431                               &dwo_abbrev_table) == 0)
7432     {
7433       /* Dummy die.  */
7434       return;
7435     }
7436
7437   /* All the "real" work is done here.  */
7438   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7439
7440   /* This duplicates the code in init_cutu_and_read_dies,
7441      but the alternative is making the latter more complex.
7442      This function is only for the special case of using DWO files directly:
7443      no point in overly complicating the general case just to handle this.  */
7444   if (new_cu != NULL && keep)
7445     {
7446       /* Link this CU into read_in_chain.  */
7447       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7448       dwarf2_per_objfile->read_in_chain = this_cu;
7449       /* The chain owns it now.  */
7450       new_cu.release ();
7451     }
7452 }
7453
7454 /* Initialize a CU (or TU) and read its DIEs.
7455    If the CU defers to a DWO file, read the DWO file as well.
7456
7457    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7458    Otherwise the table specified in the comp unit header is read in and used.
7459    This is an optimization for when we already have the abbrev table.
7460
7461    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7462    Otherwise, a new CU is allocated with xmalloc.
7463
7464    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7465    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7466
7467    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7468    linker) then DIE_READER_FUNC will not get called.  */
7469
7470 static void
7471 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7472                          struct abbrev_table *abbrev_table,
7473                          int use_existing_cu, int keep,
7474                          bool skip_partial,
7475                          die_reader_func_ftype *die_reader_func,
7476                          void *data)
7477 {
7478   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7479   struct objfile *objfile = dwarf2_per_objfile->objfile;
7480   struct dwarf2_section_info *section = this_cu->section;
7481   bfd *abfd = get_section_bfd_owner (section);
7482   struct dwarf2_cu *cu;
7483   const gdb_byte *begin_info_ptr, *info_ptr;
7484   struct die_reader_specs reader;
7485   struct die_info *comp_unit_die;
7486   int has_children;
7487   struct attribute *attr;
7488   struct signatured_type *sig_type = NULL;
7489   struct dwarf2_section_info *abbrev_section;
7490   /* Non-zero if CU currently points to a DWO file and we need to
7491      reread it.  When this happens we need to reread the skeleton die
7492      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7493   int rereading_dwo_cu = 0;
7494
7495   if (dwarf_die_debug)
7496     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7497                         this_cu->is_debug_types ? "type" : "comp",
7498                         sect_offset_str (this_cu->sect_off));
7499
7500   if (use_existing_cu)
7501     gdb_assert (keep);
7502
7503   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7504      file (instead of going through the stub), short-circuit all of this.  */
7505   if (this_cu->reading_dwo_directly)
7506     {
7507       /* Narrow down the scope of possibilities to have to understand.  */
7508       gdb_assert (this_cu->is_debug_types);
7509       gdb_assert (abbrev_table == NULL);
7510       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7511                                  die_reader_func, data);
7512       return;
7513     }
7514
7515   /* This is cheap if the section is already read in.  */
7516   dwarf2_read_section (objfile, section);
7517
7518   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7519
7520   abbrev_section = get_abbrev_section_for_cu (this_cu);
7521
7522   std::unique_ptr<dwarf2_cu> new_cu;
7523   if (use_existing_cu && this_cu->cu != NULL)
7524     {
7525       cu = this_cu->cu;
7526       /* If this CU is from a DWO file we need to start over, we need to
7527          refetch the attributes from the skeleton CU.
7528          This could be optimized by retrieving those attributes from when we
7529          were here the first time: the previous comp_unit_die was stored in
7530          comp_unit_obstack.  But there's no data yet that we need this
7531          optimization.  */
7532       if (cu->dwo_unit != NULL)
7533         rereading_dwo_cu = 1;
7534     }
7535   else
7536     {
7537       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7538       gdb_assert (this_cu->cu == NULL);
7539       new_cu.reset (new dwarf2_cu (this_cu));
7540       cu = new_cu.get ();
7541     }
7542
7543   /* Get the header.  */
7544   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7545     {
7546       /* We already have the header, there's no need to read it in again.  */
7547       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7548     }
7549   else
7550     {
7551       if (this_cu->is_debug_types)
7552         {
7553           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7554                                                     &cu->header, section,
7555                                                     abbrev_section, info_ptr,
7556                                                     rcuh_kind::TYPE);
7557
7558           /* Since per_cu is the first member of struct signatured_type,
7559              we can go from a pointer to one to a pointer to the other.  */
7560           sig_type = (struct signatured_type *) this_cu;
7561           gdb_assert (sig_type->signature == cu->header.signature);
7562           gdb_assert (sig_type->type_offset_in_tu
7563                       == cu->header.type_cu_offset_in_tu);
7564           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7565
7566           /* LENGTH has not been set yet for type units if we're
7567              using .gdb_index.  */
7568           this_cu->length = get_cu_length (&cu->header);
7569
7570           /* Establish the type offset that can be used to lookup the type.  */
7571           sig_type->type_offset_in_section =
7572             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7573
7574           this_cu->dwarf_version = cu->header.version;
7575         }
7576       else
7577         {
7578           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7579                                                     &cu->header, section,
7580                                                     abbrev_section,
7581                                                     info_ptr,
7582                                                     rcuh_kind::COMPILE);
7583
7584           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7585           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7586           this_cu->dwarf_version = cu->header.version;
7587         }
7588     }
7589
7590   /* Skip dummy compilation units.  */
7591   if (info_ptr >= begin_info_ptr + this_cu->length
7592       || peek_abbrev_code (abfd, info_ptr) == 0)
7593     return;
7594
7595   /* If we don't have them yet, read the abbrevs for this compilation unit.
7596      And if we need to read them now, make sure they're freed when we're
7597      done (own the table through ABBREV_TABLE_HOLDER).  */
7598   abbrev_table_up abbrev_table_holder;
7599   if (abbrev_table != NULL)
7600     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7601   else
7602     {
7603       abbrev_table_holder
7604         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7605                                    cu->header.abbrev_sect_off);
7606       abbrev_table = abbrev_table_holder.get ();
7607     }
7608
7609   /* Read the top level CU/TU die.  */
7610   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7611   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7612
7613   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7614     return;
7615
7616   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7617      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7618      table from the DWO file and pass the ownership over to us.  It will be
7619      referenced from READER, so we must make sure to free it after we're done
7620      with READER.
7621
7622      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7623      DWO CU, that this test will fail (the attribute will not be present).  */
7624   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7625   abbrev_table_up dwo_abbrev_table;
7626   if (attr)
7627     {
7628       struct dwo_unit *dwo_unit;
7629       struct die_info *dwo_comp_unit_die;
7630
7631       if (has_children)
7632         {
7633           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7634                        " has children (offset %s) [in module %s]"),
7635                      sect_offset_str (this_cu->sect_off),
7636                      bfd_get_filename (abfd));
7637         }
7638       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7639       if (dwo_unit != NULL)
7640         {
7641           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7642                                       comp_unit_die, NULL,
7643                                       &reader, &info_ptr,
7644                                       &dwo_comp_unit_die, &has_children,
7645                                       &dwo_abbrev_table) == 0)
7646             {
7647               /* Dummy die.  */
7648               return;
7649             }
7650           comp_unit_die = dwo_comp_unit_die;
7651         }
7652       else
7653         {
7654           /* Yikes, we couldn't find the rest of the DIE, we only have
7655              the stub.  A complaint has already been logged.  There's
7656              not much more we can do except pass on the stub DIE to
7657              die_reader_func.  We don't want to throw an error on bad
7658              debug info.  */
7659         }
7660     }
7661
7662   /* All of the above is setup for this call.  Yikes.  */
7663   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7664
7665   /* Done, clean up.  */
7666   if (new_cu != NULL && keep)
7667     {
7668       /* Link this CU into read_in_chain.  */
7669       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7670       dwarf2_per_objfile->read_in_chain = this_cu;
7671       /* The chain owns it now.  */
7672       new_cu.release ();
7673     }
7674 }
7675
7676 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7677    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7678    to have already done the lookup to find the DWO file).
7679
7680    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7681    THIS_CU->is_debug_types, but nothing else.
7682
7683    We fill in THIS_CU->length.
7684
7685    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7686    linker) then DIE_READER_FUNC will not get called.
7687
7688    THIS_CU->cu is always freed when done.
7689    This is done in order to not leave THIS_CU->cu in a state where we have
7690    to care whether it refers to the "main" CU or the DWO CU.  */
7691
7692 static void
7693 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7694                                    struct dwo_file *dwo_file,
7695                                    die_reader_func_ftype *die_reader_func,
7696                                    void *data)
7697 {
7698   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7699   struct objfile *objfile = dwarf2_per_objfile->objfile;
7700   struct dwarf2_section_info *section = this_cu->section;
7701   bfd *abfd = get_section_bfd_owner (section);
7702   struct dwarf2_section_info *abbrev_section;
7703   const gdb_byte *begin_info_ptr, *info_ptr;
7704   struct die_reader_specs reader;
7705   struct die_info *comp_unit_die;
7706   int has_children;
7707
7708   if (dwarf_die_debug)
7709     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7710                         this_cu->is_debug_types ? "type" : "comp",
7711                         sect_offset_str (this_cu->sect_off));
7712
7713   gdb_assert (this_cu->cu == NULL);
7714
7715   abbrev_section = (dwo_file != NULL
7716                     ? &dwo_file->sections.abbrev
7717                     : get_abbrev_section_for_cu (this_cu));
7718
7719   /* This is cheap if the section is already read in.  */
7720   dwarf2_read_section (objfile, section);
7721
7722   struct dwarf2_cu cu (this_cu);
7723
7724   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7725   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7726                                             &cu.header, section,
7727                                             abbrev_section, info_ptr,
7728                                             (this_cu->is_debug_types
7729                                              ? rcuh_kind::TYPE
7730                                              : rcuh_kind::COMPILE));
7731
7732   this_cu->length = get_cu_length (&cu.header);
7733
7734   /* Skip dummy compilation units.  */
7735   if (info_ptr >= begin_info_ptr + this_cu->length
7736       || peek_abbrev_code (abfd, info_ptr) == 0)
7737     return;
7738
7739   abbrev_table_up abbrev_table
7740     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7741                                cu.header.abbrev_sect_off);
7742
7743   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7744   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7745
7746   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7747 }
7748
7749 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7750    does not lookup the specified DWO file.
7751    This cannot be used to read DWO files.
7752
7753    THIS_CU->cu is always freed when done.
7754    This is done in order to not leave THIS_CU->cu in a state where we have
7755    to care whether it refers to the "main" CU or the DWO CU.
7756    We can revisit this if the data shows there's a performance issue.  */
7757
7758 static void
7759 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7760                                 die_reader_func_ftype *die_reader_func,
7761                                 void *data)
7762 {
7763   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7764 }
7765 \f
7766 /* Type Unit Groups.
7767
7768    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7769    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7770    so that all types coming from the same compilation (.o file) are grouped
7771    together.  A future step could be to put the types in the same symtab as
7772    the CU the types ultimately came from.  */
7773
7774 static hashval_t
7775 hash_type_unit_group (const void *item)
7776 {
7777   const struct type_unit_group *tu_group
7778     = (const struct type_unit_group *) item;
7779
7780   return hash_stmt_list_entry (&tu_group->hash);
7781 }
7782
7783 static int
7784 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7785 {
7786   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7787   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7788
7789   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7790 }
7791
7792 /* Allocate a hash table for type unit groups.  */
7793
7794 static htab_t
7795 allocate_type_unit_groups_table (struct objfile *objfile)
7796 {
7797   return htab_create_alloc_ex (3,
7798                                hash_type_unit_group,
7799                                eq_type_unit_group,
7800                                NULL,
7801                                &objfile->objfile_obstack,
7802                                hashtab_obstack_allocate,
7803                                dummy_obstack_deallocate);
7804 }
7805
7806 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7807    partial symtabs.  We combine several TUs per psymtab to not let the size
7808    of any one psymtab grow too big.  */
7809 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7810 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7811
7812 /* Helper routine for get_type_unit_group.
7813    Create the type_unit_group object used to hold one or more TUs.  */
7814
7815 static struct type_unit_group *
7816 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7817 {
7818   struct dwarf2_per_objfile *dwarf2_per_objfile
7819     = cu->per_cu->dwarf2_per_objfile;
7820   struct objfile *objfile = dwarf2_per_objfile->objfile;
7821   struct dwarf2_per_cu_data *per_cu;
7822   struct type_unit_group *tu_group;
7823
7824   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7825                              struct type_unit_group);
7826   per_cu = &tu_group->per_cu;
7827   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7828
7829   if (dwarf2_per_objfile->using_index)
7830     {
7831       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7832                                         struct dwarf2_per_cu_quick_data);
7833     }
7834   else
7835     {
7836       unsigned int line_offset = to_underlying (line_offset_struct);
7837       struct partial_symtab *pst;
7838       std::string name;
7839
7840       /* Give the symtab a useful name for debug purposes.  */
7841       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7842         name = string_printf ("<type_units_%d>",
7843                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7844       else
7845         name = string_printf ("<type_units_at_0x%x>", line_offset);
7846
7847       pst = create_partial_symtab (per_cu, name.c_str ());
7848       pst->anonymous = 1;
7849     }
7850
7851   tu_group->hash.dwo_unit = cu->dwo_unit;
7852   tu_group->hash.line_sect_off = line_offset_struct;
7853
7854   return tu_group;
7855 }
7856
7857 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7858    STMT_LIST is a DW_AT_stmt_list attribute.  */
7859
7860 static struct type_unit_group *
7861 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7862 {
7863   struct dwarf2_per_objfile *dwarf2_per_objfile
7864     = cu->per_cu->dwarf2_per_objfile;
7865   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7866   struct type_unit_group *tu_group;
7867   void **slot;
7868   unsigned int line_offset;
7869   struct type_unit_group type_unit_group_for_lookup;
7870
7871   if (dwarf2_per_objfile->type_unit_groups == NULL)
7872     {
7873       dwarf2_per_objfile->type_unit_groups =
7874         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7875     }
7876
7877   /* Do we need to create a new group, or can we use an existing one?  */
7878
7879   if (stmt_list)
7880     {
7881       line_offset = DW_UNSND (stmt_list);
7882       ++tu_stats->nr_symtab_sharers;
7883     }
7884   else
7885     {
7886       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7887          We can do various things here like create one group per TU or
7888          spread them over multiple groups to split up the expansion work.
7889          To avoid worst case scenarios (too many groups or too large groups)
7890          we, umm, group them in bunches.  */
7891       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7892                      | (tu_stats->nr_stmt_less_type_units
7893                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7894       ++tu_stats->nr_stmt_less_type_units;
7895     }
7896
7897   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7898   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7899   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7900                          &type_unit_group_for_lookup, INSERT);
7901   if (*slot != NULL)
7902     {
7903       tu_group = (struct type_unit_group *) *slot;
7904       gdb_assert (tu_group != NULL);
7905     }
7906   else
7907     {
7908       sect_offset line_offset_struct = (sect_offset) line_offset;
7909       tu_group = create_type_unit_group (cu, line_offset_struct);
7910       *slot = tu_group;
7911       ++tu_stats->nr_symtabs;
7912     }
7913
7914   return tu_group;
7915 }
7916 \f
7917 /* Partial symbol tables.  */
7918
7919 /* Create a psymtab named NAME and assign it to PER_CU.
7920
7921    The caller must fill in the following details:
7922    dirname, textlow, texthigh.  */
7923
7924 static struct partial_symtab *
7925 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7926 {
7927   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7928   struct partial_symtab *pst;
7929
7930   pst = start_psymtab_common (objfile, name, 0);
7931
7932   pst->psymtabs_addrmap_supported = 1;
7933
7934   /* This is the glue that links PST into GDB's symbol API.  */
7935   pst->read_symtab_private = per_cu;
7936   pst->read_symtab = dwarf2_read_symtab;
7937   per_cu->v.psymtab = pst;
7938
7939   return pst;
7940 }
7941
7942 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7943    type.  */
7944
7945 struct process_psymtab_comp_unit_data
7946 {
7947   /* True if we are reading a DW_TAG_partial_unit.  */
7948
7949   int want_partial_unit;
7950
7951   /* The "pretend" language that is used if the CU doesn't declare a
7952      language.  */
7953
7954   enum language pretend_language;
7955 };
7956
7957 /* die_reader_func for process_psymtab_comp_unit.  */
7958
7959 static void
7960 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7961                                   const gdb_byte *info_ptr,
7962                                   struct die_info *comp_unit_die,
7963                                   int has_children,
7964                                   void *data)
7965 {
7966   struct dwarf2_cu *cu = reader->cu;
7967   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7968   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7969   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7970   CORE_ADDR baseaddr;
7971   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7972   struct partial_symtab *pst;
7973   enum pc_bounds_kind cu_bounds_kind;
7974   const char *filename;
7975   struct process_psymtab_comp_unit_data *info
7976     = (struct process_psymtab_comp_unit_data *) data;
7977
7978   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7979     return;
7980
7981   gdb_assert (! per_cu->is_debug_types);
7982
7983   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7984
7985   /* Allocate a new partial symbol table structure.  */
7986   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7987   if (filename == NULL)
7988     filename = "";
7989
7990   pst = create_partial_symtab (per_cu, filename);
7991
7992   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7993   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7994
7995   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7996
7997   dwarf2_find_base_address (comp_unit_die, cu);
7998
7999   /* Possibly set the default values of LOWPC and HIGHPC from
8000      `DW_AT_ranges'.  */
8001   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8002                                          &best_highpc, cu, pst);
8003   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8004     {
8005       CORE_ADDR low
8006         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
8007            - baseaddr);
8008       CORE_ADDR high
8009         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
8010            - baseaddr - 1);
8011       /* Store the contiguous range if it is not empty; it can be
8012          empty for CUs with no code.  */
8013       addrmap_set_empty (objfile->psymtabs_addrmap, low, high, pst);
8014     }
8015
8016   /* Check if comp unit has_children.
8017      If so, read the rest of the partial symbols from this comp unit.
8018      If not, there's no more debug_info for this comp unit.  */
8019   if (has_children)
8020     {
8021       struct partial_die_info *first_die;
8022       CORE_ADDR lowpc, highpc;
8023
8024       lowpc = ((CORE_ADDR) -1);
8025       highpc = ((CORE_ADDR) 0);
8026
8027       first_die = load_partial_dies (reader, info_ptr, 1);
8028
8029       scan_partial_symbols (first_die, &lowpc, &highpc,
8030                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8031
8032       /* If we didn't find a lowpc, set it to highpc to avoid
8033          complaints from `maint check'.  */
8034       if (lowpc == ((CORE_ADDR) -1))
8035         lowpc = highpc;
8036
8037       /* If the compilation unit didn't have an explicit address range,
8038          then use the information extracted from its child dies.  */
8039       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8040         {
8041           best_lowpc = lowpc;
8042           best_highpc = highpc;
8043         }
8044     }
8045   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
8046                                                  best_lowpc + baseaddr)
8047                      - baseaddr);
8048   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
8049                                                   best_highpc + baseaddr)
8050                       - baseaddr);
8051
8052   end_psymtab_common (objfile, pst);
8053
8054   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8055     {
8056       int i;
8057       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8058       struct dwarf2_per_cu_data *iter;
8059
8060       /* Fill in 'dependencies' here; we fill in 'users' in a
8061          post-pass.  */
8062       pst->number_of_dependencies = len;
8063       pst->dependencies =
8064         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8065       for (i = 0;
8066            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8067                         i, iter);
8068            ++i)
8069         pst->dependencies[i] = iter->v.psymtab;
8070
8071       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8072     }
8073
8074   /* Get the list of files included in the current compilation unit,
8075      and build a psymtab for each of them.  */
8076   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8077
8078   if (dwarf_read_debug)
8079     fprintf_unfiltered (gdb_stdlog,
8080                         "Psymtab for %s unit @%s: %s - %s"
8081                         ", %d global, %d static syms\n",
8082                         per_cu->is_debug_types ? "type" : "comp",
8083                         sect_offset_str (per_cu->sect_off),
8084                         paddress (gdbarch, pst->text_low (objfile)),
8085                         paddress (gdbarch, pst->text_high (objfile)),
8086                         pst->n_global_syms, pst->n_static_syms);
8087 }
8088
8089 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8090    Process compilation unit THIS_CU for a psymtab.  */
8091
8092 static void
8093 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8094                            int want_partial_unit,
8095                            enum language pretend_language)
8096 {
8097   /* If this compilation unit was already read in, free the
8098      cached copy in order to read it in again.  This is
8099      necessary because we skipped some symbols when we first
8100      read in the compilation unit (see load_partial_dies).
8101      This problem could be avoided, but the benefit is unclear.  */
8102   if (this_cu->cu != NULL)
8103     free_one_cached_comp_unit (this_cu);
8104
8105   if (this_cu->is_debug_types)
8106     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8107                              build_type_psymtabs_reader, NULL);
8108   else
8109     {
8110       process_psymtab_comp_unit_data info;
8111       info.want_partial_unit = want_partial_unit;
8112       info.pretend_language = pretend_language;
8113       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8114                                process_psymtab_comp_unit_reader, &info);
8115     }
8116
8117   /* Age out any secondary CUs.  */
8118   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8119 }
8120
8121 /* Reader function for build_type_psymtabs.  */
8122
8123 static void
8124 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8125                             const gdb_byte *info_ptr,
8126                             struct die_info *type_unit_die,
8127                             int has_children,
8128                             void *data)
8129 {
8130   struct dwarf2_per_objfile *dwarf2_per_objfile
8131     = reader->cu->per_cu->dwarf2_per_objfile;
8132   struct objfile *objfile = dwarf2_per_objfile->objfile;
8133   struct dwarf2_cu *cu = reader->cu;
8134   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8135   struct signatured_type *sig_type;
8136   struct type_unit_group *tu_group;
8137   struct attribute *attr;
8138   struct partial_die_info *first_die;
8139   CORE_ADDR lowpc, highpc;
8140   struct partial_symtab *pst;
8141
8142   gdb_assert (data == NULL);
8143   gdb_assert (per_cu->is_debug_types);
8144   sig_type = (struct signatured_type *) per_cu;
8145
8146   if (! has_children)
8147     return;
8148
8149   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8150   tu_group = get_type_unit_group (cu, attr);
8151
8152   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8153
8154   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8155   pst = create_partial_symtab (per_cu, "");
8156   pst->anonymous = 1;
8157
8158   first_die = load_partial_dies (reader, info_ptr, 1);
8159
8160   lowpc = (CORE_ADDR) -1;
8161   highpc = (CORE_ADDR) 0;
8162   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8163
8164   end_psymtab_common (objfile, pst);
8165 }
8166
8167 /* Struct used to sort TUs by their abbreviation table offset.  */
8168
8169 struct tu_abbrev_offset
8170 {
8171   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8172   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8173   {}
8174
8175   signatured_type *sig_type;
8176   sect_offset abbrev_offset;
8177 };
8178
8179 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8180
8181 static bool
8182 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8183                           const struct tu_abbrev_offset &b)
8184 {
8185   return a.abbrev_offset < b.abbrev_offset;
8186 }
8187
8188 /* Efficiently read all the type units.
8189    This does the bulk of the work for build_type_psymtabs.
8190
8191    The efficiency is because we sort TUs by the abbrev table they use and
8192    only read each abbrev table once.  In one program there are 200K TUs
8193    sharing 8K abbrev tables.
8194
8195    The main purpose of this function is to support building the
8196    dwarf2_per_objfile->type_unit_groups table.
8197    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8198    can collapse the search space by grouping them by stmt_list.
8199    The savings can be significant, in the same program from above the 200K TUs
8200    share 8K stmt_list tables.
8201
8202    FUNC is expected to call get_type_unit_group, which will create the
8203    struct type_unit_group if necessary and add it to
8204    dwarf2_per_objfile->type_unit_groups.  */
8205
8206 static void
8207 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8208 {
8209   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8210   abbrev_table_up abbrev_table;
8211   sect_offset abbrev_offset;
8212
8213   /* It's up to the caller to not call us multiple times.  */
8214   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8215
8216   if (dwarf2_per_objfile->all_type_units.empty ())
8217     return;
8218
8219   /* TUs typically share abbrev tables, and there can be way more TUs than
8220      abbrev tables.  Sort by abbrev table to reduce the number of times we
8221      read each abbrev table in.
8222      Alternatives are to punt or to maintain a cache of abbrev tables.
8223      This is simpler and efficient enough for now.
8224
8225      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8226      symtab to use).  Typically TUs with the same abbrev offset have the same
8227      stmt_list value too so in practice this should work well.
8228
8229      The basic algorithm here is:
8230
8231       sort TUs by abbrev table
8232       for each TU with same abbrev table:
8233         read abbrev table if first user
8234         read TU top level DIE
8235           [IWBN if DWO skeletons had DW_AT_stmt_list]
8236         call FUNC  */
8237
8238   if (dwarf_read_debug)
8239     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8240
8241   /* Sort in a separate table to maintain the order of all_type_units
8242      for .gdb_index: TU indices directly index all_type_units.  */
8243   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8244   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8245
8246   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8247     sorted_by_abbrev.emplace_back
8248       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8249                                      sig_type->per_cu.section,
8250                                      sig_type->per_cu.sect_off));
8251
8252   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8253              sort_tu_by_abbrev_offset);
8254
8255   abbrev_offset = (sect_offset) ~(unsigned) 0;
8256
8257   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8258     {
8259       /* Switch to the next abbrev table if necessary.  */
8260       if (abbrev_table == NULL
8261           || tu.abbrev_offset != abbrev_offset)
8262         {
8263           abbrev_offset = tu.abbrev_offset;
8264           abbrev_table =
8265             abbrev_table_read_table (dwarf2_per_objfile,
8266                                      &dwarf2_per_objfile->abbrev,
8267                                      abbrev_offset);
8268           ++tu_stats->nr_uniq_abbrev_tables;
8269         }
8270
8271       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8272                                0, 0, false, build_type_psymtabs_reader, NULL);
8273     }
8274 }
8275
8276 /* Print collected type unit statistics.  */
8277
8278 static void
8279 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8280 {
8281   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8282
8283   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8284   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8285                       dwarf2_per_objfile->all_type_units.size ());
8286   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8287                       tu_stats->nr_uniq_abbrev_tables);
8288   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8289                       tu_stats->nr_symtabs);
8290   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8291                       tu_stats->nr_symtab_sharers);
8292   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8293                       tu_stats->nr_stmt_less_type_units);
8294   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8295                       tu_stats->nr_all_type_units_reallocs);
8296 }
8297
8298 /* Traversal function for build_type_psymtabs.  */
8299
8300 static int
8301 build_type_psymtab_dependencies (void **slot, void *info)
8302 {
8303   struct dwarf2_per_objfile *dwarf2_per_objfile
8304     = (struct dwarf2_per_objfile *) info;
8305   struct objfile *objfile = dwarf2_per_objfile->objfile;
8306   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8307   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8308   struct partial_symtab *pst = per_cu->v.psymtab;
8309   int len = VEC_length (sig_type_ptr, tu_group->tus);
8310   struct signatured_type *iter;
8311   int i;
8312
8313   gdb_assert (len > 0);
8314   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8315
8316   pst->number_of_dependencies = len;
8317   pst->dependencies =
8318     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8319   for (i = 0;
8320        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8321        ++i)
8322     {
8323       gdb_assert (iter->per_cu.is_debug_types);
8324       pst->dependencies[i] = iter->per_cu.v.psymtab;
8325       iter->type_unit_group = tu_group;
8326     }
8327
8328   VEC_free (sig_type_ptr, tu_group->tus);
8329
8330   return 1;
8331 }
8332
8333 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8334    Build partial symbol tables for the .debug_types comp-units.  */
8335
8336 static void
8337 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8338 {
8339   if (! create_all_type_units (dwarf2_per_objfile))
8340     return;
8341
8342   build_type_psymtabs_1 (dwarf2_per_objfile);
8343 }
8344
8345 /* Traversal function for process_skeletonless_type_unit.
8346    Read a TU in a DWO file and build partial symbols for it.  */
8347
8348 static int
8349 process_skeletonless_type_unit (void **slot, void *info)
8350 {
8351   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8352   struct dwarf2_per_objfile *dwarf2_per_objfile
8353     = (struct dwarf2_per_objfile *) info;
8354   struct signatured_type find_entry, *entry;
8355
8356   /* If this TU doesn't exist in the global table, add it and read it in.  */
8357
8358   if (dwarf2_per_objfile->signatured_types == NULL)
8359     {
8360       dwarf2_per_objfile->signatured_types
8361         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8362     }
8363
8364   find_entry.signature = dwo_unit->signature;
8365   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8366                          INSERT);
8367   /* If we've already seen this type there's nothing to do.  What's happening
8368      is we're doing our own version of comdat-folding here.  */
8369   if (*slot != NULL)
8370     return 1;
8371
8372   /* This does the job that create_all_type_units would have done for
8373      this TU.  */
8374   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8375   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8376   *slot = entry;
8377
8378   /* This does the job that build_type_psymtabs_1 would have done.  */
8379   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8380                            build_type_psymtabs_reader, NULL);
8381
8382   return 1;
8383 }
8384
8385 /* Traversal function for process_skeletonless_type_units.  */
8386
8387 static int
8388 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8389 {
8390   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8391
8392   if (dwo_file->tus != NULL)
8393     {
8394       htab_traverse_noresize (dwo_file->tus,
8395                               process_skeletonless_type_unit, info);
8396     }
8397
8398   return 1;
8399 }
8400
8401 /* Scan all TUs of DWO files, verifying we've processed them.
8402    This is needed in case a TU was emitted without its skeleton.
8403    Note: This can't be done until we know what all the DWO files are.  */
8404
8405 static void
8406 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8407 {
8408   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8409   if (get_dwp_file (dwarf2_per_objfile) == NULL
8410       && dwarf2_per_objfile->dwo_files != NULL)
8411     {
8412       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8413                               process_dwo_file_for_skeletonless_type_units,
8414                               dwarf2_per_objfile);
8415     }
8416 }
8417
8418 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8419
8420 static void
8421 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8422 {
8423   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8424     {
8425       struct partial_symtab *pst = per_cu->v.psymtab;
8426
8427       if (pst == NULL)
8428         continue;
8429
8430       for (int j = 0; j < pst->number_of_dependencies; ++j)
8431         {
8432           /* Set the 'user' field only if it is not already set.  */
8433           if (pst->dependencies[j]->user == NULL)
8434             pst->dependencies[j]->user = pst;
8435         }
8436     }
8437 }
8438
8439 /* Build the partial symbol table by doing a quick pass through the
8440    .debug_info and .debug_abbrev sections.  */
8441
8442 static void
8443 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8444 {
8445   struct objfile *objfile = dwarf2_per_objfile->objfile;
8446
8447   if (dwarf_read_debug)
8448     {
8449       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8450                           objfile_name (objfile));
8451     }
8452
8453   dwarf2_per_objfile->reading_partial_symbols = 1;
8454
8455   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8456
8457   /* Any cached compilation units will be linked by the per-objfile
8458      read_in_chain.  Make sure to free them when we're done.  */
8459   free_cached_comp_units freer (dwarf2_per_objfile);
8460
8461   build_type_psymtabs (dwarf2_per_objfile);
8462
8463   create_all_comp_units (dwarf2_per_objfile);
8464
8465   /* Create a temporary address map on a temporary obstack.  We later
8466      copy this to the final obstack.  */
8467   auto_obstack temp_obstack;
8468
8469   scoped_restore save_psymtabs_addrmap
8470     = make_scoped_restore (&objfile->psymtabs_addrmap,
8471                            addrmap_create_mutable (&temp_obstack));
8472
8473   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8474     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8475
8476   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8477   process_skeletonless_type_units (dwarf2_per_objfile);
8478
8479   /* Now that all TUs have been processed we can fill in the dependencies.  */
8480   if (dwarf2_per_objfile->type_unit_groups != NULL)
8481     {
8482       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8483                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8484     }
8485
8486   if (dwarf_read_debug)
8487     print_tu_stats (dwarf2_per_objfile);
8488
8489   set_partial_user (dwarf2_per_objfile);
8490
8491   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8492                                                     &objfile->objfile_obstack);
8493   /* At this point we want to keep the address map.  */
8494   save_psymtabs_addrmap.release ();
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, false,
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 {
8537   const gdb_byte *info_ptr;
8538   struct objfile *objfile = dwarf2_per_objfile->objfile;
8539
8540   if (dwarf_read_debug)
8541     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8542                         get_section_name (section),
8543                         get_section_file_name (section));
8544
8545   dwarf2_read_section (objfile, section);
8546
8547   info_ptr = section->buffer;
8548
8549   while (info_ptr < section->buffer + section->size)
8550     {
8551       struct dwarf2_per_cu_data *this_cu;
8552
8553       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8554
8555       comp_unit_head cu_header;
8556       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8557                                      abbrev_section, info_ptr,
8558                                      rcuh_kind::COMPILE);
8559
8560       /* Save the compilation unit for later lookup.  */
8561       if (cu_header.unit_type != DW_UT_type)
8562         {
8563           this_cu = XOBNEW (&objfile->objfile_obstack,
8564                             struct dwarf2_per_cu_data);
8565           memset (this_cu, 0, sizeof (*this_cu));
8566         }
8567       else
8568         {
8569           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8570                                   struct signatured_type);
8571           memset (sig_type, 0, sizeof (*sig_type));
8572           sig_type->signature = cu_header.signature;
8573           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8574           this_cu = &sig_type->per_cu;
8575         }
8576       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8577       this_cu->sect_off = sect_off;
8578       this_cu->length = cu_header.length + cu_header.initial_length_size;
8579       this_cu->is_dwz = is_dwz;
8580       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8581       this_cu->section = section;
8582
8583       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8584
8585       info_ptr = info_ptr + this_cu->length;
8586     }
8587 }
8588
8589 /* Create a list of all compilation units in OBJFILE.
8590    This is only done for -readnow and building partial symtabs.  */
8591
8592 static void
8593 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8594 {
8595   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8596   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8597                                 &dwarf2_per_objfile->abbrev, 0);
8598
8599   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8600   if (dwz != NULL)
8601     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8602                                   1);
8603 }
8604
8605 /* Process all loaded DIEs for compilation unit CU, starting at
8606    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8607    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8608    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8609    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8610
8611 static void
8612 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8613                       CORE_ADDR *highpc, int set_addrmap,
8614                       struct dwarf2_cu *cu)
8615 {
8616   struct partial_die_info *pdi;
8617
8618   /* Now, march along the PDI's, descending into ones which have
8619      interesting children but skipping the children of the other ones,
8620      until we reach the end of the compilation unit.  */
8621
8622   pdi = first_die;
8623
8624   while (pdi != NULL)
8625     {
8626       pdi->fixup (cu);
8627
8628       /* Anonymous namespaces or modules have no name but have interesting
8629          children, so we need to look at them.  Ditto for anonymous
8630          enums.  */
8631
8632       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8633           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8634           || pdi->tag == DW_TAG_imported_unit
8635           || pdi->tag == DW_TAG_inlined_subroutine)
8636         {
8637           switch (pdi->tag)
8638             {
8639             case DW_TAG_subprogram:
8640             case DW_TAG_inlined_subroutine:
8641               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8642               break;
8643             case DW_TAG_constant:
8644             case DW_TAG_variable:
8645             case DW_TAG_typedef:
8646             case DW_TAG_union_type:
8647               if (!pdi->is_declaration)
8648                 {
8649                   add_partial_symbol (pdi, cu);
8650                 }
8651               break;
8652             case DW_TAG_class_type:
8653             case DW_TAG_interface_type:
8654             case DW_TAG_structure_type:
8655               if (!pdi->is_declaration)
8656                 {
8657                   add_partial_symbol (pdi, cu);
8658                 }
8659               if ((cu->language == language_rust
8660                    || cu->language == language_cplus) && pdi->has_children)
8661                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8662                                       set_addrmap, cu);
8663               break;
8664             case DW_TAG_enumeration_type:
8665               if (!pdi->is_declaration)
8666                 add_partial_enumeration (pdi, cu);
8667               break;
8668             case DW_TAG_base_type:
8669             case DW_TAG_subrange_type:
8670               /* File scope base type definitions are added to the partial
8671                  symbol table.  */
8672               add_partial_symbol (pdi, cu);
8673               break;
8674             case DW_TAG_namespace:
8675               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8676               break;
8677             case DW_TAG_module:
8678               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8679               break;
8680             case DW_TAG_imported_unit:
8681               {
8682                 struct dwarf2_per_cu_data *per_cu;
8683
8684                 /* For now we don't handle imported units in type units.  */
8685                 if (cu->per_cu->is_debug_types)
8686                   {
8687                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8688                              " supported in type units [in module %s]"),
8689                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8690                   }
8691
8692                 per_cu = dwarf2_find_containing_comp_unit
8693                            (pdi->d.sect_off, pdi->is_dwz,
8694                             cu->per_cu->dwarf2_per_objfile);
8695
8696                 /* Go read the partial unit, if needed.  */
8697                 if (per_cu->v.psymtab == NULL)
8698                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8699
8700                 VEC_safe_push (dwarf2_per_cu_ptr,
8701                                cu->per_cu->imported_symtabs, per_cu);
8702               }
8703               break;
8704             case DW_TAG_imported_declaration:
8705               add_partial_symbol (pdi, cu);
8706               break;
8707             default:
8708               break;
8709             }
8710         }
8711
8712       /* If the die has a sibling, skip to the sibling.  */
8713
8714       pdi = pdi->die_sibling;
8715     }
8716 }
8717
8718 /* Functions used to compute the fully scoped name of a partial DIE.
8719
8720    Normally, this is simple.  For C++, the parent DIE's fully scoped
8721    name is concatenated with "::" and the partial DIE's name.
8722    Enumerators are an exception; they use the scope of their parent
8723    enumeration type, i.e. the name of the enumeration type is not
8724    prepended to the enumerator.
8725
8726    There are two complexities.  One is DW_AT_specification; in this
8727    case "parent" means the parent of the target of the specification,
8728    instead of the direct parent of the DIE.  The other is compilers
8729    which do not emit DW_TAG_namespace; in this case we try to guess
8730    the fully qualified name of structure types from their members'
8731    linkage names.  This must be done using the DIE's children rather
8732    than the children of any DW_AT_specification target.  We only need
8733    to do this for structures at the top level, i.e. if the target of
8734    any DW_AT_specification (if any; otherwise the DIE itself) does not
8735    have a parent.  */
8736
8737 /* Compute the scope prefix associated with PDI's parent, in
8738    compilation unit CU.  The result will be allocated on CU's
8739    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8740    field.  NULL is returned if no prefix is necessary.  */
8741 static const char *
8742 partial_die_parent_scope (struct partial_die_info *pdi,
8743                           struct dwarf2_cu *cu)
8744 {
8745   const char *grandparent_scope;
8746   struct partial_die_info *parent, *real_pdi;
8747
8748   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8749      then this means the parent of the specification DIE.  */
8750
8751   real_pdi = pdi;
8752   while (real_pdi->has_specification)
8753     real_pdi = find_partial_die (real_pdi->spec_offset,
8754                                  real_pdi->spec_is_dwz, cu);
8755
8756   parent = real_pdi->die_parent;
8757   if (parent == NULL)
8758     return NULL;
8759
8760   if (parent->scope_set)
8761     return parent->scope;
8762
8763   parent->fixup (cu);
8764
8765   grandparent_scope = partial_die_parent_scope (parent, cu);
8766
8767   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8768      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8769      Work around this problem here.  */
8770   if (cu->language == language_cplus
8771       && parent->tag == DW_TAG_namespace
8772       && strcmp (parent->name, "::") == 0
8773       && grandparent_scope == NULL)
8774     {
8775       parent->scope = NULL;
8776       parent->scope_set = 1;
8777       return NULL;
8778     }
8779
8780   if (pdi->tag == DW_TAG_enumerator)
8781     /* Enumerators should not get the name of the enumeration as a prefix.  */
8782     parent->scope = grandparent_scope;
8783   else if (parent->tag == DW_TAG_namespace
8784       || parent->tag == DW_TAG_module
8785       || parent->tag == DW_TAG_structure_type
8786       || parent->tag == DW_TAG_class_type
8787       || parent->tag == DW_TAG_interface_type
8788       || parent->tag == DW_TAG_union_type
8789       || parent->tag == DW_TAG_enumeration_type)
8790     {
8791       if (grandparent_scope == NULL)
8792         parent->scope = parent->name;
8793       else
8794         parent->scope = typename_concat (&cu->comp_unit_obstack,
8795                                          grandparent_scope,
8796                                          parent->name, 0, cu);
8797     }
8798   else
8799     {
8800       /* FIXME drow/2004-04-01: What should we be doing with
8801          function-local names?  For partial symbols, we should probably be
8802          ignoring them.  */
8803       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8804                  parent->tag, sect_offset_str (pdi->sect_off));
8805       parent->scope = grandparent_scope;
8806     }
8807
8808   parent->scope_set = 1;
8809   return parent->scope;
8810 }
8811
8812 /* Return the fully scoped name associated with PDI, from compilation unit
8813    CU.  The result will be allocated with malloc.  */
8814
8815 static char *
8816 partial_die_full_name (struct partial_die_info *pdi,
8817                        struct dwarf2_cu *cu)
8818 {
8819   const char *parent_scope;
8820
8821   /* If this is a template instantiation, we can not work out the
8822      template arguments from partial DIEs.  So, unfortunately, we have
8823      to go through the full DIEs.  At least any work we do building
8824      types here will be reused if full symbols are loaded later.  */
8825   if (pdi->has_template_arguments)
8826     {
8827       pdi->fixup (cu);
8828
8829       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8830         {
8831           struct die_info *die;
8832           struct attribute attr;
8833           struct dwarf2_cu *ref_cu = cu;
8834
8835           /* DW_FORM_ref_addr is using section offset.  */
8836           attr.name = (enum dwarf_attribute) 0;
8837           attr.form = DW_FORM_ref_addr;
8838           attr.u.unsnd = to_underlying (pdi->sect_off);
8839           die = follow_die_ref (NULL, &attr, &ref_cu);
8840
8841           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8842         }
8843     }
8844
8845   parent_scope = partial_die_parent_scope (pdi, cu);
8846   if (parent_scope == NULL)
8847     return NULL;
8848   else
8849     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8850 }
8851
8852 static void
8853 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8854 {
8855   struct dwarf2_per_objfile *dwarf2_per_objfile
8856     = cu->per_cu->dwarf2_per_objfile;
8857   struct objfile *objfile = dwarf2_per_objfile->objfile;
8858   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8859   CORE_ADDR addr = 0;
8860   const char *actual_name = NULL;
8861   CORE_ADDR baseaddr;
8862   char *built_actual_name;
8863
8864   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8865
8866   built_actual_name = partial_die_full_name (pdi, cu);
8867   if (built_actual_name != NULL)
8868     actual_name = built_actual_name;
8869
8870   if (actual_name == NULL)
8871     actual_name = pdi->name;
8872
8873   switch (pdi->tag)
8874     {
8875     case DW_TAG_inlined_subroutine:
8876     case DW_TAG_subprogram:
8877       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8878               - baseaddr);
8879       if (pdi->is_external || cu->language == language_ada)
8880         {
8881           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8882              of the global scope.  But in Ada, we want to be able to access
8883              nested procedures globally.  So all Ada subprograms are stored
8884              in the global scope.  */
8885           add_psymbol_to_list (actual_name, strlen (actual_name),
8886                                built_actual_name != NULL,
8887                                VAR_DOMAIN, LOC_BLOCK,
8888                                SECT_OFF_TEXT (objfile),
8889                                psymbol_placement::GLOBAL,
8890                                addr,
8891                                cu->language, objfile);
8892         }
8893       else
8894         {
8895           add_psymbol_to_list (actual_name, strlen (actual_name),
8896                                built_actual_name != NULL,
8897                                VAR_DOMAIN, LOC_BLOCK,
8898                                SECT_OFF_TEXT (objfile),
8899                                psymbol_placement::STATIC,
8900                                addr, cu->language, objfile);
8901         }
8902
8903       if (pdi->main_subprogram && actual_name != NULL)
8904         set_objfile_main_name (objfile, actual_name, cu->language);
8905       break;
8906     case DW_TAG_constant:
8907       add_psymbol_to_list (actual_name, strlen (actual_name),
8908                            built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8909                            -1, (pdi->is_external
8910                                 ? psymbol_placement::GLOBAL
8911                                 : psymbol_placement::STATIC),
8912                            0, cu->language, objfile);
8913       break;
8914     case DW_TAG_variable:
8915       if (pdi->d.locdesc)
8916         addr = decode_locdesc (pdi->d.locdesc, cu);
8917
8918       if (pdi->d.locdesc
8919           && addr == 0
8920           && !dwarf2_per_objfile->has_section_at_zero)
8921         {
8922           /* A global or static variable may also have been stripped
8923              out by the linker if unused, in which case its address
8924              will be nullified; do not add such variables into partial
8925              symbol table then.  */
8926         }
8927       else if (pdi->is_external)
8928         {
8929           /* Global Variable.
8930              Don't enter into the minimal symbol tables as there is
8931              a minimal symbol table entry from the ELF symbols already.
8932              Enter into partial symbol table if it has a location
8933              descriptor or a type.
8934              If the location descriptor is missing, new_symbol will create
8935              a LOC_UNRESOLVED symbol, the address of the variable will then
8936              be determined from the minimal symbol table whenever the variable
8937              is referenced.
8938              The address for the partial symbol table entry is not
8939              used by GDB, but it comes in handy for debugging partial symbol
8940              table building.  */
8941
8942           if (pdi->d.locdesc || pdi->has_type)
8943             add_psymbol_to_list (actual_name, strlen (actual_name),
8944                                  built_actual_name != NULL,
8945                                  VAR_DOMAIN, LOC_STATIC,
8946                                  SECT_OFF_TEXT (objfile),
8947                                  psymbol_placement::GLOBAL,
8948                                  addr, cu->language, objfile);
8949         }
8950       else
8951         {
8952           int has_loc = pdi->d.locdesc != NULL;
8953
8954           /* Static Variable.  Skip symbols whose value we cannot know (those
8955              without location descriptors or constant values).  */
8956           if (!has_loc && !pdi->has_const_value)
8957             {
8958               xfree (built_actual_name);
8959               return;
8960             }
8961
8962           add_psymbol_to_list (actual_name, strlen (actual_name),
8963                                built_actual_name != NULL,
8964                                VAR_DOMAIN, LOC_STATIC,
8965                                SECT_OFF_TEXT (objfile),
8966                                psymbol_placement::STATIC,
8967                                has_loc ? addr : 0,
8968                                cu->language, objfile);
8969         }
8970       break;
8971     case DW_TAG_typedef:
8972     case DW_TAG_base_type:
8973     case DW_TAG_subrange_type:
8974       add_psymbol_to_list (actual_name, strlen (actual_name),
8975                            built_actual_name != NULL,
8976                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8977                            psymbol_placement::STATIC,
8978                            0, cu->language, objfile);
8979       break;
8980     case DW_TAG_imported_declaration:
8981     case DW_TAG_namespace:
8982       add_psymbol_to_list (actual_name, strlen (actual_name),
8983                            built_actual_name != NULL,
8984                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8985                            psymbol_placement::GLOBAL,
8986                            0, cu->language, objfile);
8987       break;
8988     case DW_TAG_module:
8989       add_psymbol_to_list (actual_name, strlen (actual_name),
8990                            built_actual_name != NULL,
8991                            MODULE_DOMAIN, LOC_TYPEDEF, -1,
8992                            psymbol_placement::GLOBAL,
8993                            0, cu->language, objfile);
8994       break;
8995     case DW_TAG_class_type:
8996     case DW_TAG_interface_type:
8997     case DW_TAG_structure_type:
8998     case DW_TAG_union_type:
8999     case DW_TAG_enumeration_type:
9000       /* Skip external references.  The DWARF standard says in the section
9001          about "Structure, Union, and Class Type Entries": "An incomplete
9002          structure, union or class type is represented by a structure,
9003          union or class entry that does not have a byte size attribute
9004          and that has a DW_AT_declaration attribute."  */
9005       if (!pdi->has_byte_size && pdi->is_declaration)
9006         {
9007           xfree (built_actual_name);
9008           return;
9009         }
9010
9011       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9012          static vs. global.  */
9013       add_psymbol_to_list (actual_name, strlen (actual_name),
9014                            built_actual_name != NULL,
9015                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
9016                            cu->language == language_cplus
9017                            ? psymbol_placement::GLOBAL
9018                            : psymbol_placement::STATIC,
9019                            0, cu->language, objfile);
9020
9021       break;
9022     case DW_TAG_enumerator:
9023       add_psymbol_to_list (actual_name, strlen (actual_name),
9024                            built_actual_name != NULL,
9025                            VAR_DOMAIN, LOC_CONST, -1,
9026                            cu->language == language_cplus
9027                            ? psymbol_placement::GLOBAL
9028                            : psymbol_placement::STATIC,
9029                            0, cu->language, objfile);
9030       break;
9031     default:
9032       break;
9033     }
9034
9035   xfree (built_actual_name);
9036 }
9037
9038 /* Read a partial die corresponding to a namespace; also, add a symbol
9039    corresponding to that namespace to the symbol table.  NAMESPACE is
9040    the name of the enclosing namespace.  */
9041
9042 static void
9043 add_partial_namespace (struct partial_die_info *pdi,
9044                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9045                        int set_addrmap, struct dwarf2_cu *cu)
9046 {
9047   /* Add a symbol for the namespace.  */
9048
9049   add_partial_symbol (pdi, cu);
9050
9051   /* Now scan partial symbols in that namespace.  */
9052
9053   if (pdi->has_children)
9054     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9055 }
9056
9057 /* Read a partial die corresponding to a Fortran module.  */
9058
9059 static void
9060 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9061                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9062 {
9063   /* Add a symbol for the namespace.  */
9064
9065   add_partial_symbol (pdi, cu);
9066
9067   /* Now scan partial symbols in that module.  */
9068
9069   if (pdi->has_children)
9070     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9071 }
9072
9073 /* Read a partial die corresponding to a subprogram or an inlined
9074    subprogram and create a partial symbol for that subprogram.
9075    When the CU language allows it, this routine also defines a partial
9076    symbol for each nested subprogram that this subprogram contains.
9077    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9078    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9079
9080    PDI may also be a lexical block, in which case we simply search
9081    recursively for subprograms defined inside that lexical block.
9082    Again, this is only performed when the CU language allows this
9083    type of definitions.  */
9084
9085 static void
9086 add_partial_subprogram (struct partial_die_info *pdi,
9087                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9088                         int set_addrmap, struct dwarf2_cu *cu)
9089 {
9090   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9091     {
9092       if (pdi->has_pc_info)
9093         {
9094           if (pdi->lowpc < *lowpc)
9095             *lowpc = pdi->lowpc;
9096           if (pdi->highpc > *highpc)
9097             *highpc = pdi->highpc;
9098           if (set_addrmap)
9099             {
9100               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9101               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9102               CORE_ADDR baseaddr;
9103               CORE_ADDR this_highpc;
9104               CORE_ADDR this_lowpc;
9105
9106               baseaddr = ANOFFSET (objfile->section_offsets,
9107                                    SECT_OFF_TEXT (objfile));
9108               this_lowpc
9109                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9110                                                pdi->lowpc + baseaddr)
9111                    - baseaddr);
9112               this_highpc
9113                 = (gdbarch_adjust_dwarf2_addr (gdbarch,
9114                                                pdi->highpc + baseaddr)
9115                    - baseaddr);
9116               addrmap_set_empty (objfile->psymtabs_addrmap,
9117                                  this_lowpc, this_highpc - 1,
9118                                  cu->per_cu->v.psymtab);
9119             }
9120         }
9121
9122       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9123         {
9124           if (!pdi->is_declaration)
9125             /* Ignore subprogram DIEs that do not have a name, they are
9126                illegal.  Do not emit a complaint at this point, we will
9127                do so when we convert this psymtab into a symtab.  */
9128             if (pdi->name)
9129               add_partial_symbol (pdi, cu);
9130         }
9131     }
9132
9133   if (! pdi->has_children)
9134     return;
9135
9136   if (cu->language == language_ada)
9137     {
9138       pdi = pdi->die_child;
9139       while (pdi != NULL)
9140         {
9141           pdi->fixup (cu);
9142           if (pdi->tag == DW_TAG_subprogram
9143               || pdi->tag == DW_TAG_inlined_subroutine
9144               || pdi->tag == DW_TAG_lexical_block)
9145             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9146           pdi = pdi->die_sibling;
9147         }
9148     }
9149 }
9150
9151 /* Read a partial die corresponding to an enumeration type.  */
9152
9153 static void
9154 add_partial_enumeration (struct partial_die_info *enum_pdi,
9155                          struct dwarf2_cu *cu)
9156 {
9157   struct partial_die_info *pdi;
9158
9159   if (enum_pdi->name != NULL)
9160     add_partial_symbol (enum_pdi, cu);
9161
9162   pdi = enum_pdi->die_child;
9163   while (pdi)
9164     {
9165       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9166         complaint (_("malformed enumerator DIE ignored"));
9167       else
9168         add_partial_symbol (pdi, cu);
9169       pdi = pdi->die_sibling;
9170     }
9171 }
9172
9173 /* Return the initial uleb128 in the die at INFO_PTR.  */
9174
9175 static unsigned int
9176 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9177 {
9178   unsigned int bytes_read;
9179
9180   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9181 }
9182
9183 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9184    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9185
9186    Return the corresponding abbrev, or NULL if the number is zero (indicating
9187    an empty DIE).  In either case *BYTES_READ will be set to the length of
9188    the initial number.  */
9189
9190 static struct abbrev_info *
9191 peek_die_abbrev (const die_reader_specs &reader,
9192                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9193 {
9194   dwarf2_cu *cu = reader.cu;
9195   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9196   unsigned int abbrev_number
9197     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9198
9199   if (abbrev_number == 0)
9200     return NULL;
9201
9202   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9203   if (!abbrev)
9204     {
9205       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9206                " at offset %s [in module %s]"),
9207              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9208              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9209     }
9210
9211   return abbrev;
9212 }
9213
9214 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9215    Returns a pointer to the end of a series of DIEs, terminated by an empty
9216    DIE.  Any children of the skipped DIEs will also be skipped.  */
9217
9218 static const gdb_byte *
9219 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9220 {
9221   while (1)
9222     {
9223       unsigned int bytes_read;
9224       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9225
9226       if (abbrev == NULL)
9227         return info_ptr + bytes_read;
9228       else
9229         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9230     }
9231 }
9232
9233 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9234    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9235    abbrev corresponding to that skipped uleb128 should be passed in
9236    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9237    children.  */
9238
9239 static const gdb_byte *
9240 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9241               struct abbrev_info *abbrev)
9242 {
9243   unsigned int bytes_read;
9244   struct attribute attr;
9245   bfd *abfd = reader->abfd;
9246   struct dwarf2_cu *cu = reader->cu;
9247   const gdb_byte *buffer = reader->buffer;
9248   const gdb_byte *buffer_end = reader->buffer_end;
9249   unsigned int form, i;
9250
9251   for (i = 0; i < abbrev->num_attrs; i++)
9252     {
9253       /* The only abbrev we care about is DW_AT_sibling.  */
9254       if (abbrev->attrs[i].name == DW_AT_sibling)
9255         {
9256           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9257           if (attr.form == DW_FORM_ref_addr)
9258             complaint (_("ignoring absolute DW_AT_sibling"));
9259           else
9260             {
9261               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9262               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9263
9264               if (sibling_ptr < info_ptr)
9265                 complaint (_("DW_AT_sibling points backwards"));
9266               else if (sibling_ptr > reader->buffer_end)
9267                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9268               else
9269                 return sibling_ptr;
9270             }
9271         }
9272
9273       /* If it isn't DW_AT_sibling, skip this attribute.  */
9274       form = abbrev->attrs[i].form;
9275     skip_attribute:
9276       switch (form)
9277         {
9278         case DW_FORM_ref_addr:
9279           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9280              and later it is offset sized.  */
9281           if (cu->header.version == 2)
9282             info_ptr += cu->header.addr_size;
9283           else
9284             info_ptr += cu->header.offset_size;
9285           break;
9286         case DW_FORM_GNU_ref_alt:
9287           info_ptr += cu->header.offset_size;
9288           break;
9289         case DW_FORM_addr:
9290           info_ptr += cu->header.addr_size;
9291           break;
9292         case DW_FORM_data1:
9293         case DW_FORM_ref1:
9294         case DW_FORM_flag:
9295           info_ptr += 1;
9296           break;
9297         case DW_FORM_flag_present:
9298         case DW_FORM_implicit_const:
9299           break;
9300         case DW_FORM_data2:
9301         case DW_FORM_ref2:
9302           info_ptr += 2;
9303           break;
9304         case DW_FORM_data4:
9305         case DW_FORM_ref4:
9306           info_ptr += 4;
9307           break;
9308         case DW_FORM_data8:
9309         case DW_FORM_ref8:
9310         case DW_FORM_ref_sig8:
9311           info_ptr += 8;
9312           break;
9313         case DW_FORM_data16:
9314           info_ptr += 16;
9315           break;
9316         case DW_FORM_string:
9317           read_direct_string (abfd, info_ptr, &bytes_read);
9318           info_ptr += bytes_read;
9319           break;
9320         case DW_FORM_sec_offset:
9321         case DW_FORM_strp:
9322         case DW_FORM_GNU_strp_alt:
9323           info_ptr += cu->header.offset_size;
9324           break;
9325         case DW_FORM_exprloc:
9326         case DW_FORM_block:
9327           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9328           info_ptr += bytes_read;
9329           break;
9330         case DW_FORM_block1:
9331           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9332           break;
9333         case DW_FORM_block2:
9334           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9335           break;
9336         case DW_FORM_block4:
9337           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9338           break;
9339         case DW_FORM_sdata:
9340         case DW_FORM_udata:
9341         case DW_FORM_ref_udata:
9342         case DW_FORM_GNU_addr_index:
9343         case DW_FORM_GNU_str_index:
9344           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9345           break;
9346         case DW_FORM_indirect:
9347           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9348           info_ptr += bytes_read;
9349           /* We need to continue parsing from here, so just go back to
9350              the top.  */
9351           goto skip_attribute;
9352
9353         default:
9354           error (_("Dwarf Error: Cannot handle %s "
9355                    "in DWARF reader [in module %s]"),
9356                  dwarf_form_name (form),
9357                  bfd_get_filename (abfd));
9358         }
9359     }
9360
9361   if (abbrev->has_children)
9362     return skip_children (reader, info_ptr);
9363   else
9364     return info_ptr;
9365 }
9366
9367 /* Locate ORIG_PDI's sibling.
9368    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9369
9370 static const gdb_byte *
9371 locate_pdi_sibling (const struct die_reader_specs *reader,
9372                     struct partial_die_info *orig_pdi,
9373                     const gdb_byte *info_ptr)
9374 {
9375   /* Do we know the sibling already?  */
9376
9377   if (orig_pdi->sibling)
9378     return orig_pdi->sibling;
9379
9380   /* Are there any children to deal with?  */
9381
9382   if (!orig_pdi->has_children)
9383     return info_ptr;
9384
9385   /* Skip the children the long way.  */
9386
9387   return skip_children (reader, info_ptr);
9388 }
9389
9390 /* Expand this partial symbol table into a full symbol table.  SELF is
9391    not NULL.  */
9392
9393 static void
9394 dwarf2_read_symtab (struct partial_symtab *self,
9395                     struct objfile *objfile)
9396 {
9397   struct dwarf2_per_objfile *dwarf2_per_objfile
9398     = get_dwarf2_per_objfile (objfile);
9399
9400   if (self->readin)
9401     {
9402       warning (_("bug: psymtab for %s is already read in."),
9403                self->filename);
9404     }
9405   else
9406     {
9407       if (info_verbose)
9408         {
9409           printf_filtered (_("Reading in symbols for %s..."),
9410                            self->filename);
9411           gdb_flush (gdb_stdout);
9412         }
9413
9414       /* If this psymtab is constructed from a debug-only objfile, the
9415          has_section_at_zero flag will not necessarily be correct.  We
9416          can get the correct value for this flag by looking at the data
9417          associated with the (presumably stripped) associated objfile.  */
9418       if (objfile->separate_debug_objfile_backlink)
9419         {
9420           struct dwarf2_per_objfile *dpo_backlink
9421             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9422
9423           dwarf2_per_objfile->has_section_at_zero
9424             = dpo_backlink->has_section_at_zero;
9425         }
9426
9427       dwarf2_per_objfile->reading_partial_symbols = 0;
9428
9429       psymtab_to_symtab_1 (self);
9430
9431       /* Finish up the debug error message.  */
9432       if (info_verbose)
9433         printf_filtered (_("done.\n"));
9434     }
9435
9436   process_cu_includes (dwarf2_per_objfile);
9437 }
9438 \f
9439 /* Reading in full CUs.  */
9440
9441 /* Add PER_CU to the queue.  */
9442
9443 static void
9444 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9445                  enum language pretend_language)
9446 {
9447   struct dwarf2_queue_item *item;
9448
9449   per_cu->queued = 1;
9450   item = XNEW (struct dwarf2_queue_item);
9451   item->per_cu = per_cu;
9452   item->pretend_language = pretend_language;
9453   item->next = NULL;
9454
9455   if (dwarf2_queue == NULL)
9456     dwarf2_queue = item;
9457   else
9458     dwarf2_queue_tail->next = item;
9459
9460   dwarf2_queue_tail = item;
9461 }
9462
9463 /* If PER_CU is not yet queued, add it to the queue.
9464    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9465    dependency.
9466    The result is non-zero if PER_CU was queued, otherwise the result is zero
9467    meaning either PER_CU is already queued or it is already loaded.
9468
9469    N.B. There is an invariant here that if a CU is queued then it is loaded.
9470    The caller is required to load PER_CU if we return non-zero.  */
9471
9472 static int
9473 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9474                        struct dwarf2_per_cu_data *per_cu,
9475                        enum language pretend_language)
9476 {
9477   /* We may arrive here during partial symbol reading, if we need full
9478      DIEs to process an unusual case (e.g. template arguments).  Do
9479      not queue PER_CU, just tell our caller to load its DIEs.  */
9480   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9481     {
9482       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9483         return 1;
9484       return 0;
9485     }
9486
9487   /* Mark the dependence relation so that we don't flush PER_CU
9488      too early.  */
9489   if (dependent_cu != NULL)
9490     dwarf2_add_dependence (dependent_cu, per_cu);
9491
9492   /* If it's already on the queue, we have nothing to do.  */
9493   if (per_cu->queued)
9494     return 0;
9495
9496   /* If the compilation unit is already loaded, just mark it as
9497      used.  */
9498   if (per_cu->cu != NULL)
9499     {
9500       per_cu->cu->last_used = 0;
9501       return 0;
9502     }
9503
9504   /* Add it to the queue.  */
9505   queue_comp_unit (per_cu, pretend_language);
9506
9507   return 1;
9508 }
9509
9510 /* Process the queue.  */
9511
9512 static void
9513 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9514 {
9515   struct dwarf2_queue_item *item, *next_item;
9516
9517   if (dwarf_read_debug)
9518     {
9519       fprintf_unfiltered (gdb_stdlog,
9520                           "Expanding one or more symtabs of objfile %s ...\n",
9521                           objfile_name (dwarf2_per_objfile->objfile));
9522     }
9523
9524   /* The queue starts out with one item, but following a DIE reference
9525      may load a new CU, adding it to the end of the queue.  */
9526   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9527     {
9528       if ((dwarf2_per_objfile->using_index
9529            ? !item->per_cu->v.quick->compunit_symtab
9530            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9531           /* Skip dummy CUs.  */
9532           && item->per_cu->cu != NULL)
9533         {
9534           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9535           unsigned int debug_print_threshold;
9536           char buf[100];
9537
9538           if (per_cu->is_debug_types)
9539             {
9540               struct signatured_type *sig_type =
9541                 (struct signatured_type *) per_cu;
9542
9543               sprintf (buf, "TU %s at offset %s",
9544                        hex_string (sig_type->signature),
9545                        sect_offset_str (per_cu->sect_off));
9546               /* There can be 100s of TUs.
9547                  Only print them in verbose mode.  */
9548               debug_print_threshold = 2;
9549             }
9550           else
9551             {
9552               sprintf (buf, "CU at offset %s",
9553                        sect_offset_str (per_cu->sect_off));
9554               debug_print_threshold = 1;
9555             }
9556
9557           if (dwarf_read_debug >= debug_print_threshold)
9558             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9559
9560           if (per_cu->is_debug_types)
9561             process_full_type_unit (per_cu, item->pretend_language);
9562           else
9563             process_full_comp_unit (per_cu, item->pretend_language);
9564
9565           if (dwarf_read_debug >= debug_print_threshold)
9566             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9567         }
9568
9569       item->per_cu->queued = 0;
9570       next_item = item->next;
9571       xfree (item);
9572     }
9573
9574   dwarf2_queue_tail = NULL;
9575
9576   if (dwarf_read_debug)
9577     {
9578       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9579                           objfile_name (dwarf2_per_objfile->objfile));
9580     }
9581 }
9582
9583 /* Read in full symbols for PST, and anything it depends on.  */
9584
9585 static void
9586 psymtab_to_symtab_1 (struct partial_symtab *pst)
9587 {
9588   struct dwarf2_per_cu_data *per_cu;
9589   int i;
9590
9591   if (pst->readin)
9592     return;
9593
9594   for (i = 0; i < pst->number_of_dependencies; i++)
9595     if (!pst->dependencies[i]->readin
9596         && pst->dependencies[i]->user == NULL)
9597       {
9598         /* Inform about additional files that need to be read in.  */
9599         if (info_verbose)
9600           {
9601             /* FIXME: i18n: Need to make this a single string.  */
9602             fputs_filtered (" ", gdb_stdout);
9603             wrap_here ("");
9604             fputs_filtered ("and ", gdb_stdout);
9605             wrap_here ("");
9606             printf_filtered ("%s...", pst->dependencies[i]->filename);
9607             wrap_here ("");     /* Flush output.  */
9608             gdb_flush (gdb_stdout);
9609           }
9610         psymtab_to_symtab_1 (pst->dependencies[i]);
9611       }
9612
9613   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9614
9615   if (per_cu == NULL)
9616     {
9617       /* It's an include file, no symbols to read for it.
9618          Everything is in the parent symtab.  */
9619       pst->readin = 1;
9620       return;
9621     }
9622
9623   dw2_do_instantiate_symtab (per_cu, false);
9624 }
9625
9626 /* Trivial hash function for die_info: the hash value of a DIE
9627    is its offset in .debug_info for this objfile.  */
9628
9629 static hashval_t
9630 die_hash (const void *item)
9631 {
9632   const struct die_info *die = (const struct die_info *) item;
9633
9634   return to_underlying (die->sect_off);
9635 }
9636
9637 /* Trivial comparison function for die_info structures: two DIEs
9638    are equal if they have the same offset.  */
9639
9640 static int
9641 die_eq (const void *item_lhs, const void *item_rhs)
9642 {
9643   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9644   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9645
9646   return die_lhs->sect_off == die_rhs->sect_off;
9647 }
9648
9649 /* die_reader_func for load_full_comp_unit.
9650    This is identical to read_signatured_type_reader,
9651    but is kept separate for now.  */
9652
9653 static void
9654 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9655                             const gdb_byte *info_ptr,
9656                             struct die_info *comp_unit_die,
9657                             int has_children,
9658                             void *data)
9659 {
9660   struct dwarf2_cu *cu = reader->cu;
9661   enum language *language_ptr = (enum language *) data;
9662
9663   gdb_assert (cu->die_hash == NULL);
9664   cu->die_hash =
9665     htab_create_alloc_ex (cu->header.length / 12,
9666                           die_hash,
9667                           die_eq,
9668                           NULL,
9669                           &cu->comp_unit_obstack,
9670                           hashtab_obstack_allocate,
9671                           dummy_obstack_deallocate);
9672
9673   if (has_children)
9674     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9675                                                   &info_ptr, comp_unit_die);
9676   cu->dies = comp_unit_die;
9677   /* comp_unit_die is not stored in die_hash, no need.  */
9678
9679   /* We try not to read any attributes in this function, because not
9680      all CUs needed for references have been loaded yet, and symbol
9681      table processing isn't initialized.  But we have to set the CU language,
9682      or we won't be able to build types correctly.
9683      Similarly, if we do not read the producer, we can not apply
9684      producer-specific interpretation.  */
9685   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9686 }
9687
9688 /* Load the DIEs associated with PER_CU into memory.  */
9689
9690 static void
9691 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9692                      bool skip_partial,
9693                      enum language pretend_language)
9694 {
9695   gdb_assert (! this_cu->is_debug_types);
9696
9697   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9698                            load_full_comp_unit_reader, &pretend_language);
9699 }
9700
9701 /* Add a DIE to the delayed physname list.  */
9702
9703 static void
9704 add_to_method_list (struct type *type, int fnfield_index, int index,
9705                     const char *name, struct die_info *die,
9706                     struct dwarf2_cu *cu)
9707 {
9708   struct delayed_method_info mi;
9709   mi.type = type;
9710   mi.fnfield_index = fnfield_index;
9711   mi.index = index;
9712   mi.name = name;
9713   mi.die = die;
9714   cu->method_list.push_back (mi);
9715 }
9716
9717 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9718    "const" / "volatile".  If so, decrements LEN by the length of the
9719    modifier and return true.  Otherwise return false.  */
9720
9721 template<size_t N>
9722 static bool
9723 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9724 {
9725   size_t mod_len = sizeof (mod) - 1;
9726   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9727     {
9728       len -= mod_len;
9729       return true;
9730     }
9731   return false;
9732 }
9733
9734 /* Compute the physnames of any methods on the CU's method list.
9735
9736    The computation of method physnames is delayed in order to avoid the
9737    (bad) condition that one of the method's formal parameters is of an as yet
9738    incomplete type.  */
9739
9740 static void
9741 compute_delayed_physnames (struct dwarf2_cu *cu)
9742 {
9743   /* Only C++ delays computing physnames.  */
9744   if (cu->method_list.empty ())
9745     return;
9746   gdb_assert (cu->language == language_cplus);
9747
9748   for (const delayed_method_info &mi : cu->method_list)
9749     {
9750       const char *physname;
9751       struct fn_fieldlist *fn_flp
9752         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9753       physname = dwarf2_physname (mi.name, mi.die, cu);
9754       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9755         = physname ? physname : "";
9756
9757       /* Since there's no tag to indicate whether a method is a
9758          const/volatile overload, extract that information out of the
9759          demangled name.  */
9760       if (physname != NULL)
9761         {
9762           size_t len = strlen (physname);
9763
9764           while (1)
9765             {
9766               if (physname[len] == ')') /* shortcut */
9767                 break;
9768               else if (check_modifier (physname, len, " const"))
9769                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9770               else if (check_modifier (physname, len, " volatile"))
9771                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9772               else
9773                 break;
9774             }
9775         }
9776     }
9777
9778   /* The list is no longer needed.  */
9779   cu->method_list.clear ();
9780 }
9781
9782 /* A wrapper for add_symbol_to_list to ensure that SYMBOL's language is
9783    the same as all other symbols in LISTHEAD.  If a new symbol is added
9784    with a different language, this function asserts.  */
9785
9786 static inline void
9787 dw2_add_symbol_to_list (struct symbol *symbol, struct pending **listhead)
9788 {
9789   /* Only assert if LISTHEAD already contains symbols of a different
9790      language (dict_create_hashed/insert_symbol_hashed requires that all
9791      symbols in this list are of the same language).  */
9792   gdb_assert ((*listhead) == NULL
9793               || (SYMBOL_LANGUAGE ((*listhead)->symbol[0])
9794                   == SYMBOL_LANGUAGE (symbol)));
9795
9796   add_symbol_to_list (symbol, listhead);
9797 }
9798
9799 /* Go objects should be embedded in a DW_TAG_module DIE,
9800    and it's not clear if/how imported objects will appear.
9801    To keep Go support simple until that's worked out,
9802    go back through what we've read and create something usable.
9803    We could do this while processing each DIE, and feels kinda cleaner,
9804    but that way is more invasive.
9805    This is to, for example, allow the user to type "p var" or "b main"
9806    without having to specify the package name, and allow lookups
9807    of module.object to work in contexts that use the expression
9808    parser.  */
9809
9810 static void
9811 fixup_go_packaging (struct dwarf2_cu *cu)
9812 {
9813   char *package_name = NULL;
9814   struct pending *list;
9815   int i;
9816
9817   for (list = *cu->builder->get_global_symbols ();
9818        list != NULL;
9819        list = list->next)
9820     {
9821       for (i = 0; i < list->nsyms; ++i)
9822         {
9823           struct symbol *sym = list->symbol[i];
9824
9825           if (SYMBOL_LANGUAGE (sym) == language_go
9826               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9827             {
9828               char *this_package_name = go_symbol_package_name (sym);
9829
9830               if (this_package_name == NULL)
9831                 continue;
9832               if (package_name == NULL)
9833                 package_name = this_package_name;
9834               else
9835                 {
9836                   struct objfile *objfile
9837                     = cu->per_cu->dwarf2_per_objfile->objfile;
9838                   if (strcmp (package_name, this_package_name) != 0)
9839                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9840                                (symbol_symtab (sym) != NULL
9841                                 ? symtab_to_filename_for_display
9842                                     (symbol_symtab (sym))
9843                                 : objfile_name (objfile)),
9844                                this_package_name, package_name);
9845                   xfree (this_package_name);
9846                 }
9847             }
9848         }
9849     }
9850
9851   if (package_name != NULL)
9852     {
9853       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9854       const char *saved_package_name
9855         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9856                                         package_name,
9857                                         strlen (package_name));
9858       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9859                                      saved_package_name);
9860       struct symbol *sym;
9861
9862       sym = allocate_symbol (objfile);
9863       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9864       SYMBOL_SET_NAMES (sym, saved_package_name,
9865                         strlen (saved_package_name), 0, objfile);
9866       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9867          e.g., "main" finds the "main" module and not C's main().  */
9868       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9869       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9870       SYMBOL_TYPE (sym) = type;
9871
9872       dw2_add_symbol_to_list (sym, cu->builder->get_global_symbols ());
9873
9874       xfree (package_name);
9875     }
9876 }
9877
9878 /* Allocate a fully-qualified name consisting of the two parts on the
9879    obstack.  */
9880
9881 static const char *
9882 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9883 {
9884   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9885 }
9886
9887 /* A helper that allocates a struct discriminant_info to attach to a
9888    union type.  */
9889
9890 static struct discriminant_info *
9891 alloc_discriminant_info (struct type *type, int discriminant_index,
9892                          int default_index)
9893 {
9894   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9895   gdb_assert (discriminant_index == -1
9896               || (discriminant_index >= 0
9897                   && discriminant_index < TYPE_NFIELDS (type)));
9898   gdb_assert (default_index == -1
9899               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9900
9901   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9902
9903   struct discriminant_info *disc
9904     = ((struct discriminant_info *)
9905        TYPE_ZALLOC (type,
9906                     offsetof (struct discriminant_info, discriminants)
9907                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9908   disc->default_index = default_index;
9909   disc->discriminant_index = discriminant_index;
9910
9911   struct dynamic_prop prop;
9912   prop.kind = PROP_UNDEFINED;
9913   prop.data.baton = disc;
9914
9915   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9916
9917   return disc;
9918 }
9919
9920 /* Some versions of rustc emitted enums in an unusual way.
9921
9922    Ordinary enums were emitted as unions.  The first element of each
9923    structure in the union was named "RUST$ENUM$DISR".  This element
9924    held the discriminant.
9925
9926    These versions of Rust also implemented the "non-zero"
9927    optimization.  When the enum had two values, and one is empty and
9928    the other holds a pointer that cannot be zero, the pointer is used
9929    as the discriminant, with a zero value meaning the empty variant.
9930    Here, the union's first member is of the form
9931    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9932    where the fieldnos are the indices of the fields that should be
9933    traversed in order to find the field (which may be several fields deep)
9934    and the variantname is the name of the variant of the case when the
9935    field is zero.
9936
9937    This function recognizes whether TYPE is of one of these forms,
9938    and, if so, smashes it to be a variant type.  */
9939
9940 static void
9941 quirk_rust_enum (struct type *type, struct objfile *objfile)
9942 {
9943   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9944
9945   /* We don't need to deal with empty enums.  */
9946   if (TYPE_NFIELDS (type) == 0)
9947     return;
9948
9949 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9950   if (TYPE_NFIELDS (type) == 1
9951       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9952     {
9953       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9954
9955       /* Decode the field name to find the offset of the
9956          discriminant.  */
9957       ULONGEST bit_offset = 0;
9958       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9959       while (name[0] >= '0' && name[0] <= '9')
9960         {
9961           char *tail;
9962           unsigned long index = strtoul (name, &tail, 10);
9963           name = tail;
9964           if (*name != '$'
9965               || index >= TYPE_NFIELDS (field_type)
9966               || (TYPE_FIELD_LOC_KIND (field_type, index)
9967                   != FIELD_LOC_KIND_BITPOS))
9968             {
9969               complaint (_("Could not parse Rust enum encoding string \"%s\""
9970                            "[in module %s]"),
9971                          TYPE_FIELD_NAME (type, 0),
9972                          objfile_name (objfile));
9973               return;
9974             }
9975           ++name;
9976
9977           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9978           field_type = TYPE_FIELD_TYPE (field_type, index);
9979         }
9980
9981       /* Make a union to hold the variants.  */
9982       struct type *union_type = alloc_type (objfile);
9983       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9984       TYPE_NFIELDS (union_type) = 3;
9985       TYPE_FIELDS (union_type)
9986         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9987       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9988       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9989
9990       /* Put the discriminant must at index 0.  */
9991       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9992       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9993       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9994       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9995
9996       /* The order of fields doesn't really matter, so put the real
9997          field at index 1 and the data-less field at index 2.  */
9998       struct discriminant_info *disc
9999         = alloc_discriminant_info (union_type, 0, 1);
10000       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
10001       TYPE_FIELD_NAME (union_type, 1)
10002         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
10003       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
10004         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10005                               TYPE_FIELD_NAME (union_type, 1));
10006
10007       const char *dataless_name
10008         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
10009                               name);
10010       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
10011                                               dataless_name);
10012       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
10013       /* NAME points into the original discriminant name, which
10014          already has the correct lifetime.  */
10015       TYPE_FIELD_NAME (union_type, 2) = name;
10016       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
10017       disc->discriminants[2] = 0;
10018
10019       /* Smash this type to be a structure type.  We have to do this
10020          because the type has already been recorded.  */
10021       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10022       TYPE_NFIELDS (type) = 1;
10023       TYPE_FIELDS (type)
10024         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
10025
10026       /* Install the variant part.  */
10027       TYPE_FIELD_TYPE (type, 0) = union_type;
10028       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10029       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10030     }
10031   else if (TYPE_NFIELDS (type) == 1)
10032     {
10033       /* We assume that a union with a single field is a univariant
10034          enum.  */
10035       /* Smash this type to be a structure type.  We have to do this
10036          because the type has already been recorded.  */
10037       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10038
10039       /* Make a union to hold the variants.  */
10040       struct type *union_type = alloc_type (objfile);
10041       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10042       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10043       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10044       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10045       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10046
10047       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10048       const char *variant_name
10049         = rust_last_path_segment (TYPE_NAME (field_type));
10050       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10051       TYPE_NAME (field_type)
10052         = rust_fully_qualify (&objfile->objfile_obstack,
10053                               TYPE_NAME (type), variant_name);
10054
10055       /* Install the union in the outer struct type.  */
10056       TYPE_NFIELDS (type) = 1;
10057       TYPE_FIELDS (type)
10058         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10059       TYPE_FIELD_TYPE (type, 0) = union_type;
10060       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10061       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10062
10063       alloc_discriminant_info (union_type, -1, 0);
10064     }
10065   else
10066     {
10067       struct type *disr_type = nullptr;
10068       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10069         {
10070           disr_type = TYPE_FIELD_TYPE (type, i);
10071
10072           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10073             {
10074               /* All fields of a true enum will be structs.  */
10075               return;
10076             }
10077           else if (TYPE_NFIELDS (disr_type) == 0)
10078             {
10079               /* Could be data-less variant, so keep going.  */
10080               disr_type = nullptr;
10081             }
10082           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10083                            "RUST$ENUM$DISR") != 0)
10084             {
10085               /* Not a Rust enum.  */
10086               return;
10087             }
10088           else
10089             {
10090               /* Found one.  */
10091               break;
10092             }
10093         }
10094
10095       /* If we got here without a discriminant, then it's probably
10096          just a union.  */
10097       if (disr_type == nullptr)
10098         return;
10099
10100       /* Smash this type to be a structure type.  We have to do this
10101          because the type has already been recorded.  */
10102       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10103
10104       /* Make a union to hold the variants.  */
10105       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10106       struct type *union_type = alloc_type (objfile);
10107       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10108       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10109       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10110       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10111       TYPE_FIELDS (union_type)
10112         = (struct field *) TYPE_ZALLOC (union_type,
10113                                         (TYPE_NFIELDS (union_type)
10114                                          * sizeof (struct field)));
10115
10116       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10117               TYPE_NFIELDS (type) * sizeof (struct field));
10118
10119       /* Install the discriminant at index 0 in the union.  */
10120       TYPE_FIELD (union_type, 0) = *disr_field;
10121       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10122       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10123
10124       /* Install the union in the outer struct type.  */
10125       TYPE_FIELD_TYPE (type, 0) = union_type;
10126       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10127       TYPE_NFIELDS (type) = 1;
10128
10129       /* Set the size and offset of the union type.  */
10130       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10131
10132       /* We need a way to find the correct discriminant given a
10133          variant name.  For convenience we build a map here.  */
10134       struct type *enum_type = FIELD_TYPE (*disr_field);
10135       std::unordered_map<std::string, ULONGEST> discriminant_map;
10136       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10137         {
10138           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10139             {
10140               const char *name
10141                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10142               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10143             }
10144         }
10145
10146       int n_fields = TYPE_NFIELDS (union_type);
10147       struct discriminant_info *disc
10148         = alloc_discriminant_info (union_type, 0, -1);
10149       /* Skip the discriminant here.  */
10150       for (int i = 1; i < n_fields; ++i)
10151         {
10152           /* Find the final word in the name of this variant's type.
10153              That name can be used to look up the correct
10154              discriminant.  */
10155           const char *variant_name
10156             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10157                                                                   i)));
10158
10159           auto iter = discriminant_map.find (variant_name);
10160           if (iter != discriminant_map.end ())
10161             disc->discriminants[i] = iter->second;
10162
10163           /* Remove the discriminant field, if it exists.  */
10164           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10165           if (TYPE_NFIELDS (sub_type) > 0)
10166             {
10167               --TYPE_NFIELDS (sub_type);
10168               ++TYPE_FIELDS (sub_type);
10169             }
10170           TYPE_FIELD_NAME (union_type, i) = variant_name;
10171           TYPE_NAME (sub_type)
10172             = rust_fully_qualify (&objfile->objfile_obstack,
10173                                   TYPE_NAME (type), variant_name);
10174         }
10175     }
10176 }
10177
10178 /* Rewrite some Rust unions to be structures with variants parts.  */
10179
10180 static void
10181 rust_union_quirks (struct dwarf2_cu *cu)
10182 {
10183   gdb_assert (cu->language == language_rust);
10184   for (type *type_ : cu->rust_unions)
10185     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10186   /* We don't need this any more.  */
10187   cu->rust_unions.clear ();
10188 }
10189
10190 /* Return the symtab for PER_CU.  This works properly regardless of
10191    whether we're using the index or psymtabs.  */
10192
10193 static struct compunit_symtab *
10194 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10195 {
10196   return (per_cu->dwarf2_per_objfile->using_index
10197           ? per_cu->v.quick->compunit_symtab
10198           : per_cu->v.psymtab->compunit_symtab);
10199 }
10200
10201 /* A helper function for computing the list of all symbol tables
10202    included by PER_CU.  */
10203
10204 static void
10205 recursively_compute_inclusions (std::vector<compunit_symtab *> *result,
10206                                 htab_t all_children, htab_t all_type_symtabs,
10207                                 struct dwarf2_per_cu_data *per_cu,
10208                                 struct compunit_symtab *immediate_parent)
10209 {
10210   void **slot;
10211   int ix;
10212   struct compunit_symtab *cust;
10213   struct dwarf2_per_cu_data *iter;
10214
10215   slot = htab_find_slot (all_children, per_cu, INSERT);
10216   if (*slot != NULL)
10217     {
10218       /* This inclusion and its children have been processed.  */
10219       return;
10220     }
10221
10222   *slot = per_cu;
10223   /* Only add a CU if it has a symbol table.  */
10224   cust = get_compunit_symtab (per_cu);
10225   if (cust != NULL)
10226     {
10227       /* If this is a type unit only add its symbol table if we haven't
10228          seen it yet (type unit per_cu's can share symtabs).  */
10229       if (per_cu->is_debug_types)
10230         {
10231           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10232           if (*slot == NULL)
10233             {
10234               *slot = cust;
10235               result->push_back (cust);
10236               if (cust->user == NULL)
10237                 cust->user = immediate_parent;
10238             }
10239         }
10240       else
10241         {
10242           result->push_back (cust);
10243           if (cust->user == NULL)
10244             cust->user = immediate_parent;
10245         }
10246     }
10247
10248   for (ix = 0;
10249        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10250        ++ix)
10251     {
10252       recursively_compute_inclusions (result, all_children,
10253                                       all_type_symtabs, iter, cust);
10254     }
10255 }
10256
10257 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10258    PER_CU.  */
10259
10260 static void
10261 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10262 {
10263   gdb_assert (! per_cu->is_debug_types);
10264
10265   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10266     {
10267       int ix, len;
10268       struct dwarf2_per_cu_data *per_cu_iter;
10269       std::vector<compunit_symtab *> result_symtabs;
10270       htab_t all_children, all_type_symtabs;
10271       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10272
10273       /* If we don't have a symtab, we can just skip this case.  */
10274       if (cust == NULL)
10275         return;
10276
10277       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10278                                         NULL, xcalloc, xfree);
10279       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10280                                             NULL, xcalloc, xfree);
10281
10282       for (ix = 0;
10283            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10284                         ix, per_cu_iter);
10285            ++ix)
10286         {
10287           recursively_compute_inclusions (&result_symtabs, all_children,
10288                                           all_type_symtabs, per_cu_iter,
10289                                           cust);
10290         }
10291
10292       /* Now we have a transitive closure of all the included symtabs.  */
10293       len = result_symtabs.size ();
10294       cust->includes
10295         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10296                      struct compunit_symtab *, len + 1);
10297       memcpy (cust->includes, result_symtabs.data (),
10298               len * sizeof (compunit_symtab *));
10299       cust->includes[len] = NULL;
10300
10301       htab_delete (all_children);
10302       htab_delete (all_type_symtabs);
10303     }
10304 }
10305
10306 /* Compute the 'includes' field for the symtabs of all the CUs we just
10307    read.  */
10308
10309 static void
10310 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10311 {
10312   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10313     {
10314       if (! iter->is_debug_types)
10315         compute_compunit_symtab_includes (iter);
10316     }
10317
10318   dwarf2_per_objfile->just_read_cus.clear ();
10319 }
10320
10321 /* Generate full symbol information for PER_CU, whose DIEs have
10322    already been loaded into memory.  */
10323
10324 static void
10325 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10326                         enum language pretend_language)
10327 {
10328   struct dwarf2_cu *cu = per_cu->cu;
10329   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10330   struct objfile *objfile = dwarf2_per_objfile->objfile;
10331   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10332   CORE_ADDR lowpc, highpc;
10333   struct compunit_symtab *cust;
10334   CORE_ADDR baseaddr;
10335   struct block *static_block;
10336   CORE_ADDR addr;
10337
10338   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10339
10340   /* Clear the list here in case something was left over.  */
10341   cu->method_list.clear ();
10342
10343   cu->language = pretend_language;
10344   cu->language_defn = language_def (cu->language);
10345
10346   /* Do line number decoding in read_file_scope () */
10347   process_die (cu->dies, cu);
10348
10349   /* For now fudge the Go package.  */
10350   if (cu->language == language_go)
10351     fixup_go_packaging (cu);
10352
10353   /* Now that we have processed all the DIEs in the CU, all the types 
10354      should be complete, and it should now be safe to compute all of the
10355      physnames.  */
10356   compute_delayed_physnames (cu);
10357
10358   if (cu->language == language_rust)
10359     rust_union_quirks (cu);
10360
10361   /* Some compilers don't define a DW_AT_high_pc attribute for the
10362      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10363      it, by scanning the DIE's below the compilation unit.  */
10364   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10365
10366   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10367   static_block = cu->builder->end_symtab_get_static_block (addr, 0, 1);
10368
10369   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10370      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10371      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10372      addrmap to help ensure it has an accurate map of pc values belonging to
10373      this comp unit.  */
10374   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10375
10376   cust = cu->builder->end_symtab_from_static_block (static_block,
10377                                                     SECT_OFF_TEXT (objfile),
10378                                                     0);
10379
10380   if (cust != NULL)
10381     {
10382       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10383
10384       /* Set symtab language to language from DW_AT_language.  If the
10385          compilation is from a C file generated by language preprocessors, do
10386          not set the language if it was already deduced by start_subfile.  */
10387       if (!(cu->language == language_c
10388             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10389         COMPUNIT_FILETABS (cust)->language = cu->language;
10390
10391       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10392          produce DW_AT_location with location lists but it can be possibly
10393          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10394          there were bugs in prologue debug info, fixed later in GCC-4.5
10395          by "unwind info for epilogues" patch (which is not directly related).
10396
10397          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10398          needed, it would be wrong due to missing DW_AT_producer there.
10399
10400          Still one can confuse GDB by using non-standard GCC compilation
10401          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10402          */ 
10403       if (cu->has_loclist && gcc_4_minor >= 5)
10404         cust->locations_valid = 1;
10405
10406       if (gcc_4_minor >= 5)
10407         cust->epilogue_unwind_valid = 1;
10408
10409       cust->call_site_htab = cu->call_site_htab;
10410     }
10411
10412   if (dwarf2_per_objfile->using_index)
10413     per_cu->v.quick->compunit_symtab = cust;
10414   else
10415     {
10416       struct partial_symtab *pst = per_cu->v.psymtab;
10417       pst->compunit_symtab = cust;
10418       pst->readin = 1;
10419     }
10420
10421   /* Push it for inclusion processing later.  */
10422   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10423
10424   /* Not needed any more.  */
10425   cu->builder.reset ();
10426 }
10427
10428 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10429    already been loaded into memory.  */
10430
10431 static void
10432 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10433                         enum language pretend_language)
10434 {
10435   struct dwarf2_cu *cu = per_cu->cu;
10436   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10437   struct objfile *objfile = dwarf2_per_objfile->objfile;
10438   struct compunit_symtab *cust;
10439   struct signatured_type *sig_type;
10440
10441   gdb_assert (per_cu->is_debug_types);
10442   sig_type = (struct signatured_type *) per_cu;
10443
10444   /* Clear the list here in case something was left over.  */
10445   cu->method_list.clear ();
10446
10447   cu->language = pretend_language;
10448   cu->language_defn = language_def (cu->language);
10449
10450   /* The symbol tables are set up in read_type_unit_scope.  */
10451   process_die (cu->dies, cu);
10452
10453   /* For now fudge the Go package.  */
10454   if (cu->language == language_go)
10455     fixup_go_packaging (cu);
10456
10457   /* Now that we have processed all the DIEs in the CU, all the types 
10458      should be complete, and it should now be safe to compute all of the
10459      physnames.  */
10460   compute_delayed_physnames (cu);
10461
10462   if (cu->language == language_rust)
10463     rust_union_quirks (cu);
10464
10465   /* TUs share symbol tables.
10466      If this is the first TU to use this symtab, complete the construction
10467      of it with end_expandable_symtab.  Otherwise, complete the addition of
10468      this TU's symbols to the existing symtab.  */
10469   if (sig_type->type_unit_group->compunit_symtab == NULL)
10470     {
10471       cust = cu->builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10472       sig_type->type_unit_group->compunit_symtab = cust;
10473
10474       if (cust != NULL)
10475         {
10476           /* Set symtab language to language from DW_AT_language.  If the
10477              compilation is from a C file generated by language preprocessors,
10478              do not set the language if it was already deduced by
10479              start_subfile.  */
10480           if (!(cu->language == language_c
10481                 && COMPUNIT_FILETABS (cust)->language != language_c))
10482             COMPUNIT_FILETABS (cust)->language = cu->language;
10483         }
10484     }
10485   else
10486     {
10487       cu->builder->augment_type_symtab ();
10488       cust = sig_type->type_unit_group->compunit_symtab;
10489     }
10490
10491   if (dwarf2_per_objfile->using_index)
10492     per_cu->v.quick->compunit_symtab = cust;
10493   else
10494     {
10495       struct partial_symtab *pst = per_cu->v.psymtab;
10496       pst->compunit_symtab = cust;
10497       pst->readin = 1;
10498     }
10499
10500   /* Not needed any more.  */
10501   cu->builder.reset ();
10502 }
10503
10504 /* Process an imported unit DIE.  */
10505
10506 static void
10507 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10508 {
10509   struct attribute *attr;
10510
10511   /* For now we don't handle imported units in type units.  */
10512   if (cu->per_cu->is_debug_types)
10513     {
10514       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10515                " supported in type units [in module %s]"),
10516              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10517     }
10518
10519   attr = dwarf2_attr (die, DW_AT_import, cu);
10520   if (attr != NULL)
10521     {
10522       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10523       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10524       dwarf2_per_cu_data *per_cu
10525         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10526                                             cu->per_cu->dwarf2_per_objfile);
10527
10528       /* If necessary, add it to the queue and load its DIEs.  */
10529       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10530         load_full_comp_unit (per_cu, false, cu->language);
10531
10532       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10533                      per_cu);
10534     }
10535 }
10536
10537 /* RAII object that represents a process_die scope: i.e.,
10538    starts/finishes processing a DIE.  */
10539 class process_die_scope
10540 {
10541 public:
10542   process_die_scope (die_info *die, dwarf2_cu *cu)
10543     : m_die (die), m_cu (cu)
10544   {
10545     /* We should only be processing DIEs not already in process.  */
10546     gdb_assert (!m_die->in_process);
10547     m_die->in_process = true;
10548   }
10549
10550   ~process_die_scope ()
10551   {
10552     m_die->in_process = false;
10553
10554     /* If we're done processing the DIE for the CU that owns the line
10555        header, we don't need the line header anymore.  */
10556     if (m_cu->line_header_die_owner == m_die)
10557       {
10558         delete m_cu->line_header;
10559         m_cu->line_header = NULL;
10560         m_cu->line_header_die_owner = NULL;
10561       }
10562   }
10563
10564 private:
10565   die_info *m_die;
10566   dwarf2_cu *m_cu;
10567 };
10568
10569 /* Process a die and its children.  */
10570
10571 static void
10572 process_die (struct die_info *die, struct dwarf2_cu *cu)
10573 {
10574   process_die_scope scope (die, cu);
10575
10576   switch (die->tag)
10577     {
10578     case DW_TAG_padding:
10579       break;
10580     case DW_TAG_compile_unit:
10581     case DW_TAG_partial_unit:
10582       read_file_scope (die, cu);
10583       break;
10584     case DW_TAG_type_unit:
10585       read_type_unit_scope (die, cu);
10586       break;
10587     case DW_TAG_subprogram:
10588     case DW_TAG_inlined_subroutine:
10589       read_func_scope (die, cu);
10590       break;
10591     case DW_TAG_lexical_block:
10592     case DW_TAG_try_block:
10593     case DW_TAG_catch_block:
10594       read_lexical_block_scope (die, cu);
10595       break;
10596     case DW_TAG_call_site:
10597     case DW_TAG_GNU_call_site:
10598       read_call_site_scope (die, cu);
10599       break;
10600     case DW_TAG_class_type:
10601     case DW_TAG_interface_type:
10602     case DW_TAG_structure_type:
10603     case DW_TAG_union_type:
10604       process_structure_scope (die, cu);
10605       break;
10606     case DW_TAG_enumeration_type:
10607       process_enumeration_scope (die, cu);
10608       break;
10609
10610     /* These dies have a type, but processing them does not create
10611        a symbol or recurse to process the children.  Therefore we can
10612        read them on-demand through read_type_die.  */
10613     case DW_TAG_subroutine_type:
10614     case DW_TAG_set_type:
10615     case DW_TAG_array_type:
10616     case DW_TAG_pointer_type:
10617     case DW_TAG_ptr_to_member_type:
10618     case DW_TAG_reference_type:
10619     case DW_TAG_rvalue_reference_type:
10620     case DW_TAG_string_type:
10621       break;
10622
10623     case DW_TAG_base_type:
10624     case DW_TAG_subrange_type:
10625     case DW_TAG_typedef:
10626       /* Add a typedef symbol for the type definition, if it has a
10627          DW_AT_name.  */
10628       new_symbol (die, read_type_die (die, cu), cu);
10629       break;
10630     case DW_TAG_common_block:
10631       read_common_block (die, cu);
10632       break;
10633     case DW_TAG_common_inclusion:
10634       break;
10635     case DW_TAG_namespace:
10636       cu->processing_has_namespace_info = true;
10637       read_namespace (die, cu);
10638       break;
10639     case DW_TAG_module:
10640       cu->processing_has_namespace_info = true;
10641       read_module (die, cu);
10642       break;
10643     case DW_TAG_imported_declaration:
10644       cu->processing_has_namespace_info = true;
10645       if (read_namespace_alias (die, cu))
10646         break;
10647       /* The declaration is not a global namespace alias.  */
10648       /* Fall through.  */
10649     case DW_TAG_imported_module:
10650       cu->processing_has_namespace_info = true;
10651       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10652                                  || cu->language != language_fortran))
10653         complaint (_("Tag '%s' has unexpected children"),
10654                    dwarf_tag_name (die->tag));
10655       read_import_statement (die, cu);
10656       break;
10657
10658     case DW_TAG_imported_unit:
10659       process_imported_unit_die (die, cu);
10660       break;
10661
10662     case DW_TAG_variable:
10663       read_variable (die, cu);
10664       break;
10665
10666     default:
10667       new_symbol (die, NULL, cu);
10668       break;
10669     }
10670 }
10671 \f
10672 /* DWARF name computation.  */
10673
10674 /* A helper function for dwarf2_compute_name which determines whether DIE
10675    needs to have the name of the scope prepended to the name listed in the
10676    die.  */
10677
10678 static int
10679 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10680 {
10681   struct attribute *attr;
10682
10683   switch (die->tag)
10684     {
10685     case DW_TAG_namespace:
10686     case DW_TAG_typedef:
10687     case DW_TAG_class_type:
10688     case DW_TAG_interface_type:
10689     case DW_TAG_structure_type:
10690     case DW_TAG_union_type:
10691     case DW_TAG_enumeration_type:
10692     case DW_TAG_enumerator:
10693     case DW_TAG_subprogram:
10694     case DW_TAG_inlined_subroutine:
10695     case DW_TAG_member:
10696     case DW_TAG_imported_declaration:
10697       return 1;
10698
10699     case DW_TAG_variable:
10700     case DW_TAG_constant:
10701       /* We only need to prefix "globally" visible variables.  These include
10702          any variable marked with DW_AT_external or any variable that
10703          lives in a namespace.  [Variables in anonymous namespaces
10704          require prefixing, but they are not DW_AT_external.]  */
10705
10706       if (dwarf2_attr (die, DW_AT_specification, cu))
10707         {
10708           struct dwarf2_cu *spec_cu = cu;
10709
10710           return die_needs_namespace (die_specification (die, &spec_cu),
10711                                       spec_cu);
10712         }
10713
10714       attr = dwarf2_attr (die, DW_AT_external, cu);
10715       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10716           && die->parent->tag != DW_TAG_module)
10717         return 0;
10718       /* A variable in a lexical block of some kind does not need a
10719          namespace, even though in C++ such variables may be external
10720          and have a mangled name.  */
10721       if (die->parent->tag ==  DW_TAG_lexical_block
10722           || die->parent->tag ==  DW_TAG_try_block
10723           || die->parent->tag ==  DW_TAG_catch_block
10724           || die->parent->tag == DW_TAG_subprogram)
10725         return 0;
10726       return 1;
10727
10728     default:
10729       return 0;
10730     }
10731 }
10732
10733 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10734    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10735    defined for the given DIE.  */
10736
10737 static struct attribute *
10738 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10739 {
10740   struct attribute *attr;
10741
10742   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10743   if (attr == NULL)
10744     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10745
10746   return attr;
10747 }
10748
10749 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10750    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10751    defined for the given DIE.  */
10752
10753 static const char *
10754 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10755 {
10756   const char *linkage_name;
10757
10758   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10759   if (linkage_name == NULL)
10760     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10761
10762   return linkage_name;
10763 }
10764
10765 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10766    compute the physname for the object, which include a method's:
10767    - formal parameters (C++),
10768    - receiver type (Go),
10769
10770    The term "physname" is a bit confusing.
10771    For C++, for example, it is the demangled name.
10772    For Go, for example, it's the mangled name.
10773
10774    For Ada, return the DIE's linkage name rather than the fully qualified
10775    name.  PHYSNAME is ignored..
10776
10777    The result is allocated on the objfile_obstack and canonicalized.  */
10778
10779 static const char *
10780 dwarf2_compute_name (const char *name,
10781                      struct die_info *die, struct dwarf2_cu *cu,
10782                      int physname)
10783 {
10784   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10785
10786   if (name == NULL)
10787     name = dwarf2_name (die, cu);
10788
10789   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10790      but otherwise compute it by typename_concat inside GDB.
10791      FIXME: Actually this is not really true, or at least not always true.
10792      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10793      Fortran names because there is no mangling standard.  So new_symbol
10794      will set the demangled name to the result of dwarf2_full_name, and it is
10795      the demangled name that GDB uses if it exists.  */
10796   if (cu->language == language_ada
10797       || (cu->language == language_fortran && physname))
10798     {
10799       /* For Ada unit, we prefer the linkage name over the name, as
10800          the former contains the exported name, which the user expects
10801          to be able to reference.  Ideally, we want the user to be able
10802          to reference this entity using either natural or linkage name,
10803          but we haven't started looking at this enhancement yet.  */
10804       const char *linkage_name = dw2_linkage_name (die, cu);
10805
10806       if (linkage_name != NULL)
10807         return linkage_name;
10808     }
10809
10810   /* These are the only languages we know how to qualify names in.  */
10811   if (name != NULL
10812       && (cu->language == language_cplus
10813           || cu->language == language_fortran || cu->language == language_d
10814           || cu->language == language_rust))
10815     {
10816       if (die_needs_namespace (die, cu))
10817         {
10818           const char *prefix;
10819           const char *canonical_name = NULL;
10820
10821           string_file buf;
10822
10823           prefix = determine_prefix (die, cu);
10824           if (*prefix != '\0')
10825             {
10826               char *prefixed_name = typename_concat (NULL, prefix, name,
10827                                                      physname, cu);
10828
10829               buf.puts (prefixed_name);
10830               xfree (prefixed_name);
10831             }
10832           else
10833             buf.puts (name);
10834
10835           /* Template parameters may be specified in the DIE's DW_AT_name, or
10836              as children with DW_TAG_template_type_param or
10837              DW_TAG_value_type_param.  If the latter, add them to the name
10838              here.  If the name already has template parameters, then
10839              skip this step; some versions of GCC emit both, and
10840              it is more efficient to use the pre-computed name.
10841
10842              Something to keep in mind about this process: it is very
10843              unlikely, or in some cases downright impossible, to produce
10844              something that will match the mangled name of a function.
10845              If the definition of the function has the same debug info,
10846              we should be able to match up with it anyway.  But fallbacks
10847              using the minimal symbol, for instance to find a method
10848              implemented in a stripped copy of libstdc++, will not work.
10849              If we do not have debug info for the definition, we will have to
10850              match them up some other way.
10851
10852              When we do name matching there is a related problem with function
10853              templates; two instantiated function templates are allowed to
10854              differ only by their return types, which we do not add here.  */
10855
10856           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10857             {
10858               struct attribute *attr;
10859               struct die_info *child;
10860               int first = 1;
10861
10862               die->building_fullname = 1;
10863
10864               for (child = die->child; child != NULL; child = child->sibling)
10865                 {
10866                   struct type *type;
10867                   LONGEST value;
10868                   const gdb_byte *bytes;
10869                   struct dwarf2_locexpr_baton *baton;
10870                   struct value *v;
10871
10872                   if (child->tag != DW_TAG_template_type_param
10873                       && child->tag != DW_TAG_template_value_param)
10874                     continue;
10875
10876                   if (first)
10877                     {
10878                       buf.puts ("<");
10879                       first = 0;
10880                     }
10881                   else
10882                     buf.puts (", ");
10883
10884                   attr = dwarf2_attr (child, DW_AT_type, cu);
10885                   if (attr == NULL)
10886                     {
10887                       complaint (_("template parameter missing DW_AT_type"));
10888                       buf.puts ("UNKNOWN_TYPE");
10889                       continue;
10890                     }
10891                   type = die_type (child, cu);
10892
10893                   if (child->tag == DW_TAG_template_type_param)
10894                     {
10895                       c_print_type (type, "", &buf, -1, 0, cu->language,
10896                                     &type_print_raw_options);
10897                       continue;
10898                     }
10899
10900                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10901                   if (attr == NULL)
10902                     {
10903                       complaint (_("template parameter missing "
10904                                    "DW_AT_const_value"));
10905                       buf.puts ("UNKNOWN_VALUE");
10906                       continue;
10907                     }
10908
10909                   dwarf2_const_value_attr (attr, type, name,
10910                                            &cu->comp_unit_obstack, cu,
10911                                            &value, &bytes, &baton);
10912
10913                   if (TYPE_NOSIGN (type))
10914                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10915                        changed, this can use value_print instead.  */
10916                     c_printchar (value, type, &buf);
10917                   else
10918                     {
10919                       struct value_print_options opts;
10920
10921                       if (baton != NULL)
10922                         v = dwarf2_evaluate_loc_desc (type, NULL,
10923                                                       baton->data,
10924                                                       baton->size,
10925                                                       baton->per_cu);
10926                       else if (bytes != NULL)
10927                         {
10928                           v = allocate_value (type);
10929                           memcpy (value_contents_writeable (v), bytes,
10930                                   TYPE_LENGTH (type));
10931                         }
10932                       else
10933                         v = value_from_longest (type, value);
10934
10935                       /* Specify decimal so that we do not depend on
10936                          the radix.  */
10937                       get_formatted_print_options (&opts, 'd');
10938                       opts.raw = 1;
10939                       value_print (v, &buf, &opts);
10940                       release_value (v);
10941                     }
10942                 }
10943
10944               die->building_fullname = 0;
10945
10946               if (!first)
10947                 {
10948                   /* Close the argument list, with a space if necessary
10949                      (nested templates).  */
10950                   if (!buf.empty () && buf.string ().back () == '>')
10951                     buf.puts (" >");
10952                   else
10953                     buf.puts (">");
10954                 }
10955             }
10956
10957           /* For C++ methods, append formal parameter type
10958              information, if PHYSNAME.  */
10959
10960           if (physname && die->tag == DW_TAG_subprogram
10961               && cu->language == language_cplus)
10962             {
10963               struct type *type = read_type_die (die, cu);
10964
10965               c_type_print_args (type, &buf, 1, cu->language,
10966                                  &type_print_raw_options);
10967
10968               if (cu->language == language_cplus)
10969                 {
10970                   /* Assume that an artificial first parameter is
10971                      "this", but do not crash if it is not.  RealView
10972                      marks unnamed (and thus unused) parameters as
10973                      artificial; there is no way to differentiate
10974                      the two cases.  */
10975                   if (TYPE_NFIELDS (type) > 0
10976                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10977                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10978                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10979                                                                         0))))
10980                     buf.puts (" const");
10981                 }
10982             }
10983
10984           const std::string &intermediate_name = buf.string ();
10985
10986           if (cu->language == language_cplus)
10987             canonical_name
10988               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10989                                           &objfile->per_bfd->storage_obstack);
10990
10991           /* If we only computed INTERMEDIATE_NAME, or if
10992              INTERMEDIATE_NAME is already canonical, then we need to
10993              copy it to the appropriate obstack.  */
10994           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10995             name = ((const char *)
10996                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10997                                    intermediate_name.c_str (),
10998                                    intermediate_name.length ()));
10999           else
11000             name = canonical_name;
11001         }
11002     }
11003
11004   return name;
11005 }
11006
11007 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11008    If scope qualifiers are appropriate they will be added.  The result
11009    will be allocated on the storage_obstack, or NULL if the DIE does
11010    not have a name.  NAME may either be from a previous call to
11011    dwarf2_name or NULL.
11012
11013    The output string will be canonicalized (if C++).  */
11014
11015 static const char *
11016 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11017 {
11018   return dwarf2_compute_name (name, die, cu, 0);
11019 }
11020
11021 /* Construct a physname for the given DIE in CU.  NAME may either be
11022    from a previous call to dwarf2_name or NULL.  The result will be
11023    allocated on the objfile_objstack or NULL if the DIE does not have a
11024    name.
11025
11026    The output string will be canonicalized (if C++).  */
11027
11028 static const char *
11029 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11030 {
11031   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11032   const char *retval, *mangled = NULL, *canon = NULL;
11033   int need_copy = 1;
11034
11035   /* In this case dwarf2_compute_name is just a shortcut not building anything
11036      on its own.  */
11037   if (!die_needs_namespace (die, cu))
11038     return dwarf2_compute_name (name, die, cu, 1);
11039
11040   mangled = dw2_linkage_name (die, cu);
11041
11042   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11043      See https://github.com/rust-lang/rust/issues/32925.  */
11044   if (cu->language == language_rust && mangled != NULL
11045       && strchr (mangled, '{') != NULL)
11046     mangled = NULL;
11047
11048   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11049      has computed.  */
11050   gdb::unique_xmalloc_ptr<char> demangled;
11051   if (mangled != NULL)
11052     {
11053
11054       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11055         {
11056           /* Do nothing (do not demangle the symbol name).  */
11057         }
11058       else if (cu->language == language_go)
11059         {
11060           /* This is a lie, but we already lie to the caller new_symbol.
11061              new_symbol assumes we return the mangled name.
11062              This just undoes that lie until things are cleaned up.  */
11063         }
11064       else
11065         {
11066           /* Use DMGL_RET_DROP for C++ template functions to suppress
11067              their return type.  It is easier for GDB users to search
11068              for such functions as `name(params)' than `long name(params)'.
11069              In such case the minimal symbol names do not match the full
11070              symbol names but for template functions there is never a need
11071              to look up their definition from their declaration so
11072              the only disadvantage remains the minimal symbol variant
11073              `long name(params)' does not have the proper inferior type.  */
11074           demangled.reset (gdb_demangle (mangled,
11075                                          (DMGL_PARAMS | DMGL_ANSI
11076                                           | DMGL_RET_DROP)));
11077         }
11078       if (demangled)
11079         canon = demangled.get ();
11080       else
11081         {
11082           canon = mangled;
11083           need_copy = 0;
11084         }
11085     }
11086
11087   if (canon == NULL || check_physname)
11088     {
11089       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11090
11091       if (canon != NULL && strcmp (physname, canon) != 0)
11092         {
11093           /* It may not mean a bug in GDB.  The compiler could also
11094              compute DW_AT_linkage_name incorrectly.  But in such case
11095              GDB would need to be bug-to-bug compatible.  */
11096
11097           complaint (_("Computed physname <%s> does not match demangled <%s> "
11098                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11099                      physname, canon, mangled, sect_offset_str (die->sect_off),
11100                      objfile_name (objfile));
11101
11102           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11103              is available here - over computed PHYSNAME.  It is safer
11104              against both buggy GDB and buggy compilers.  */
11105
11106           retval = canon;
11107         }
11108       else
11109         {
11110           retval = physname;
11111           need_copy = 0;
11112         }
11113     }
11114   else
11115     retval = canon;
11116
11117   if (need_copy)
11118     retval = ((const char *)
11119               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11120                              retval, strlen (retval)));
11121
11122   return retval;
11123 }
11124
11125 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11126    a new symbol for it.
11127
11128    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11129
11130 static int
11131 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11132 {
11133   struct attribute *attr;
11134
11135   /* If the die does not have a name, this is not a namespace
11136      alias.  */
11137   attr = dwarf2_attr (die, DW_AT_name, cu);
11138   if (attr != NULL)
11139     {
11140       int num;
11141       struct die_info *d = die;
11142       struct dwarf2_cu *imported_cu = cu;
11143
11144       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11145          keep inspecting DIEs until we hit the underlying import.  */
11146 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11147       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11148         {
11149           attr = dwarf2_attr (d, DW_AT_import, cu);
11150           if (attr == NULL)
11151             break;
11152
11153           d = follow_die_ref (d, attr, &imported_cu);
11154           if (d->tag != DW_TAG_imported_declaration)
11155             break;
11156         }
11157
11158       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11159         {
11160           complaint (_("DIE at %s has too many recursively imported "
11161                        "declarations"), sect_offset_str (d->sect_off));
11162           return 0;
11163         }
11164
11165       if (attr != NULL)
11166         {
11167           struct type *type;
11168           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11169
11170           type = get_die_type_at_offset (sect_off, cu->per_cu);
11171           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11172             {
11173               /* This declaration is a global namespace alias.  Add
11174                  a symbol for it whose type is the aliased namespace.  */
11175               new_symbol (die, type, cu);
11176               return 1;
11177             }
11178         }
11179     }
11180
11181   return 0;
11182 }
11183
11184 /* Return the using directives repository (global or local?) to use in the
11185    current context for CU.
11186
11187    For Ada, imported declarations can materialize renamings, which *may* be
11188    global.  However it is impossible (for now?) in DWARF to distinguish
11189    "external" imported declarations and "static" ones.  As all imported
11190    declarations seem to be static in all other languages, make them all CU-wide
11191    global only in Ada.  */
11192
11193 static struct using_direct **
11194 using_directives (struct dwarf2_cu *cu)
11195 {
11196   if (cu->language == language_ada && cu->builder->outermost_context_p ())
11197     return cu->builder->get_global_using_directives ();
11198   else
11199     return cu->builder->get_local_using_directives ();
11200 }
11201
11202 /* Read the import statement specified by the given die and record it.  */
11203
11204 static void
11205 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11206 {
11207   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11208   struct attribute *import_attr;
11209   struct die_info *imported_die, *child_die;
11210   struct dwarf2_cu *imported_cu;
11211   const char *imported_name;
11212   const char *imported_name_prefix;
11213   const char *canonical_name;
11214   const char *import_alias;
11215   const char *imported_declaration = NULL;
11216   const char *import_prefix;
11217   std::vector<const char *> excludes;
11218
11219   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11220   if (import_attr == NULL)
11221     {
11222       complaint (_("Tag '%s' has no DW_AT_import"),
11223                  dwarf_tag_name (die->tag));
11224       return;
11225     }
11226
11227   imported_cu = cu;
11228   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11229   imported_name = dwarf2_name (imported_die, imported_cu);
11230   if (imported_name == NULL)
11231     {
11232       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11233
11234         The import in the following code:
11235         namespace A
11236           {
11237             typedef int B;
11238           }
11239
11240         int main ()
11241           {
11242             using A::B;
11243             B b;
11244             return b;
11245           }
11246
11247         ...
11248          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11249             <52>   DW_AT_decl_file   : 1
11250             <53>   DW_AT_decl_line   : 6
11251             <54>   DW_AT_import      : <0x75>
11252          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11253             <59>   DW_AT_name        : B
11254             <5b>   DW_AT_decl_file   : 1
11255             <5c>   DW_AT_decl_line   : 2
11256             <5d>   DW_AT_type        : <0x6e>
11257         ...
11258          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11259             <76>   DW_AT_byte_size   : 4
11260             <77>   DW_AT_encoding    : 5        (signed)
11261
11262         imports the wrong die ( 0x75 instead of 0x58 ).
11263         This case will be ignored until the gcc bug is fixed.  */
11264       return;
11265     }
11266
11267   /* Figure out the local name after import.  */
11268   import_alias = dwarf2_name (die, cu);
11269
11270   /* Figure out where the statement is being imported to.  */
11271   import_prefix = determine_prefix (die, cu);
11272
11273   /* Figure out what the scope of the imported die is and prepend it
11274      to the name of the imported die.  */
11275   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11276
11277   if (imported_die->tag != DW_TAG_namespace
11278       && imported_die->tag != DW_TAG_module)
11279     {
11280       imported_declaration = imported_name;
11281       canonical_name = imported_name_prefix;
11282     }
11283   else if (strlen (imported_name_prefix) > 0)
11284     canonical_name = obconcat (&objfile->objfile_obstack,
11285                                imported_name_prefix,
11286                                (cu->language == language_d ? "." : "::"),
11287                                imported_name, (char *) NULL);
11288   else
11289     canonical_name = imported_name;
11290
11291   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11292     for (child_die = die->child; child_die && child_die->tag;
11293          child_die = sibling_die (child_die))
11294       {
11295         /* DWARF-4: A Fortran use statement with a “rename list” may be
11296            represented by an imported module entry with an import attribute
11297            referring to the module and owned entries corresponding to those
11298            entities that are renamed as part of being imported.  */
11299
11300         if (child_die->tag != DW_TAG_imported_declaration)
11301           {
11302             complaint (_("child DW_TAG_imported_declaration expected "
11303                          "- DIE at %s [in module %s]"),
11304                        sect_offset_str (child_die->sect_off),
11305                        objfile_name (objfile));
11306             continue;
11307           }
11308
11309         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11310         if (import_attr == NULL)
11311           {
11312             complaint (_("Tag '%s' has no DW_AT_import"),
11313                        dwarf_tag_name (child_die->tag));
11314             continue;
11315           }
11316
11317         imported_cu = cu;
11318         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11319                                               &imported_cu);
11320         imported_name = dwarf2_name (imported_die, imported_cu);
11321         if (imported_name == NULL)
11322           {
11323             complaint (_("child DW_TAG_imported_declaration has unknown "
11324                          "imported name - DIE at %s [in module %s]"),
11325                        sect_offset_str (child_die->sect_off),
11326                        objfile_name (objfile));
11327             continue;
11328           }
11329
11330         excludes.push_back (imported_name);
11331
11332         process_die (child_die, cu);
11333       }
11334
11335   add_using_directive (using_directives (cu),
11336                        import_prefix,
11337                        canonical_name,
11338                        import_alias,
11339                        imported_declaration,
11340                        excludes,
11341                        0,
11342                        &objfile->objfile_obstack);
11343 }
11344
11345 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11346    types, but gives them a size of zero.  Starting with version 14,
11347    ICC is compatible with GCC.  */
11348
11349 static bool
11350 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11351 {
11352   if (!cu->checked_producer)
11353     check_producer (cu);
11354
11355   return cu->producer_is_icc_lt_14;
11356 }
11357
11358 /* ICC generates a DW_AT_type for C void functions.  This was observed on
11359    ICC 14.0.5.212, and appears to be against the DWARF spec (V5 3.3.2)
11360    which says that void functions should not have a DW_AT_type.  */
11361
11362 static bool
11363 producer_is_icc (struct dwarf2_cu *cu)
11364 {
11365   if (!cu->checked_producer)
11366     check_producer (cu);
11367
11368   return cu->producer_is_icc;
11369 }
11370
11371 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11372    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11373    this, it was first present in GCC release 4.3.0.  */
11374
11375 static bool
11376 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11377 {
11378   if (!cu->checked_producer)
11379     check_producer (cu);
11380
11381   return cu->producer_is_gcc_lt_4_3;
11382 }
11383
11384 static file_and_directory
11385 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11386 {
11387   file_and_directory res;
11388
11389   /* Find the filename.  Do not use dwarf2_name here, since the filename
11390      is not a source language identifier.  */
11391   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11392   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11393
11394   if (res.comp_dir == NULL
11395       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11396       && IS_ABSOLUTE_PATH (res.name))
11397     {
11398       res.comp_dir_storage = ldirname (res.name);
11399       if (!res.comp_dir_storage.empty ())
11400         res.comp_dir = res.comp_dir_storage.c_str ();
11401     }
11402   if (res.comp_dir != NULL)
11403     {
11404       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11405          directory, get rid of it.  */
11406       const char *cp = strchr (res.comp_dir, ':');
11407
11408       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11409         res.comp_dir = cp + 1;
11410     }
11411
11412   if (res.name == NULL)
11413     res.name = "<unknown>";
11414
11415   return res;
11416 }
11417
11418 /* Handle DW_AT_stmt_list for a compilation unit.
11419    DIE is the DW_TAG_compile_unit die for CU.
11420    COMP_DIR is the compilation directory.  LOWPC is passed to
11421    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11422
11423 static void
11424 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11425                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11426 {
11427   struct dwarf2_per_objfile *dwarf2_per_objfile
11428     = cu->per_cu->dwarf2_per_objfile;
11429   struct objfile *objfile = dwarf2_per_objfile->objfile;
11430   struct attribute *attr;
11431   struct line_header line_header_local;
11432   hashval_t line_header_local_hash;
11433   void **slot;
11434   int decode_mapping;
11435
11436   gdb_assert (! cu->per_cu->is_debug_types);
11437
11438   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11439   if (attr == NULL)
11440     return;
11441
11442   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11443
11444   /* The line header hash table is only created if needed (it exists to
11445      prevent redundant reading of the line table for partial_units).
11446      If we're given a partial_unit, we'll need it.  If we're given a
11447      compile_unit, then use the line header hash table if it's already
11448      created, but don't create one just yet.  */
11449
11450   if (dwarf2_per_objfile->line_header_hash == NULL
11451       && die->tag == DW_TAG_partial_unit)
11452     {
11453       dwarf2_per_objfile->line_header_hash
11454         = htab_create_alloc_ex (127, line_header_hash_voidp,
11455                                 line_header_eq_voidp,
11456                                 free_line_header_voidp,
11457                                 &objfile->objfile_obstack,
11458                                 hashtab_obstack_allocate,
11459                                 dummy_obstack_deallocate);
11460     }
11461
11462   line_header_local.sect_off = line_offset;
11463   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11464   line_header_local_hash = line_header_hash (&line_header_local);
11465   if (dwarf2_per_objfile->line_header_hash != NULL)
11466     {
11467       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11468                                        &line_header_local,
11469                                        line_header_local_hash, NO_INSERT);
11470
11471       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11472          is not present in *SLOT (since if there is something in *SLOT then
11473          it will be for a partial_unit).  */
11474       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11475         {
11476           gdb_assert (*slot != NULL);
11477           cu->line_header = (struct line_header *) *slot;
11478           return;
11479         }
11480     }
11481
11482   /* dwarf_decode_line_header does not yet provide sufficient information.
11483      We always have to call also dwarf_decode_lines for it.  */
11484   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11485   if (lh == NULL)
11486     return;
11487
11488   cu->line_header = lh.release ();
11489   cu->line_header_die_owner = die;
11490
11491   if (dwarf2_per_objfile->line_header_hash == NULL)
11492     slot = NULL;
11493   else
11494     {
11495       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11496                                        &line_header_local,
11497                                        line_header_local_hash, INSERT);
11498       gdb_assert (slot != NULL);
11499     }
11500   if (slot != NULL && *slot == NULL)
11501     {
11502       /* This newly decoded line number information unit will be owned
11503          by line_header_hash hash table.  */
11504       *slot = cu->line_header;
11505       cu->line_header_die_owner = NULL;
11506     }
11507   else
11508     {
11509       /* We cannot free any current entry in (*slot) as that struct line_header
11510          may be already used by multiple CUs.  Create only temporary decoded
11511          line_header for this CU - it may happen at most once for each line
11512          number information unit.  And if we're not using line_header_hash
11513          then this is what we want as well.  */
11514       gdb_assert (die->tag != DW_TAG_partial_unit);
11515     }
11516   decode_mapping = (die->tag != DW_TAG_partial_unit);
11517   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11518                       decode_mapping);
11519
11520 }
11521
11522 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11523
11524 static void
11525 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11526 {
11527   struct dwarf2_per_objfile *dwarf2_per_objfile
11528     = cu->per_cu->dwarf2_per_objfile;
11529   struct objfile *objfile = dwarf2_per_objfile->objfile;
11530   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11531   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11532   CORE_ADDR highpc = ((CORE_ADDR) 0);
11533   struct attribute *attr;
11534   struct die_info *child_die;
11535   CORE_ADDR baseaddr;
11536
11537   prepare_one_comp_unit (cu, die, cu->language);
11538   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11539
11540   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11541
11542   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11543      from finish_block.  */
11544   if (lowpc == ((CORE_ADDR) -1))
11545     lowpc = highpc;
11546   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11547
11548   file_and_directory fnd = find_file_and_directory (die, cu);
11549
11550   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11551      standardised yet.  As a workaround for the language detection we fall
11552      back to the DW_AT_producer string.  */
11553   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11554     cu->language = language_opencl;
11555
11556   /* Similar hack for Go.  */
11557   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11558     set_cu_language (DW_LANG_Go, cu);
11559
11560   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11561
11562   /* Decode line number information if present.  We do this before
11563      processing child DIEs, so that the line header table is available
11564      for DW_AT_decl_file.  */
11565   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11566
11567   /* Process all dies in compilation unit.  */
11568   if (die->child != NULL)
11569     {
11570       child_die = die->child;
11571       while (child_die && child_die->tag)
11572         {
11573           process_die (child_die, cu);
11574           child_die = sibling_die (child_die);
11575         }
11576     }
11577
11578   /* Decode macro information, if present.  Dwarf 2 macro information
11579      refers to information in the line number info statement program
11580      header, so we can only read it if we've read the header
11581      successfully.  */
11582   attr = dwarf2_attr (die, DW_AT_macros, cu);
11583   if (attr == NULL)
11584     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11585   if (attr && cu->line_header)
11586     {
11587       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11588         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11589
11590       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11591     }
11592   else
11593     {
11594       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11595       if (attr && cu->line_header)
11596         {
11597           unsigned int macro_offset = DW_UNSND (attr);
11598
11599           dwarf_decode_macros (cu, macro_offset, 0);
11600         }
11601     }
11602 }
11603
11604 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11605    Create the set of symtabs used by this TU, or if this TU is sharing
11606    symtabs with another TU and the symtabs have already been created
11607    then restore those symtabs in the line header.
11608    We don't need the pc/line-number mapping for type units.  */
11609
11610 static void
11611 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11612 {
11613   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11614   struct type_unit_group *tu_group;
11615   int first_time;
11616   struct attribute *attr;
11617   unsigned int i;
11618   struct signatured_type *sig_type;
11619
11620   gdb_assert (per_cu->is_debug_types);
11621   sig_type = (struct signatured_type *) per_cu;
11622
11623   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11624
11625   /* If we're using .gdb_index (includes -readnow) then
11626      per_cu->type_unit_group may not have been set up yet.  */
11627   if (sig_type->type_unit_group == NULL)
11628     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11629   tu_group = sig_type->type_unit_group;
11630
11631   /* If we've already processed this stmt_list there's no real need to
11632      do it again, we could fake it and just recreate the part we need
11633      (file name,index -> symtab mapping).  If data shows this optimization
11634      is useful we can do it then.  */
11635   first_time = tu_group->compunit_symtab == NULL;
11636
11637   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11638      debug info.  */
11639   line_header_up lh;
11640   if (attr != NULL)
11641     {
11642       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11643       lh = dwarf_decode_line_header (line_offset, cu);
11644     }
11645   if (lh == NULL)
11646     {
11647       if (first_time)
11648         dwarf2_start_symtab (cu, "", NULL, 0);
11649       else
11650         {
11651           gdb_assert (tu_group->symtabs == NULL);
11652           gdb_assert (cu->builder == nullptr);
11653           struct compunit_symtab *cust = tu_group->compunit_symtab;
11654           cu->builder.reset (new struct buildsym_compunit
11655                              (COMPUNIT_OBJFILE (cust), "",
11656                               COMPUNIT_DIRNAME (cust),
11657                               compunit_language (cust),
11658                               0, cust));
11659         }
11660       return;
11661     }
11662
11663   cu->line_header = lh.release ();
11664   cu->line_header_die_owner = die;
11665
11666   if (first_time)
11667     {
11668       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11669
11670       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11671          still initializing it, and our caller (a few levels up)
11672          process_full_type_unit still needs to know if this is the first
11673          time.  */
11674
11675       tu_group->num_symtabs = cu->line_header->file_names.size ();
11676       tu_group->symtabs = XNEWVEC (struct symtab *,
11677                                    cu->line_header->file_names.size ());
11678
11679       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11680         {
11681           file_entry &fe = cu->line_header->file_names[i];
11682
11683           dwarf2_start_subfile (cu, fe.name, fe.include_dir (cu->line_header));
11684
11685           if (cu->builder->get_current_subfile ()->symtab == NULL)
11686             {
11687               /* NOTE: start_subfile will recognize when it's been
11688                  passed a file it has already seen.  So we can't
11689                  assume there's a simple mapping from
11690                  cu->line_header->file_names to subfiles, plus
11691                  cu->line_header->file_names may contain dups.  */
11692               cu->builder->get_current_subfile ()->symtab
11693                 = allocate_symtab (cust,
11694                                    cu->builder->get_current_subfile ()->name);
11695             }
11696
11697           fe.symtab = cu->builder->get_current_subfile ()->symtab;
11698           tu_group->symtabs[i] = fe.symtab;
11699         }
11700     }
11701   else
11702     {
11703       gdb_assert (cu->builder == nullptr);
11704       struct compunit_symtab *cust = tu_group->compunit_symtab;
11705       cu->builder.reset (new struct buildsym_compunit
11706                          (COMPUNIT_OBJFILE (cust), "",
11707                           COMPUNIT_DIRNAME (cust),
11708                           compunit_language (cust),
11709                           0, cust));
11710
11711       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11712         {
11713           file_entry &fe = cu->line_header->file_names[i];
11714
11715           fe.symtab = tu_group->symtabs[i];
11716         }
11717     }
11718
11719   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11720      so they don't have a "real" (so to speak) symtab anyway.
11721      There is later code that will assign the main symtab to all symbols
11722      that don't have one.  We need to handle the case of a symbol with a
11723      missing symtab (DW_AT_decl_file) anyway.  */
11724 }
11725
11726 /* Process DW_TAG_type_unit.
11727    For TUs we want to skip the first top level sibling if it's not the
11728    actual type being defined by this TU.  In this case the first top
11729    level sibling is there to provide context only.  */
11730
11731 static void
11732 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11733 {
11734   struct die_info *child_die;
11735
11736   prepare_one_comp_unit (cu, die, language_minimal);
11737
11738   /* Initialize (or reinitialize) the machinery for building symtabs.
11739      We do this before processing child DIEs, so that the line header table
11740      is available for DW_AT_decl_file.  */
11741   setup_type_unit_groups (die, cu);
11742
11743   if (die->child != NULL)
11744     {
11745       child_die = die->child;
11746       while (child_die && child_die->tag)
11747         {
11748           process_die (child_die, cu);
11749           child_die = sibling_die (child_die);
11750         }
11751     }
11752 }
11753 \f
11754 /* DWO/DWP files.
11755
11756    http://gcc.gnu.org/wiki/DebugFission
11757    http://gcc.gnu.org/wiki/DebugFissionDWP
11758
11759    To simplify handling of both DWO files ("object" files with the DWARF info)
11760    and DWP files (a file with the DWOs packaged up into one file), we treat
11761    DWP files as having a collection of virtual DWO files.  */
11762
11763 static hashval_t
11764 hash_dwo_file (const void *item)
11765 {
11766   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11767   hashval_t hash;
11768
11769   hash = htab_hash_string (dwo_file->dwo_name);
11770   if (dwo_file->comp_dir != NULL)
11771     hash += htab_hash_string (dwo_file->comp_dir);
11772   return hash;
11773 }
11774
11775 static int
11776 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11777 {
11778   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11779   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11780
11781   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11782     return 0;
11783   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11784     return lhs->comp_dir == rhs->comp_dir;
11785   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11786 }
11787
11788 /* Allocate a hash table for DWO files.  */
11789
11790 static htab_t
11791 allocate_dwo_file_hash_table (struct objfile *objfile)
11792 {
11793   return htab_create_alloc_ex (41,
11794                                hash_dwo_file,
11795                                eq_dwo_file,
11796                                NULL,
11797                                &objfile->objfile_obstack,
11798                                hashtab_obstack_allocate,
11799                                dummy_obstack_deallocate);
11800 }
11801
11802 /* Lookup DWO file DWO_NAME.  */
11803
11804 static void **
11805 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11806                       const char *dwo_name,
11807                       const char *comp_dir)
11808 {
11809   struct dwo_file find_entry;
11810   void **slot;
11811
11812   if (dwarf2_per_objfile->dwo_files == NULL)
11813     dwarf2_per_objfile->dwo_files
11814       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11815
11816   memset (&find_entry, 0, sizeof (find_entry));
11817   find_entry.dwo_name = dwo_name;
11818   find_entry.comp_dir = comp_dir;
11819   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11820
11821   return slot;
11822 }
11823
11824 static hashval_t
11825 hash_dwo_unit (const void *item)
11826 {
11827   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11828
11829   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11830   return dwo_unit->signature;
11831 }
11832
11833 static int
11834 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11835 {
11836   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11837   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11838
11839   /* The signature is assumed to be unique within the DWO file.
11840      So while object file CU dwo_id's always have the value zero,
11841      that's OK, assuming each object file DWO file has only one CU,
11842      and that's the rule for now.  */
11843   return lhs->signature == rhs->signature;
11844 }
11845
11846 /* Allocate a hash table for DWO CUs,TUs.
11847    There is one of these tables for each of CUs,TUs for each DWO file.  */
11848
11849 static htab_t
11850 allocate_dwo_unit_table (struct objfile *objfile)
11851 {
11852   /* Start out with a pretty small number.
11853      Generally DWO files contain only one CU and maybe some TUs.  */
11854   return htab_create_alloc_ex (3,
11855                                hash_dwo_unit,
11856                                eq_dwo_unit,
11857                                NULL,
11858                                &objfile->objfile_obstack,
11859                                hashtab_obstack_allocate,
11860                                dummy_obstack_deallocate);
11861 }
11862
11863 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11864
11865 struct create_dwo_cu_data
11866 {
11867   struct dwo_file *dwo_file;
11868   struct dwo_unit dwo_unit;
11869 };
11870
11871 /* die_reader_func for create_dwo_cu.  */
11872
11873 static void
11874 create_dwo_cu_reader (const struct die_reader_specs *reader,
11875                       const gdb_byte *info_ptr,
11876                       struct die_info *comp_unit_die,
11877                       int has_children,
11878                       void *datap)
11879 {
11880   struct dwarf2_cu *cu = reader->cu;
11881   sect_offset sect_off = cu->per_cu->sect_off;
11882   struct dwarf2_section_info *section = cu->per_cu->section;
11883   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11884   struct dwo_file *dwo_file = data->dwo_file;
11885   struct dwo_unit *dwo_unit = &data->dwo_unit;
11886   struct attribute *attr;
11887
11888   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11889   if (attr == NULL)
11890     {
11891       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11892                    " its dwo_id [in module %s]"),
11893                  sect_offset_str (sect_off), dwo_file->dwo_name);
11894       return;
11895     }
11896
11897   dwo_unit->dwo_file = dwo_file;
11898   dwo_unit->signature = DW_UNSND (attr);
11899   dwo_unit->section = section;
11900   dwo_unit->sect_off = sect_off;
11901   dwo_unit->length = cu->per_cu->length;
11902
11903   if (dwarf_read_debug)
11904     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11905                         sect_offset_str (sect_off),
11906                         hex_string (dwo_unit->signature));
11907 }
11908
11909 /* Create the dwo_units for the CUs in a DWO_FILE.
11910    Note: This function processes DWO files only, not DWP files.  */
11911
11912 static void
11913 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11914                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11915                        htab_t &cus_htab)
11916 {
11917   struct objfile *objfile = dwarf2_per_objfile->objfile;
11918   const gdb_byte *info_ptr, *end_ptr;
11919
11920   dwarf2_read_section (objfile, &section);
11921   info_ptr = section.buffer;
11922
11923   if (info_ptr == NULL)
11924     return;
11925
11926   if (dwarf_read_debug)
11927     {
11928       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11929                           get_section_name (&section),
11930                           get_section_file_name (&section));
11931     }
11932
11933   end_ptr = info_ptr + section.size;
11934   while (info_ptr < end_ptr)
11935     {
11936       struct dwarf2_per_cu_data per_cu;
11937       struct create_dwo_cu_data create_dwo_cu_data;
11938       struct dwo_unit *dwo_unit;
11939       void **slot;
11940       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11941
11942       memset (&create_dwo_cu_data.dwo_unit, 0,
11943               sizeof (create_dwo_cu_data.dwo_unit));
11944       memset (&per_cu, 0, sizeof (per_cu));
11945       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11946       per_cu.is_debug_types = 0;
11947       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11948       per_cu.section = &section;
11949       create_dwo_cu_data.dwo_file = &dwo_file;
11950
11951       init_cutu_and_read_dies_no_follow (
11952           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11953       info_ptr += per_cu.length;
11954
11955       // If the unit could not be parsed, skip it.
11956       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11957         continue;
11958
11959       if (cus_htab == NULL)
11960         cus_htab = allocate_dwo_unit_table (objfile);
11961
11962       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11963       *dwo_unit = create_dwo_cu_data.dwo_unit;
11964       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11965       gdb_assert (slot != NULL);
11966       if (*slot != NULL)
11967         {
11968           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11969           sect_offset dup_sect_off = dup_cu->sect_off;
11970
11971           complaint (_("debug cu entry at offset %s is duplicate to"
11972                        " the entry at offset %s, signature %s"),
11973                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11974                      hex_string (dwo_unit->signature));
11975         }
11976       *slot = (void *)dwo_unit;
11977     }
11978 }
11979
11980 /* DWP file .debug_{cu,tu}_index section format:
11981    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11982
11983    DWP Version 1:
11984
11985    Both index sections have the same format, and serve to map a 64-bit
11986    signature to a set of section numbers.  Each section begins with a header,
11987    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11988    indexes, and a pool of 32-bit section numbers.  The index sections will be
11989    aligned at 8-byte boundaries in the file.
11990
11991    The index section header consists of:
11992
11993     V, 32 bit version number
11994     -, 32 bits unused
11995     N, 32 bit number of compilation units or type units in the index
11996     M, 32 bit number of slots in the hash table
11997
11998    Numbers are recorded using the byte order of the application binary.
11999
12000    The hash table begins at offset 16 in the section, and consists of an array
12001    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12002    order of the application binary).  Unused slots in the hash table are 0.
12003    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12004
12005    The parallel table begins immediately after the hash table
12006    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12007    array of 32-bit indexes (using the byte order of the application binary),
12008    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12009    table contains a 32-bit index into the pool of section numbers.  For unused
12010    hash table slots, the corresponding entry in the parallel table will be 0.
12011
12012    The pool of section numbers begins immediately following the hash table
12013    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12014    section numbers consists of an array of 32-bit words (using the byte order
12015    of the application binary).  Each item in the array is indexed starting
12016    from 0.  The hash table entry provides the index of the first section
12017    number in the set.  Additional section numbers in the set follow, and the
12018    set is terminated by a 0 entry (section number 0 is not used in ELF).
12019
12020    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12021    section must be the first entry in the set, and the .debug_abbrev.dwo must
12022    be the second entry. Other members of the set may follow in any order.
12023
12024    ---
12025
12026    DWP Version 2:
12027
12028    DWP Version 2 combines all the .debug_info, etc. sections into one,
12029    and the entries in the index tables are now offsets into these sections.
12030    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12031    section.
12032
12033    Index Section Contents:
12034     Header
12035     Hash Table of Signatures   dwp_hash_table.hash_table
12036     Parallel Table of Indices  dwp_hash_table.unit_table
12037     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12038     Table of Section Sizes     dwp_hash_table.v2.sizes
12039
12040    The index section header consists of:
12041
12042     V, 32 bit version number
12043     L, 32 bit number of columns in the table of section offsets
12044     N, 32 bit number of compilation units or type units in the index
12045     M, 32 bit number of slots in the hash table
12046
12047    Numbers are recorded using the byte order of the application binary.
12048
12049    The hash table has the same format as version 1.
12050    The parallel table of indices has the same format as version 1,
12051    except that the entries are origin-1 indices into the table of sections
12052    offsets and the table of section sizes.
12053
12054    The table of offsets begins immediately following the parallel table
12055    (at offset 16 + 12 * M from the beginning of the section).  The table is
12056    a two-dimensional array of 32-bit words (using the byte order of the
12057    application binary), with L columns and N+1 rows, in row-major order.
12058    Each row in the array is indexed starting from 0.  The first row provides
12059    a key to the remaining rows: each column in this row provides an identifier
12060    for a debug section, and the offsets in the same column of subsequent rows
12061    refer to that section.  The section identifiers are:
12062
12063     DW_SECT_INFO         1  .debug_info.dwo
12064     DW_SECT_TYPES        2  .debug_types.dwo
12065     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12066     DW_SECT_LINE         4  .debug_line.dwo
12067     DW_SECT_LOC          5  .debug_loc.dwo
12068     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12069     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12070     DW_SECT_MACRO        8  .debug_macro.dwo
12071
12072    The offsets provided by the CU and TU index sections are the base offsets
12073    for the contributions made by each CU or TU to the corresponding section
12074    in the package file.  Each CU and TU header contains an abbrev_offset
12075    field, used to find the abbreviations table for that CU or TU within the
12076    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12077    be interpreted as relative to the base offset given in the index section.
12078    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12079    should be interpreted as relative to the base offset for .debug_line.dwo,
12080    and offsets into other debug sections obtained from DWARF attributes should
12081    also be interpreted as relative to the corresponding base offset.
12082
12083    The table of sizes begins immediately following the table of offsets.
12084    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12085    with L columns and N rows, in row-major order.  Each row in the array is
12086    indexed starting from 1 (row 0 is shared by the two tables).
12087
12088    ---
12089
12090    Hash table lookup is handled the same in version 1 and 2:
12091
12092    We assume that N and M will not exceed 2^32 - 1.
12093    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12094
12095    Given a 64-bit compilation unit signature or a type signature S, an entry
12096    in the hash table is located as follows:
12097
12098    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12099       the low-order k bits all set to 1.
12100
12101    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12102
12103    3) If the hash table entry at index H matches the signature, use that
12104       entry.  If the hash table entry at index H is unused (all zeroes),
12105       terminate the search: the signature is not present in the table.
12106
12107    4) Let H = (H + H') modulo M. Repeat at Step 3.
12108
12109    Because M > N and H' and M are relatively prime, the search is guaranteed
12110    to stop at an unused slot or find the match.  */
12111
12112 /* Create a hash table to map DWO IDs to their CU/TU entry in
12113    .debug_{info,types}.dwo in DWP_FILE.
12114    Returns NULL if there isn't one.
12115    Note: This function processes DWP files only, not DWO files.  */
12116
12117 static struct dwp_hash_table *
12118 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12119                        struct dwp_file *dwp_file, int is_debug_types)
12120 {
12121   struct objfile *objfile = dwarf2_per_objfile->objfile;
12122   bfd *dbfd = dwp_file->dbfd.get ();
12123   const gdb_byte *index_ptr, *index_end;
12124   struct dwarf2_section_info *index;
12125   uint32_t version, nr_columns, nr_units, nr_slots;
12126   struct dwp_hash_table *htab;
12127
12128   if (is_debug_types)
12129     index = &dwp_file->sections.tu_index;
12130   else
12131     index = &dwp_file->sections.cu_index;
12132
12133   if (dwarf2_section_empty_p (index))
12134     return NULL;
12135   dwarf2_read_section (objfile, index);
12136
12137   index_ptr = index->buffer;
12138   index_end = index_ptr + index->size;
12139
12140   version = read_4_bytes (dbfd, index_ptr);
12141   index_ptr += 4;
12142   if (version == 2)
12143     nr_columns = read_4_bytes (dbfd, index_ptr);
12144   else
12145     nr_columns = 0;
12146   index_ptr += 4;
12147   nr_units = read_4_bytes (dbfd, index_ptr);
12148   index_ptr += 4;
12149   nr_slots = read_4_bytes (dbfd, index_ptr);
12150   index_ptr += 4;
12151
12152   if (version != 1 && version != 2)
12153     {
12154       error (_("Dwarf Error: unsupported DWP file version (%s)"
12155                " [in module %s]"),
12156              pulongest (version), dwp_file->name);
12157     }
12158   if (nr_slots != (nr_slots & -nr_slots))
12159     {
12160       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12161                " is not power of 2 [in module %s]"),
12162              pulongest (nr_slots), dwp_file->name);
12163     }
12164
12165   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12166   htab->version = version;
12167   htab->nr_columns = nr_columns;
12168   htab->nr_units = nr_units;
12169   htab->nr_slots = nr_slots;
12170   htab->hash_table = index_ptr;
12171   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12172
12173   /* Exit early if the table is empty.  */
12174   if (nr_slots == 0 || nr_units == 0
12175       || (version == 2 && nr_columns == 0))
12176     {
12177       /* All must be zero.  */
12178       if (nr_slots != 0 || nr_units != 0
12179           || (version == 2 && nr_columns != 0))
12180         {
12181           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12182                        " all zero [in modules %s]"),
12183                      dwp_file->name);
12184         }
12185       return htab;
12186     }
12187
12188   if (version == 1)
12189     {
12190       htab->section_pool.v1.indices =
12191         htab->unit_table + sizeof (uint32_t) * nr_slots;
12192       /* It's harder to decide whether the section is too small in v1.
12193          V1 is deprecated anyway so we punt.  */
12194     }
12195   else
12196     {
12197       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12198       int *ids = htab->section_pool.v2.section_ids;
12199       size_t sizeof_ids = sizeof (htab->section_pool.v2.section_ids);
12200       /* Reverse map for error checking.  */
12201       int ids_seen[DW_SECT_MAX + 1];
12202       int i;
12203
12204       if (nr_columns < 2)
12205         {
12206           error (_("Dwarf Error: bad DWP hash table, too few columns"
12207                    " in section table [in module %s]"),
12208                  dwp_file->name);
12209         }
12210       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12211         {
12212           error (_("Dwarf Error: bad DWP hash table, too many columns"
12213                    " in section table [in module %s]"),
12214                  dwp_file->name);
12215         }
12216       memset (ids, 255, sizeof_ids);
12217       memset (ids_seen, 255, sizeof (ids_seen));
12218       for (i = 0; i < nr_columns; ++i)
12219         {
12220           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12221
12222           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12223             {
12224               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12225                        " in section table [in module %s]"),
12226                      id, dwp_file->name);
12227             }
12228           if (ids_seen[id] != -1)
12229             {
12230               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12231                        " id %d in section table [in module %s]"),
12232                      id, dwp_file->name);
12233             }
12234           ids_seen[id] = i;
12235           ids[i] = id;
12236         }
12237       /* Must have exactly one info or types section.  */
12238       if (((ids_seen[DW_SECT_INFO] != -1)
12239            + (ids_seen[DW_SECT_TYPES] != -1))
12240           != 1)
12241         {
12242           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12243                    " DWO info/types section [in module %s]"),
12244                  dwp_file->name);
12245         }
12246       /* Must have an abbrev section.  */
12247       if (ids_seen[DW_SECT_ABBREV] == -1)
12248         {
12249           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12250                    " section [in module %s]"),
12251                  dwp_file->name);
12252         }
12253       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12254       htab->section_pool.v2.sizes =
12255         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12256                                          * nr_units * nr_columns);
12257       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12258                                           * nr_units * nr_columns))
12259           > index_end)
12260         {
12261           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12262                    " [in module %s]"),
12263                  dwp_file->name);
12264         }
12265     }
12266
12267   return htab;
12268 }
12269
12270 /* Update SECTIONS with the data from SECTP.
12271
12272    This function is like the other "locate" section routines that are
12273    passed to bfd_map_over_sections, but in this context the sections to
12274    read comes from the DWP V1 hash table, not the full ELF section table.
12275
12276    The result is non-zero for success, or zero if an error was found.  */
12277
12278 static int
12279 locate_v1_virtual_dwo_sections (asection *sectp,
12280                                 struct virtual_v1_dwo_sections *sections)
12281 {
12282   const struct dwop_section_names *names = &dwop_section_names;
12283
12284   if (section_is_p (sectp->name, &names->abbrev_dwo))
12285     {
12286       /* There can be only one.  */
12287       if (sections->abbrev.s.section != NULL)
12288         return 0;
12289       sections->abbrev.s.section = sectp;
12290       sections->abbrev.size = bfd_get_section_size (sectp);
12291     }
12292   else if (section_is_p (sectp->name, &names->info_dwo)
12293            || section_is_p (sectp->name, &names->types_dwo))
12294     {
12295       /* There can be only one.  */
12296       if (sections->info_or_types.s.section != NULL)
12297         return 0;
12298       sections->info_or_types.s.section = sectp;
12299       sections->info_or_types.size = bfd_get_section_size (sectp);
12300     }
12301   else if (section_is_p (sectp->name, &names->line_dwo))
12302     {
12303       /* There can be only one.  */
12304       if (sections->line.s.section != NULL)
12305         return 0;
12306       sections->line.s.section = sectp;
12307       sections->line.size = bfd_get_section_size (sectp);
12308     }
12309   else if (section_is_p (sectp->name, &names->loc_dwo))
12310     {
12311       /* There can be only one.  */
12312       if (sections->loc.s.section != NULL)
12313         return 0;
12314       sections->loc.s.section = sectp;
12315       sections->loc.size = bfd_get_section_size (sectp);
12316     }
12317   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12318     {
12319       /* There can be only one.  */
12320       if (sections->macinfo.s.section != NULL)
12321         return 0;
12322       sections->macinfo.s.section = sectp;
12323       sections->macinfo.size = bfd_get_section_size (sectp);
12324     }
12325   else if (section_is_p (sectp->name, &names->macro_dwo))
12326     {
12327       /* There can be only one.  */
12328       if (sections->macro.s.section != NULL)
12329         return 0;
12330       sections->macro.s.section = sectp;
12331       sections->macro.size = bfd_get_section_size (sectp);
12332     }
12333   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12334     {
12335       /* There can be only one.  */
12336       if (sections->str_offsets.s.section != NULL)
12337         return 0;
12338       sections->str_offsets.s.section = sectp;
12339       sections->str_offsets.size = bfd_get_section_size (sectp);
12340     }
12341   else
12342     {
12343       /* No other kind of section is valid.  */
12344       return 0;
12345     }
12346
12347   return 1;
12348 }
12349
12350 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12351    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12352    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12353    This is for DWP version 1 files.  */
12354
12355 static struct dwo_unit *
12356 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12357                            struct dwp_file *dwp_file,
12358                            uint32_t unit_index,
12359                            const char *comp_dir,
12360                            ULONGEST signature, int is_debug_types)
12361 {
12362   struct objfile *objfile = dwarf2_per_objfile->objfile;
12363   const struct dwp_hash_table *dwp_htab =
12364     is_debug_types ? dwp_file->tus : dwp_file->cus;
12365   bfd *dbfd = dwp_file->dbfd.get ();
12366   const char *kind = is_debug_types ? "TU" : "CU";
12367   struct dwo_file *dwo_file;
12368   struct dwo_unit *dwo_unit;
12369   struct virtual_v1_dwo_sections sections;
12370   void **dwo_file_slot;
12371   int i;
12372
12373   gdb_assert (dwp_file->version == 1);
12374
12375   if (dwarf_read_debug)
12376     {
12377       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12378                           kind,
12379                           pulongest (unit_index), hex_string (signature),
12380                           dwp_file->name);
12381     }
12382
12383   /* Fetch the sections of this DWO unit.
12384      Put a limit on the number of sections we look for so that bad data
12385      doesn't cause us to loop forever.  */
12386
12387 #define MAX_NR_V1_DWO_SECTIONS \
12388   (1 /* .debug_info or .debug_types */ \
12389    + 1 /* .debug_abbrev */ \
12390    + 1 /* .debug_line */ \
12391    + 1 /* .debug_loc */ \
12392    + 1 /* .debug_str_offsets */ \
12393    + 1 /* .debug_macro or .debug_macinfo */ \
12394    + 1 /* trailing zero */)
12395
12396   memset (&sections, 0, sizeof (sections));
12397
12398   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12399     {
12400       asection *sectp;
12401       uint32_t section_nr =
12402         read_4_bytes (dbfd,
12403                       dwp_htab->section_pool.v1.indices
12404                       + (unit_index + i) * sizeof (uint32_t));
12405
12406       if (section_nr == 0)
12407         break;
12408       if (section_nr >= dwp_file->num_sections)
12409         {
12410           error (_("Dwarf Error: bad DWP hash table, section number too large"
12411                    " [in module %s]"),
12412                  dwp_file->name);
12413         }
12414
12415       sectp = dwp_file->elf_sections[section_nr];
12416       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12417         {
12418           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12419                    " [in module %s]"),
12420                  dwp_file->name);
12421         }
12422     }
12423
12424   if (i < 2
12425       || dwarf2_section_empty_p (&sections.info_or_types)
12426       || dwarf2_section_empty_p (&sections.abbrev))
12427     {
12428       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12429                " [in module %s]"),
12430              dwp_file->name);
12431     }
12432   if (i == MAX_NR_V1_DWO_SECTIONS)
12433     {
12434       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12435                " [in module %s]"),
12436              dwp_file->name);
12437     }
12438
12439   /* It's easier for the rest of the code if we fake a struct dwo_file and
12440      have dwo_unit "live" in that.  At least for now.
12441
12442      The DWP file can be made up of a random collection of CUs and TUs.
12443      However, for each CU + set of TUs that came from the same original DWO
12444      file, we can combine them back into a virtual DWO file to save space
12445      (fewer struct dwo_file objects to allocate).  Remember that for really
12446      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12447
12448   std::string virtual_dwo_name =
12449     string_printf ("virtual-dwo/%d-%d-%d-%d",
12450                    get_section_id (&sections.abbrev),
12451                    get_section_id (&sections.line),
12452                    get_section_id (&sections.loc),
12453                    get_section_id (&sections.str_offsets));
12454   /* Can we use an existing virtual DWO file?  */
12455   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12456                                         virtual_dwo_name.c_str (),
12457                                         comp_dir);
12458   /* Create one if necessary.  */
12459   if (*dwo_file_slot == NULL)
12460     {
12461       if (dwarf_read_debug)
12462         {
12463           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12464                               virtual_dwo_name.c_str ());
12465         }
12466       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12467       dwo_file->dwo_name
12468         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12469                                         virtual_dwo_name.c_str (),
12470                                         virtual_dwo_name.size ());
12471       dwo_file->comp_dir = comp_dir;
12472       dwo_file->sections.abbrev = sections.abbrev;
12473       dwo_file->sections.line = sections.line;
12474       dwo_file->sections.loc = sections.loc;
12475       dwo_file->sections.macinfo = sections.macinfo;
12476       dwo_file->sections.macro = sections.macro;
12477       dwo_file->sections.str_offsets = sections.str_offsets;
12478       /* The "str" section is global to the entire DWP file.  */
12479       dwo_file->sections.str = dwp_file->sections.str;
12480       /* The info or types section is assigned below to dwo_unit,
12481          there's no need to record it in dwo_file.
12482          Also, we can't simply record type sections in dwo_file because
12483          we record a pointer into the vector in dwo_unit.  As we collect more
12484          types we'll grow the vector and eventually have to reallocate space
12485          for it, invalidating all copies of pointers into the previous
12486          contents.  */
12487       *dwo_file_slot = dwo_file;
12488     }
12489   else
12490     {
12491       if (dwarf_read_debug)
12492         {
12493           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12494                               virtual_dwo_name.c_str ());
12495         }
12496       dwo_file = (struct dwo_file *) *dwo_file_slot;
12497     }
12498
12499   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12500   dwo_unit->dwo_file = dwo_file;
12501   dwo_unit->signature = signature;
12502   dwo_unit->section =
12503     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12504   *dwo_unit->section = sections.info_or_types;
12505   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12506
12507   return dwo_unit;
12508 }
12509
12510 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12511    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12512    piece within that section used by a TU/CU, return a virtual section
12513    of just that piece.  */
12514
12515 static struct dwarf2_section_info
12516 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12517                        struct dwarf2_section_info *section,
12518                        bfd_size_type offset, bfd_size_type size)
12519 {
12520   struct dwarf2_section_info result;
12521   asection *sectp;
12522
12523   gdb_assert (section != NULL);
12524   gdb_assert (!section->is_virtual);
12525
12526   memset (&result, 0, sizeof (result));
12527   result.s.containing_section = section;
12528   result.is_virtual = 1;
12529
12530   if (size == 0)
12531     return result;
12532
12533   sectp = get_section_bfd_section (section);
12534
12535   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12536      bounds of the real section.  This is a pretty-rare event, so just
12537      flag an error (easier) instead of a warning and trying to cope.  */
12538   if (sectp == NULL
12539       || offset + size > bfd_get_section_size (sectp))
12540     {
12541       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12542                " in section %s [in module %s]"),
12543              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12544              objfile_name (dwarf2_per_objfile->objfile));
12545     }
12546
12547   result.virtual_offset = offset;
12548   result.size = size;
12549   return result;
12550 }
12551
12552 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12553    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12554    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12555    This is for DWP version 2 files.  */
12556
12557 static struct dwo_unit *
12558 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12559                            struct dwp_file *dwp_file,
12560                            uint32_t unit_index,
12561                            const char *comp_dir,
12562                            ULONGEST signature, int is_debug_types)
12563 {
12564   struct objfile *objfile = dwarf2_per_objfile->objfile;
12565   const struct dwp_hash_table *dwp_htab =
12566     is_debug_types ? dwp_file->tus : dwp_file->cus;
12567   bfd *dbfd = dwp_file->dbfd.get ();
12568   const char *kind = is_debug_types ? "TU" : "CU";
12569   struct dwo_file *dwo_file;
12570   struct dwo_unit *dwo_unit;
12571   struct virtual_v2_dwo_sections sections;
12572   void **dwo_file_slot;
12573   int i;
12574
12575   gdb_assert (dwp_file->version == 2);
12576
12577   if (dwarf_read_debug)
12578     {
12579       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12580                           kind,
12581                           pulongest (unit_index), hex_string (signature),
12582                           dwp_file->name);
12583     }
12584
12585   /* Fetch the section offsets of this DWO unit.  */
12586
12587   memset (&sections, 0, sizeof (sections));
12588
12589   for (i = 0; i < dwp_htab->nr_columns; ++i)
12590     {
12591       uint32_t offset = read_4_bytes (dbfd,
12592                                       dwp_htab->section_pool.v2.offsets
12593                                       + (((unit_index - 1) * dwp_htab->nr_columns
12594                                           + i)
12595                                          * sizeof (uint32_t)));
12596       uint32_t size = read_4_bytes (dbfd,
12597                                     dwp_htab->section_pool.v2.sizes
12598                                     + (((unit_index - 1) * dwp_htab->nr_columns
12599                                         + i)
12600                                        * sizeof (uint32_t)));
12601
12602       switch (dwp_htab->section_pool.v2.section_ids[i])
12603         {
12604         case DW_SECT_INFO:
12605         case DW_SECT_TYPES:
12606           sections.info_or_types_offset = offset;
12607           sections.info_or_types_size = size;
12608           break;
12609         case DW_SECT_ABBREV:
12610           sections.abbrev_offset = offset;
12611           sections.abbrev_size = size;
12612           break;
12613         case DW_SECT_LINE:
12614           sections.line_offset = offset;
12615           sections.line_size = size;
12616           break;
12617         case DW_SECT_LOC:
12618           sections.loc_offset = offset;
12619           sections.loc_size = size;
12620           break;
12621         case DW_SECT_STR_OFFSETS:
12622           sections.str_offsets_offset = offset;
12623           sections.str_offsets_size = size;
12624           break;
12625         case DW_SECT_MACINFO:
12626           sections.macinfo_offset = offset;
12627           sections.macinfo_size = size;
12628           break;
12629         case DW_SECT_MACRO:
12630           sections.macro_offset = offset;
12631           sections.macro_size = size;
12632           break;
12633         }
12634     }
12635
12636   /* It's easier for the rest of the code if we fake a struct dwo_file and
12637      have dwo_unit "live" in that.  At least for now.
12638
12639      The DWP file can be made up of a random collection of CUs and TUs.
12640      However, for each CU + set of TUs that came from the same original DWO
12641      file, we can combine them back into a virtual DWO file to save space
12642      (fewer struct dwo_file objects to allocate).  Remember that for really
12643      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12644
12645   std::string virtual_dwo_name =
12646     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12647                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12648                    (long) (sections.line_size ? sections.line_offset : 0),
12649                    (long) (sections.loc_size ? sections.loc_offset : 0),
12650                    (long) (sections.str_offsets_size
12651                            ? sections.str_offsets_offset : 0));
12652   /* Can we use an existing virtual DWO file?  */
12653   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12654                                         virtual_dwo_name.c_str (),
12655                                         comp_dir);
12656   /* Create one if necessary.  */
12657   if (*dwo_file_slot == NULL)
12658     {
12659       if (dwarf_read_debug)
12660         {
12661           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12662                               virtual_dwo_name.c_str ());
12663         }
12664       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12665       dwo_file->dwo_name
12666         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12667                                         virtual_dwo_name.c_str (),
12668                                         virtual_dwo_name.size ());
12669       dwo_file->comp_dir = comp_dir;
12670       dwo_file->sections.abbrev =
12671         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12672                                sections.abbrev_offset, sections.abbrev_size);
12673       dwo_file->sections.line =
12674         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12675                                sections.line_offset, sections.line_size);
12676       dwo_file->sections.loc =
12677         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12678                                sections.loc_offset, sections.loc_size);
12679       dwo_file->sections.macinfo =
12680         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12681                                sections.macinfo_offset, sections.macinfo_size);
12682       dwo_file->sections.macro =
12683         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12684                                sections.macro_offset, sections.macro_size);
12685       dwo_file->sections.str_offsets =
12686         create_dwp_v2_section (dwarf2_per_objfile,
12687                                &dwp_file->sections.str_offsets,
12688                                sections.str_offsets_offset,
12689                                sections.str_offsets_size);
12690       /* The "str" section is global to the entire DWP file.  */
12691       dwo_file->sections.str = dwp_file->sections.str;
12692       /* The info or types section is assigned below to dwo_unit,
12693          there's no need to record it in dwo_file.
12694          Also, we can't simply record type sections in dwo_file because
12695          we record a pointer into the vector in dwo_unit.  As we collect more
12696          types we'll grow the vector and eventually have to reallocate space
12697          for it, invalidating all copies of pointers into the previous
12698          contents.  */
12699       *dwo_file_slot = dwo_file;
12700     }
12701   else
12702     {
12703       if (dwarf_read_debug)
12704         {
12705           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12706                               virtual_dwo_name.c_str ());
12707         }
12708       dwo_file = (struct dwo_file *) *dwo_file_slot;
12709     }
12710
12711   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12712   dwo_unit->dwo_file = dwo_file;
12713   dwo_unit->signature = signature;
12714   dwo_unit->section =
12715     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12716   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12717                                               is_debug_types
12718                                               ? &dwp_file->sections.types
12719                                               : &dwp_file->sections.info,
12720                                               sections.info_or_types_offset,
12721                                               sections.info_or_types_size);
12722   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12723
12724   return dwo_unit;
12725 }
12726
12727 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12728    Returns NULL if the signature isn't found.  */
12729
12730 static struct dwo_unit *
12731 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12732                         struct dwp_file *dwp_file, const char *comp_dir,
12733                         ULONGEST signature, int is_debug_types)
12734 {
12735   const struct dwp_hash_table *dwp_htab =
12736     is_debug_types ? dwp_file->tus : dwp_file->cus;
12737   bfd *dbfd = dwp_file->dbfd.get ();
12738   uint32_t mask = dwp_htab->nr_slots - 1;
12739   uint32_t hash = signature & mask;
12740   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12741   unsigned int i;
12742   void **slot;
12743   struct dwo_unit find_dwo_cu;
12744
12745   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12746   find_dwo_cu.signature = signature;
12747   slot = htab_find_slot (is_debug_types
12748                          ? dwp_file->loaded_tus
12749                          : dwp_file->loaded_cus,
12750                          &find_dwo_cu, INSERT);
12751
12752   if (*slot != NULL)
12753     return (struct dwo_unit *) *slot;
12754
12755   /* Use a for loop so that we don't loop forever on bad debug info.  */
12756   for (i = 0; i < dwp_htab->nr_slots; ++i)
12757     {
12758       ULONGEST signature_in_table;
12759
12760       signature_in_table =
12761         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12762       if (signature_in_table == signature)
12763         {
12764           uint32_t unit_index =
12765             read_4_bytes (dbfd,
12766                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12767
12768           if (dwp_file->version == 1)
12769             {
12770               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12771                                                  dwp_file, unit_index,
12772                                                  comp_dir, signature,
12773                                                  is_debug_types);
12774             }
12775           else
12776             {
12777               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12778                                                  dwp_file, unit_index,
12779                                                  comp_dir, signature,
12780                                                  is_debug_types);
12781             }
12782           return (struct dwo_unit *) *slot;
12783         }
12784       if (signature_in_table == 0)
12785         return NULL;
12786       hash = (hash + hash2) & mask;
12787     }
12788
12789   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12790            " [in module %s]"),
12791          dwp_file->name);
12792 }
12793
12794 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12795    Open the file specified by FILE_NAME and hand it off to BFD for
12796    preliminary analysis.  Return a newly initialized bfd *, which
12797    includes a canonicalized copy of FILE_NAME.
12798    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12799    SEARCH_CWD is true if the current directory is to be searched.
12800    It will be searched before debug-file-directory.
12801    If successful, the file is added to the bfd include table of the
12802    objfile's bfd (see gdb_bfd_record_inclusion).
12803    If unable to find/open the file, return NULL.
12804    NOTE: This function is derived from symfile_bfd_open.  */
12805
12806 static gdb_bfd_ref_ptr
12807 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12808                     const char *file_name, int is_dwp, int search_cwd)
12809 {
12810   int desc;
12811   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12812      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12813      to debug_file_directory.  */
12814   const char *search_path;
12815   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12816
12817   gdb::unique_xmalloc_ptr<char> search_path_holder;
12818   if (search_cwd)
12819     {
12820       if (*debug_file_directory != '\0')
12821         {
12822           search_path_holder.reset (concat (".", dirname_separator_string,
12823                                             debug_file_directory,
12824                                             (char *) NULL));
12825           search_path = search_path_holder.get ();
12826         }
12827       else
12828         search_path = ".";
12829     }
12830   else
12831     search_path = debug_file_directory;
12832
12833   openp_flags flags = OPF_RETURN_REALPATH;
12834   if (is_dwp)
12835     flags |= OPF_SEARCH_IN_PATH;
12836
12837   gdb::unique_xmalloc_ptr<char> absolute_name;
12838   desc = openp (search_path, flags, file_name,
12839                 O_RDONLY | O_BINARY, &absolute_name);
12840   if (desc < 0)
12841     return NULL;
12842
12843   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12844                                          gnutarget, desc));
12845   if (sym_bfd == NULL)
12846     return NULL;
12847   bfd_set_cacheable (sym_bfd.get (), 1);
12848
12849   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12850     return NULL;
12851
12852   /* Success.  Record the bfd as having been included by the objfile's bfd.
12853      This is important because things like demangled_names_hash lives in the
12854      objfile's per_bfd space and may have references to things like symbol
12855      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12856   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12857
12858   return sym_bfd;
12859 }
12860
12861 /* Try to open DWO file FILE_NAME.
12862    COMP_DIR is the DW_AT_comp_dir attribute.
12863    The result is the bfd handle of the file.
12864    If there is a problem finding or opening the file, return NULL.
12865    Upon success, the canonicalized path of the file is stored in the bfd,
12866    same as symfile_bfd_open.  */
12867
12868 static gdb_bfd_ref_ptr
12869 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12870                const char *file_name, const char *comp_dir)
12871 {
12872   if (IS_ABSOLUTE_PATH (file_name))
12873     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12874                                0 /*is_dwp*/, 0 /*search_cwd*/);
12875
12876   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12877
12878   if (comp_dir != NULL)
12879     {
12880       char *path_to_try = concat (comp_dir, SLASH_STRING,
12881                                   file_name, (char *) NULL);
12882
12883       /* NOTE: If comp_dir is a relative path, this will also try the
12884          search path, which seems useful.  */
12885       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12886                                                 path_to_try,
12887                                                 0 /*is_dwp*/,
12888                                                 1 /*search_cwd*/));
12889       xfree (path_to_try);
12890       if (abfd != NULL)
12891         return abfd;
12892     }
12893
12894   /* That didn't work, try debug-file-directory, which, despite its name,
12895      is a list of paths.  */
12896
12897   if (*debug_file_directory == '\0')
12898     return NULL;
12899
12900   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12901                              0 /*is_dwp*/, 1 /*search_cwd*/);
12902 }
12903
12904 /* This function is mapped across the sections and remembers the offset and
12905    size of each of the DWO debugging sections we are interested in.  */
12906
12907 static void
12908 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12909 {
12910   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12911   const struct dwop_section_names *names = &dwop_section_names;
12912
12913   if (section_is_p (sectp->name, &names->abbrev_dwo))
12914     {
12915       dwo_sections->abbrev.s.section = sectp;
12916       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12917     }
12918   else if (section_is_p (sectp->name, &names->info_dwo))
12919     {
12920       dwo_sections->info.s.section = sectp;
12921       dwo_sections->info.size = bfd_get_section_size (sectp);
12922     }
12923   else if (section_is_p (sectp->name, &names->line_dwo))
12924     {
12925       dwo_sections->line.s.section = sectp;
12926       dwo_sections->line.size = bfd_get_section_size (sectp);
12927     }
12928   else if (section_is_p (sectp->name, &names->loc_dwo))
12929     {
12930       dwo_sections->loc.s.section = sectp;
12931       dwo_sections->loc.size = bfd_get_section_size (sectp);
12932     }
12933   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12934     {
12935       dwo_sections->macinfo.s.section = sectp;
12936       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12937     }
12938   else if (section_is_p (sectp->name, &names->macro_dwo))
12939     {
12940       dwo_sections->macro.s.section = sectp;
12941       dwo_sections->macro.size = bfd_get_section_size (sectp);
12942     }
12943   else if (section_is_p (sectp->name, &names->str_dwo))
12944     {
12945       dwo_sections->str.s.section = sectp;
12946       dwo_sections->str.size = bfd_get_section_size (sectp);
12947     }
12948   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12949     {
12950       dwo_sections->str_offsets.s.section = sectp;
12951       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12952     }
12953   else if (section_is_p (sectp->name, &names->types_dwo))
12954     {
12955       struct dwarf2_section_info type_section;
12956
12957       memset (&type_section, 0, sizeof (type_section));
12958       type_section.s.section = sectp;
12959       type_section.size = bfd_get_section_size (sectp);
12960       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12961                      &type_section);
12962     }
12963 }
12964
12965 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12966    by PER_CU.  This is for the non-DWP case.
12967    The result is NULL if DWO_NAME can't be found.  */
12968
12969 static struct dwo_file *
12970 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12971                         const char *dwo_name, const char *comp_dir)
12972 {
12973   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12974   struct objfile *objfile = dwarf2_per_objfile->objfile;
12975
12976   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12977   if (dbfd == NULL)
12978     {
12979       if (dwarf_read_debug)
12980         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12981       return NULL;
12982     }
12983
12984   /* We use a unique pointer here, despite the obstack allocation,
12985      because a dwo_file needs some cleanup if it is abandoned.  */
12986   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12987                                         struct dwo_file));
12988   dwo_file->dwo_name = dwo_name;
12989   dwo_file->comp_dir = comp_dir;
12990   dwo_file->dbfd = dbfd.release ();
12991
12992   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12993                          &dwo_file->sections);
12994
12995   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12996                          dwo_file->cus);
12997
12998   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12999                                  dwo_file->sections.types, dwo_file->tus);
13000
13001   if (dwarf_read_debug)
13002     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13003
13004   return dwo_file.release ();
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 std::unique_ptr<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
13184   /* Try to find first .dwp for the binary file before any symbolic links
13185      resolving.  */
13186
13187   /* If the objfile is a debug file, find the name of the real binary
13188      file and get the name of dwp file from there.  */
13189   std::string dwp_name;
13190   if (objfile->separate_debug_objfile_backlink != NULL)
13191     {
13192       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13193       const char *backlink_basename = lbasename (backlink->original_name);
13194
13195       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13196     }
13197   else
13198     dwp_name = objfile->original_name;
13199
13200   dwp_name += ".dwp";
13201
13202   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13203   if (dbfd == NULL
13204       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13205     {
13206       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13207       dwp_name = objfile_name (objfile);
13208       dwp_name += ".dwp";
13209       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13210     }
13211
13212   if (dbfd == NULL)
13213     {
13214       if (dwarf_read_debug)
13215         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13216       return std::unique_ptr<dwp_file> ();
13217     }
13218
13219   const char *name = bfd_get_filename (dbfd.get ());
13220   std::unique_ptr<struct dwp_file> dwp_file
13221     (new struct dwp_file (name, std::move (dbfd)));
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.get (),
13230                          dwarf2_locate_common_dwp_sections,
13231                          dwp_file.get ());
13232
13233   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13234                                          0);
13235
13236   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13237                                          1);
13238
13239   /* The DWP file version is stored in the hash table.  Oh well.  */
13240   if (dwp_file->cus && dwp_file->tus
13241       && dwp_file->cus->version != dwp_file->tus->version)
13242     {
13243       /* Technically speaking, we should try to limp along, but this is
13244          pretty bizarre.  We use pulongest here because that's the established
13245          portability solution (e.g, we cannot use %u for uint32_t).  */
13246       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13247                " TU version %s [in DWP file %s]"),
13248              pulongest (dwp_file->cus->version),
13249              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13250     }
13251
13252   if (dwp_file->cus)
13253     dwp_file->version = dwp_file->cus->version;
13254   else if (dwp_file->tus)
13255     dwp_file->version = dwp_file->tus->version;
13256   else
13257     dwp_file->version = 2;
13258
13259   if (dwp_file->version == 2)
13260     bfd_map_over_sections (dwp_file->dbfd.get (),
13261                            dwarf2_locate_v2_dwp_sections,
13262                            dwp_file.get ());
13263
13264   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13265   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13266
13267   if (dwarf_read_debug)
13268     {
13269       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13270       fprintf_unfiltered (gdb_stdlog,
13271                           "    %s CUs, %s TUs\n",
13272                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13273                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13274     }
13275
13276   return dwp_file;
13277 }
13278
13279 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13280
13281 static struct dwp_file *
13282 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13283 {
13284   if (! dwarf2_per_objfile->dwp_checked)
13285     {
13286       dwarf2_per_objfile->dwp_file
13287         = open_and_init_dwp_file (dwarf2_per_objfile);
13288       dwarf2_per_objfile->dwp_checked = 1;
13289     }
13290   return dwarf2_per_objfile->dwp_file.get ();
13291 }
13292
13293 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13294    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13295    or in the DWP file for the objfile, referenced by THIS_UNIT.
13296    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13297    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13298
13299    This is called, for example, when wanting to read a variable with a
13300    complex location.  Therefore we don't want to do file i/o for every call.
13301    Therefore we don't want to look for a DWO file on every call.
13302    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13303    then we check if we've already seen DWO_NAME, and only THEN do we check
13304    for a DWO file.
13305
13306    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13307    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13308
13309 static struct dwo_unit *
13310 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13311                  const char *dwo_name, const char *comp_dir,
13312                  ULONGEST signature, int is_debug_types)
13313 {
13314   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13315   struct objfile *objfile = dwarf2_per_objfile->objfile;
13316   const char *kind = is_debug_types ? "TU" : "CU";
13317   void **dwo_file_slot;
13318   struct dwo_file *dwo_file;
13319   struct dwp_file *dwp_file;
13320
13321   /* First see if there's a DWP file.
13322      If we have a DWP file but didn't find the DWO inside it, don't
13323      look for the original DWO file.  It makes gdb behave differently
13324      depending on whether one is debugging in the build tree.  */
13325
13326   dwp_file = get_dwp_file (dwarf2_per_objfile);
13327   if (dwp_file != NULL)
13328     {
13329       const struct dwp_hash_table *dwp_htab =
13330         is_debug_types ? dwp_file->tus : dwp_file->cus;
13331
13332       if (dwp_htab != NULL)
13333         {
13334           struct dwo_unit *dwo_cutu =
13335             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13336                                     signature, is_debug_types);
13337
13338           if (dwo_cutu != NULL)
13339             {
13340               if (dwarf_read_debug)
13341                 {
13342                   fprintf_unfiltered (gdb_stdlog,
13343                                       "Virtual DWO %s %s found: @%s\n",
13344                                       kind, hex_string (signature),
13345                                       host_address_to_string (dwo_cutu));
13346                 }
13347               return dwo_cutu;
13348             }
13349         }
13350     }
13351   else
13352     {
13353       /* No DWP file, look for the DWO file.  */
13354
13355       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13356                                             dwo_name, comp_dir);
13357       if (*dwo_file_slot == NULL)
13358         {
13359           /* Read in the file and build a table of the CUs/TUs it contains.  */
13360           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13361         }
13362       /* NOTE: This will be NULL if unable to open the file.  */
13363       dwo_file = (struct dwo_file *) *dwo_file_slot;
13364
13365       if (dwo_file != NULL)
13366         {
13367           struct dwo_unit *dwo_cutu = NULL;
13368
13369           if (is_debug_types && dwo_file->tus)
13370             {
13371               struct dwo_unit find_dwo_cutu;
13372
13373               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13374               find_dwo_cutu.signature = signature;
13375               dwo_cutu
13376                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13377             }
13378           else if (!is_debug_types && dwo_file->cus)
13379             {
13380               struct dwo_unit find_dwo_cutu;
13381
13382               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13383               find_dwo_cutu.signature = signature;
13384               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13385                                                        &find_dwo_cutu);
13386             }
13387
13388           if (dwo_cutu != NULL)
13389             {
13390               if (dwarf_read_debug)
13391                 {
13392                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13393                                       kind, dwo_name, hex_string (signature),
13394                                       host_address_to_string (dwo_cutu));
13395                 }
13396               return dwo_cutu;
13397             }
13398         }
13399     }
13400
13401   /* We didn't find it.  This could mean a dwo_id mismatch, or
13402      someone deleted the DWO/DWP file, or the search path isn't set up
13403      correctly to find the file.  */
13404
13405   if (dwarf_read_debug)
13406     {
13407       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13408                           kind, dwo_name, hex_string (signature));
13409     }
13410
13411   /* This is a warning and not a complaint because it can be caused by
13412      pilot error (e.g., user accidentally deleting the DWO).  */
13413   {
13414     /* Print the name of the DWP file if we looked there, helps the user
13415        better diagnose the problem.  */
13416     std::string dwp_text;
13417
13418     if (dwp_file != NULL)
13419       dwp_text = string_printf (" [in DWP file %s]",
13420                                 lbasename (dwp_file->name));
13421
13422     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13423                " [in module %s]"),
13424              kind, dwo_name, hex_string (signature),
13425              dwp_text.c_str (),
13426              this_unit->is_debug_types ? "TU" : "CU",
13427              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13428   }
13429   return NULL;
13430 }
13431
13432 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13433    See lookup_dwo_cutu_unit for details.  */
13434
13435 static struct dwo_unit *
13436 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13437                       const char *dwo_name, const char *comp_dir,
13438                       ULONGEST signature)
13439 {
13440   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13441 }
13442
13443 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13444    See lookup_dwo_cutu_unit for details.  */
13445
13446 static struct dwo_unit *
13447 lookup_dwo_type_unit (struct signatured_type *this_tu,
13448                       const char *dwo_name, const char *comp_dir)
13449 {
13450   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13451 }
13452
13453 /* Traversal function for queue_and_load_all_dwo_tus.  */
13454
13455 static int
13456 queue_and_load_dwo_tu (void **slot, void *info)
13457 {
13458   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13459   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13460   ULONGEST signature = dwo_unit->signature;
13461   struct signatured_type *sig_type =
13462     lookup_dwo_signatured_type (per_cu->cu, signature);
13463
13464   if (sig_type != NULL)
13465     {
13466       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13467
13468       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13469          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13470          while processing PER_CU.  */
13471       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13472         load_full_type_unit (sig_cu);
13473       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13474     }
13475
13476   return 1;
13477 }
13478
13479 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13480    The DWO may have the only definition of the type, though it may not be
13481    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13482    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13483
13484 static void
13485 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13486 {
13487   struct dwo_unit *dwo_unit;
13488   struct dwo_file *dwo_file;
13489
13490   gdb_assert (!per_cu->is_debug_types);
13491   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13492   gdb_assert (per_cu->cu != NULL);
13493
13494   dwo_unit = per_cu->cu->dwo_unit;
13495   gdb_assert (dwo_unit != NULL);
13496
13497   dwo_file = dwo_unit->dwo_file;
13498   if (dwo_file->tus != NULL)
13499     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13500 }
13501
13502 /* Free all resources associated with DWO_FILE.
13503    Close the DWO file and munmap the sections.  */
13504
13505 static void
13506 free_dwo_file (struct dwo_file *dwo_file)
13507 {
13508   /* Note: dbfd is NULL for virtual DWO files.  */
13509   gdb_bfd_unref (dwo_file->dbfd);
13510
13511   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13512 }
13513
13514 /* Traversal function for free_dwo_files.  */
13515
13516 static int
13517 free_dwo_file_from_slot (void **slot, void *info)
13518 {
13519   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13520
13521   free_dwo_file (dwo_file);
13522
13523   return 1;
13524 }
13525
13526 /* Free all resources associated with DWO_FILES.  */
13527
13528 static void
13529 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13530 {
13531   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13532 }
13533 \f
13534 /* Read in various DIEs.  */
13535
13536 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13537    Inherit only the children of the DW_AT_abstract_origin DIE not being
13538    already referenced by DW_AT_abstract_origin from the children of the
13539    current DIE.  */
13540
13541 static void
13542 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13543 {
13544   struct die_info *child_die;
13545   sect_offset *offsetp;
13546   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13547   struct die_info *origin_die;
13548   /* Iterator of the ORIGIN_DIE children.  */
13549   struct die_info *origin_child_die;
13550   struct attribute *attr;
13551   struct dwarf2_cu *origin_cu;
13552   struct pending **origin_previous_list_in_scope;
13553
13554   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13555   if (!attr)
13556     return;
13557
13558   /* Note that following die references may follow to a die in a
13559      different cu.  */
13560
13561   origin_cu = cu;
13562   origin_die = follow_die_ref (die, attr, &origin_cu);
13563
13564   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13565      symbols in.  */
13566   origin_previous_list_in_scope = origin_cu->list_in_scope;
13567   origin_cu->list_in_scope = cu->list_in_scope;
13568
13569   if (die->tag != origin_die->tag
13570       && !(die->tag == DW_TAG_inlined_subroutine
13571            && origin_die->tag == DW_TAG_subprogram))
13572     complaint (_("DIE %s and its abstract origin %s have different tags"),
13573                sect_offset_str (die->sect_off),
13574                sect_offset_str (origin_die->sect_off));
13575
13576   std::vector<sect_offset> offsets;
13577
13578   for (child_die = die->child;
13579        child_die && child_die->tag;
13580        child_die = sibling_die (child_die))
13581     {
13582       struct die_info *child_origin_die;
13583       struct dwarf2_cu *child_origin_cu;
13584
13585       /* We are trying to process concrete instance entries:
13586          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13587          it's not relevant to our analysis here. i.e. detecting DIEs that are
13588          present in the abstract instance but not referenced in the concrete
13589          one.  */
13590       if (child_die->tag == DW_TAG_call_site
13591           || child_die->tag == DW_TAG_GNU_call_site)
13592         continue;
13593
13594       /* For each CHILD_DIE, find the corresponding child of
13595          ORIGIN_DIE.  If there is more than one layer of
13596          DW_AT_abstract_origin, follow them all; there shouldn't be,
13597          but GCC versions at least through 4.4 generate this (GCC PR
13598          40573).  */
13599       child_origin_die = child_die;
13600       child_origin_cu = cu;
13601       while (1)
13602         {
13603           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13604                               child_origin_cu);
13605           if (attr == NULL)
13606             break;
13607           child_origin_die = follow_die_ref (child_origin_die, attr,
13608                                              &child_origin_cu);
13609         }
13610
13611       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13612          counterpart may exist.  */
13613       if (child_origin_die != child_die)
13614         {
13615           if (child_die->tag != child_origin_die->tag
13616               && !(child_die->tag == DW_TAG_inlined_subroutine
13617                    && child_origin_die->tag == DW_TAG_subprogram))
13618             complaint (_("Child DIE %s and its abstract origin %s have "
13619                          "different tags"),
13620                        sect_offset_str (child_die->sect_off),
13621                        sect_offset_str (child_origin_die->sect_off));
13622           if (child_origin_die->parent != origin_die)
13623             complaint (_("Child DIE %s and its abstract origin %s have "
13624                          "different parents"),
13625                        sect_offset_str (child_die->sect_off),
13626                        sect_offset_str (child_origin_die->sect_off));
13627           else
13628             offsets.push_back (child_origin_die->sect_off);
13629         }
13630     }
13631   std::sort (offsets.begin (), offsets.end ());
13632   sect_offset *offsets_end = offsets.data () + offsets.size ();
13633   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13634     if (offsetp[-1] == *offsetp)
13635       complaint (_("Multiple children of DIE %s refer "
13636                    "to DIE %s as their abstract origin"),
13637                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13638
13639   offsetp = offsets.data ();
13640   origin_child_die = origin_die->child;
13641   while (origin_child_die && origin_child_die->tag)
13642     {
13643       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13644       while (offsetp < offsets_end
13645              && *offsetp < origin_child_die->sect_off)
13646         offsetp++;
13647       if (offsetp >= offsets_end
13648           || *offsetp > origin_child_die->sect_off)
13649         {
13650           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13651              Check whether we're already processing ORIGIN_CHILD_DIE.
13652              This can happen with mutually referenced abstract_origins.
13653              PR 16581.  */
13654           if (!origin_child_die->in_process)
13655             process_die (origin_child_die, origin_cu);
13656         }
13657       origin_child_die = sibling_die (origin_child_die);
13658     }
13659   origin_cu->list_in_scope = origin_previous_list_in_scope;
13660 }
13661
13662 static void
13663 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13664 {
13665   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13666   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13667   struct context_stack *newobj;
13668   CORE_ADDR lowpc;
13669   CORE_ADDR highpc;
13670   struct die_info *child_die;
13671   struct attribute *attr, *call_line, *call_file;
13672   const char *name;
13673   CORE_ADDR baseaddr;
13674   struct block *block;
13675   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13676   std::vector<struct symbol *> template_args;
13677   struct template_symbol *templ_func = NULL;
13678
13679   if (inlined_func)
13680     {
13681       /* If we do not have call site information, we can't show the
13682          caller of this inlined function.  That's too confusing, so
13683          only use the scope for local variables.  */
13684       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13685       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13686       if (call_line == NULL || call_file == NULL)
13687         {
13688           read_lexical_block_scope (die, cu);
13689           return;
13690         }
13691     }
13692
13693   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13694
13695   name = dwarf2_name (die, cu);
13696
13697   /* Ignore functions with missing or empty names.  These are actually
13698      illegal according to the DWARF standard.  */
13699   if (name == NULL)
13700     {
13701       complaint (_("missing name for subprogram DIE at %s"),
13702                  sect_offset_str (die->sect_off));
13703       return;
13704     }
13705
13706   /* Ignore functions with missing or invalid low and high pc attributes.  */
13707   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13708       <= PC_BOUNDS_INVALID)
13709     {
13710       attr = dwarf2_attr (die, DW_AT_external, cu);
13711       if (!attr || !DW_UNSND (attr))
13712         complaint (_("cannot get low and high bounds "
13713                      "for subprogram DIE at %s"),
13714                    sect_offset_str (die->sect_off));
13715       return;
13716     }
13717
13718   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13719   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13720
13721   /* If we have any template arguments, then we must allocate a
13722      different sort of symbol.  */
13723   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13724     {
13725       if (child_die->tag == DW_TAG_template_type_param
13726           || child_die->tag == DW_TAG_template_value_param)
13727         {
13728           templ_func = allocate_template_symbol (objfile);
13729           templ_func->subclass = SYMBOL_TEMPLATE;
13730           break;
13731         }
13732     }
13733
13734   newobj = cu->builder->push_context (0, lowpc);
13735   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13736                              (struct symbol *) templ_func);
13737
13738   /* If there is a location expression for DW_AT_frame_base, record
13739      it.  */
13740   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13741   if (attr)
13742     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13743
13744   /* If there is a location for the static link, record it.  */
13745   newobj->static_link = NULL;
13746   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13747   if (attr)
13748     {
13749       newobj->static_link
13750         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13751       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13752     }
13753
13754   cu->list_in_scope = cu->builder->get_local_symbols ();
13755
13756   if (die->child != NULL)
13757     {
13758       child_die = die->child;
13759       while (child_die && child_die->tag)
13760         {
13761           if (child_die->tag == DW_TAG_template_type_param
13762               || child_die->tag == DW_TAG_template_value_param)
13763             {
13764               struct symbol *arg = new_symbol (child_die, NULL, cu);
13765
13766               if (arg != NULL)
13767                 template_args.push_back (arg);
13768             }
13769           else
13770             process_die (child_die, cu);
13771           child_die = sibling_die (child_die);
13772         }
13773     }
13774
13775   inherit_abstract_dies (die, cu);
13776
13777   /* If we have a DW_AT_specification, we might need to import using
13778      directives from the context of the specification DIE.  See the
13779      comment in determine_prefix.  */
13780   if (cu->language == language_cplus
13781       && dwarf2_attr (die, DW_AT_specification, cu))
13782     {
13783       struct dwarf2_cu *spec_cu = cu;
13784       struct die_info *spec_die = die_specification (die, &spec_cu);
13785
13786       while (spec_die)
13787         {
13788           child_die = spec_die->child;
13789           while (child_die && child_die->tag)
13790             {
13791               if (child_die->tag == DW_TAG_imported_module)
13792                 process_die (child_die, spec_cu);
13793               child_die = sibling_die (child_die);
13794             }
13795
13796           /* In some cases, GCC generates specification DIEs that
13797              themselves contain DW_AT_specification attributes.  */
13798           spec_die = die_specification (spec_die, &spec_cu);
13799         }
13800     }
13801
13802   struct context_stack cstk = cu->builder->pop_context ();
13803   /* Make a block for the local symbols within.  */
13804   block = cu->builder->finish_block (cstk.name, cstk.old_blocks,
13805                                      cstk.static_link, lowpc, highpc);
13806
13807   /* For C++, set the block's scope.  */
13808   if ((cu->language == language_cplus
13809        || cu->language == language_fortran
13810        || cu->language == language_d
13811        || cu->language == language_rust)
13812       && cu->processing_has_namespace_info)
13813     block_set_scope (block, determine_prefix (die, cu),
13814                      &objfile->objfile_obstack);
13815
13816   /* If we have address ranges, record them.  */
13817   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13818
13819   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13820
13821   /* Attach template arguments to function.  */
13822   if (!template_args.empty ())
13823     {
13824       gdb_assert (templ_func != NULL);
13825
13826       templ_func->n_template_arguments = template_args.size ();
13827       templ_func->template_arguments
13828         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13829                      templ_func->n_template_arguments);
13830       memcpy (templ_func->template_arguments,
13831               template_args.data (),
13832               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13833
13834       /* Make sure that the symtab is set on the new symbols.  Even
13835          though they don't appear in this symtab directly, other parts
13836          of gdb assume that symbols do, and this is reasonably
13837          true.  */
13838       for (symbol *sym : template_args)
13839         symbol_set_symtab (sym, symbol_symtab (templ_func));
13840     }
13841
13842   /* In C++, we can have functions nested inside functions (e.g., when
13843      a function declares a class that has methods).  This means that
13844      when we finish processing a function scope, we may need to go
13845      back to building a containing block's symbol lists.  */
13846   *cu->builder->get_local_symbols () = cstk.locals;
13847   cu->builder->set_local_using_directives (cstk.local_using_directives);
13848
13849   /* If we've finished processing a top-level function, subsequent
13850      symbols go in the file symbol list.  */
13851   if (cu->builder->outermost_context_p ())
13852     cu->list_in_scope = cu->builder->get_file_symbols ();
13853 }
13854
13855 /* Process all the DIES contained within a lexical block scope.  Start
13856    a new scope, process the dies, and then close the scope.  */
13857
13858 static void
13859 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13860 {
13861   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13862   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13863   CORE_ADDR lowpc, highpc;
13864   struct die_info *child_die;
13865   CORE_ADDR baseaddr;
13866
13867   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13868
13869   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13870   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13871      as multiple lexical blocks?  Handling children in a sane way would
13872      be nasty.  Might be easier to properly extend generic blocks to
13873      describe ranges.  */
13874   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13875     {
13876     case PC_BOUNDS_NOT_PRESENT:
13877       /* DW_TAG_lexical_block has no attributes, process its children as if
13878          there was no wrapping by that DW_TAG_lexical_block.
13879          GCC does no longer produces such DWARF since GCC r224161.  */
13880       for (child_die = die->child;
13881            child_die != NULL && child_die->tag;
13882            child_die = sibling_die (child_die))
13883         process_die (child_die, cu);
13884       return;
13885     case PC_BOUNDS_INVALID:
13886       return;
13887     }
13888   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13889   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13890
13891   cu->builder->push_context (0, lowpc);
13892   if (die->child != NULL)
13893     {
13894       child_die = die->child;
13895       while (child_die && child_die->tag)
13896         {
13897           process_die (child_die, cu);
13898           child_die = sibling_die (child_die);
13899         }
13900     }
13901   inherit_abstract_dies (die, cu);
13902   struct context_stack cstk = cu->builder->pop_context ();
13903
13904   if (*cu->builder->get_local_symbols () != NULL
13905       || (*cu->builder->get_local_using_directives ()) != NULL)
13906     {
13907       struct block *block
13908         = cu->builder->finish_block (0, cstk.old_blocks, NULL,
13909                                      cstk.start_addr, highpc);
13910
13911       /* Note that recording ranges after traversing children, as we
13912          do here, means that recording a parent's ranges entails
13913          walking across all its children's ranges as they appear in
13914          the address map, which is quadratic behavior.
13915
13916          It would be nicer to record the parent's ranges before
13917          traversing its children, simply overriding whatever you find
13918          there.  But since we don't even decide whether to create a
13919          block until after we've traversed its children, that's hard
13920          to do.  */
13921       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13922     }
13923   *cu->builder->get_local_symbols () = cstk.locals;
13924   cu->builder->set_local_using_directives (cstk.local_using_directives);
13925 }
13926
13927 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13928
13929 static void
13930 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13931 {
13932   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13933   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13934   CORE_ADDR pc, baseaddr;
13935   struct attribute *attr;
13936   struct call_site *call_site, call_site_local;
13937   void **slot;
13938   int nparams;
13939   struct die_info *child_die;
13940
13941   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13942
13943   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13944   if (attr == NULL)
13945     {
13946       /* This was a pre-DWARF-5 GNU extension alias
13947          for DW_AT_call_return_pc.  */
13948       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13949     }
13950   if (!attr)
13951     {
13952       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13953                    "DIE %s [in module %s]"),
13954                  sect_offset_str (die->sect_off), objfile_name (objfile));
13955       return;
13956     }
13957   pc = attr_value_as_address (attr) + baseaddr;
13958   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13959
13960   if (cu->call_site_htab == NULL)
13961     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13962                                                NULL, &objfile->objfile_obstack,
13963                                                hashtab_obstack_allocate, NULL);
13964   call_site_local.pc = pc;
13965   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13966   if (*slot != NULL)
13967     {
13968       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13969                    "DIE %s [in module %s]"),
13970                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13971                  objfile_name (objfile));
13972       return;
13973     }
13974
13975   /* Count parameters at the caller.  */
13976
13977   nparams = 0;
13978   for (child_die = die->child; child_die && child_die->tag;
13979        child_die = sibling_die (child_die))
13980     {
13981       if (child_die->tag != DW_TAG_call_site_parameter
13982           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13983         {
13984           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13985                        "DW_TAG_call_site child DIE %s [in module %s]"),
13986                      child_die->tag, sect_offset_str (child_die->sect_off),
13987                      objfile_name (objfile));
13988           continue;
13989         }
13990
13991       nparams++;
13992     }
13993
13994   call_site
13995     = ((struct call_site *)
13996        obstack_alloc (&objfile->objfile_obstack,
13997                       sizeof (*call_site)
13998                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13999   *slot = call_site;
14000   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14001   call_site->pc = pc;
14002
14003   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14004       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14005     {
14006       struct die_info *func_die;
14007
14008       /* Skip also over DW_TAG_inlined_subroutine.  */
14009       for (func_die = die->parent;
14010            func_die && func_die->tag != DW_TAG_subprogram
14011            && func_die->tag != DW_TAG_subroutine_type;
14012            func_die = func_die->parent);
14013
14014       /* DW_AT_call_all_calls is a superset
14015          of DW_AT_call_all_tail_calls.  */
14016       if (func_die
14017           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14018           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14019           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14020           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14021         {
14022           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14023              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14024              both the initial caller containing the real return address PC and
14025              the final callee containing the current PC of a chain of tail
14026              calls do not need to have the tail call list complete.  But any
14027              function candidate for a virtual tail call frame searched via
14028              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14029              determined unambiguously.  */
14030         }
14031       else
14032         {
14033           struct type *func_type = NULL;
14034
14035           if (func_die)
14036             func_type = get_die_type (func_die, cu);
14037           if (func_type != NULL)
14038             {
14039               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14040
14041               /* Enlist this call site to the function.  */
14042               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14043               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14044             }
14045           else
14046             complaint (_("Cannot find function owning DW_TAG_call_site "
14047                          "DIE %s [in module %s]"),
14048                        sect_offset_str (die->sect_off), objfile_name (objfile));
14049         }
14050     }
14051
14052   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14053   if (attr == NULL)
14054     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14055   if (attr == NULL)
14056     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14057   if (attr == NULL)
14058     {
14059       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14060       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14061     }
14062   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14063   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14064     /* Keep NULL DWARF_BLOCK.  */;
14065   else if (attr_form_is_block (attr))
14066     {
14067       struct dwarf2_locexpr_baton *dlbaton;
14068
14069       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14070       dlbaton->data = DW_BLOCK (attr)->data;
14071       dlbaton->size = DW_BLOCK (attr)->size;
14072       dlbaton->per_cu = cu->per_cu;
14073
14074       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14075     }
14076   else if (attr_form_is_ref (attr))
14077     {
14078       struct dwarf2_cu *target_cu = cu;
14079       struct die_info *target_die;
14080
14081       target_die = follow_die_ref (die, attr, &target_cu);
14082       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14083       if (die_is_declaration (target_die, target_cu))
14084         {
14085           const char *target_physname;
14086
14087           /* Prefer the mangled name; otherwise compute the demangled one.  */
14088           target_physname = dw2_linkage_name (target_die, target_cu);
14089           if (target_physname == NULL)
14090             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14091           if (target_physname == NULL)
14092             complaint (_("DW_AT_call_target target DIE has invalid "
14093                          "physname, for referencing DIE %s [in module %s]"),
14094                        sect_offset_str (die->sect_off), objfile_name (objfile));
14095           else
14096             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14097         }
14098       else
14099         {
14100           CORE_ADDR lowpc;
14101
14102           /* DW_AT_entry_pc should be preferred.  */
14103           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14104               <= PC_BOUNDS_INVALID)
14105             complaint (_("DW_AT_call_target target DIE has invalid "
14106                          "low pc, for referencing DIE %s [in module %s]"),
14107                        sect_offset_str (die->sect_off), objfile_name (objfile));
14108           else
14109             {
14110               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14111               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14112             }
14113         }
14114     }
14115   else
14116     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14117                  "block nor reference, for DIE %s [in module %s]"),
14118                sect_offset_str (die->sect_off), objfile_name (objfile));
14119
14120   call_site->per_cu = cu->per_cu;
14121
14122   for (child_die = die->child;
14123        child_die && child_die->tag;
14124        child_die = sibling_die (child_die))
14125     {
14126       struct call_site_parameter *parameter;
14127       struct attribute *loc, *origin;
14128
14129       if (child_die->tag != DW_TAG_call_site_parameter
14130           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14131         {
14132           /* Already printed the complaint above.  */
14133           continue;
14134         }
14135
14136       gdb_assert (call_site->parameter_count < nparams);
14137       parameter = &call_site->parameter[call_site->parameter_count];
14138
14139       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14140          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14141          register is contained in DW_AT_call_value.  */
14142
14143       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14144       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14145       if (origin == NULL)
14146         {
14147           /* This was a pre-DWARF-5 GNU extension alias
14148              for DW_AT_call_parameter.  */
14149           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14150         }
14151       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14152         {
14153           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14154
14155           sect_offset sect_off
14156             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14157           if (!offset_in_cu_p (&cu->header, sect_off))
14158             {
14159               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14160                  binding can be done only inside one CU.  Such referenced DIE
14161                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14162               complaint (_("DW_AT_call_parameter offset is not in CU for "
14163                            "DW_TAG_call_site child DIE %s [in module %s]"),
14164                          sect_offset_str (child_die->sect_off),
14165                          objfile_name (objfile));
14166               continue;
14167             }
14168           parameter->u.param_cu_off
14169             = (cu_offset) (sect_off - cu->header.sect_off);
14170         }
14171       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14172         {
14173           complaint (_("No DW_FORM_block* DW_AT_location for "
14174                        "DW_TAG_call_site child DIE %s [in module %s]"),
14175                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14176           continue;
14177         }
14178       else
14179         {
14180           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14181             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14182           if (parameter->u.dwarf_reg != -1)
14183             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14184           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14185                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14186                                              &parameter->u.fb_offset))
14187             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14188           else
14189             {
14190               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14191                            "for DW_FORM_block* DW_AT_location is supported for "
14192                            "DW_TAG_call_site child DIE %s "
14193                            "[in module %s]"),
14194                          sect_offset_str (child_die->sect_off),
14195                          objfile_name (objfile));
14196               continue;
14197             }
14198         }
14199
14200       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14201       if (attr == NULL)
14202         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14203       if (!attr_form_is_block (attr))
14204         {
14205           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14206                        "DW_TAG_call_site child DIE %s [in module %s]"),
14207                      sect_offset_str (child_die->sect_off),
14208                      objfile_name (objfile));
14209           continue;
14210         }
14211       parameter->value = DW_BLOCK (attr)->data;
14212       parameter->value_size = DW_BLOCK (attr)->size;
14213
14214       /* Parameters are not pre-cleared by memset above.  */
14215       parameter->data_value = NULL;
14216       parameter->data_value_size = 0;
14217       call_site->parameter_count++;
14218
14219       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14220       if (attr == NULL)
14221         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14222       if (attr)
14223         {
14224           if (!attr_form_is_block (attr))
14225             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14226                          "DW_TAG_call_site child DIE %s [in module %s]"),
14227                        sect_offset_str (child_die->sect_off),
14228                        objfile_name (objfile));
14229           else
14230             {
14231               parameter->data_value = DW_BLOCK (attr)->data;
14232               parameter->data_value_size = DW_BLOCK (attr)->size;
14233             }
14234         }
14235     }
14236 }
14237
14238 /* Helper function for read_variable.  If DIE represents a virtual
14239    table, then return the type of the concrete object that is
14240    associated with the virtual table.  Otherwise, return NULL.  */
14241
14242 static struct type *
14243 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14244 {
14245   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14246   if (attr == NULL)
14247     return NULL;
14248
14249   /* Find the type DIE.  */
14250   struct die_info *type_die = NULL;
14251   struct dwarf2_cu *type_cu = cu;
14252
14253   if (attr_form_is_ref (attr))
14254     type_die = follow_die_ref (die, attr, &type_cu);
14255   if (type_die == NULL)
14256     return NULL;
14257
14258   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14259     return NULL;
14260   return die_containing_type (type_die, type_cu);
14261 }
14262
14263 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14264
14265 static void
14266 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14267 {
14268   struct rust_vtable_symbol *storage = NULL;
14269
14270   if (cu->language == language_rust)
14271     {
14272       struct type *containing_type = rust_containing_type (die, cu);
14273
14274       if (containing_type != NULL)
14275         {
14276           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14277
14278           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14279                                     struct rust_vtable_symbol);
14280           initialize_objfile_symbol (storage);
14281           storage->concrete_type = containing_type;
14282           storage->subclass = SYMBOL_RUST_VTABLE;
14283         }
14284     }
14285
14286   struct symbol *res = new_symbol (die, NULL, cu, storage);
14287   struct attribute *abstract_origin
14288     = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14289   struct attribute *loc = dwarf2_attr (die, DW_AT_location, cu);
14290   if (res == NULL && loc && abstract_origin)
14291     {
14292       /* We have a variable without a name, but with a location and an abstract
14293          origin.  This may be a concrete instance of an abstract variable
14294          referenced from an DW_OP_GNU_variable_value, so save it to find it back
14295          later.  */
14296       struct dwarf2_cu *origin_cu = cu;
14297       struct die_info *origin_die
14298         = follow_die_ref (die, abstract_origin, &origin_cu);
14299       dwarf2_per_objfile *dpo = cu->per_cu->dwarf2_per_objfile;
14300       dpo->abstract_to_concrete[origin_die].push_back (die);
14301     }
14302 }
14303
14304 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14305    reading .debug_rnglists.
14306    Callback's type should be:
14307     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14308    Return true if the attributes are present and valid, otherwise,
14309    return false.  */
14310
14311 template <typename Callback>
14312 static bool
14313 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14314                          Callback &&callback)
14315 {
14316   struct dwarf2_per_objfile *dwarf2_per_objfile
14317     = cu->per_cu->dwarf2_per_objfile;
14318   struct objfile *objfile = dwarf2_per_objfile->objfile;
14319   bfd *obfd = objfile->obfd;
14320   /* Base address selection entry.  */
14321   CORE_ADDR base;
14322   int found_base;
14323   const gdb_byte *buffer;
14324   CORE_ADDR baseaddr;
14325   bool overflow = false;
14326
14327   found_base = cu->base_known;
14328   base = cu->base_address;
14329
14330   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14331   if (offset >= dwarf2_per_objfile->rnglists.size)
14332     {
14333       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14334                  offset);
14335       return false;
14336     }
14337   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14338
14339   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14340
14341   while (1)
14342     {
14343       /* Initialize it due to a false compiler warning.  */
14344       CORE_ADDR range_beginning = 0, range_end = 0;
14345       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14346                                  + dwarf2_per_objfile->rnglists.size);
14347       unsigned int bytes_read;
14348
14349       if (buffer == buf_end)
14350         {
14351           overflow = true;
14352           break;
14353         }
14354       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14355       switch (rlet)
14356         {
14357         case DW_RLE_end_of_list:
14358           break;
14359         case DW_RLE_base_address:
14360           if (buffer + cu->header.addr_size > buf_end)
14361             {
14362               overflow = true;
14363               break;
14364             }
14365           base = read_address (obfd, buffer, cu, &bytes_read);
14366           found_base = 1;
14367           buffer += bytes_read;
14368           break;
14369         case DW_RLE_start_length:
14370           if (buffer + cu->header.addr_size > buf_end)
14371             {
14372               overflow = true;
14373               break;
14374             }
14375           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14376           buffer += bytes_read;
14377           range_end = (range_beginning
14378                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14379           buffer += bytes_read;
14380           if (buffer > buf_end)
14381             {
14382               overflow = true;
14383               break;
14384             }
14385           break;
14386         case DW_RLE_offset_pair:
14387           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14388           buffer += bytes_read;
14389           if (buffer > buf_end)
14390             {
14391               overflow = true;
14392               break;
14393             }
14394           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14395           buffer += bytes_read;
14396           if (buffer > buf_end)
14397             {
14398               overflow = true;
14399               break;
14400             }
14401           break;
14402         case DW_RLE_start_end:
14403           if (buffer + 2 * cu->header.addr_size > buf_end)
14404             {
14405               overflow = true;
14406               break;
14407             }
14408           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14409           buffer += bytes_read;
14410           range_end = read_address (obfd, buffer, cu, &bytes_read);
14411           buffer += bytes_read;
14412           break;
14413         default:
14414           complaint (_("Invalid .debug_rnglists data (no base address)"));
14415           return false;
14416         }
14417       if (rlet == DW_RLE_end_of_list || overflow)
14418         break;
14419       if (rlet == DW_RLE_base_address)
14420         continue;
14421
14422       if (!found_base)
14423         {
14424           /* We have no valid base address for the ranges
14425              data.  */
14426           complaint (_("Invalid .debug_rnglists data (no base address)"));
14427           return false;
14428         }
14429
14430       if (range_beginning > range_end)
14431         {
14432           /* Inverted range entries are invalid.  */
14433           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14434           return false;
14435         }
14436
14437       /* Empty range entries have no effect.  */
14438       if (range_beginning == range_end)
14439         continue;
14440
14441       range_beginning += base;
14442       range_end += base;
14443
14444       /* A not-uncommon case of bad debug info.
14445          Don't pollute the addrmap with bad data.  */
14446       if (range_beginning + baseaddr == 0
14447           && !dwarf2_per_objfile->has_section_at_zero)
14448         {
14449           complaint (_(".debug_rnglists entry has start address of zero"
14450                        " [in module %s]"), objfile_name (objfile));
14451           continue;
14452         }
14453
14454       callback (range_beginning, range_end);
14455     }
14456
14457   if (overflow)
14458     {
14459       complaint (_("Offset %d is not terminated "
14460                    "for DW_AT_ranges attribute"),
14461                  offset);
14462       return false;
14463     }
14464
14465   return true;
14466 }
14467
14468 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14469    Callback's type should be:
14470     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14471    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14472
14473 template <typename Callback>
14474 static int
14475 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14476                        Callback &&callback)
14477 {
14478   struct dwarf2_per_objfile *dwarf2_per_objfile
14479       = cu->per_cu->dwarf2_per_objfile;
14480   struct objfile *objfile = dwarf2_per_objfile->objfile;
14481   struct comp_unit_head *cu_header = &cu->header;
14482   bfd *obfd = objfile->obfd;
14483   unsigned int addr_size = cu_header->addr_size;
14484   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14485   /* Base address selection entry.  */
14486   CORE_ADDR base;
14487   int found_base;
14488   unsigned int dummy;
14489   const gdb_byte *buffer;
14490   CORE_ADDR baseaddr;
14491
14492   if (cu_header->version >= 5)
14493     return dwarf2_rnglists_process (offset, cu, callback);
14494
14495   found_base = cu->base_known;
14496   base = cu->base_address;
14497
14498   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14499   if (offset >= dwarf2_per_objfile->ranges.size)
14500     {
14501       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14502                  offset);
14503       return 0;
14504     }
14505   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14506
14507   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14508
14509   while (1)
14510     {
14511       CORE_ADDR range_beginning, range_end;
14512
14513       range_beginning = read_address (obfd, buffer, cu, &dummy);
14514       buffer += addr_size;
14515       range_end = read_address (obfd, buffer, cu, &dummy);
14516       buffer += addr_size;
14517       offset += 2 * addr_size;
14518
14519       /* An end of list marker is a pair of zero addresses.  */
14520       if (range_beginning == 0 && range_end == 0)
14521         /* Found the end of list entry.  */
14522         break;
14523
14524       /* Each base address selection entry is a pair of 2 values.
14525          The first is the largest possible address, the second is
14526          the base address.  Check for a base address here.  */
14527       if ((range_beginning & mask) == mask)
14528         {
14529           /* If we found the largest possible address, then we already
14530              have the base address in range_end.  */
14531           base = range_end;
14532           found_base = 1;
14533           continue;
14534         }
14535
14536       if (!found_base)
14537         {
14538           /* We have no valid base address for the ranges
14539              data.  */
14540           complaint (_("Invalid .debug_ranges data (no base address)"));
14541           return 0;
14542         }
14543
14544       if (range_beginning > range_end)
14545         {
14546           /* Inverted range entries are invalid.  */
14547           complaint (_("Invalid .debug_ranges data (inverted range)"));
14548           return 0;
14549         }
14550
14551       /* Empty range entries have no effect.  */
14552       if (range_beginning == range_end)
14553         continue;
14554
14555       range_beginning += base;
14556       range_end += base;
14557
14558       /* A not-uncommon case of bad debug info.
14559          Don't pollute the addrmap with bad data.  */
14560       if (range_beginning + baseaddr == 0
14561           && !dwarf2_per_objfile->has_section_at_zero)
14562         {
14563           complaint (_(".debug_ranges entry has start address of zero"
14564                        " [in module %s]"), objfile_name (objfile));
14565           continue;
14566         }
14567
14568       callback (range_beginning, range_end);
14569     }
14570
14571   return 1;
14572 }
14573
14574 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14575    Return 1 if the attributes are present and valid, otherwise, return 0.
14576    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14577
14578 static int
14579 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14580                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14581                     struct partial_symtab *ranges_pst)
14582 {
14583   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14584   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14585   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14586                                        SECT_OFF_TEXT (objfile));
14587   int low_set = 0;
14588   CORE_ADDR low = 0;
14589   CORE_ADDR high = 0;
14590   int retval;
14591
14592   retval = dwarf2_ranges_process (offset, cu,
14593     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14594     {
14595       if (ranges_pst != NULL)
14596         {
14597           CORE_ADDR lowpc;
14598           CORE_ADDR highpc;
14599
14600           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14601                                                range_beginning + baseaddr)
14602                    - baseaddr);
14603           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14604                                                 range_end + baseaddr)
14605                     - baseaddr);
14606           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14607                              ranges_pst);
14608         }
14609
14610       /* FIXME: This is recording everything as a low-high
14611          segment of consecutive addresses.  We should have a
14612          data structure for discontiguous block ranges
14613          instead.  */
14614       if (! low_set)
14615         {
14616           low = range_beginning;
14617           high = range_end;
14618           low_set = 1;
14619         }
14620       else
14621         {
14622           if (range_beginning < low)
14623             low = range_beginning;
14624           if (range_end > high)
14625             high = range_end;
14626         }
14627     });
14628   if (!retval)
14629     return 0;
14630
14631   if (! low_set)
14632     /* If the first entry is an end-of-list marker, the range
14633        describes an empty scope, i.e. no instructions.  */
14634     return 0;
14635
14636   if (low_return)
14637     *low_return = low;
14638   if (high_return)
14639     *high_return = high;
14640   return 1;
14641 }
14642
14643 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14644    definition for the return value.  *LOWPC and *HIGHPC are set iff
14645    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14646
14647 static enum pc_bounds_kind
14648 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14649                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14650                       struct partial_symtab *pst)
14651 {
14652   struct dwarf2_per_objfile *dwarf2_per_objfile
14653     = cu->per_cu->dwarf2_per_objfile;
14654   struct attribute *attr;
14655   struct attribute *attr_high;
14656   CORE_ADDR low = 0;
14657   CORE_ADDR high = 0;
14658   enum pc_bounds_kind ret;
14659
14660   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14661   if (attr_high)
14662     {
14663       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14664       if (attr)
14665         {
14666           low = attr_value_as_address (attr);
14667           high = attr_value_as_address (attr_high);
14668           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14669             high += low;
14670         }
14671       else
14672         /* Found high w/o low attribute.  */
14673         return PC_BOUNDS_INVALID;
14674
14675       /* Found consecutive range of addresses.  */
14676       ret = PC_BOUNDS_HIGH_LOW;
14677     }
14678   else
14679     {
14680       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14681       if (attr != NULL)
14682         {
14683           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14684              We take advantage of the fact that DW_AT_ranges does not appear
14685              in DW_TAG_compile_unit of DWO files.  */
14686           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14687           unsigned int ranges_offset = (DW_UNSND (attr)
14688                                         + (need_ranges_base
14689                                            ? cu->ranges_base
14690                                            : 0));
14691
14692           /* Value of the DW_AT_ranges attribute is the offset in the
14693              .debug_ranges section.  */
14694           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14695             return PC_BOUNDS_INVALID;
14696           /* Found discontinuous range of addresses.  */
14697           ret = PC_BOUNDS_RANGES;
14698         }
14699       else
14700         return PC_BOUNDS_NOT_PRESENT;
14701     }
14702
14703   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14704   if (high <= low)
14705     return PC_BOUNDS_INVALID;
14706
14707   /* When using the GNU linker, .gnu.linkonce. sections are used to
14708      eliminate duplicate copies of functions and vtables and such.
14709      The linker will arbitrarily choose one and discard the others.
14710      The AT_*_pc values for such functions refer to local labels in
14711      these sections.  If the section from that file was discarded, the
14712      labels are not in the output, so the relocs get a value of 0.
14713      If this is a discarded function, mark the pc bounds as invalid,
14714      so that GDB will ignore it.  */
14715   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14716     return PC_BOUNDS_INVALID;
14717
14718   *lowpc = low;
14719   if (highpc)
14720     *highpc = high;
14721   return ret;
14722 }
14723
14724 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14725    its low and high PC addresses.  Do nothing if these addresses could not
14726    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14727    and HIGHPC to the high address if greater than HIGHPC.  */
14728
14729 static void
14730 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14731                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14732                                  struct dwarf2_cu *cu)
14733 {
14734   CORE_ADDR low, high;
14735   struct die_info *child = die->child;
14736
14737   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14738     {
14739       *lowpc = std::min (*lowpc, low);
14740       *highpc = std::max (*highpc, high);
14741     }
14742
14743   /* If the language does not allow nested subprograms (either inside
14744      subprograms or lexical blocks), we're done.  */
14745   if (cu->language != language_ada)
14746     return;
14747
14748   /* Check all the children of the given DIE.  If it contains nested
14749      subprograms, then check their pc bounds.  Likewise, we need to
14750      check lexical blocks as well, as they may also contain subprogram
14751      definitions.  */
14752   while (child && child->tag)
14753     {
14754       if (child->tag == DW_TAG_subprogram
14755           || child->tag == DW_TAG_lexical_block)
14756         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14757       child = sibling_die (child);
14758     }
14759 }
14760
14761 /* Get the low and high pc's represented by the scope DIE, and store
14762    them in *LOWPC and *HIGHPC.  If the correct values can't be
14763    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14764
14765 static void
14766 get_scope_pc_bounds (struct die_info *die,
14767                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14768                      struct dwarf2_cu *cu)
14769 {
14770   CORE_ADDR best_low = (CORE_ADDR) -1;
14771   CORE_ADDR best_high = (CORE_ADDR) 0;
14772   CORE_ADDR current_low, current_high;
14773
14774   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14775       >= PC_BOUNDS_RANGES)
14776     {
14777       best_low = current_low;
14778       best_high = current_high;
14779     }
14780   else
14781     {
14782       struct die_info *child = die->child;
14783
14784       while (child && child->tag)
14785         {
14786           switch (child->tag) {
14787           case DW_TAG_subprogram:
14788             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14789             break;
14790           case DW_TAG_namespace:
14791           case DW_TAG_module:
14792             /* FIXME: carlton/2004-01-16: Should we do this for
14793                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14794                that current GCC's always emit the DIEs corresponding
14795                to definitions of methods of classes as children of a
14796                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14797                the DIEs giving the declarations, which could be
14798                anywhere).  But I don't see any reason why the
14799                standards says that they have to be there.  */
14800             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14801
14802             if (current_low != ((CORE_ADDR) -1))
14803               {
14804                 best_low = std::min (best_low, current_low);
14805                 best_high = std::max (best_high, current_high);
14806               }
14807             break;
14808           default:
14809             /* Ignore.  */
14810             break;
14811           }
14812
14813           child = sibling_die (child);
14814         }
14815     }
14816
14817   *lowpc = best_low;
14818   *highpc = best_high;
14819 }
14820
14821 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14822    in DIE.  */
14823
14824 static void
14825 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14826                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14827 {
14828   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14829   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14830   struct attribute *attr;
14831   struct attribute *attr_high;
14832
14833   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14834   if (attr_high)
14835     {
14836       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14837       if (attr)
14838         {
14839           CORE_ADDR low = attr_value_as_address (attr);
14840           CORE_ADDR high = attr_value_as_address (attr_high);
14841
14842           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14843             high += low;
14844
14845           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14846           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14847           cu->builder->record_block_range (block, low, high - 1);
14848         }
14849     }
14850
14851   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14852   if (attr)
14853     {
14854       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14855          We take advantage of the fact that DW_AT_ranges does not appear
14856          in DW_TAG_compile_unit of DWO files.  */
14857       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14858
14859       /* The value of the DW_AT_ranges attribute is the offset of the
14860          address range list in the .debug_ranges section.  */
14861       unsigned long offset = (DW_UNSND (attr)
14862                               + (need_ranges_base ? cu->ranges_base : 0));
14863
14864       std::vector<blockrange> blockvec;
14865       dwarf2_ranges_process (offset, cu,
14866         [&] (CORE_ADDR start, CORE_ADDR end)
14867         {
14868           start += baseaddr;
14869           end += baseaddr;
14870           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14871           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14872           cu->builder->record_block_range (block, start, end - 1);
14873           blockvec.emplace_back (start, end);
14874         });
14875
14876       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14877     }
14878 }
14879
14880 /* Check whether the producer field indicates either of GCC < 4.6, or the
14881    Intel C/C++ compiler, and cache the result in CU.  */
14882
14883 static void
14884 check_producer (struct dwarf2_cu *cu)
14885 {
14886   int major, minor;
14887
14888   if (cu->producer == NULL)
14889     {
14890       /* For unknown compilers expect their behavior is DWARF version
14891          compliant.
14892
14893          GCC started to support .debug_types sections by -gdwarf-4 since
14894          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14895          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14896          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14897          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14898     }
14899   else if (producer_is_gcc (cu->producer, &major, &minor))
14900     {
14901       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14902       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14903     }
14904   else if (producer_is_icc (cu->producer, &major, &minor))
14905     {
14906       cu->producer_is_icc = true;
14907       cu->producer_is_icc_lt_14 = major < 14;
14908     }
14909   else if (startswith (cu->producer, "CodeWarrior S12/L-ISA"))
14910     cu->producer_is_codewarrior = true;
14911   else
14912     {
14913       /* For other non-GCC compilers, expect their behavior is DWARF version
14914          compliant.  */
14915     }
14916
14917   cu->checked_producer = true;
14918 }
14919
14920 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14921    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14922    during 4.6.0 experimental.  */
14923
14924 static bool
14925 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14926 {
14927   if (!cu->checked_producer)
14928     check_producer (cu);
14929
14930   return cu->producer_is_gxx_lt_4_6;
14931 }
14932
14933
14934 /* Codewarrior (at least as of version 5.0.40) generates dwarf line information
14935    with incorrect is_stmt attributes.  */
14936
14937 static bool
14938 producer_is_codewarrior (struct dwarf2_cu *cu)
14939 {
14940   if (!cu->checked_producer)
14941     check_producer (cu);
14942
14943   return cu->producer_is_codewarrior;
14944 }
14945
14946 /* Return the default accessibility type if it is not overriden by
14947    DW_AT_accessibility.  */
14948
14949 static enum dwarf_access_attribute
14950 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14951 {
14952   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14953     {
14954       /* The default DWARF 2 accessibility for members is public, the default
14955          accessibility for inheritance is private.  */
14956
14957       if (die->tag != DW_TAG_inheritance)
14958         return DW_ACCESS_public;
14959       else
14960         return DW_ACCESS_private;
14961     }
14962   else
14963     {
14964       /* DWARF 3+ defines the default accessibility a different way.  The same
14965          rules apply now for DW_TAG_inheritance as for the members and it only
14966          depends on the container kind.  */
14967
14968       if (die->parent->tag == DW_TAG_class_type)
14969         return DW_ACCESS_private;
14970       else
14971         return DW_ACCESS_public;
14972     }
14973 }
14974
14975 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14976    offset.  If the attribute was not found return 0, otherwise return
14977    1.  If it was found but could not properly be handled, set *OFFSET
14978    to 0.  */
14979
14980 static int
14981 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14982                              LONGEST *offset)
14983 {
14984   struct attribute *attr;
14985
14986   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14987   if (attr != NULL)
14988     {
14989       *offset = 0;
14990
14991       /* Note that we do not check for a section offset first here.
14992          This is because DW_AT_data_member_location is new in DWARF 4,
14993          so if we see it, we can assume that a constant form is really
14994          a constant and not a section offset.  */
14995       if (attr_form_is_constant (attr))
14996         *offset = dwarf2_get_attr_constant_value (attr, 0);
14997       else if (attr_form_is_section_offset (attr))
14998         dwarf2_complex_location_expr_complaint ();
14999       else if (attr_form_is_block (attr))
15000         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15001       else
15002         dwarf2_complex_location_expr_complaint ();
15003
15004       return 1;
15005     }
15006
15007   return 0;
15008 }
15009
15010 /* Add an aggregate field to the field list.  */
15011
15012 static void
15013 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15014                   struct dwarf2_cu *cu)
15015 {
15016   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15017   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15018   struct nextfield *new_field;
15019   struct attribute *attr;
15020   struct field *fp;
15021   const char *fieldname = "";
15022
15023   if (die->tag == DW_TAG_inheritance)
15024     {
15025       fip->baseclasses.emplace_back ();
15026       new_field = &fip->baseclasses.back ();
15027     }
15028   else
15029     {
15030       fip->fields.emplace_back ();
15031       new_field = &fip->fields.back ();
15032     }
15033
15034   fip->nfields++;
15035
15036   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15037   if (attr)
15038     new_field->accessibility = DW_UNSND (attr);
15039   else
15040     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15041   if (new_field->accessibility != DW_ACCESS_public)
15042     fip->non_public_fields = 1;
15043
15044   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15045   if (attr)
15046     new_field->virtuality = DW_UNSND (attr);
15047   else
15048     new_field->virtuality = DW_VIRTUALITY_none;
15049
15050   fp = &new_field->field;
15051
15052   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15053     {
15054       LONGEST offset;
15055
15056       /* Data member other than a C++ static data member.  */
15057
15058       /* Get type of field.  */
15059       fp->type = die_type (die, cu);
15060
15061       SET_FIELD_BITPOS (*fp, 0);
15062
15063       /* Get bit size of field (zero if none).  */
15064       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15065       if (attr)
15066         {
15067           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15068         }
15069       else
15070         {
15071           FIELD_BITSIZE (*fp) = 0;
15072         }
15073
15074       /* Get bit offset of field.  */
15075       if (handle_data_member_location (die, cu, &offset))
15076         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15077       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15078       if (attr)
15079         {
15080           if (gdbarch_bits_big_endian (gdbarch))
15081             {
15082               /* For big endian bits, the DW_AT_bit_offset gives the
15083                  additional bit offset from the MSB of the containing
15084                  anonymous object to the MSB of the field.  We don't
15085                  have to do anything special since we don't need to
15086                  know the size of the anonymous object.  */
15087               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15088             }
15089           else
15090             {
15091               /* For little endian bits, compute the bit offset to the
15092                  MSB of the anonymous object, subtract off the number of
15093                  bits from the MSB of the field to the MSB of the
15094                  object, and then subtract off the number of bits of
15095                  the field itself.  The result is the bit offset of
15096                  the LSB of the field.  */
15097               int anonymous_size;
15098               int bit_offset = DW_UNSND (attr);
15099
15100               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15101               if (attr)
15102                 {
15103                   /* The size of the anonymous object containing
15104                      the bit field is explicit, so use the
15105                      indicated size (in bytes).  */
15106                   anonymous_size = DW_UNSND (attr);
15107                 }
15108               else
15109                 {
15110                   /* The size of the anonymous object containing
15111                      the bit field must be inferred from the type
15112                      attribute of the data member containing the
15113                      bit field.  */
15114                   anonymous_size = TYPE_LENGTH (fp->type);
15115                 }
15116               SET_FIELD_BITPOS (*fp,
15117                                 (FIELD_BITPOS (*fp)
15118                                  + anonymous_size * bits_per_byte
15119                                  - bit_offset - FIELD_BITSIZE (*fp)));
15120             }
15121         }
15122       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15123       if (attr != NULL)
15124         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15125                                 + dwarf2_get_attr_constant_value (attr, 0)));
15126
15127       /* Get name of field.  */
15128       fieldname = dwarf2_name (die, cu);
15129       if (fieldname == NULL)
15130         fieldname = "";
15131
15132       /* The name is already allocated along with this objfile, so we don't
15133          need to duplicate it for the type.  */
15134       fp->name = fieldname;
15135
15136       /* Change accessibility for artificial fields (e.g. virtual table
15137          pointer or virtual base class pointer) to private.  */
15138       if (dwarf2_attr (die, DW_AT_artificial, cu))
15139         {
15140           FIELD_ARTIFICIAL (*fp) = 1;
15141           new_field->accessibility = DW_ACCESS_private;
15142           fip->non_public_fields = 1;
15143         }
15144     }
15145   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15146     {
15147       /* C++ static member.  */
15148
15149       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15150          is a declaration, but all versions of G++ as of this writing
15151          (so through at least 3.2.1) incorrectly generate
15152          DW_TAG_variable tags.  */
15153
15154       const char *physname;
15155
15156       /* Get name of field.  */
15157       fieldname = dwarf2_name (die, cu);
15158       if (fieldname == NULL)
15159         return;
15160
15161       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15162       if (attr
15163           /* Only create a symbol if this is an external value.
15164              new_symbol checks this and puts the value in the global symbol
15165              table, which we want.  If it is not external, new_symbol
15166              will try to put the value in cu->list_in_scope which is wrong.  */
15167           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15168         {
15169           /* A static const member, not much different than an enum as far as
15170              we're concerned, except that we can support more types.  */
15171           new_symbol (die, NULL, cu);
15172         }
15173
15174       /* Get physical name.  */
15175       physname = dwarf2_physname (fieldname, die, cu);
15176
15177       /* The name is already allocated along with this objfile, so we don't
15178          need to duplicate it for the type.  */
15179       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15180       FIELD_TYPE (*fp) = die_type (die, cu);
15181       FIELD_NAME (*fp) = fieldname;
15182     }
15183   else if (die->tag == DW_TAG_inheritance)
15184     {
15185       LONGEST offset;
15186
15187       /* C++ base class field.  */
15188       if (handle_data_member_location (die, cu, &offset))
15189         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15190       FIELD_BITSIZE (*fp) = 0;
15191       FIELD_TYPE (*fp) = die_type (die, cu);
15192       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15193     }
15194   else if (die->tag == DW_TAG_variant_part)
15195     {
15196       /* process_structure_scope will treat this DIE as a union.  */
15197       process_structure_scope (die, cu);
15198
15199       /* The variant part is relative to the start of the enclosing
15200          structure.  */
15201       SET_FIELD_BITPOS (*fp, 0);
15202       fp->type = get_die_type (die, cu);
15203       fp->artificial = 1;
15204       fp->name = "<<variant>>";
15205
15206       /* Normally a DW_TAG_variant_part won't have a size, but our
15207          representation requires one, so set it to the maximum of the
15208          child sizes.  */
15209       if (TYPE_LENGTH (fp->type) == 0)
15210         {
15211           unsigned max = 0;
15212           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
15213             if (TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)) > max)
15214               max = TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i));
15215           TYPE_LENGTH (fp->type) = max;
15216         }
15217     }
15218   else
15219     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15220 }
15221
15222 /* Can the type given by DIE define another type?  */
15223
15224 static bool
15225 type_can_define_types (const struct die_info *die)
15226 {
15227   switch (die->tag)
15228     {
15229     case DW_TAG_typedef:
15230     case DW_TAG_class_type:
15231     case DW_TAG_structure_type:
15232     case DW_TAG_union_type:
15233     case DW_TAG_enumeration_type:
15234       return true;
15235
15236     default:
15237       return false;
15238     }
15239 }
15240
15241 /* Add a type definition defined in the scope of the FIP's class.  */
15242
15243 static void
15244 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15245                       struct dwarf2_cu *cu)
15246 {
15247   struct decl_field fp;
15248   memset (&fp, 0, sizeof (fp));
15249
15250   gdb_assert (type_can_define_types (die));
15251
15252   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15253   fp.name = dwarf2_name (die, cu);
15254   fp.type = read_type_die (die, cu);
15255
15256   /* Save accessibility.  */
15257   enum dwarf_access_attribute accessibility;
15258   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15259   if (attr != NULL)
15260     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15261   else
15262     accessibility = dwarf2_default_access_attribute (die, cu);
15263   switch (accessibility)
15264     {
15265     case DW_ACCESS_public:
15266       /* The assumed value if neither private nor protected.  */
15267       break;
15268     case DW_ACCESS_private:
15269       fp.is_private = 1;
15270       break;
15271     case DW_ACCESS_protected:
15272       fp.is_protected = 1;
15273       break;
15274     default:
15275       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15276     }
15277
15278   if (die->tag == DW_TAG_typedef)
15279     fip->typedef_field_list.push_back (fp);
15280   else
15281     fip->nested_types_list.push_back (fp);
15282 }
15283
15284 /* Create the vector of fields, and attach it to the type.  */
15285
15286 static void
15287 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15288                               struct dwarf2_cu *cu)
15289 {
15290   int nfields = fip->nfields;
15291
15292   /* Record the field count, allocate space for the array of fields,
15293      and create blank accessibility bitfields if necessary.  */
15294   TYPE_NFIELDS (type) = nfields;
15295   TYPE_FIELDS (type) = (struct field *)
15296     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15297
15298   if (fip->non_public_fields && cu->language != language_ada)
15299     {
15300       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15301
15302       TYPE_FIELD_PRIVATE_BITS (type) =
15303         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15304       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15305
15306       TYPE_FIELD_PROTECTED_BITS (type) =
15307         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15308       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15309
15310       TYPE_FIELD_IGNORE_BITS (type) =
15311         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15312       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15313     }
15314
15315   /* If the type has baseclasses, allocate and clear a bit vector for
15316      TYPE_FIELD_VIRTUAL_BITS.  */
15317   if (!fip->baseclasses.empty () && cu->language != language_ada)
15318     {
15319       int num_bytes = B_BYTES (fip->baseclasses.size ());
15320       unsigned char *pointer;
15321
15322       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15323       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15324       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15325       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15326       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15327     }
15328
15329   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15330     {
15331       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15332
15333       for (int index = 0; index < nfields; ++index)
15334         {
15335           struct nextfield &field = fip->fields[index];
15336
15337           if (field.variant.is_discriminant)
15338             di->discriminant_index = index;
15339           else if (field.variant.default_branch)
15340             di->default_index = index;
15341           else
15342             di->discriminants[index] = field.variant.discriminant_value;
15343         }
15344     }
15345
15346   /* Copy the saved-up fields into the field vector.  */
15347   for (int i = 0; i < nfields; ++i)
15348     {
15349       struct nextfield &field
15350         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15351            : fip->fields[i - fip->baseclasses.size ()]);
15352
15353       TYPE_FIELD (type, i) = field.field;
15354       switch (field.accessibility)
15355         {
15356         case DW_ACCESS_private:
15357           if (cu->language != language_ada)
15358             SET_TYPE_FIELD_PRIVATE (type, i);
15359           break;
15360
15361         case DW_ACCESS_protected:
15362           if (cu->language != language_ada)
15363             SET_TYPE_FIELD_PROTECTED (type, i);
15364           break;
15365
15366         case DW_ACCESS_public:
15367           break;
15368
15369         default:
15370           /* Unknown accessibility.  Complain and treat it as public.  */
15371           {
15372             complaint (_("unsupported accessibility %d"),
15373                        field.accessibility);
15374           }
15375           break;
15376         }
15377       if (i < fip->baseclasses.size ())
15378         {
15379           switch (field.virtuality)
15380             {
15381             case DW_VIRTUALITY_virtual:
15382             case DW_VIRTUALITY_pure_virtual:
15383               if (cu->language == language_ada)
15384                 error (_("unexpected virtuality in component of Ada type"));
15385               SET_TYPE_FIELD_VIRTUAL (type, i);
15386               break;
15387             }
15388         }
15389     }
15390 }
15391
15392 /* Return true if this member function is a constructor, false
15393    otherwise.  */
15394
15395 static int
15396 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15397 {
15398   const char *fieldname;
15399   const char *type_name;
15400   int len;
15401
15402   if (die->parent == NULL)
15403     return 0;
15404
15405   if (die->parent->tag != DW_TAG_structure_type
15406       && die->parent->tag != DW_TAG_union_type
15407       && die->parent->tag != DW_TAG_class_type)
15408     return 0;
15409
15410   fieldname = dwarf2_name (die, cu);
15411   type_name = dwarf2_name (die->parent, cu);
15412   if (fieldname == NULL || type_name == NULL)
15413     return 0;
15414
15415   len = strlen (fieldname);
15416   return (strncmp (fieldname, type_name, len) == 0
15417           && (type_name[len] == '\0' || type_name[len] == '<'));
15418 }
15419
15420 /* Add a member function to the proper fieldlist.  */
15421
15422 static void
15423 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15424                       struct type *type, struct dwarf2_cu *cu)
15425 {
15426   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15427   struct attribute *attr;
15428   int i;
15429   struct fnfieldlist *flp = nullptr;
15430   struct fn_field *fnp;
15431   const char *fieldname;
15432   struct type *this_type;
15433   enum dwarf_access_attribute accessibility;
15434
15435   if (cu->language == language_ada)
15436     error (_("unexpected member function in Ada type"));
15437
15438   /* Get name of member function.  */
15439   fieldname = dwarf2_name (die, cu);
15440   if (fieldname == NULL)
15441     return;
15442
15443   /* Look up member function name in fieldlist.  */
15444   for (i = 0; i < fip->fnfieldlists.size (); i++)
15445     {
15446       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15447         {
15448           flp = &fip->fnfieldlists[i];
15449           break;
15450         }
15451     }
15452
15453   /* Create a new fnfieldlist if necessary.  */
15454   if (flp == nullptr)
15455     {
15456       fip->fnfieldlists.emplace_back ();
15457       flp = &fip->fnfieldlists.back ();
15458       flp->name = fieldname;
15459       i = fip->fnfieldlists.size () - 1;
15460     }
15461
15462   /* Create a new member function field and add it to the vector of
15463      fnfieldlists.  */
15464   flp->fnfields.emplace_back ();
15465   fnp = &flp->fnfields.back ();
15466
15467   /* Delay processing of the physname until later.  */
15468   if (cu->language == language_cplus)
15469     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15470                         die, cu);
15471   else
15472     {
15473       const char *physname = dwarf2_physname (fieldname, die, cu);
15474       fnp->physname = physname ? physname : "";
15475     }
15476
15477   fnp->type = alloc_type (objfile);
15478   this_type = read_type_die (die, cu);
15479   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15480     {
15481       int nparams = TYPE_NFIELDS (this_type);
15482
15483       /* TYPE is the domain of this method, and THIS_TYPE is the type
15484            of the method itself (TYPE_CODE_METHOD).  */
15485       smash_to_method_type (fnp->type, type,
15486                             TYPE_TARGET_TYPE (this_type),
15487                             TYPE_FIELDS (this_type),
15488                             TYPE_NFIELDS (this_type),
15489                             TYPE_VARARGS (this_type));
15490
15491       /* Handle static member functions.
15492          Dwarf2 has no clean way to discern C++ static and non-static
15493          member functions.  G++ helps GDB by marking the first
15494          parameter for non-static member functions (which is the this
15495          pointer) as artificial.  We obtain this information from
15496          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15497       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15498         fnp->voffset = VOFFSET_STATIC;
15499     }
15500   else
15501     complaint (_("member function type missing for '%s'"),
15502                dwarf2_full_name (fieldname, die, cu));
15503
15504   /* Get fcontext from DW_AT_containing_type if present.  */
15505   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15506     fnp->fcontext = die_containing_type (die, cu);
15507
15508   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15509      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15510
15511   /* Get accessibility.  */
15512   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15513   if (attr)
15514     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15515   else
15516     accessibility = dwarf2_default_access_attribute (die, cu);
15517   switch (accessibility)
15518     {
15519     case DW_ACCESS_private:
15520       fnp->is_private = 1;
15521       break;
15522     case DW_ACCESS_protected:
15523       fnp->is_protected = 1;
15524       break;
15525     }
15526
15527   /* Check for artificial methods.  */
15528   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15529   if (attr && DW_UNSND (attr) != 0)
15530     fnp->is_artificial = 1;
15531
15532   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15533
15534   /* Get index in virtual function table if it is a virtual member
15535      function.  For older versions of GCC, this is an offset in the
15536      appropriate virtual table, as specified by DW_AT_containing_type.
15537      For everyone else, it is an expression to be evaluated relative
15538      to the object address.  */
15539
15540   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15541   if (attr)
15542     {
15543       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15544         {
15545           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15546             {
15547               /* Old-style GCC.  */
15548               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15549             }
15550           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15551                    || (DW_BLOCK (attr)->size > 1
15552                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15553                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15554             {
15555               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15556               if ((fnp->voffset % cu->header.addr_size) != 0)
15557                 dwarf2_complex_location_expr_complaint ();
15558               else
15559                 fnp->voffset /= cu->header.addr_size;
15560               fnp->voffset += 2;
15561             }
15562           else
15563             dwarf2_complex_location_expr_complaint ();
15564
15565           if (!fnp->fcontext)
15566             {
15567               /* If there is no `this' field and no DW_AT_containing_type,
15568                  we cannot actually find a base class context for the
15569                  vtable!  */
15570               if (TYPE_NFIELDS (this_type) == 0
15571                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15572                 {
15573                   complaint (_("cannot determine context for virtual member "
15574                                "function \"%s\" (offset %s)"),
15575                              fieldname, sect_offset_str (die->sect_off));
15576                 }
15577               else
15578                 {
15579                   fnp->fcontext
15580                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15581                 }
15582             }
15583         }
15584       else if (attr_form_is_section_offset (attr))
15585         {
15586           dwarf2_complex_location_expr_complaint ();
15587         }
15588       else
15589         {
15590           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15591                                                  fieldname);
15592         }
15593     }
15594   else
15595     {
15596       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15597       if (attr && DW_UNSND (attr))
15598         {
15599           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15600           complaint (_("Member function \"%s\" (offset %s) is virtual "
15601                        "but the vtable offset is not specified"),
15602                      fieldname, sect_offset_str (die->sect_off));
15603           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15604           TYPE_CPLUS_DYNAMIC (type) = 1;
15605         }
15606     }
15607 }
15608
15609 /* Create the vector of member function fields, and attach it to the type.  */
15610
15611 static void
15612 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15613                                  struct dwarf2_cu *cu)
15614 {
15615   if (cu->language == language_ada)
15616     error (_("unexpected member functions in Ada type"));
15617
15618   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15619   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15620     TYPE_ALLOC (type,
15621                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15622
15623   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15624     {
15625       struct fnfieldlist &nf = fip->fnfieldlists[i];
15626       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15627
15628       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15629       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15630       fn_flp->fn_fields = (struct fn_field *)
15631         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15632
15633       for (int k = 0; k < nf.fnfields.size (); ++k)
15634         fn_flp->fn_fields[k] = nf.fnfields[k];
15635     }
15636
15637   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15638 }
15639
15640 /* Returns non-zero if NAME is the name of a vtable member in CU's
15641    language, zero otherwise.  */
15642 static int
15643 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15644 {
15645   static const char vptr[] = "_vptr";
15646
15647   /* Look for the C++ form of the vtable.  */
15648   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15649     return 1;
15650
15651   return 0;
15652 }
15653
15654 /* GCC outputs unnamed structures that are really pointers to member
15655    functions, with the ABI-specified layout.  If TYPE describes
15656    such a structure, smash it into a member function type.
15657
15658    GCC shouldn't do this; it should just output pointer to member DIEs.
15659    This is GCC PR debug/28767.  */
15660
15661 static void
15662 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15663 {
15664   struct type *pfn_type, *self_type, *new_type;
15665
15666   /* Check for a structure with no name and two children.  */
15667   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15668     return;
15669
15670   /* Check for __pfn and __delta members.  */
15671   if (TYPE_FIELD_NAME (type, 0) == NULL
15672       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15673       || TYPE_FIELD_NAME (type, 1) == NULL
15674       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15675     return;
15676
15677   /* Find the type of the method.  */
15678   pfn_type = TYPE_FIELD_TYPE (type, 0);
15679   if (pfn_type == NULL
15680       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15681       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15682     return;
15683
15684   /* Look for the "this" argument.  */
15685   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15686   if (TYPE_NFIELDS (pfn_type) == 0
15687       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15688       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15689     return;
15690
15691   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15692   new_type = alloc_type (objfile);
15693   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15694                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15695                         TYPE_VARARGS (pfn_type));
15696   smash_to_methodptr_type (type, new_type);
15697 }
15698
15699 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15700    appropriate error checking and issuing complaints if there is a
15701    problem.  */
15702
15703 static ULONGEST
15704 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15705 {
15706   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15707
15708   if (attr == nullptr)
15709     return 0;
15710
15711   if (!attr_form_is_constant (attr))
15712     {
15713       complaint (_("DW_AT_alignment must have constant form"
15714                    " - DIE at %s [in module %s]"),
15715                  sect_offset_str (die->sect_off),
15716                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15717       return 0;
15718     }
15719
15720   ULONGEST align;
15721   if (attr->form == DW_FORM_sdata)
15722     {
15723       LONGEST val = DW_SND (attr);
15724       if (val < 0)
15725         {
15726           complaint (_("DW_AT_alignment value must not be negative"
15727                        " - DIE at %s [in module %s]"),
15728                      sect_offset_str (die->sect_off),
15729                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15730           return 0;
15731         }
15732       align = val;
15733     }
15734   else
15735     align = DW_UNSND (attr);
15736
15737   if (align == 0)
15738     {
15739       complaint (_("DW_AT_alignment value must not be zero"
15740                    " - DIE at %s [in module %s]"),
15741                  sect_offset_str (die->sect_off),
15742                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15743       return 0;
15744     }
15745   if ((align & (align - 1)) != 0)
15746     {
15747       complaint (_("DW_AT_alignment value must be a power of 2"
15748                    " - DIE at %s [in module %s]"),
15749                  sect_offset_str (die->sect_off),
15750                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15751       return 0;
15752     }
15753
15754   return align;
15755 }
15756
15757 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15758    the alignment for TYPE.  */
15759
15760 static void
15761 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15762                      struct type *type)
15763 {
15764   if (!set_type_align (type, get_alignment (cu, die)))
15765     complaint (_("DW_AT_alignment value too large"
15766                  " - DIE at %s [in module %s]"),
15767                sect_offset_str (die->sect_off),
15768                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15769 }
15770
15771 /* Called when we find the DIE that starts a structure or union scope
15772    (definition) to create a type for the structure or union.  Fill in
15773    the type's name and general properties; the members will not be
15774    processed until process_structure_scope.  A symbol table entry for
15775    the type will also not be done until process_structure_scope (assuming
15776    the type has a name).
15777
15778    NOTE: we need to call these functions regardless of whether or not the
15779    DIE has a DW_AT_name attribute, since it might be an anonymous
15780    structure or union.  This gets the type entered into our set of
15781    user defined types.  */
15782
15783 static struct type *
15784 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15785 {
15786   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15787   struct type *type;
15788   struct attribute *attr;
15789   const char *name;
15790
15791   /* If the definition of this type lives in .debug_types, read that type.
15792      Don't follow DW_AT_specification though, that will take us back up
15793      the chain and we want to go down.  */
15794   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15795   if (attr)
15796     {
15797       type = get_DW_AT_signature_type (die, attr, cu);
15798
15799       /* The type's CU may not be the same as CU.
15800          Ensure TYPE is recorded with CU in die_type_hash.  */
15801       return set_die_type (die, type, cu);
15802     }
15803
15804   type = alloc_type (objfile);
15805   INIT_CPLUS_SPECIFIC (type);
15806
15807   name = dwarf2_name (die, cu);
15808   if (name != NULL)
15809     {
15810       if (cu->language == language_cplus
15811           || cu->language == language_d
15812           || cu->language == language_rust)
15813         {
15814           const char *full_name = dwarf2_full_name (name, die, cu);
15815
15816           /* dwarf2_full_name might have already finished building the DIE's
15817              type.  If so, there is no need to continue.  */
15818           if (get_die_type (die, cu) != NULL)
15819             return get_die_type (die, cu);
15820
15821           TYPE_NAME (type) = full_name;
15822         }
15823       else
15824         {
15825           /* The name is already allocated along with this objfile, so
15826              we don't need to duplicate it for the type.  */
15827           TYPE_NAME (type) = name;
15828         }
15829     }
15830
15831   if (die->tag == DW_TAG_structure_type)
15832     {
15833       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15834     }
15835   else if (die->tag == DW_TAG_union_type)
15836     {
15837       TYPE_CODE (type) = TYPE_CODE_UNION;
15838     }
15839   else if (die->tag == DW_TAG_variant_part)
15840     {
15841       TYPE_CODE (type) = TYPE_CODE_UNION;
15842       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15843     }
15844   else
15845     {
15846       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15847     }
15848
15849   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15850     TYPE_DECLARED_CLASS (type) = 1;
15851
15852   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15853   if (attr)
15854     {
15855       if (attr_form_is_constant (attr))
15856         TYPE_LENGTH (type) = DW_UNSND (attr);
15857       else
15858         {
15859           /* For the moment, dynamic type sizes are not supported
15860              by GDB's struct type.  The actual size is determined
15861              on-demand when resolving the type of a given object,
15862              so set the type's length to zero for now.  Otherwise,
15863              we record an expression as the length, and that expression
15864              could lead to a very large value, which could eventually
15865              lead to us trying to allocate that much memory when creating
15866              a value of that type.  */
15867           TYPE_LENGTH (type) = 0;
15868         }
15869     }
15870   else
15871     {
15872       TYPE_LENGTH (type) = 0;
15873     }
15874
15875   maybe_set_alignment (cu, die, type);
15876
15877   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15878     {
15879       /* ICC<14 does not output the required DW_AT_declaration on
15880          incomplete types, but gives them a size of zero.  */
15881       TYPE_STUB (type) = 1;
15882     }
15883   else
15884     TYPE_STUB_SUPPORTED (type) = 1;
15885
15886   if (die_is_declaration (die, cu))
15887     TYPE_STUB (type) = 1;
15888   else if (attr == NULL && die->child == NULL
15889            && producer_is_realview (cu->producer))
15890     /* RealView does not output the required DW_AT_declaration
15891        on incomplete types.  */
15892     TYPE_STUB (type) = 1;
15893
15894   /* We need to add the type field to the die immediately so we don't
15895      infinitely recurse when dealing with pointers to the structure
15896      type within the structure itself.  */
15897   set_die_type (die, type, cu);
15898
15899   /* set_die_type should be already done.  */
15900   set_descriptive_type (type, die, cu);
15901
15902   return type;
15903 }
15904
15905 /* A helper for process_structure_scope that handles a single member
15906    DIE.  */
15907
15908 static void
15909 handle_struct_member_die (struct die_info *child_die, struct type *type,
15910                           struct field_info *fi,
15911                           std::vector<struct symbol *> *template_args,
15912                           struct dwarf2_cu *cu)
15913 {
15914   if (child_die->tag == DW_TAG_member
15915       || child_die->tag == DW_TAG_variable
15916       || child_die->tag == DW_TAG_variant_part)
15917     {
15918       /* NOTE: carlton/2002-11-05: A C++ static data member
15919          should be a DW_TAG_member that is a declaration, but
15920          all versions of G++ as of this writing (so through at
15921          least 3.2.1) incorrectly generate DW_TAG_variable
15922          tags for them instead.  */
15923       dwarf2_add_field (fi, child_die, cu);
15924     }
15925   else if (child_die->tag == DW_TAG_subprogram)
15926     {
15927       /* Rust doesn't have member functions in the C++ sense.
15928          However, it does emit ordinary functions as children
15929          of a struct DIE.  */
15930       if (cu->language == language_rust)
15931         read_func_scope (child_die, cu);
15932       else
15933         {
15934           /* C++ member function.  */
15935           dwarf2_add_member_fn (fi, child_die, type, cu);
15936         }
15937     }
15938   else if (child_die->tag == DW_TAG_inheritance)
15939     {
15940       /* C++ base class field.  */
15941       dwarf2_add_field (fi, child_die, cu);
15942     }
15943   else if (type_can_define_types (child_die))
15944     dwarf2_add_type_defn (fi, child_die, cu);
15945   else if (child_die->tag == DW_TAG_template_type_param
15946            || child_die->tag == DW_TAG_template_value_param)
15947     {
15948       struct symbol *arg = new_symbol (child_die, NULL, cu);
15949
15950       if (arg != NULL)
15951         template_args->push_back (arg);
15952     }
15953   else if (child_die->tag == DW_TAG_variant)
15954     {
15955       /* In a variant we want to get the discriminant and also add a
15956          field for our sole member child.  */
15957       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15958
15959       for (struct die_info *variant_child = child_die->child;
15960            variant_child != NULL;
15961            variant_child = sibling_die (variant_child))
15962         {
15963           if (variant_child->tag == DW_TAG_member)
15964             {
15965               handle_struct_member_die (variant_child, type, fi,
15966                                         template_args, cu);
15967               /* Only handle the one.  */
15968               break;
15969             }
15970         }
15971
15972       /* We don't handle this but we might as well report it if we see
15973          it.  */
15974       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15975           complaint (_("DW_AT_discr_list is not supported yet"
15976                        " - DIE at %s [in module %s]"),
15977                      sect_offset_str (child_die->sect_off),
15978                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15979
15980       /* The first field was just added, so we can stash the
15981          discriminant there.  */
15982       gdb_assert (!fi->fields.empty ());
15983       if (discr == NULL)
15984         fi->fields.back ().variant.default_branch = true;
15985       else
15986         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15987     }
15988 }
15989
15990 /* Finish creating a structure or union type, including filling in
15991    its members and creating a symbol for it.  */
15992
15993 static void
15994 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15995 {
15996   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15997   struct die_info *child_die;
15998   struct type *type;
15999
16000   type = get_die_type (die, cu);
16001   if (type == NULL)
16002     type = read_structure_type (die, cu);
16003
16004   /* When reading a DW_TAG_variant_part, we need to notice when we
16005      read the discriminant member, so we can record it later in the
16006      discriminant_info.  */
16007   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
16008   sect_offset discr_offset;
16009   bool has_template_parameters = false;
16010
16011   if (is_variant_part)
16012     {
16013       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
16014       if (discr == NULL)
16015         {
16016           /* Maybe it's a univariant form, an extension we support.
16017              In this case arrange not to check the offset.  */
16018           is_variant_part = false;
16019         }
16020       else if (attr_form_is_ref (discr))
16021         {
16022           struct dwarf2_cu *target_cu = cu;
16023           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
16024
16025           discr_offset = target_die->sect_off;
16026         }
16027       else
16028         {
16029           complaint (_("DW_AT_discr does not have DIE reference form"
16030                        " - DIE at %s [in module %s]"),
16031                      sect_offset_str (die->sect_off),
16032                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16033           is_variant_part = false;
16034         }
16035     }
16036
16037   if (die->child != NULL && ! die_is_declaration (die, cu))
16038     {
16039       struct field_info fi;
16040       std::vector<struct symbol *> template_args;
16041
16042       child_die = die->child;
16043
16044       while (child_die && child_die->tag)
16045         {
16046           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
16047
16048           if (is_variant_part && discr_offset == child_die->sect_off)
16049             fi.fields.back ().variant.is_discriminant = true;
16050
16051           child_die = sibling_die (child_die);
16052         }
16053
16054       /* Attach template arguments to type.  */
16055       if (!template_args.empty ())
16056         {
16057           has_template_parameters = true;
16058           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16059           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16060           TYPE_TEMPLATE_ARGUMENTS (type)
16061             = XOBNEWVEC (&objfile->objfile_obstack,
16062                          struct symbol *,
16063                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16064           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16065                   template_args.data (),
16066                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16067                    * sizeof (struct symbol *)));
16068         }
16069
16070       /* Attach fields and member functions to the type.  */
16071       if (fi.nfields)
16072         dwarf2_attach_fields_to_type (&fi, type, cu);
16073       if (!fi.fnfieldlists.empty ())
16074         {
16075           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16076
16077           /* Get the type which refers to the base class (possibly this
16078              class itself) which contains the vtable pointer for the current
16079              class from the DW_AT_containing_type attribute.  This use of
16080              DW_AT_containing_type is a GNU extension.  */
16081
16082           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16083             {
16084               struct type *t = die_containing_type (die, cu);
16085
16086               set_type_vptr_basetype (type, t);
16087               if (type == t)
16088                 {
16089                   int i;
16090
16091                   /* Our own class provides vtbl ptr.  */
16092                   for (i = TYPE_NFIELDS (t) - 1;
16093                        i >= TYPE_N_BASECLASSES (t);
16094                        --i)
16095                     {
16096                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16097
16098                       if (is_vtable_name (fieldname, cu))
16099                         {
16100                           set_type_vptr_fieldno (type, i);
16101                           break;
16102                         }
16103                     }
16104
16105                   /* Complain if virtual function table field not found.  */
16106                   if (i < TYPE_N_BASECLASSES (t))
16107                     complaint (_("virtual function table pointer "
16108                                  "not found when defining class '%s'"),
16109                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
16110                 }
16111               else
16112                 {
16113                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16114                 }
16115             }
16116           else if (cu->producer
16117                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16118             {
16119               /* The IBM XLC compiler does not provide direct indication
16120                  of the containing type, but the vtable pointer is
16121                  always named __vfp.  */
16122
16123               int i;
16124
16125               for (i = TYPE_NFIELDS (type) - 1;
16126                    i >= TYPE_N_BASECLASSES (type);
16127                    --i)
16128                 {
16129                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16130                     {
16131                       set_type_vptr_fieldno (type, i);
16132                       set_type_vptr_basetype (type, type);
16133                       break;
16134                     }
16135                 }
16136             }
16137         }
16138
16139       /* Copy fi.typedef_field_list linked list elements content into the
16140          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16141       if (!fi.typedef_field_list.empty ())
16142         {
16143           int count = fi.typedef_field_list.size ();
16144
16145           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16146           TYPE_TYPEDEF_FIELD_ARRAY (type)
16147             = ((struct decl_field *)
16148                TYPE_ALLOC (type,
16149                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16150           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16151
16152           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16153             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16154         }
16155
16156       /* Copy fi.nested_types_list linked list elements content into the
16157          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16158       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16159         {
16160           int count = fi.nested_types_list.size ();
16161
16162           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16163           TYPE_NESTED_TYPES_ARRAY (type)
16164             = ((struct decl_field *)
16165                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16166           TYPE_NESTED_TYPES_COUNT (type) = count;
16167
16168           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16169             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16170         }
16171     }
16172
16173   quirk_gcc_member_function_pointer (type, objfile);
16174   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16175     cu->rust_unions.push_back (type);
16176
16177   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16178      snapshots) has been known to create a die giving a declaration
16179      for a class that has, as a child, a die giving a definition for a
16180      nested class.  So we have to process our children even if the
16181      current die is a declaration.  Normally, of course, a declaration
16182      won't have any children at all.  */
16183
16184   child_die = die->child;
16185
16186   while (child_die != NULL && child_die->tag)
16187     {
16188       if (child_die->tag == DW_TAG_member
16189           || child_die->tag == DW_TAG_variable
16190           || child_die->tag == DW_TAG_inheritance
16191           || child_die->tag == DW_TAG_template_value_param
16192           || child_die->tag == DW_TAG_template_type_param)
16193         {
16194           /* Do nothing.  */
16195         }
16196       else
16197         process_die (child_die, cu);
16198
16199       child_die = sibling_die (child_die);
16200     }
16201
16202   /* Do not consider external references.  According to the DWARF standard,
16203      these DIEs are identified by the fact that they have no byte_size
16204      attribute, and a declaration attribute.  */
16205   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16206       || !die_is_declaration (die, cu))
16207     {
16208       struct symbol *sym = new_symbol (die, type, cu);
16209
16210       if (has_template_parameters)
16211         {
16212           /* Make sure that the symtab is set on the new symbols.
16213              Even though they don't appear in this symtab directly,
16214              other parts of gdb assume that symbols do, and this is
16215              reasonably true.  */
16216           for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16217             symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i),
16218                                symbol_symtab (sym));
16219         }
16220     }
16221 }
16222
16223 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16224    update TYPE using some information only available in DIE's children.  */
16225
16226 static void
16227 update_enumeration_type_from_children (struct die_info *die,
16228                                        struct type *type,
16229                                        struct dwarf2_cu *cu)
16230 {
16231   struct die_info *child_die;
16232   int unsigned_enum = 1;
16233   int flag_enum = 1;
16234   ULONGEST mask = 0;
16235
16236   auto_obstack obstack;
16237
16238   for (child_die = die->child;
16239        child_die != NULL && child_die->tag;
16240        child_die = sibling_die (child_die))
16241     {
16242       struct attribute *attr;
16243       LONGEST value;
16244       const gdb_byte *bytes;
16245       struct dwarf2_locexpr_baton *baton;
16246       const char *name;
16247
16248       if (child_die->tag != DW_TAG_enumerator)
16249         continue;
16250
16251       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16252       if (attr == NULL)
16253         continue;
16254
16255       name = dwarf2_name (child_die, cu);
16256       if (name == NULL)
16257         name = "<anonymous enumerator>";
16258
16259       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16260                                &value, &bytes, &baton);
16261       if (value < 0)
16262         {
16263           unsigned_enum = 0;
16264           flag_enum = 0;
16265         }
16266       else if ((mask & value) != 0)
16267         flag_enum = 0;
16268       else
16269         mask |= value;
16270
16271       /* If we already know that the enum type is neither unsigned, nor
16272          a flag type, no need to look at the rest of the enumerates.  */
16273       if (!unsigned_enum && !flag_enum)
16274         break;
16275     }
16276
16277   if (unsigned_enum)
16278     TYPE_UNSIGNED (type) = 1;
16279   if (flag_enum)
16280     TYPE_FLAG_ENUM (type) = 1;
16281 }
16282
16283 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16284    complete the type's fields yet, or create any symbols.  */
16285
16286 static struct type *
16287 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16288 {
16289   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16290   struct type *type;
16291   struct attribute *attr;
16292   const char *name;
16293
16294   /* If the definition of this type lives in .debug_types, read that type.
16295      Don't follow DW_AT_specification though, that will take us back up
16296      the chain and we want to go down.  */
16297   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16298   if (attr)
16299     {
16300       type = get_DW_AT_signature_type (die, attr, cu);
16301
16302       /* The type's CU may not be the same as CU.
16303          Ensure TYPE is recorded with CU in die_type_hash.  */
16304       return set_die_type (die, type, cu);
16305     }
16306
16307   type = alloc_type (objfile);
16308
16309   TYPE_CODE (type) = TYPE_CODE_ENUM;
16310   name = dwarf2_full_name (NULL, die, cu);
16311   if (name != NULL)
16312     TYPE_NAME (type) = name;
16313
16314   attr = dwarf2_attr (die, DW_AT_type, cu);
16315   if (attr != NULL)
16316     {
16317       struct type *underlying_type = die_type (die, cu);
16318
16319       TYPE_TARGET_TYPE (type) = underlying_type;
16320     }
16321
16322   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16323   if (attr)
16324     {
16325       TYPE_LENGTH (type) = DW_UNSND (attr);
16326     }
16327   else
16328     {
16329       TYPE_LENGTH (type) = 0;
16330     }
16331
16332   maybe_set_alignment (cu, die, type);
16333
16334   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16335      declared as private in the package spec, and then defined only
16336      inside the package body.  Such types are known as Taft Amendment
16337      Types.  When another package uses such a type, an incomplete DIE
16338      may be generated by the compiler.  */
16339   if (die_is_declaration (die, cu))
16340     TYPE_STUB (type) = 1;
16341
16342   /* Finish the creation of this type by using the enum's children.
16343      We must call this even when the underlying type has been provided
16344      so that we can determine if we're looking at a "flag" enum.  */
16345   update_enumeration_type_from_children (die, type, cu);
16346
16347   /* If this type has an underlying type that is not a stub, then we
16348      may use its attributes.  We always use the "unsigned" attribute
16349      in this situation, because ordinarily we guess whether the type
16350      is unsigned -- but the guess can be wrong and the underlying type
16351      can tell us the reality.  However, we defer to a local size
16352      attribute if one exists, because this lets the compiler override
16353      the underlying type if needed.  */
16354   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16355     {
16356       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16357       if (TYPE_LENGTH (type) == 0)
16358         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16359       if (TYPE_RAW_ALIGN (type) == 0
16360           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16361         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16362     }
16363
16364   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16365
16366   return set_die_type (die, type, cu);
16367 }
16368
16369 /* Given a pointer to a die which begins an enumeration, process all
16370    the dies that define the members of the enumeration, and create the
16371    symbol for the enumeration type.
16372
16373    NOTE: We reverse the order of the element list.  */
16374
16375 static void
16376 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16377 {
16378   struct type *this_type;
16379
16380   this_type = get_die_type (die, cu);
16381   if (this_type == NULL)
16382     this_type = read_enumeration_type (die, cu);
16383
16384   if (die->child != NULL)
16385     {
16386       struct die_info *child_die;
16387       struct symbol *sym;
16388       struct field *fields = NULL;
16389       int num_fields = 0;
16390       const char *name;
16391
16392       child_die = die->child;
16393       while (child_die && child_die->tag)
16394         {
16395           if (child_die->tag != DW_TAG_enumerator)
16396             {
16397               process_die (child_die, cu);
16398             }
16399           else
16400             {
16401               name = dwarf2_name (child_die, cu);
16402               if (name)
16403                 {
16404                   sym = new_symbol (child_die, this_type, cu);
16405
16406                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16407                     {
16408                       fields = (struct field *)
16409                         xrealloc (fields,
16410                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16411                                   * sizeof (struct field));
16412                     }
16413
16414                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16415                   FIELD_TYPE (fields[num_fields]) = NULL;
16416                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16417                   FIELD_BITSIZE (fields[num_fields]) = 0;
16418
16419                   num_fields++;
16420                 }
16421             }
16422
16423           child_die = sibling_die (child_die);
16424         }
16425
16426       if (num_fields)
16427         {
16428           TYPE_NFIELDS (this_type) = num_fields;
16429           TYPE_FIELDS (this_type) = (struct field *)
16430             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16431           memcpy (TYPE_FIELDS (this_type), fields,
16432                   sizeof (struct field) * num_fields);
16433           xfree (fields);
16434         }
16435     }
16436
16437   /* If we are reading an enum from a .debug_types unit, and the enum
16438      is a declaration, and the enum is not the signatured type in the
16439      unit, then we do not want to add a symbol for it.  Adding a
16440      symbol would in some cases obscure the true definition of the
16441      enum, giving users an incomplete type when the definition is
16442      actually available.  Note that we do not want to do this for all
16443      enums which are just declarations, because C++0x allows forward
16444      enum declarations.  */
16445   if (cu->per_cu->is_debug_types
16446       && die_is_declaration (die, cu))
16447     {
16448       struct signatured_type *sig_type;
16449
16450       sig_type = (struct signatured_type *) cu->per_cu;
16451       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16452       if (sig_type->type_offset_in_section != die->sect_off)
16453         return;
16454     }
16455
16456   new_symbol (die, this_type, cu);
16457 }
16458
16459 /* Extract all information from a DW_TAG_array_type DIE and put it in
16460    the DIE's type field.  For now, this only handles one dimensional
16461    arrays.  */
16462
16463 static struct type *
16464 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16465 {
16466   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16467   struct die_info *child_die;
16468   struct type *type;
16469   struct type *element_type, *range_type, *index_type;
16470   struct attribute *attr;
16471   const char *name;
16472   struct dynamic_prop *byte_stride_prop = NULL;
16473   unsigned int bit_stride = 0;
16474
16475   element_type = die_type (die, cu);
16476
16477   /* The die_type call above may have already set the type for this DIE.  */
16478   type = get_die_type (die, cu);
16479   if (type)
16480     return type;
16481
16482   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16483   if (attr != NULL)
16484     {
16485       int stride_ok;
16486
16487       byte_stride_prop
16488         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16489       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16490       if (!stride_ok)
16491         {
16492           complaint (_("unable to read array DW_AT_byte_stride "
16493                        " - DIE at %s [in module %s]"),
16494                      sect_offset_str (die->sect_off),
16495                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16496           /* Ignore this attribute.  We will likely not be able to print
16497              arrays of this type correctly, but there is little we can do
16498              to help if we cannot read the attribute's value.  */
16499           byte_stride_prop = NULL;
16500         }
16501     }
16502
16503   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16504   if (attr != NULL)
16505     bit_stride = DW_UNSND (attr);
16506
16507   /* Irix 6.2 native cc creates array types without children for
16508      arrays with unspecified length.  */
16509   if (die->child == NULL)
16510     {
16511       index_type = objfile_type (objfile)->builtin_int;
16512       range_type = create_static_range_type (NULL, index_type, 0, -1);
16513       type = create_array_type_with_stride (NULL, element_type, range_type,
16514                                             byte_stride_prop, bit_stride);
16515       return set_die_type (die, type, cu);
16516     }
16517
16518   std::vector<struct type *> range_types;
16519   child_die = die->child;
16520   while (child_die && child_die->tag)
16521     {
16522       if (child_die->tag == DW_TAG_subrange_type)
16523         {
16524           struct type *child_type = read_type_die (child_die, cu);
16525
16526           if (child_type != NULL)
16527             {
16528               /* The range type was succesfully read.  Save it for the
16529                  array type creation.  */
16530               range_types.push_back (child_type);
16531             }
16532         }
16533       child_die = sibling_die (child_die);
16534     }
16535
16536   /* Dwarf2 dimensions are output from left to right, create the
16537      necessary array types in backwards order.  */
16538
16539   type = element_type;
16540
16541   if (read_array_order (die, cu) == DW_ORD_col_major)
16542     {
16543       int i = 0;
16544
16545       while (i < range_types.size ())
16546         type = create_array_type_with_stride (NULL, type, range_types[i++],
16547                                               byte_stride_prop, bit_stride);
16548     }
16549   else
16550     {
16551       size_t ndim = range_types.size ();
16552       while (ndim-- > 0)
16553         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16554                                               byte_stride_prop, bit_stride);
16555     }
16556
16557   /* Understand Dwarf2 support for vector types (like they occur on
16558      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16559      array type.  This is not part of the Dwarf2/3 standard yet, but a
16560      custom vendor extension.  The main difference between a regular
16561      array and the vector variant is that vectors are passed by value
16562      to functions.  */
16563   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16564   if (attr)
16565     make_vector_type (type);
16566
16567   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16568      implementation may choose to implement triple vectors using this
16569      attribute.  */
16570   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16571   if (attr)
16572     {
16573       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16574         TYPE_LENGTH (type) = DW_UNSND (attr);
16575       else
16576         complaint (_("DW_AT_byte_size for array type smaller "
16577                      "than the total size of elements"));
16578     }
16579
16580   name = dwarf2_name (die, cu);
16581   if (name)
16582     TYPE_NAME (type) = name;
16583
16584   maybe_set_alignment (cu, die, type);
16585
16586   /* Install the type in the die.  */
16587   set_die_type (die, type, cu);
16588
16589   /* set_die_type should be already done.  */
16590   set_descriptive_type (type, die, cu);
16591
16592   return type;
16593 }
16594
16595 static enum dwarf_array_dim_ordering
16596 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16597 {
16598   struct attribute *attr;
16599
16600   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16601
16602   if (attr)
16603     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16604
16605   /* GNU F77 is a special case, as at 08/2004 array type info is the
16606      opposite order to the dwarf2 specification, but data is still
16607      laid out as per normal fortran.
16608
16609      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16610      version checking.  */
16611
16612   if (cu->language == language_fortran
16613       && cu->producer && strstr (cu->producer, "GNU F77"))
16614     {
16615       return DW_ORD_row_major;
16616     }
16617
16618   switch (cu->language_defn->la_array_ordering)
16619     {
16620     case array_column_major:
16621       return DW_ORD_col_major;
16622     case array_row_major:
16623     default:
16624       return DW_ORD_row_major;
16625     };
16626 }
16627
16628 /* Extract all information from a DW_TAG_set_type DIE and put it in
16629    the DIE's type field.  */
16630
16631 static struct type *
16632 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16633 {
16634   struct type *domain_type, *set_type;
16635   struct attribute *attr;
16636
16637   domain_type = die_type (die, cu);
16638
16639   /* The die_type call above may have already set the type for this DIE.  */
16640   set_type = get_die_type (die, cu);
16641   if (set_type)
16642     return set_type;
16643
16644   set_type = create_set_type (NULL, domain_type);
16645
16646   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16647   if (attr)
16648     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16649
16650   maybe_set_alignment (cu, die, set_type);
16651
16652   return set_die_type (die, set_type, cu);
16653 }
16654
16655 /* A helper for read_common_block that creates a locexpr baton.
16656    SYM is the symbol which we are marking as computed.
16657    COMMON_DIE is the DIE for the common block.
16658    COMMON_LOC is the location expression attribute for the common
16659    block itself.
16660    MEMBER_LOC is the location expression attribute for the particular
16661    member of the common block that we are processing.
16662    CU is the CU from which the above come.  */
16663
16664 static void
16665 mark_common_block_symbol_computed (struct symbol *sym,
16666                                    struct die_info *common_die,
16667                                    struct attribute *common_loc,
16668                                    struct attribute *member_loc,
16669                                    struct dwarf2_cu *cu)
16670 {
16671   struct dwarf2_per_objfile *dwarf2_per_objfile
16672     = cu->per_cu->dwarf2_per_objfile;
16673   struct objfile *objfile = dwarf2_per_objfile->objfile;
16674   struct dwarf2_locexpr_baton *baton;
16675   gdb_byte *ptr;
16676   unsigned int cu_off;
16677   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16678   LONGEST offset = 0;
16679
16680   gdb_assert (common_loc && member_loc);
16681   gdb_assert (attr_form_is_block (common_loc));
16682   gdb_assert (attr_form_is_block (member_loc)
16683               || attr_form_is_constant (member_loc));
16684
16685   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16686   baton->per_cu = cu->per_cu;
16687   gdb_assert (baton->per_cu);
16688
16689   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16690
16691   if (attr_form_is_constant (member_loc))
16692     {
16693       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16694       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16695     }
16696   else
16697     baton->size += DW_BLOCK (member_loc)->size;
16698
16699   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16700   baton->data = ptr;
16701
16702   *ptr++ = DW_OP_call4;
16703   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16704   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16705   ptr += 4;
16706
16707   if (attr_form_is_constant (member_loc))
16708     {
16709       *ptr++ = DW_OP_addr;
16710       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16711       ptr += cu->header.addr_size;
16712     }
16713   else
16714     {
16715       /* We have to copy the data here, because DW_OP_call4 will only
16716          use a DW_AT_location attribute.  */
16717       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16718       ptr += DW_BLOCK (member_loc)->size;
16719     }
16720
16721   *ptr++ = DW_OP_plus;
16722   gdb_assert (ptr - baton->data == baton->size);
16723
16724   SYMBOL_LOCATION_BATON (sym) = baton;
16725   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16726 }
16727
16728 /* Create appropriate locally-scoped variables for all the
16729    DW_TAG_common_block entries.  Also create a struct common_block
16730    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16731    is used to sepate the common blocks name namespace from regular
16732    variable names.  */
16733
16734 static void
16735 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16736 {
16737   struct attribute *attr;
16738
16739   attr = dwarf2_attr (die, DW_AT_location, cu);
16740   if (attr)
16741     {
16742       /* Support the .debug_loc offsets.  */
16743       if (attr_form_is_block (attr))
16744         {
16745           /* Ok.  */
16746         }
16747       else if (attr_form_is_section_offset (attr))
16748         {
16749           dwarf2_complex_location_expr_complaint ();
16750           attr = NULL;
16751         }
16752       else
16753         {
16754           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16755                                                  "common block member");
16756           attr = NULL;
16757         }
16758     }
16759
16760   if (die->child != NULL)
16761     {
16762       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16763       struct die_info *child_die;
16764       size_t n_entries = 0, size;
16765       struct common_block *common_block;
16766       struct symbol *sym;
16767
16768       for (child_die = die->child;
16769            child_die && child_die->tag;
16770            child_die = sibling_die (child_die))
16771         ++n_entries;
16772
16773       size = (sizeof (struct common_block)
16774               + (n_entries - 1) * sizeof (struct symbol *));
16775       common_block
16776         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16777                                                  size);
16778       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16779       common_block->n_entries = 0;
16780
16781       for (child_die = die->child;
16782            child_die && child_die->tag;
16783            child_die = sibling_die (child_die))
16784         {
16785           /* Create the symbol in the DW_TAG_common_block block in the current
16786              symbol scope.  */
16787           sym = new_symbol (child_die, NULL, cu);
16788           if (sym != NULL)
16789             {
16790               struct attribute *member_loc;
16791
16792               common_block->contents[common_block->n_entries++] = sym;
16793
16794               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16795                                         cu);
16796               if (member_loc)
16797                 {
16798                   /* GDB has handled this for a long time, but it is
16799                      not specified by DWARF.  It seems to have been
16800                      emitted by gfortran at least as recently as:
16801                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16802                   complaint (_("Variable in common block has "
16803                                "DW_AT_data_member_location "
16804                                "- DIE at %s [in module %s]"),
16805                                sect_offset_str (child_die->sect_off),
16806                              objfile_name (objfile));
16807
16808                   if (attr_form_is_section_offset (member_loc))
16809                     dwarf2_complex_location_expr_complaint ();
16810                   else if (attr_form_is_constant (member_loc)
16811                            || attr_form_is_block (member_loc))
16812                     {
16813                       if (attr)
16814                         mark_common_block_symbol_computed (sym, die, attr,
16815                                                            member_loc, cu);
16816                     }
16817                   else
16818                     dwarf2_complex_location_expr_complaint ();
16819                 }
16820             }
16821         }
16822
16823       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16824       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16825     }
16826 }
16827
16828 /* Create a type for a C++ namespace.  */
16829
16830 static struct type *
16831 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16832 {
16833   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16834   const char *previous_prefix, *name;
16835   int is_anonymous;
16836   struct type *type;
16837
16838   /* For extensions, reuse the type of the original namespace.  */
16839   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16840     {
16841       struct die_info *ext_die;
16842       struct dwarf2_cu *ext_cu = cu;
16843
16844       ext_die = dwarf2_extension (die, &ext_cu);
16845       type = read_type_die (ext_die, ext_cu);
16846
16847       /* EXT_CU may not be the same as CU.
16848          Ensure TYPE is recorded with CU in die_type_hash.  */
16849       return set_die_type (die, type, cu);
16850     }
16851
16852   name = namespace_name (die, &is_anonymous, cu);
16853
16854   /* Now build the name of the current namespace.  */
16855
16856   previous_prefix = determine_prefix (die, cu);
16857   if (previous_prefix[0] != '\0')
16858     name = typename_concat (&objfile->objfile_obstack,
16859                             previous_prefix, name, 0, cu);
16860
16861   /* Create the type.  */
16862   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16863
16864   return set_die_type (die, type, cu);
16865 }
16866
16867 /* Read a namespace scope.  */
16868
16869 static void
16870 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16871 {
16872   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16873   int is_anonymous;
16874
16875   /* Add a symbol associated to this if we haven't seen the namespace
16876      before.  Also, add a using directive if it's an anonymous
16877      namespace.  */
16878
16879   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16880     {
16881       struct type *type;
16882
16883       type = read_type_die (die, cu);
16884       new_symbol (die, type, cu);
16885
16886       namespace_name (die, &is_anonymous, cu);
16887       if (is_anonymous)
16888         {
16889           const char *previous_prefix = determine_prefix (die, cu);
16890
16891           std::vector<const char *> excludes;
16892           add_using_directive (using_directives (cu),
16893                                previous_prefix, TYPE_NAME (type), NULL,
16894                                NULL, excludes, 0, &objfile->objfile_obstack);
16895         }
16896     }
16897
16898   if (die->child != NULL)
16899     {
16900       struct die_info *child_die = die->child;
16901
16902       while (child_die && child_die->tag)
16903         {
16904           process_die (child_die, cu);
16905           child_die = sibling_die (child_die);
16906         }
16907     }
16908 }
16909
16910 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16911    imported module.  Still we need that type as local Fortran "use ... only"
16912    declaration imports depend on the created type in determine_prefix.  */
16913
16914 static struct type *
16915 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16916 {
16917   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16918   const char *module_name;
16919   struct type *type;
16920
16921   module_name = dwarf2_name (die, cu);
16922   if (!module_name)
16923     complaint (_("DW_TAG_module has no name, offset %s"),
16924                sect_offset_str (die->sect_off));
16925   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16926
16927   return set_die_type (die, type, cu);
16928 }
16929
16930 /* Read a Fortran module.  */
16931
16932 static void
16933 read_module (struct die_info *die, struct dwarf2_cu *cu)
16934 {
16935   struct die_info *child_die = die->child;
16936   struct type *type;
16937
16938   type = read_type_die (die, cu);
16939   new_symbol (die, type, cu);
16940
16941   while (child_die && child_die->tag)
16942     {
16943       process_die (child_die, cu);
16944       child_die = sibling_die (child_die);
16945     }
16946 }
16947
16948 /* Return the name of the namespace represented by DIE.  Set
16949    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16950    namespace.  */
16951
16952 static const char *
16953 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16954 {
16955   struct die_info *current_die;
16956   const char *name = NULL;
16957
16958   /* Loop through the extensions until we find a name.  */
16959
16960   for (current_die = die;
16961        current_die != NULL;
16962        current_die = dwarf2_extension (die, &cu))
16963     {
16964       /* We don't use dwarf2_name here so that we can detect the absence
16965          of a name -> anonymous namespace.  */
16966       name = dwarf2_string_attr (die, DW_AT_name, cu);
16967
16968       if (name != NULL)
16969         break;
16970     }
16971
16972   /* Is it an anonymous namespace?  */
16973
16974   *is_anonymous = (name == NULL);
16975   if (*is_anonymous)
16976     name = CP_ANONYMOUS_NAMESPACE_STR;
16977
16978   return name;
16979 }
16980
16981 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16982    the user defined type vector.  */
16983
16984 static struct type *
16985 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16986 {
16987   struct gdbarch *gdbarch
16988     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16989   struct comp_unit_head *cu_header = &cu->header;
16990   struct type *type;
16991   struct attribute *attr_byte_size;
16992   struct attribute *attr_address_class;
16993   int byte_size, addr_class;
16994   struct type *target_type;
16995
16996   target_type = die_type (die, cu);
16997
16998   /* The die_type call above may have already set the type for this DIE.  */
16999   type = get_die_type (die, cu);
17000   if (type)
17001     return type;
17002
17003   type = lookup_pointer_type (target_type);
17004
17005   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17006   if (attr_byte_size)
17007     byte_size = DW_UNSND (attr_byte_size);
17008   else
17009     byte_size = cu_header->addr_size;
17010
17011   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17012   if (attr_address_class)
17013     addr_class = DW_UNSND (attr_address_class);
17014   else
17015     addr_class = DW_ADDR_none;
17016
17017   ULONGEST alignment = get_alignment (cu, die);
17018
17019   /* If the pointer size, alignment, or address class is different
17020      than the default, create a type variant marked as such and set
17021      the length accordingly.  */
17022   if (TYPE_LENGTH (type) != byte_size
17023       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
17024           && alignment != TYPE_RAW_ALIGN (type))
17025       || addr_class != DW_ADDR_none)
17026     {
17027       if (gdbarch_address_class_type_flags_p (gdbarch))
17028         {
17029           int type_flags;
17030
17031           type_flags = gdbarch_address_class_type_flags
17032                          (gdbarch, byte_size, addr_class);
17033           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17034                       == 0);
17035           type = make_type_with_address_space (type, type_flags);
17036         }
17037       else if (TYPE_LENGTH (type) != byte_size)
17038         {
17039           complaint (_("invalid pointer size %d"), byte_size);
17040         }
17041       else if (TYPE_RAW_ALIGN (type) != alignment)
17042         {
17043           complaint (_("Invalid DW_AT_alignment"
17044                        " - DIE at %s [in module %s]"),
17045                      sect_offset_str (die->sect_off),
17046                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17047         }
17048       else
17049         {
17050           /* Should we also complain about unhandled address classes?  */
17051         }
17052     }
17053
17054   TYPE_LENGTH (type) = byte_size;
17055   set_type_align (type, alignment);
17056   return set_die_type (die, type, cu);
17057 }
17058
17059 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17060    the user defined type vector.  */
17061
17062 static struct type *
17063 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17064 {
17065   struct type *type;
17066   struct type *to_type;
17067   struct type *domain;
17068
17069   to_type = die_type (die, cu);
17070   domain = die_containing_type (die, cu);
17071
17072   /* The calls above may have already set the type for this DIE.  */
17073   type = get_die_type (die, cu);
17074   if (type)
17075     return type;
17076
17077   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17078     type = lookup_methodptr_type (to_type);
17079   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17080     {
17081       struct type *new_type
17082         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17083
17084       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17085                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17086                             TYPE_VARARGS (to_type));
17087       type = lookup_methodptr_type (new_type);
17088     }
17089   else
17090     type = lookup_memberptr_type (to_type, domain);
17091
17092   return set_die_type (die, type, cu);
17093 }
17094
17095 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17096    the user defined type vector.  */
17097
17098 static struct type *
17099 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17100                           enum type_code refcode)
17101 {
17102   struct comp_unit_head *cu_header = &cu->header;
17103   struct type *type, *target_type;
17104   struct attribute *attr;
17105
17106   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17107
17108   target_type = die_type (die, cu);
17109
17110   /* The die_type call above may have already set the type for this DIE.  */
17111   type = get_die_type (die, cu);
17112   if (type)
17113     return type;
17114
17115   type = lookup_reference_type (target_type, refcode);
17116   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17117   if (attr)
17118     {
17119       TYPE_LENGTH (type) = DW_UNSND (attr);
17120     }
17121   else
17122     {
17123       TYPE_LENGTH (type) = cu_header->addr_size;
17124     }
17125   maybe_set_alignment (cu, die, type);
17126   return set_die_type (die, type, cu);
17127 }
17128
17129 /* Add the given cv-qualifiers to the element type of the array.  GCC
17130    outputs DWARF type qualifiers that apply to an array, not the
17131    element type.  But GDB relies on the array element type to carry
17132    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17133    specification.  */
17134
17135 static struct type *
17136 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17137                    struct type *base_type, int cnst, int voltl)
17138 {
17139   struct type *el_type, *inner_array;
17140
17141   base_type = copy_type (base_type);
17142   inner_array = base_type;
17143
17144   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17145     {
17146       TYPE_TARGET_TYPE (inner_array) =
17147         copy_type (TYPE_TARGET_TYPE (inner_array));
17148       inner_array = TYPE_TARGET_TYPE (inner_array);
17149     }
17150
17151   el_type = TYPE_TARGET_TYPE (inner_array);
17152   cnst |= TYPE_CONST (el_type);
17153   voltl |= TYPE_VOLATILE (el_type);
17154   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17155
17156   return set_die_type (die, base_type, cu);
17157 }
17158
17159 static struct type *
17160 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17161 {
17162   struct type *base_type, *cv_type;
17163
17164   base_type = die_type (die, cu);
17165
17166   /* The die_type call above may have already set the type for this DIE.  */
17167   cv_type = get_die_type (die, cu);
17168   if (cv_type)
17169     return cv_type;
17170
17171   /* In case the const qualifier is applied to an array type, the element type
17172      is so qualified, not the array type (section 6.7.3 of C99).  */
17173   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17174     return add_array_cv_type (die, cu, base_type, 1, 0);
17175
17176   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17177   return set_die_type (die, cv_type, cu);
17178 }
17179
17180 static struct type *
17181 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17182 {
17183   struct type *base_type, *cv_type;
17184
17185   base_type = die_type (die, cu);
17186
17187   /* The die_type call above may have already set the type for this DIE.  */
17188   cv_type = get_die_type (die, cu);
17189   if (cv_type)
17190     return cv_type;
17191
17192   /* In case the volatile qualifier is applied to an array type, the
17193      element type is so qualified, not the array type (section 6.7.3
17194      of C99).  */
17195   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17196     return add_array_cv_type (die, cu, base_type, 0, 1);
17197
17198   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17199   return set_die_type (die, cv_type, cu);
17200 }
17201
17202 /* Handle DW_TAG_restrict_type.  */
17203
17204 static struct type *
17205 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17206 {
17207   struct type *base_type, *cv_type;
17208
17209   base_type = die_type (die, cu);
17210
17211   /* The die_type call above may have already set the type for this DIE.  */
17212   cv_type = get_die_type (die, cu);
17213   if (cv_type)
17214     return cv_type;
17215
17216   cv_type = make_restrict_type (base_type);
17217   return set_die_type (die, cv_type, cu);
17218 }
17219
17220 /* Handle DW_TAG_atomic_type.  */
17221
17222 static struct type *
17223 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17224 {
17225   struct type *base_type, *cv_type;
17226
17227   base_type = die_type (die, cu);
17228
17229   /* The die_type call above may have already set the type for this DIE.  */
17230   cv_type = get_die_type (die, cu);
17231   if (cv_type)
17232     return cv_type;
17233
17234   cv_type = make_atomic_type (base_type);
17235   return set_die_type (die, cv_type, cu);
17236 }
17237
17238 /* Extract all information from a DW_TAG_string_type DIE and add to
17239    the user defined type vector.  It isn't really a user defined type,
17240    but it behaves like one, with other DIE's using an AT_user_def_type
17241    attribute to reference it.  */
17242
17243 static struct type *
17244 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17245 {
17246   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17247   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17248   struct type *type, *range_type, *index_type, *char_type;
17249   struct attribute *attr;
17250   unsigned int length;
17251
17252   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17253   if (attr)
17254     {
17255       length = DW_UNSND (attr);
17256     }
17257   else
17258     {
17259       /* Check for the DW_AT_byte_size attribute.  */
17260       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17261       if (attr)
17262         {
17263           length = DW_UNSND (attr);
17264         }
17265       else
17266         {
17267           length = 1;
17268         }
17269     }
17270
17271   index_type = objfile_type (objfile)->builtin_int;
17272   range_type = create_static_range_type (NULL, index_type, 1, length);
17273   char_type = language_string_char_type (cu->language_defn, gdbarch);
17274   type = create_string_type (NULL, char_type, range_type);
17275
17276   return set_die_type (die, type, cu);
17277 }
17278
17279 /* Assuming that DIE corresponds to a function, returns nonzero
17280    if the function is prototyped.  */
17281
17282 static int
17283 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17284 {
17285   struct attribute *attr;
17286
17287   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17288   if (attr && (DW_UNSND (attr) != 0))
17289     return 1;
17290
17291   /* The DWARF standard implies that the DW_AT_prototyped attribute
17292      is only meaninful for C, but the concept also extends to other
17293      languages that allow unprototyped functions (Eg: Objective C).
17294      For all other languages, assume that functions are always
17295      prototyped.  */
17296   if (cu->language != language_c
17297       && cu->language != language_objc
17298       && cu->language != language_opencl)
17299     return 1;
17300
17301   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17302      prototyped and unprototyped functions; default to prototyped,
17303      since that is more common in modern code (and RealView warns
17304      about unprototyped functions).  */
17305   if (producer_is_realview (cu->producer))
17306     return 1;
17307
17308   return 0;
17309 }
17310
17311 /* Handle DIES due to C code like:
17312
17313    struct foo
17314    {
17315    int (*funcp)(int a, long l);
17316    int b;
17317    };
17318
17319    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17320
17321 static struct type *
17322 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17323 {
17324   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17325   struct type *type;            /* Type that this function returns.  */
17326   struct type *ftype;           /* Function that returns above type.  */
17327   struct attribute *attr;
17328
17329   type = die_type (die, cu);
17330
17331   /* The die_type call above may have already set the type for this DIE.  */
17332   ftype = get_die_type (die, cu);
17333   if (ftype)
17334     return ftype;
17335
17336   ftype = lookup_function_type (type);
17337
17338   if (prototyped_function_p (die, cu))
17339     TYPE_PROTOTYPED (ftype) = 1;
17340
17341   /* Store the calling convention in the type if it's available in
17342      the subroutine die.  Otherwise set the calling convention to
17343      the default value DW_CC_normal.  */
17344   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17345   if (attr)
17346     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17347   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17348     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17349   else
17350     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17351
17352   /* Record whether the function returns normally to its caller or not
17353      if the DWARF producer set that information.  */
17354   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17355   if (attr && (DW_UNSND (attr) != 0))
17356     TYPE_NO_RETURN (ftype) = 1;
17357
17358   /* We need to add the subroutine type to the die immediately so
17359      we don't infinitely recurse when dealing with parameters
17360      declared as the same subroutine type.  */
17361   set_die_type (die, ftype, cu);
17362
17363   if (die->child != NULL)
17364     {
17365       struct type *void_type = objfile_type (objfile)->builtin_void;
17366       struct die_info *child_die;
17367       int nparams, iparams;
17368
17369       /* Count the number of parameters.
17370          FIXME: GDB currently ignores vararg functions, but knows about
17371          vararg member functions.  */
17372       nparams = 0;
17373       child_die = die->child;
17374       while (child_die && child_die->tag)
17375         {
17376           if (child_die->tag == DW_TAG_formal_parameter)
17377             nparams++;
17378           else if (child_die->tag == DW_TAG_unspecified_parameters)
17379             TYPE_VARARGS (ftype) = 1;
17380           child_die = sibling_die (child_die);
17381         }
17382
17383       /* Allocate storage for parameters and fill them in.  */
17384       TYPE_NFIELDS (ftype) = nparams;
17385       TYPE_FIELDS (ftype) = (struct field *)
17386         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17387
17388       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17389          even if we error out during the parameters reading below.  */
17390       for (iparams = 0; iparams < nparams; iparams++)
17391         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17392
17393       iparams = 0;
17394       child_die = die->child;
17395       while (child_die && child_die->tag)
17396         {
17397           if (child_die->tag == DW_TAG_formal_parameter)
17398             {
17399               struct type *arg_type;
17400
17401               /* DWARF version 2 has no clean way to discern C++
17402                  static and non-static member functions.  G++ helps
17403                  GDB by marking the first parameter for non-static
17404                  member functions (which is the this pointer) as
17405                  artificial.  We pass this information to
17406                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17407
17408                  DWARF version 3 added DW_AT_object_pointer, which GCC
17409                  4.5 does not yet generate.  */
17410               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17411               if (attr)
17412                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17413               else
17414                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17415               arg_type = die_type (child_die, cu);
17416
17417               /* RealView does not mark THIS as const, which the testsuite
17418                  expects.  GCC marks THIS as const in method definitions,
17419                  but not in the class specifications (GCC PR 43053).  */
17420               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17421                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17422                 {
17423                   int is_this = 0;
17424                   struct dwarf2_cu *arg_cu = cu;
17425                   const char *name = dwarf2_name (child_die, cu);
17426
17427                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17428                   if (attr)
17429                     {
17430                       /* If the compiler emits this, use it.  */
17431                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17432                         is_this = 1;
17433                     }
17434                   else if (name && strcmp (name, "this") == 0)
17435                     /* Function definitions will have the argument names.  */
17436                     is_this = 1;
17437                   else if (name == NULL && iparams == 0)
17438                     /* Declarations may not have the names, so like
17439                        elsewhere in GDB, assume an artificial first
17440                        argument is "this".  */
17441                     is_this = 1;
17442
17443                   if (is_this)
17444                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17445                                              arg_type, 0);
17446                 }
17447
17448               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17449               iparams++;
17450             }
17451           child_die = sibling_die (child_die);
17452         }
17453     }
17454
17455   return ftype;
17456 }
17457
17458 static struct type *
17459 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17460 {
17461   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17462   const char *name = NULL;
17463   struct type *this_type, *target_type;
17464
17465   name = dwarf2_full_name (NULL, die, cu);
17466   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17467   TYPE_TARGET_STUB (this_type) = 1;
17468   set_die_type (die, this_type, cu);
17469   target_type = die_type (die, cu);
17470   if (target_type != this_type)
17471     TYPE_TARGET_TYPE (this_type) = target_type;
17472   else
17473     {
17474       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17475          spec and cause infinite loops in GDB.  */
17476       complaint (_("Self-referential DW_TAG_typedef "
17477                    "- DIE at %s [in module %s]"),
17478                  sect_offset_str (die->sect_off), objfile_name (objfile));
17479       TYPE_TARGET_TYPE (this_type) = NULL;
17480     }
17481   return this_type;
17482 }
17483
17484 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17485    (which may be different from NAME) to the architecture back-end to allow
17486    it to guess the correct format if necessary.  */
17487
17488 static struct type *
17489 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17490                         const char *name_hint)
17491 {
17492   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17493   const struct floatformat **format;
17494   struct type *type;
17495
17496   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17497   if (format)
17498     type = init_float_type (objfile, bits, name, format);
17499   else
17500     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17501
17502   return type;
17503 }
17504
17505 /* Allocate an integer type of size BITS and name NAME.  */
17506
17507 static struct type *
17508 dwarf2_init_integer_type (struct dwarf2_cu *cu, struct objfile *objfile,
17509                           int bits, int unsigned_p, const char *name)
17510 {
17511   struct type *type;
17512
17513   /* Versions of Intel's C Compiler generate an integer type called "void"
17514      instead of using DW_TAG_unspecified_type.  This has been seen on
17515      at least versions 14, 17, and 18.  */
17516   if (bits == 0 && producer_is_icc (cu) && name != nullptr
17517       && strcmp (name, "void") == 0)
17518     type = objfile_type (objfile)->builtin_void;
17519   else
17520     type = init_integer_type (objfile, bits, unsigned_p, name);
17521
17522   return type;
17523 }
17524
17525 /* Find a representation of a given base type and install
17526    it in the TYPE field of the die.  */
17527
17528 static struct type *
17529 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17530 {
17531   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17532   struct type *type;
17533   struct attribute *attr;
17534   int encoding = 0, bits = 0;
17535   const char *name;
17536
17537   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17538   if (attr)
17539     {
17540       encoding = DW_UNSND (attr);
17541     }
17542   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17543   if (attr)
17544     {
17545       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17546     }
17547   name = dwarf2_name (die, cu);
17548   if (!name)
17549     {
17550       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17551     }
17552
17553   switch (encoding)
17554     {
17555       case DW_ATE_address:
17556         /* Turn DW_ATE_address into a void * pointer.  */
17557         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17558         type = init_pointer_type (objfile, bits, name, type);
17559         break;
17560       case DW_ATE_boolean:
17561         type = init_boolean_type (objfile, bits, 1, name);
17562         break;
17563       case DW_ATE_complex_float:
17564         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17565         type = init_complex_type (objfile, name, type);
17566         break;
17567       case DW_ATE_decimal_float:
17568         type = init_decfloat_type (objfile, bits, name);
17569         break;
17570       case DW_ATE_float:
17571         type = dwarf2_init_float_type (objfile, bits, name, name);
17572         break;
17573       case DW_ATE_signed:
17574         type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17575         break;
17576       case DW_ATE_unsigned:
17577         if (cu->language == language_fortran
17578             && name
17579             && startswith (name, "character("))
17580           type = init_character_type (objfile, bits, 1, name);
17581         else
17582           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17583         break;
17584       case DW_ATE_signed_char:
17585         if (cu->language == language_ada || cu->language == language_m2
17586             || cu->language == language_pascal
17587             || cu->language == language_fortran)
17588           type = init_character_type (objfile, bits, 0, name);
17589         else
17590           type = dwarf2_init_integer_type (cu, objfile, bits, 0, name);
17591         break;
17592       case DW_ATE_unsigned_char:
17593         if (cu->language == language_ada || cu->language == language_m2
17594             || cu->language == language_pascal
17595             || cu->language == language_fortran
17596             || cu->language == language_rust)
17597           type = init_character_type (objfile, bits, 1, name);
17598         else
17599           type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17600         break;
17601       case DW_ATE_UTF:
17602         {
17603           gdbarch *arch = get_objfile_arch (objfile);
17604
17605           if (bits == 16)
17606             type = builtin_type (arch)->builtin_char16;
17607           else if (bits == 32)
17608             type = builtin_type (arch)->builtin_char32;
17609           else
17610             {
17611               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17612                          bits);
17613               type = dwarf2_init_integer_type (cu, objfile, bits, 1, name);
17614             }
17615           return set_die_type (die, type, cu);
17616         }
17617         break;
17618
17619       default:
17620         complaint (_("unsupported DW_AT_encoding: '%s'"),
17621                    dwarf_type_encoding_name (encoding));
17622         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17623         break;
17624     }
17625
17626   if (name && strcmp (name, "char") == 0)
17627     TYPE_NOSIGN (type) = 1;
17628
17629   maybe_set_alignment (cu, die, type);
17630
17631   return set_die_type (die, type, cu);
17632 }
17633
17634 /* Parse dwarf attribute if it's a block, reference or constant and put the
17635    resulting value of the attribute into struct bound_prop.
17636    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17637
17638 static int
17639 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17640                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17641 {
17642   struct dwarf2_property_baton *baton;
17643   struct obstack *obstack
17644     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17645
17646   if (attr == NULL || prop == NULL)
17647     return 0;
17648
17649   if (attr_form_is_block (attr))
17650     {
17651       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17652       baton->referenced_type = NULL;
17653       baton->locexpr.per_cu = cu->per_cu;
17654       baton->locexpr.size = DW_BLOCK (attr)->size;
17655       baton->locexpr.data = DW_BLOCK (attr)->data;
17656       prop->data.baton = baton;
17657       prop->kind = PROP_LOCEXPR;
17658       gdb_assert (prop->data.baton != NULL);
17659     }
17660   else if (attr_form_is_ref (attr))
17661     {
17662       struct dwarf2_cu *target_cu = cu;
17663       struct die_info *target_die;
17664       struct attribute *target_attr;
17665
17666       target_die = follow_die_ref (die, attr, &target_cu);
17667       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17668       if (target_attr == NULL)
17669         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17670                                    target_cu);
17671       if (target_attr == NULL)
17672         return 0;
17673
17674       switch (target_attr->name)
17675         {
17676           case DW_AT_location:
17677             if (attr_form_is_section_offset (target_attr))
17678               {
17679                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17680                 baton->referenced_type = die_type (target_die, target_cu);
17681                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17682                 prop->data.baton = baton;
17683                 prop->kind = PROP_LOCLIST;
17684                 gdb_assert (prop->data.baton != NULL);
17685               }
17686             else if (attr_form_is_block (target_attr))
17687               {
17688                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17689                 baton->referenced_type = die_type (target_die, target_cu);
17690                 baton->locexpr.per_cu = cu->per_cu;
17691                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17692                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17693                 prop->data.baton = baton;
17694                 prop->kind = PROP_LOCEXPR;
17695                 gdb_assert (prop->data.baton != NULL);
17696               }
17697             else
17698               {
17699                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17700                                                        "dynamic property");
17701                 return 0;
17702               }
17703             break;
17704           case DW_AT_data_member_location:
17705             {
17706               LONGEST offset;
17707
17708               if (!handle_data_member_location (target_die, target_cu,
17709                                                 &offset))
17710                 return 0;
17711
17712               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17713               baton->referenced_type = read_type_die (target_die->parent,
17714                                                       target_cu);
17715               baton->offset_info.offset = offset;
17716               baton->offset_info.type = die_type (target_die, target_cu);
17717               prop->data.baton = baton;
17718               prop->kind = PROP_ADDR_OFFSET;
17719               break;
17720             }
17721         }
17722     }
17723   else if (attr_form_is_constant (attr))
17724     {
17725       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17726       prop->kind = PROP_CONST;
17727     }
17728   else
17729     {
17730       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17731                                              dwarf2_name (die, cu));
17732       return 0;
17733     }
17734
17735   return 1;
17736 }
17737
17738 /* Read the given DW_AT_subrange DIE.  */
17739
17740 static struct type *
17741 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17742 {
17743   struct type *base_type, *orig_base_type;
17744   struct type *range_type;
17745   struct attribute *attr;
17746   struct dynamic_prop low, high;
17747   int low_default_is_valid;
17748   int high_bound_is_count = 0;
17749   const char *name;
17750   ULONGEST negative_mask;
17751
17752   orig_base_type = die_type (die, cu);
17753   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17754      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17755      creating the range type, but we use the result of check_typedef
17756      when examining properties of the type.  */
17757   base_type = check_typedef (orig_base_type);
17758
17759   /* The die_type call above may have already set the type for this DIE.  */
17760   range_type = get_die_type (die, cu);
17761   if (range_type)
17762     return range_type;
17763
17764   low.kind = PROP_CONST;
17765   high.kind = PROP_CONST;
17766   high.data.const_val = 0;
17767
17768   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17769      omitting DW_AT_lower_bound.  */
17770   switch (cu->language)
17771     {
17772     case language_c:
17773     case language_cplus:
17774       low.data.const_val = 0;
17775       low_default_is_valid = 1;
17776       break;
17777     case language_fortran:
17778       low.data.const_val = 1;
17779       low_default_is_valid = 1;
17780       break;
17781     case language_d:
17782     case language_objc:
17783     case language_rust:
17784       low.data.const_val = 0;
17785       low_default_is_valid = (cu->header.version >= 4);
17786       break;
17787     case language_ada:
17788     case language_m2:
17789     case language_pascal:
17790       low.data.const_val = 1;
17791       low_default_is_valid = (cu->header.version >= 4);
17792       break;
17793     default:
17794       low.data.const_val = 0;
17795       low_default_is_valid = 0;
17796       break;
17797     }
17798
17799   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17800   if (attr)
17801     attr_to_dynamic_prop (attr, die, cu, &low);
17802   else if (!low_default_is_valid)
17803     complaint (_("Missing DW_AT_lower_bound "
17804                                       "- DIE at %s [in module %s]"),
17805                sect_offset_str (die->sect_off),
17806                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17807
17808   struct attribute *attr_ub, *attr_count;
17809   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17810   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17811     {
17812       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17813       if (attr_to_dynamic_prop (attr, die, cu, &high))
17814         {
17815           /* If bounds are constant do the final calculation here.  */
17816           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17817             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17818           else
17819             high_bound_is_count = 1;
17820         }
17821       else
17822         {
17823           if (attr_ub != NULL)
17824             complaint (_("Unresolved DW_AT_upper_bound "
17825                          "- DIE at %s [in module %s]"),
17826                        sect_offset_str (die->sect_off),
17827                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17828           if (attr_count != NULL)
17829             complaint (_("Unresolved DW_AT_count "
17830                          "- DIE at %s [in module %s]"),
17831                        sect_offset_str (die->sect_off),
17832                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17833         }
17834         
17835     }
17836
17837   /* Dwarf-2 specifications explicitly allows to create subrange types
17838      without specifying a base type.
17839      In that case, the base type must be set to the type of
17840      the lower bound, upper bound or count, in that order, if any of these
17841      three attributes references an object that has a type.
17842      If no base type is found, the Dwarf-2 specifications say that
17843      a signed integer type of size equal to the size of an address should
17844      be used.
17845      For the following C code: `extern char gdb_int [];'
17846      GCC produces an empty range DIE.
17847      FIXME: muller/2010-05-28: Possible references to object for low bound,
17848      high bound or count are not yet handled by this code.  */
17849   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17850     {
17851       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17852       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17853       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17854       struct type *int_type = objfile_type (objfile)->builtin_int;
17855
17856       /* Test "int", "long int", and "long long int" objfile types,
17857          and select the first one having a size above or equal to the
17858          architecture address size.  */
17859       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17860         base_type = int_type;
17861       else
17862         {
17863           int_type = objfile_type (objfile)->builtin_long;
17864           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17865             base_type = int_type;
17866           else
17867             {
17868               int_type = objfile_type (objfile)->builtin_long_long;
17869               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17870                 base_type = int_type;
17871             }
17872         }
17873     }
17874
17875   /* Normally, the DWARF producers are expected to use a signed
17876      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17877      But this is unfortunately not always the case, as witnessed
17878      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17879      is used instead.  To work around that ambiguity, we treat
17880      the bounds as signed, and thus sign-extend their values, when
17881      the base type is signed.  */
17882   negative_mask =
17883     -((ULONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17884   if (low.kind == PROP_CONST
17885       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17886     low.data.const_val |= negative_mask;
17887   if (high.kind == PROP_CONST
17888       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17889     high.data.const_val |= negative_mask;
17890
17891   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17892
17893   if (high_bound_is_count)
17894     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17895
17896   /* Ada expects an empty array on no boundary attributes.  */
17897   if (attr == NULL && cu->language != language_ada)
17898     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17899
17900   name = dwarf2_name (die, cu);
17901   if (name)
17902     TYPE_NAME (range_type) = name;
17903
17904   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17905   if (attr)
17906     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17907
17908   maybe_set_alignment (cu, die, range_type);
17909
17910   set_die_type (die, range_type, cu);
17911
17912   /* set_die_type should be already done.  */
17913   set_descriptive_type (range_type, die, cu);
17914
17915   return range_type;
17916 }
17917
17918 static struct type *
17919 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17920 {
17921   struct type *type;
17922
17923   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17924                     NULL);
17925   TYPE_NAME (type) = dwarf2_name (die, cu);
17926
17927   /* In Ada, an unspecified type is typically used when the description
17928      of the type is defered to a different unit.  When encountering
17929      such a type, we treat it as a stub, and try to resolve it later on,
17930      when needed.  */
17931   if (cu->language == language_ada)
17932     TYPE_STUB (type) = 1;
17933
17934   return set_die_type (die, type, cu);
17935 }
17936
17937 /* Read a single die and all its descendents.  Set the die's sibling
17938    field to NULL; set other fields in the die correctly, and set all
17939    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17940    location of the info_ptr after reading all of those dies.  PARENT
17941    is the parent of the die in question.  */
17942
17943 static struct die_info *
17944 read_die_and_children (const struct die_reader_specs *reader,
17945                        const gdb_byte *info_ptr,
17946                        const gdb_byte **new_info_ptr,
17947                        struct die_info *parent)
17948 {
17949   struct die_info *die;
17950   const gdb_byte *cur_ptr;
17951   int has_children;
17952
17953   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17954   if (die == NULL)
17955     {
17956       *new_info_ptr = cur_ptr;
17957       return NULL;
17958     }
17959   store_in_ref_table (die, reader->cu);
17960
17961   if (has_children)
17962     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17963   else
17964     {
17965       die->child = NULL;
17966       *new_info_ptr = cur_ptr;
17967     }
17968
17969   die->sibling = NULL;
17970   die->parent = parent;
17971   return die;
17972 }
17973
17974 /* Read a die, all of its descendents, and all of its siblings; set
17975    all of the fields of all of the dies correctly.  Arguments are as
17976    in read_die_and_children.  */
17977
17978 static struct die_info *
17979 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17980                          const gdb_byte *info_ptr,
17981                          const gdb_byte **new_info_ptr,
17982                          struct die_info *parent)
17983 {
17984   struct die_info *first_die, *last_sibling;
17985   const gdb_byte *cur_ptr;
17986
17987   cur_ptr = info_ptr;
17988   first_die = last_sibling = NULL;
17989
17990   while (1)
17991     {
17992       struct die_info *die
17993         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17994
17995       if (die == NULL)
17996         {
17997           *new_info_ptr = cur_ptr;
17998           return first_die;
17999         }
18000
18001       if (!first_die)
18002         first_die = die;
18003       else
18004         last_sibling->sibling = die;
18005
18006       last_sibling = die;
18007     }
18008 }
18009
18010 /* Read a die, all of its descendents, and all of its siblings; set
18011    all of the fields of all of the dies correctly.  Arguments are as
18012    in read_die_and_children.
18013    This the main entry point for reading a DIE and all its children.  */
18014
18015 static struct die_info *
18016 read_die_and_siblings (const struct die_reader_specs *reader,
18017                        const gdb_byte *info_ptr,
18018                        const gdb_byte **new_info_ptr,
18019                        struct die_info *parent)
18020 {
18021   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
18022                                                   new_info_ptr, parent);
18023
18024   if (dwarf_die_debug)
18025     {
18026       fprintf_unfiltered (gdb_stdlog,
18027                           "Read die from %s@0x%x of %s:\n",
18028                           get_section_name (reader->die_section),
18029                           (unsigned) (info_ptr - reader->die_section->buffer),
18030                           bfd_get_filename (reader->abfd));
18031       dump_die (die, dwarf_die_debug);
18032     }
18033
18034   return die;
18035 }
18036
18037 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
18038    attributes.
18039    The caller is responsible for filling in the extra attributes
18040    and updating (*DIEP)->num_attrs.
18041    Set DIEP to point to a newly allocated die with its information,
18042    except for its child, sibling, and parent fields.
18043    Set HAS_CHILDREN to tell whether the die has children or not.  */
18044
18045 static const gdb_byte *
18046 read_full_die_1 (const struct die_reader_specs *reader,
18047                  struct die_info **diep, const gdb_byte *info_ptr,
18048                  int *has_children, int num_extra_attrs)
18049 {
18050   unsigned int abbrev_number, bytes_read, i;
18051   struct abbrev_info *abbrev;
18052   struct die_info *die;
18053   struct dwarf2_cu *cu = reader->cu;
18054   bfd *abfd = reader->abfd;
18055
18056   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18057   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18058   info_ptr += bytes_read;
18059   if (!abbrev_number)
18060     {
18061       *diep = NULL;
18062       *has_children = 0;
18063       return info_ptr;
18064     }
18065
18066   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
18067   if (!abbrev)
18068     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18069            abbrev_number,
18070            bfd_get_filename (abfd));
18071
18072   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18073   die->sect_off = sect_off;
18074   die->tag = abbrev->tag;
18075   die->abbrev = abbrev_number;
18076
18077   /* Make the result usable.
18078      The caller needs to update num_attrs after adding the extra
18079      attributes.  */
18080   die->num_attrs = abbrev->num_attrs;
18081
18082   for (i = 0; i < abbrev->num_attrs; ++i)
18083     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18084                                info_ptr);
18085
18086   *diep = die;
18087   *has_children = abbrev->has_children;
18088   return info_ptr;
18089 }
18090
18091 /* Read a die and all its attributes.
18092    Set DIEP to point to a newly allocated die with its information,
18093    except for its child, sibling, and parent fields.
18094    Set HAS_CHILDREN to tell whether the die has children or not.  */
18095
18096 static const gdb_byte *
18097 read_full_die (const struct die_reader_specs *reader,
18098                struct die_info **diep, const gdb_byte *info_ptr,
18099                int *has_children)
18100 {
18101   const gdb_byte *result;
18102
18103   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18104
18105   if (dwarf_die_debug)
18106     {
18107       fprintf_unfiltered (gdb_stdlog,
18108                           "Read die from %s@0x%x of %s:\n",
18109                           get_section_name (reader->die_section),
18110                           (unsigned) (info_ptr - reader->die_section->buffer),
18111                           bfd_get_filename (reader->abfd));
18112       dump_die (*diep, dwarf_die_debug);
18113     }
18114
18115   return result;
18116 }
18117 \f
18118 /* Abbreviation tables.
18119
18120    In DWARF version 2, the description of the debugging information is
18121    stored in a separate .debug_abbrev section.  Before we read any
18122    dies from a section we read in all abbreviations and install them
18123    in a hash table.  */
18124
18125 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18126
18127 struct abbrev_info *
18128 abbrev_table::alloc_abbrev ()
18129 {
18130   struct abbrev_info *abbrev;
18131
18132   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18133   memset (abbrev, 0, sizeof (struct abbrev_info));
18134
18135   return abbrev;
18136 }
18137
18138 /* Add an abbreviation to the table.  */
18139
18140 void
18141 abbrev_table::add_abbrev (unsigned int abbrev_number,
18142                           struct abbrev_info *abbrev)
18143 {
18144   unsigned int hash_number;
18145
18146   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18147   abbrev->next = m_abbrevs[hash_number];
18148   m_abbrevs[hash_number] = abbrev;
18149 }
18150
18151 /* Look up an abbrev in the table.
18152    Returns NULL if the abbrev is not found.  */
18153
18154 struct abbrev_info *
18155 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18156 {
18157   unsigned int hash_number;
18158   struct abbrev_info *abbrev;
18159
18160   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18161   abbrev = m_abbrevs[hash_number];
18162
18163   while (abbrev)
18164     {
18165       if (abbrev->number == abbrev_number)
18166         return abbrev;
18167       abbrev = abbrev->next;
18168     }
18169   return NULL;
18170 }
18171
18172 /* Read in an abbrev table.  */
18173
18174 static abbrev_table_up
18175 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18176                          struct dwarf2_section_info *section,
18177                          sect_offset sect_off)
18178 {
18179   struct objfile *objfile = dwarf2_per_objfile->objfile;
18180   bfd *abfd = get_section_bfd_owner (section);
18181   const gdb_byte *abbrev_ptr;
18182   struct abbrev_info *cur_abbrev;
18183   unsigned int abbrev_number, bytes_read, abbrev_name;
18184   unsigned int abbrev_form;
18185   struct attr_abbrev *cur_attrs;
18186   unsigned int allocated_attrs;
18187
18188   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18189
18190   dwarf2_read_section (objfile, section);
18191   abbrev_ptr = section->buffer + to_underlying (sect_off);
18192   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18193   abbrev_ptr += bytes_read;
18194
18195   allocated_attrs = ATTR_ALLOC_CHUNK;
18196   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18197
18198   /* Loop until we reach an abbrev number of 0.  */
18199   while (abbrev_number)
18200     {
18201       cur_abbrev = abbrev_table->alloc_abbrev ();
18202
18203       /* read in abbrev header */
18204       cur_abbrev->number = abbrev_number;
18205       cur_abbrev->tag
18206         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18207       abbrev_ptr += bytes_read;
18208       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18209       abbrev_ptr += 1;
18210
18211       /* now read in declarations */
18212       for (;;)
18213         {
18214           LONGEST implicit_const;
18215
18216           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18217           abbrev_ptr += bytes_read;
18218           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18219           abbrev_ptr += bytes_read;
18220           if (abbrev_form == DW_FORM_implicit_const)
18221             {
18222               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18223                                                    &bytes_read);
18224               abbrev_ptr += bytes_read;
18225             }
18226           else
18227             {
18228               /* Initialize it due to a false compiler warning.  */
18229               implicit_const = -1;
18230             }
18231
18232           if (abbrev_name == 0)
18233             break;
18234
18235           if (cur_abbrev->num_attrs == allocated_attrs)
18236             {
18237               allocated_attrs += ATTR_ALLOC_CHUNK;
18238               cur_attrs
18239                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18240             }
18241
18242           cur_attrs[cur_abbrev->num_attrs].name
18243             = (enum dwarf_attribute) abbrev_name;
18244           cur_attrs[cur_abbrev->num_attrs].form
18245             = (enum dwarf_form) abbrev_form;
18246           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18247           ++cur_abbrev->num_attrs;
18248         }
18249
18250       cur_abbrev->attrs =
18251         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18252                    cur_abbrev->num_attrs);
18253       memcpy (cur_abbrev->attrs, cur_attrs,
18254               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18255
18256       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18257
18258       /* Get next abbreviation.
18259          Under Irix6 the abbreviations for a compilation unit are not
18260          always properly terminated with an abbrev number of 0.
18261          Exit loop if we encounter an abbreviation which we have
18262          already read (which means we are about to read the abbreviations
18263          for the next compile unit) or if the end of the abbreviation
18264          table is reached.  */
18265       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18266         break;
18267       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18268       abbrev_ptr += bytes_read;
18269       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18270         break;
18271     }
18272
18273   xfree (cur_attrs);
18274   return abbrev_table;
18275 }
18276
18277 /* Returns nonzero if TAG represents a type that we might generate a partial
18278    symbol for.  */
18279
18280 static int
18281 is_type_tag_for_partial (int tag)
18282 {
18283   switch (tag)
18284     {
18285 #if 0
18286     /* Some types that would be reasonable to generate partial symbols for,
18287        that we don't at present.  */
18288     case DW_TAG_array_type:
18289     case DW_TAG_file_type:
18290     case DW_TAG_ptr_to_member_type:
18291     case DW_TAG_set_type:
18292     case DW_TAG_string_type:
18293     case DW_TAG_subroutine_type:
18294 #endif
18295     case DW_TAG_base_type:
18296     case DW_TAG_class_type:
18297     case DW_TAG_interface_type:
18298     case DW_TAG_enumeration_type:
18299     case DW_TAG_structure_type:
18300     case DW_TAG_subrange_type:
18301     case DW_TAG_typedef:
18302     case DW_TAG_union_type:
18303       return 1;
18304     default:
18305       return 0;
18306     }
18307 }
18308
18309 /* Load all DIEs that are interesting for partial symbols into memory.  */
18310
18311 static struct partial_die_info *
18312 load_partial_dies (const struct die_reader_specs *reader,
18313                    const gdb_byte *info_ptr, int building_psymtab)
18314 {
18315   struct dwarf2_cu *cu = reader->cu;
18316   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18317   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18318   unsigned int bytes_read;
18319   unsigned int load_all = 0;
18320   int nesting_level = 1;
18321
18322   parent_die = NULL;
18323   last_die = NULL;
18324
18325   gdb_assert (cu->per_cu != NULL);
18326   if (cu->per_cu->load_all_dies)
18327     load_all = 1;
18328
18329   cu->partial_dies
18330     = htab_create_alloc_ex (cu->header.length / 12,
18331                             partial_die_hash,
18332                             partial_die_eq,
18333                             NULL,
18334                             &cu->comp_unit_obstack,
18335                             hashtab_obstack_allocate,
18336                             dummy_obstack_deallocate);
18337
18338   while (1)
18339     {
18340       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18341
18342       /* A NULL abbrev means the end of a series of children.  */
18343       if (abbrev == NULL)
18344         {
18345           if (--nesting_level == 0)
18346             return first_die;
18347
18348           info_ptr += bytes_read;
18349           last_die = parent_die;
18350           parent_die = parent_die->die_parent;
18351           continue;
18352         }
18353
18354       /* Check for template arguments.  We never save these; if
18355          they're seen, we just mark the parent, and go on our way.  */
18356       if (parent_die != NULL
18357           && cu->language == language_cplus
18358           && (abbrev->tag == DW_TAG_template_type_param
18359               || abbrev->tag == DW_TAG_template_value_param))
18360         {
18361           parent_die->has_template_arguments = 1;
18362
18363           if (!load_all)
18364             {
18365               /* We don't need a partial DIE for the template argument.  */
18366               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18367               continue;
18368             }
18369         }
18370
18371       /* We only recurse into c++ subprograms looking for template arguments.
18372          Skip their other children.  */
18373       if (!load_all
18374           && cu->language == language_cplus
18375           && parent_die != NULL
18376           && parent_die->tag == DW_TAG_subprogram)
18377         {
18378           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18379           continue;
18380         }
18381
18382       /* Check whether this DIE is interesting enough to save.  Normally
18383          we would not be interested in members here, but there may be
18384          later variables referencing them via DW_AT_specification (for
18385          static members).  */
18386       if (!load_all
18387           && !is_type_tag_for_partial (abbrev->tag)
18388           && abbrev->tag != DW_TAG_constant
18389           && abbrev->tag != DW_TAG_enumerator
18390           && abbrev->tag != DW_TAG_subprogram
18391           && abbrev->tag != DW_TAG_inlined_subroutine
18392           && abbrev->tag != DW_TAG_lexical_block
18393           && abbrev->tag != DW_TAG_variable
18394           && abbrev->tag != DW_TAG_namespace
18395           && abbrev->tag != DW_TAG_module
18396           && abbrev->tag != DW_TAG_member
18397           && abbrev->tag != DW_TAG_imported_unit
18398           && abbrev->tag != DW_TAG_imported_declaration)
18399         {
18400           /* Otherwise we skip to the next sibling, if any.  */
18401           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18402           continue;
18403         }
18404
18405       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18406                                    abbrev);
18407
18408       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18409
18410       /* This two-pass algorithm for processing partial symbols has a
18411          high cost in cache pressure.  Thus, handle some simple cases
18412          here which cover the majority of C partial symbols.  DIEs
18413          which neither have specification tags in them, nor could have
18414          specification tags elsewhere pointing at them, can simply be
18415          processed and discarded.
18416
18417          This segment is also optional; scan_partial_symbols and
18418          add_partial_symbol will handle these DIEs if we chain
18419          them in normally.  When compilers which do not emit large
18420          quantities of duplicate debug information are more common,
18421          this code can probably be removed.  */
18422
18423       /* Any complete simple types at the top level (pretty much all
18424          of them, for a language without namespaces), can be processed
18425          directly.  */
18426       if (parent_die == NULL
18427           && pdi.has_specification == 0
18428           && pdi.is_declaration == 0
18429           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18430               || pdi.tag == DW_TAG_base_type
18431               || pdi.tag == DW_TAG_subrange_type))
18432         {
18433           if (building_psymtab && pdi.name != NULL)
18434             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18435                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18436                                  psymbol_placement::STATIC,
18437                                  0, cu->language, objfile);
18438           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18439           continue;
18440         }
18441
18442       /* The exception for DW_TAG_typedef with has_children above is
18443          a workaround of GCC PR debug/47510.  In the case of this complaint
18444          type_name_or_error will error on such types later.
18445
18446          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18447          it could not find the child DIEs referenced later, this is checked
18448          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18449
18450       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18451         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18452                      "- DIE at %s [in module %s]"),
18453                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18454
18455       /* If we're at the second level, and we're an enumerator, and
18456          our parent has no specification (meaning possibly lives in a
18457          namespace elsewhere), then we can add the partial symbol now
18458          instead of queueing it.  */
18459       if (pdi.tag == DW_TAG_enumerator
18460           && parent_die != NULL
18461           && parent_die->die_parent == NULL
18462           && parent_die->tag == DW_TAG_enumeration_type
18463           && parent_die->has_specification == 0)
18464         {
18465           if (pdi.name == NULL)
18466             complaint (_("malformed enumerator DIE ignored"));
18467           else if (building_psymtab)
18468             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18469                                  VAR_DOMAIN, LOC_CONST, -1,
18470                                  cu->language == language_cplus
18471                                  ? psymbol_placement::GLOBAL
18472                                  : psymbol_placement::STATIC,
18473                                  0, cu->language, objfile);
18474
18475           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18476           continue;
18477         }
18478
18479       struct partial_die_info *part_die
18480         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18481
18482       /* We'll save this DIE so link it in.  */
18483       part_die->die_parent = parent_die;
18484       part_die->die_sibling = NULL;
18485       part_die->die_child = NULL;
18486
18487       if (last_die && last_die == parent_die)
18488         last_die->die_child = part_die;
18489       else if (last_die)
18490         last_die->die_sibling = part_die;
18491
18492       last_die = part_die;
18493
18494       if (first_die == NULL)
18495         first_die = part_die;
18496
18497       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18498          find interesting need to be in the hash table, because we
18499          also have the parent/sibling/child chains; only those that we
18500          might refer to by offset later during partial symbol reading.
18501
18502          For now this means things that might have be the target of a
18503          DW_AT_specification, DW_AT_abstract_origin, or
18504          DW_AT_extension.  DW_AT_extension will refer only to
18505          namespaces; DW_AT_abstract_origin refers to functions (and
18506          many things under the function DIE, but we do not recurse
18507          into function DIEs during partial symbol reading) and
18508          possibly variables as well; DW_AT_specification refers to
18509          declarations.  Declarations ought to have the DW_AT_declaration
18510          flag.  It happens that GCC forgets to put it in sometimes, but
18511          only for functions, not for types.
18512
18513          Adding more things than necessary to the hash table is harmless
18514          except for the performance cost.  Adding too few will result in
18515          wasted time in find_partial_die, when we reread the compilation
18516          unit with load_all_dies set.  */
18517
18518       if (load_all
18519           || abbrev->tag == DW_TAG_constant
18520           || abbrev->tag == DW_TAG_subprogram
18521           || abbrev->tag == DW_TAG_variable
18522           || abbrev->tag == DW_TAG_namespace
18523           || part_die->is_declaration)
18524         {
18525           void **slot;
18526
18527           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18528                                            to_underlying (part_die->sect_off),
18529                                            INSERT);
18530           *slot = part_die;
18531         }
18532
18533       /* For some DIEs we want to follow their children (if any).  For C
18534          we have no reason to follow the children of structures; for other
18535          languages we have to, so that we can get at method physnames
18536          to infer fully qualified class names, for DW_AT_specification,
18537          and for C++ template arguments.  For C++, we also look one level
18538          inside functions to find template arguments (if the name of the
18539          function does not already contain the template arguments).
18540
18541          For Ada, we need to scan the children of subprograms and lexical
18542          blocks as well because Ada allows the definition of nested
18543          entities that could be interesting for the debugger, such as
18544          nested subprograms for instance.  */
18545       if (last_die->has_children
18546           && (load_all
18547               || last_die->tag == DW_TAG_namespace
18548               || last_die->tag == DW_TAG_module
18549               || last_die->tag == DW_TAG_enumeration_type
18550               || (cu->language == language_cplus
18551                   && last_die->tag == DW_TAG_subprogram
18552                   && (last_die->name == NULL
18553                       || strchr (last_die->name, '<') == NULL))
18554               || (cu->language != language_c
18555                   && (last_die->tag == DW_TAG_class_type
18556                       || last_die->tag == DW_TAG_interface_type
18557                       || last_die->tag == DW_TAG_structure_type
18558                       || last_die->tag == DW_TAG_union_type))
18559               || (cu->language == language_ada
18560                   && (last_die->tag == DW_TAG_subprogram
18561                       || last_die->tag == DW_TAG_lexical_block))))
18562         {
18563           nesting_level++;
18564           parent_die = last_die;
18565           continue;
18566         }
18567
18568       /* Otherwise we skip to the next sibling, if any.  */
18569       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18570
18571       /* Back to the top, do it again.  */
18572     }
18573 }
18574
18575 partial_die_info::partial_die_info (sect_offset sect_off_,
18576                                     struct abbrev_info *abbrev)
18577   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18578 {
18579 }
18580
18581 /* Read a minimal amount of information into the minimal die structure.
18582    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18583
18584 const gdb_byte *
18585 partial_die_info::read (const struct die_reader_specs *reader,
18586                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18587 {
18588   struct dwarf2_cu *cu = reader->cu;
18589   struct dwarf2_per_objfile *dwarf2_per_objfile
18590     = cu->per_cu->dwarf2_per_objfile;
18591   unsigned int i;
18592   int has_low_pc_attr = 0;
18593   int has_high_pc_attr = 0;
18594   int high_pc_relative = 0;
18595
18596   for (i = 0; i < abbrev.num_attrs; ++i)
18597     {
18598       struct attribute attr;
18599
18600       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18601
18602       /* Store the data if it is of an attribute we want to keep in a
18603          partial symbol table.  */
18604       switch (attr.name)
18605         {
18606         case DW_AT_name:
18607           switch (tag)
18608             {
18609             case DW_TAG_compile_unit:
18610             case DW_TAG_partial_unit:
18611             case DW_TAG_type_unit:
18612               /* Compilation units have a DW_AT_name that is a filename, not
18613                  a source language identifier.  */
18614             case DW_TAG_enumeration_type:
18615             case DW_TAG_enumerator:
18616               /* These tags always have simple identifiers already; no need
18617                  to canonicalize them.  */
18618               name = DW_STRING (&attr);
18619               break;
18620             default:
18621               {
18622                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18623
18624                 name
18625                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18626                                               &objfile->per_bfd->storage_obstack);
18627               }
18628               break;
18629             }
18630           break;
18631         case DW_AT_linkage_name:
18632         case DW_AT_MIPS_linkage_name:
18633           /* Note that both forms of linkage name might appear.  We
18634              assume they will be the same, and we only store the last
18635              one we see.  */
18636           if (cu->language == language_ada)
18637             name = DW_STRING (&attr);
18638           linkage_name = DW_STRING (&attr);
18639           break;
18640         case DW_AT_low_pc:
18641           has_low_pc_attr = 1;
18642           lowpc = attr_value_as_address (&attr);
18643           break;
18644         case DW_AT_high_pc:
18645           has_high_pc_attr = 1;
18646           highpc = attr_value_as_address (&attr);
18647           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18648                 high_pc_relative = 1;
18649           break;
18650         case DW_AT_location:
18651           /* Support the .debug_loc offsets.  */
18652           if (attr_form_is_block (&attr))
18653             {
18654                d.locdesc = DW_BLOCK (&attr);
18655             }
18656           else if (attr_form_is_section_offset (&attr))
18657             {
18658               dwarf2_complex_location_expr_complaint ();
18659             }
18660           else
18661             {
18662               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18663                                                      "partial symbol information");
18664             }
18665           break;
18666         case DW_AT_external:
18667           is_external = DW_UNSND (&attr);
18668           break;
18669         case DW_AT_declaration:
18670           is_declaration = DW_UNSND (&attr);
18671           break;
18672         case DW_AT_type:
18673           has_type = 1;
18674           break;
18675         case DW_AT_abstract_origin:
18676         case DW_AT_specification:
18677         case DW_AT_extension:
18678           has_specification = 1;
18679           spec_offset = dwarf2_get_ref_die_offset (&attr);
18680           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18681                                    || cu->per_cu->is_dwz);
18682           break;
18683         case DW_AT_sibling:
18684           /* Ignore absolute siblings, they might point outside of
18685              the current compile unit.  */
18686           if (attr.form == DW_FORM_ref_addr)
18687             complaint (_("ignoring absolute DW_AT_sibling"));
18688           else
18689             {
18690               const gdb_byte *buffer = reader->buffer;
18691               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18692               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18693
18694               if (sibling_ptr < info_ptr)
18695                 complaint (_("DW_AT_sibling points backwards"));
18696               else if (sibling_ptr > reader->buffer_end)
18697                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18698               else
18699                 sibling = sibling_ptr;
18700             }
18701           break;
18702         case DW_AT_byte_size:
18703           has_byte_size = 1;
18704           break;
18705         case DW_AT_const_value:
18706           has_const_value = 1;
18707           break;
18708         case DW_AT_calling_convention:
18709           /* DWARF doesn't provide a way to identify a program's source-level
18710              entry point.  DW_AT_calling_convention attributes are only meant
18711              to describe functions' calling conventions.
18712
18713              However, because it's a necessary piece of information in
18714              Fortran, and before DWARF 4 DW_CC_program was the only
18715              piece of debugging information whose definition refers to
18716              a 'main program' at all, several compilers marked Fortran
18717              main programs with DW_CC_program --- even when those
18718              functions use the standard calling conventions.
18719
18720              Although DWARF now specifies a way to provide this
18721              information, we support this practice for backward
18722              compatibility.  */
18723           if (DW_UNSND (&attr) == DW_CC_program
18724               && cu->language == language_fortran)
18725             main_subprogram = 1;
18726           break;
18727         case DW_AT_inline:
18728           if (DW_UNSND (&attr) == DW_INL_inlined
18729               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18730             may_be_inlined = 1;
18731           break;
18732
18733         case DW_AT_import:
18734           if (tag == DW_TAG_imported_unit)
18735             {
18736               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18737               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18738                                   || cu->per_cu->is_dwz);
18739             }
18740           break;
18741
18742         case DW_AT_main_subprogram:
18743           main_subprogram = DW_UNSND (&attr);
18744           break;
18745
18746         default:
18747           break;
18748         }
18749     }
18750
18751   if (high_pc_relative)
18752     highpc += lowpc;
18753
18754   if (has_low_pc_attr && has_high_pc_attr)
18755     {
18756       /* When using the GNU linker, .gnu.linkonce. sections are used to
18757          eliminate duplicate copies of functions and vtables and such.
18758          The linker will arbitrarily choose one and discard the others.
18759          The AT_*_pc values for such functions refer to local labels in
18760          these sections.  If the section from that file was discarded, the
18761          labels are not in the output, so the relocs get a value of 0.
18762          If this is a discarded function, mark the pc bounds as invalid,
18763          so that GDB will ignore it.  */
18764       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18765         {
18766           struct objfile *objfile = dwarf2_per_objfile->objfile;
18767           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18768
18769           complaint (_("DW_AT_low_pc %s is zero "
18770                        "for DIE at %s [in module %s]"),
18771                      paddress (gdbarch, lowpc),
18772                      sect_offset_str (sect_off),
18773                      objfile_name (objfile));
18774         }
18775       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18776       else if (lowpc >= highpc)
18777         {
18778           struct objfile *objfile = dwarf2_per_objfile->objfile;
18779           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18780
18781           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18782                        "for DIE at %s [in module %s]"),
18783                      paddress (gdbarch, lowpc),
18784                      paddress (gdbarch, highpc),
18785                      sect_offset_str (sect_off),
18786                      objfile_name (objfile));
18787         }
18788       else
18789         has_pc_info = 1;
18790     }
18791
18792   return info_ptr;
18793 }
18794
18795 /* Find a cached partial DIE at OFFSET in CU.  */
18796
18797 struct partial_die_info *
18798 dwarf2_cu::find_partial_die (sect_offset sect_off)
18799 {
18800   struct partial_die_info *lookup_die = NULL;
18801   struct partial_die_info part_die (sect_off);
18802
18803   lookup_die = ((struct partial_die_info *)
18804                 htab_find_with_hash (partial_dies, &part_die,
18805                                      to_underlying (sect_off)));
18806
18807   return lookup_die;
18808 }
18809
18810 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18811    except in the case of .debug_types DIEs which do not reference
18812    outside their CU (they do however referencing other types via
18813    DW_FORM_ref_sig8).  */
18814
18815 static struct partial_die_info *
18816 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18817 {
18818   struct dwarf2_per_objfile *dwarf2_per_objfile
18819     = cu->per_cu->dwarf2_per_objfile;
18820   struct objfile *objfile = dwarf2_per_objfile->objfile;
18821   struct dwarf2_per_cu_data *per_cu = NULL;
18822   struct partial_die_info *pd = NULL;
18823
18824   if (offset_in_dwz == cu->per_cu->is_dwz
18825       && offset_in_cu_p (&cu->header, sect_off))
18826     {
18827       pd = cu->find_partial_die (sect_off);
18828       if (pd != NULL)
18829         return pd;
18830       /* We missed recording what we needed.
18831          Load all dies and try again.  */
18832       per_cu = cu->per_cu;
18833     }
18834   else
18835     {
18836       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18837       if (cu->per_cu->is_debug_types)
18838         {
18839           error (_("Dwarf Error: Type Unit at offset %s contains"
18840                    " external reference to offset %s [in module %s].\n"),
18841                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18842                  bfd_get_filename (objfile->obfd));
18843         }
18844       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18845                                                  dwarf2_per_objfile);
18846
18847       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18848         load_partial_comp_unit (per_cu);
18849
18850       per_cu->cu->last_used = 0;
18851       pd = per_cu->cu->find_partial_die (sect_off);
18852     }
18853
18854   /* If we didn't find it, and not all dies have been loaded,
18855      load them all and try again.  */
18856
18857   if (pd == NULL && per_cu->load_all_dies == 0)
18858     {
18859       per_cu->load_all_dies = 1;
18860
18861       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18862          THIS_CU->cu may already be in use.  So we can't just free it and
18863          replace its DIEs with the ones we read in.  Instead, we leave those
18864          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18865          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18866          set.  */
18867       load_partial_comp_unit (per_cu);
18868
18869       pd = per_cu->cu->find_partial_die (sect_off);
18870     }
18871
18872   if (pd == NULL)
18873     internal_error (__FILE__, __LINE__,
18874                     _("could not find partial DIE %s "
18875                       "in cache [from module %s]\n"),
18876                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18877   return pd;
18878 }
18879
18880 /* See if we can figure out if the class lives in a namespace.  We do
18881    this by looking for a member function; its demangled name will
18882    contain namespace info, if there is any.  */
18883
18884 static void
18885 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18886                                   struct dwarf2_cu *cu)
18887 {
18888   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18889      what template types look like, because the demangler
18890      frequently doesn't give the same name as the debug info.  We
18891      could fix this by only using the demangled name to get the
18892      prefix (but see comment in read_structure_type).  */
18893
18894   struct partial_die_info *real_pdi;
18895   struct partial_die_info *child_pdi;
18896
18897   /* If this DIE (this DIE's specification, if any) has a parent, then
18898      we should not do this.  We'll prepend the parent's fully qualified
18899      name when we create the partial symbol.  */
18900
18901   real_pdi = struct_pdi;
18902   while (real_pdi->has_specification)
18903     real_pdi = find_partial_die (real_pdi->spec_offset,
18904                                  real_pdi->spec_is_dwz, cu);
18905
18906   if (real_pdi->die_parent != NULL)
18907     return;
18908
18909   for (child_pdi = struct_pdi->die_child;
18910        child_pdi != NULL;
18911        child_pdi = child_pdi->die_sibling)
18912     {
18913       if (child_pdi->tag == DW_TAG_subprogram
18914           && child_pdi->linkage_name != NULL)
18915         {
18916           char *actual_class_name
18917             = language_class_name_from_physname (cu->language_defn,
18918                                                  child_pdi->linkage_name);
18919           if (actual_class_name != NULL)
18920             {
18921               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18922               struct_pdi->name
18923                 = ((const char *)
18924                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18925                                   actual_class_name,
18926                                   strlen (actual_class_name)));
18927               xfree (actual_class_name);
18928             }
18929           break;
18930         }
18931     }
18932 }
18933
18934 void
18935 partial_die_info::fixup (struct dwarf2_cu *cu)
18936 {
18937   /* Once we've fixed up a die, there's no point in doing so again.
18938      This also avoids a memory leak if we were to call
18939      guess_partial_die_structure_name multiple times.  */
18940   if (fixup_called)
18941     return;
18942
18943   /* If we found a reference attribute and the DIE has no name, try
18944      to find a name in the referred to DIE.  */
18945
18946   if (name == NULL && has_specification)
18947     {
18948       struct partial_die_info *spec_die;
18949
18950       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18951
18952       spec_die->fixup (cu);
18953
18954       if (spec_die->name)
18955         {
18956           name = spec_die->name;
18957
18958           /* Copy DW_AT_external attribute if it is set.  */
18959           if (spec_die->is_external)
18960             is_external = spec_die->is_external;
18961         }
18962     }
18963
18964   /* Set default names for some unnamed DIEs.  */
18965
18966   if (name == NULL && tag == DW_TAG_namespace)
18967     name = CP_ANONYMOUS_NAMESPACE_STR;
18968
18969   /* If there is no parent die to provide a namespace, and there are
18970      children, see if we can determine the namespace from their linkage
18971      name.  */
18972   if (cu->language == language_cplus
18973       && !VEC_empty (dwarf2_section_info_def,
18974                      cu->per_cu->dwarf2_per_objfile->types)
18975       && die_parent == NULL
18976       && has_children
18977       && (tag == DW_TAG_class_type
18978           || tag == DW_TAG_structure_type
18979           || tag == DW_TAG_union_type))
18980     guess_partial_die_structure_name (this, cu);
18981
18982   /* GCC might emit a nameless struct or union that has a linkage
18983      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18984   if (name == NULL
18985       && (tag == DW_TAG_class_type
18986           || tag == DW_TAG_interface_type
18987           || tag == DW_TAG_structure_type
18988           || tag == DW_TAG_union_type)
18989       && linkage_name != NULL)
18990     {
18991       char *demangled;
18992
18993       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18994       if (demangled)
18995         {
18996           const char *base;
18997
18998           /* Strip any leading namespaces/classes, keep only the base name.
18999              DW_AT_name for named DIEs does not contain the prefixes.  */
19000           base = strrchr (demangled, ':');
19001           if (base && base > demangled && base[-1] == ':')
19002             base++;
19003           else
19004             base = demangled;
19005
19006           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19007           name
19008             = ((const char *)
19009                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19010                               base, strlen (base)));
19011           xfree (demangled);
19012         }
19013     }
19014
19015   fixup_called = 1;
19016 }
19017
19018 /* Read an attribute value described by an attribute form.  */
19019
19020 static const gdb_byte *
19021 read_attribute_value (const struct die_reader_specs *reader,
19022                       struct attribute *attr, unsigned form,
19023                       LONGEST implicit_const, const gdb_byte *info_ptr)
19024 {
19025   struct dwarf2_cu *cu = reader->cu;
19026   struct dwarf2_per_objfile *dwarf2_per_objfile
19027     = cu->per_cu->dwarf2_per_objfile;
19028   struct objfile *objfile = dwarf2_per_objfile->objfile;
19029   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19030   bfd *abfd = reader->abfd;
19031   struct comp_unit_head *cu_header = &cu->header;
19032   unsigned int bytes_read;
19033   struct dwarf_block *blk;
19034
19035   attr->form = (enum dwarf_form) form;
19036   switch (form)
19037     {
19038     case DW_FORM_ref_addr:
19039       if (cu->header.version == 2)
19040         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19041       else
19042         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19043                                        &cu->header, &bytes_read);
19044       info_ptr += bytes_read;
19045       break;
19046     case DW_FORM_GNU_ref_alt:
19047       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19048       info_ptr += bytes_read;
19049       break;
19050     case DW_FORM_addr:
19051       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19052       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19053       info_ptr += bytes_read;
19054       break;
19055     case DW_FORM_block2:
19056       blk = dwarf_alloc_block (cu);
19057       blk->size = read_2_bytes (abfd, info_ptr);
19058       info_ptr += 2;
19059       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19060       info_ptr += blk->size;
19061       DW_BLOCK (attr) = blk;
19062       break;
19063     case DW_FORM_block4:
19064       blk = dwarf_alloc_block (cu);
19065       blk->size = read_4_bytes (abfd, info_ptr);
19066       info_ptr += 4;
19067       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19068       info_ptr += blk->size;
19069       DW_BLOCK (attr) = blk;
19070       break;
19071     case DW_FORM_data2:
19072       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19073       info_ptr += 2;
19074       break;
19075     case DW_FORM_data4:
19076       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19077       info_ptr += 4;
19078       break;
19079     case DW_FORM_data8:
19080       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19081       info_ptr += 8;
19082       break;
19083     case DW_FORM_data16:
19084       blk = dwarf_alloc_block (cu);
19085       blk->size = 16;
19086       blk->data = read_n_bytes (abfd, info_ptr, 16);
19087       info_ptr += 16;
19088       DW_BLOCK (attr) = blk;
19089       break;
19090     case DW_FORM_sec_offset:
19091       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19092       info_ptr += bytes_read;
19093       break;
19094     case DW_FORM_string:
19095       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19096       DW_STRING_IS_CANONICAL (attr) = 0;
19097       info_ptr += bytes_read;
19098       break;
19099     case DW_FORM_strp:
19100       if (!cu->per_cu->is_dwz)
19101         {
19102           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19103                                                    abfd, info_ptr, cu_header,
19104                                                    &bytes_read);
19105           DW_STRING_IS_CANONICAL (attr) = 0;
19106           info_ptr += bytes_read;
19107           break;
19108         }
19109       /* FALLTHROUGH */
19110     case DW_FORM_line_strp:
19111       if (!cu->per_cu->is_dwz)
19112         {
19113           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19114                                                         abfd, info_ptr,
19115                                                         cu_header, &bytes_read);
19116           DW_STRING_IS_CANONICAL (attr) = 0;
19117           info_ptr += bytes_read;
19118           break;
19119         }
19120       /* FALLTHROUGH */
19121     case DW_FORM_GNU_strp_alt:
19122       {
19123         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19124         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19125                                           &bytes_read);
19126
19127         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19128                                                           dwz, str_offset);
19129         DW_STRING_IS_CANONICAL (attr) = 0;
19130         info_ptr += bytes_read;
19131       }
19132       break;
19133     case DW_FORM_exprloc:
19134     case DW_FORM_block:
19135       blk = dwarf_alloc_block (cu);
19136       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19137       info_ptr += bytes_read;
19138       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19139       info_ptr += blk->size;
19140       DW_BLOCK (attr) = blk;
19141       break;
19142     case DW_FORM_block1:
19143       blk = dwarf_alloc_block (cu);
19144       blk->size = read_1_byte (abfd, info_ptr);
19145       info_ptr += 1;
19146       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19147       info_ptr += blk->size;
19148       DW_BLOCK (attr) = blk;
19149       break;
19150     case DW_FORM_data1:
19151       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19152       info_ptr += 1;
19153       break;
19154     case DW_FORM_flag:
19155       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19156       info_ptr += 1;
19157       break;
19158     case DW_FORM_flag_present:
19159       DW_UNSND (attr) = 1;
19160       break;
19161     case DW_FORM_sdata:
19162       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19163       info_ptr += bytes_read;
19164       break;
19165     case DW_FORM_udata:
19166       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19167       info_ptr += bytes_read;
19168       break;
19169     case DW_FORM_ref1:
19170       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19171                          + read_1_byte (abfd, info_ptr));
19172       info_ptr += 1;
19173       break;
19174     case DW_FORM_ref2:
19175       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19176                          + read_2_bytes (abfd, info_ptr));
19177       info_ptr += 2;
19178       break;
19179     case DW_FORM_ref4:
19180       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19181                          + read_4_bytes (abfd, info_ptr));
19182       info_ptr += 4;
19183       break;
19184     case DW_FORM_ref8:
19185       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19186                          + read_8_bytes (abfd, info_ptr));
19187       info_ptr += 8;
19188       break;
19189     case DW_FORM_ref_sig8:
19190       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19191       info_ptr += 8;
19192       break;
19193     case DW_FORM_ref_udata:
19194       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19195                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19196       info_ptr += bytes_read;
19197       break;
19198     case DW_FORM_indirect:
19199       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19200       info_ptr += bytes_read;
19201       if (form == DW_FORM_implicit_const)
19202         {
19203           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19204           info_ptr += bytes_read;
19205         }
19206       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19207                                        info_ptr);
19208       break;
19209     case DW_FORM_implicit_const:
19210       DW_SND (attr) = implicit_const;
19211       break;
19212     case DW_FORM_GNU_addr_index:
19213       if (reader->dwo_file == NULL)
19214         {
19215           /* For now flag a hard error.
19216              Later we can turn this into a complaint.  */
19217           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19218                  dwarf_form_name (form),
19219                  bfd_get_filename (abfd));
19220         }
19221       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19222       info_ptr += bytes_read;
19223       break;
19224     case DW_FORM_GNU_str_index:
19225       if (reader->dwo_file == NULL)
19226         {
19227           /* For now flag a hard error.
19228              Later we can turn this into a complaint if warranted.  */
19229           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19230                  dwarf_form_name (form),
19231                  bfd_get_filename (abfd));
19232         }
19233       {
19234         ULONGEST str_index =
19235           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19236
19237         DW_STRING (attr) = read_str_index (reader, str_index);
19238         DW_STRING_IS_CANONICAL (attr) = 0;
19239         info_ptr += bytes_read;
19240       }
19241       break;
19242     default:
19243       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19244              dwarf_form_name (form),
19245              bfd_get_filename (abfd));
19246     }
19247
19248   /* Super hack.  */
19249   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19250     attr->form = DW_FORM_GNU_ref_alt;
19251
19252   /* We have seen instances where the compiler tried to emit a byte
19253      size attribute of -1 which ended up being encoded as an unsigned
19254      0xffffffff.  Although 0xffffffff is technically a valid size value,
19255      an object of this size seems pretty unlikely so we can relatively
19256      safely treat these cases as if the size attribute was invalid and
19257      treat them as zero by default.  */
19258   if (attr->name == DW_AT_byte_size
19259       && form == DW_FORM_data4
19260       && DW_UNSND (attr) >= 0xffffffff)
19261     {
19262       complaint
19263         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19264          hex_string (DW_UNSND (attr)));
19265       DW_UNSND (attr) = 0;
19266     }
19267
19268   return info_ptr;
19269 }
19270
19271 /* Read an attribute described by an abbreviated attribute.  */
19272
19273 static const gdb_byte *
19274 read_attribute (const struct die_reader_specs *reader,
19275                 struct attribute *attr, struct attr_abbrev *abbrev,
19276                 const gdb_byte *info_ptr)
19277 {
19278   attr->name = abbrev->name;
19279   return read_attribute_value (reader, attr, abbrev->form,
19280                                abbrev->implicit_const, info_ptr);
19281 }
19282
19283 /* Read dwarf information from a buffer.  */
19284
19285 static unsigned int
19286 read_1_byte (bfd *abfd, const gdb_byte *buf)
19287 {
19288   return bfd_get_8 (abfd, buf);
19289 }
19290
19291 static int
19292 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19293 {
19294   return bfd_get_signed_8 (abfd, buf);
19295 }
19296
19297 static unsigned int
19298 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19299 {
19300   return bfd_get_16 (abfd, buf);
19301 }
19302
19303 static int
19304 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19305 {
19306   return bfd_get_signed_16 (abfd, buf);
19307 }
19308
19309 static unsigned int
19310 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19311 {
19312   return bfd_get_32 (abfd, buf);
19313 }
19314
19315 static int
19316 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19317 {
19318   return bfd_get_signed_32 (abfd, buf);
19319 }
19320
19321 static ULONGEST
19322 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19323 {
19324   return bfd_get_64 (abfd, buf);
19325 }
19326
19327 static CORE_ADDR
19328 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19329               unsigned int *bytes_read)
19330 {
19331   struct comp_unit_head *cu_header = &cu->header;
19332   CORE_ADDR retval = 0;
19333
19334   if (cu_header->signed_addr_p)
19335     {
19336       switch (cu_header->addr_size)
19337         {
19338         case 2:
19339           retval = bfd_get_signed_16 (abfd, buf);
19340           break;
19341         case 4:
19342           retval = bfd_get_signed_32 (abfd, buf);
19343           break;
19344         case 8:
19345           retval = bfd_get_signed_64 (abfd, buf);
19346           break;
19347         default:
19348           internal_error (__FILE__, __LINE__,
19349                           _("read_address: bad switch, signed [in module %s]"),
19350                           bfd_get_filename (abfd));
19351         }
19352     }
19353   else
19354     {
19355       switch (cu_header->addr_size)
19356         {
19357         case 2:
19358           retval = bfd_get_16 (abfd, buf);
19359           break;
19360         case 4:
19361           retval = bfd_get_32 (abfd, buf);
19362           break;
19363         case 8:
19364           retval = bfd_get_64 (abfd, buf);
19365           break;
19366         default:
19367           internal_error (__FILE__, __LINE__,
19368                           _("read_address: bad switch, "
19369                             "unsigned [in module %s]"),
19370                           bfd_get_filename (abfd));
19371         }
19372     }
19373
19374   *bytes_read = cu_header->addr_size;
19375   return retval;
19376 }
19377
19378 /* Read the initial length from a section.  The (draft) DWARF 3
19379    specification allows the initial length to take up either 4 bytes
19380    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19381    bytes describe the length and all offsets will be 8 bytes in length
19382    instead of 4.
19383
19384    An older, non-standard 64-bit format is also handled by this
19385    function.  The older format in question stores the initial length
19386    as an 8-byte quantity without an escape value.  Lengths greater
19387    than 2^32 aren't very common which means that the initial 4 bytes
19388    is almost always zero.  Since a length value of zero doesn't make
19389    sense for the 32-bit format, this initial zero can be considered to
19390    be an escape value which indicates the presence of the older 64-bit
19391    format.  As written, the code can't detect (old format) lengths
19392    greater than 4GB.  If it becomes necessary to handle lengths
19393    somewhat larger than 4GB, we could allow other small values (such
19394    as the non-sensical values of 1, 2, and 3) to also be used as
19395    escape values indicating the presence of the old format.
19396
19397    The value returned via bytes_read should be used to increment the
19398    relevant pointer after calling read_initial_length().
19399
19400    [ Note:  read_initial_length() and read_offset() are based on the
19401      document entitled "DWARF Debugging Information Format", revision
19402      3, draft 8, dated November 19, 2001.  This document was obtained
19403      from:
19404
19405         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19406
19407      This document is only a draft and is subject to change.  (So beware.)
19408
19409      Details regarding the older, non-standard 64-bit format were
19410      determined empirically by examining 64-bit ELF files produced by
19411      the SGI toolchain on an IRIX 6.5 machine.
19412
19413      - Kevin, July 16, 2002
19414    ] */
19415
19416 static LONGEST
19417 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19418 {
19419   LONGEST length = bfd_get_32 (abfd, buf);
19420
19421   if (length == 0xffffffff)
19422     {
19423       length = bfd_get_64 (abfd, buf + 4);
19424       *bytes_read = 12;
19425     }
19426   else if (length == 0)
19427     {
19428       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19429       length = bfd_get_64 (abfd, buf);
19430       *bytes_read = 8;
19431     }
19432   else
19433     {
19434       *bytes_read = 4;
19435     }
19436
19437   return length;
19438 }
19439
19440 /* Cover function for read_initial_length.
19441    Returns the length of the object at BUF, and stores the size of the
19442    initial length in *BYTES_READ and stores the size that offsets will be in
19443    *OFFSET_SIZE.
19444    If the initial length size is not equivalent to that specified in
19445    CU_HEADER then issue a complaint.
19446    This is useful when reading non-comp-unit headers.  */
19447
19448 static LONGEST
19449 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19450                                         const struct comp_unit_head *cu_header,
19451                                         unsigned int *bytes_read,
19452                                         unsigned int *offset_size)
19453 {
19454   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19455
19456   gdb_assert (cu_header->initial_length_size == 4
19457               || cu_header->initial_length_size == 8
19458               || cu_header->initial_length_size == 12);
19459
19460   if (cu_header->initial_length_size != *bytes_read)
19461     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19462
19463   *offset_size = (*bytes_read == 4) ? 4 : 8;
19464   return length;
19465 }
19466
19467 /* Read an offset from the data stream.  The size of the offset is
19468    given by cu_header->offset_size.  */
19469
19470 static LONGEST
19471 read_offset (bfd *abfd, const gdb_byte *buf,
19472              const struct comp_unit_head *cu_header,
19473              unsigned int *bytes_read)
19474 {
19475   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19476
19477   *bytes_read = cu_header->offset_size;
19478   return offset;
19479 }
19480
19481 /* Read an offset from the data stream.  */
19482
19483 static LONGEST
19484 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19485 {
19486   LONGEST retval = 0;
19487
19488   switch (offset_size)
19489     {
19490     case 4:
19491       retval = bfd_get_32 (abfd, buf);
19492       break;
19493     case 8:
19494       retval = bfd_get_64 (abfd, buf);
19495       break;
19496     default:
19497       internal_error (__FILE__, __LINE__,
19498                       _("read_offset_1: bad switch [in module %s]"),
19499                       bfd_get_filename (abfd));
19500     }
19501
19502   return retval;
19503 }
19504
19505 static const gdb_byte *
19506 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19507 {
19508   /* If the size of a host char is 8 bits, we can return a pointer
19509      to the buffer, otherwise we have to copy the data to a buffer
19510      allocated on the temporary obstack.  */
19511   gdb_assert (HOST_CHAR_BIT == 8);
19512   return buf;
19513 }
19514
19515 static const char *
19516 read_direct_string (bfd *abfd, const gdb_byte *buf,
19517                     unsigned int *bytes_read_ptr)
19518 {
19519   /* If the size of a host char is 8 bits, we can return a pointer
19520      to the string, otherwise we have to copy the string to a buffer
19521      allocated on the temporary obstack.  */
19522   gdb_assert (HOST_CHAR_BIT == 8);
19523   if (*buf == '\0')
19524     {
19525       *bytes_read_ptr = 1;
19526       return NULL;
19527     }
19528   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19529   return (const char *) buf;
19530 }
19531
19532 /* Return pointer to string at section SECT offset STR_OFFSET with error
19533    reporting strings FORM_NAME and SECT_NAME.  */
19534
19535 static const char *
19536 read_indirect_string_at_offset_from (struct objfile *objfile,
19537                                      bfd *abfd, LONGEST str_offset,
19538                                      struct dwarf2_section_info *sect,
19539                                      const char *form_name,
19540                                      const char *sect_name)
19541 {
19542   dwarf2_read_section (objfile, sect);
19543   if (sect->buffer == NULL)
19544     error (_("%s used without %s section [in module %s]"),
19545            form_name, sect_name, bfd_get_filename (abfd));
19546   if (str_offset >= sect->size)
19547     error (_("%s pointing outside of %s section [in module %s]"),
19548            form_name, sect_name, bfd_get_filename (abfd));
19549   gdb_assert (HOST_CHAR_BIT == 8);
19550   if (sect->buffer[str_offset] == '\0')
19551     return NULL;
19552   return (const char *) (sect->buffer + str_offset);
19553 }
19554
19555 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19556
19557 static const char *
19558 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19559                                 bfd *abfd, LONGEST str_offset)
19560 {
19561   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19562                                               abfd, str_offset,
19563                                               &dwarf2_per_objfile->str,
19564                                               "DW_FORM_strp", ".debug_str");
19565 }
19566
19567 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19568
19569 static const char *
19570 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19571                                      bfd *abfd, LONGEST str_offset)
19572 {
19573   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19574                                               abfd, str_offset,
19575                                               &dwarf2_per_objfile->line_str,
19576                                               "DW_FORM_line_strp",
19577                                               ".debug_line_str");
19578 }
19579
19580 /* Read a string at offset STR_OFFSET in the .debug_str section from
19581    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19582    the string consists of a single NUL byte, return NULL; otherwise
19583    return a pointer to the string.  */
19584
19585 static const char *
19586 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19587                                LONGEST str_offset)
19588 {
19589   dwarf2_read_section (objfile, &dwz->str);
19590
19591   if (dwz->str.buffer == NULL)
19592     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19593              "section [in module %s]"),
19594            bfd_get_filename (dwz->dwz_bfd));
19595   if (str_offset >= dwz->str.size)
19596     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19597              ".debug_str section [in module %s]"),
19598            bfd_get_filename (dwz->dwz_bfd));
19599   gdb_assert (HOST_CHAR_BIT == 8);
19600   if (dwz->str.buffer[str_offset] == '\0')
19601     return NULL;
19602   return (const char *) (dwz->str.buffer + str_offset);
19603 }
19604
19605 /* Return pointer to string at .debug_str offset as read from BUF.
19606    BUF is assumed to be in a compilation unit described by CU_HEADER.
19607    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19608
19609 static const char *
19610 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19611                       const gdb_byte *buf,
19612                       const struct comp_unit_head *cu_header,
19613                       unsigned int *bytes_read_ptr)
19614 {
19615   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19616
19617   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19618 }
19619
19620 /* Return pointer to string at .debug_line_str offset as read from BUF.
19621    BUF is assumed to be in a compilation unit described by CU_HEADER.
19622    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19623
19624 static const char *
19625 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19626                            bfd *abfd, const gdb_byte *buf,
19627                            const struct comp_unit_head *cu_header,
19628                            unsigned int *bytes_read_ptr)
19629 {
19630   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19631
19632   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19633                                               str_offset);
19634 }
19635
19636 ULONGEST
19637 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19638                           unsigned int *bytes_read_ptr)
19639 {
19640   ULONGEST result;
19641   unsigned int num_read;
19642   int shift;
19643   unsigned char byte;
19644
19645   result = 0;
19646   shift = 0;
19647   num_read = 0;
19648   while (1)
19649     {
19650       byte = bfd_get_8 (abfd, buf);
19651       buf++;
19652       num_read++;
19653       result |= ((ULONGEST) (byte & 127) << shift);
19654       if ((byte & 128) == 0)
19655         {
19656           break;
19657         }
19658       shift += 7;
19659     }
19660   *bytes_read_ptr = num_read;
19661   return result;
19662 }
19663
19664 static LONGEST
19665 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19666                     unsigned int *bytes_read_ptr)
19667 {
19668   ULONGEST result;
19669   int shift, num_read;
19670   unsigned char byte;
19671
19672   result = 0;
19673   shift = 0;
19674   num_read = 0;
19675   while (1)
19676     {
19677       byte = bfd_get_8 (abfd, buf);
19678       buf++;
19679       num_read++;
19680       result |= ((ULONGEST) (byte & 127) << shift);
19681       shift += 7;
19682       if ((byte & 128) == 0)
19683         {
19684           break;
19685         }
19686     }
19687   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19688     result |= -(((ULONGEST) 1) << shift);
19689   *bytes_read_ptr = num_read;
19690   return result;
19691 }
19692
19693 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19694    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19695    ADDR_SIZE is the size of addresses from the CU header.  */
19696
19697 static CORE_ADDR
19698 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19699                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19700 {
19701   struct objfile *objfile = dwarf2_per_objfile->objfile;
19702   bfd *abfd = objfile->obfd;
19703   const gdb_byte *info_ptr;
19704
19705   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19706   if (dwarf2_per_objfile->addr.buffer == NULL)
19707     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19708            objfile_name (objfile));
19709   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19710     error (_("DW_FORM_addr_index pointing outside of "
19711              ".debug_addr section [in module %s]"),
19712            objfile_name (objfile));
19713   info_ptr = (dwarf2_per_objfile->addr.buffer
19714               + addr_base + addr_index * addr_size);
19715   if (addr_size == 4)
19716     return bfd_get_32 (abfd, info_ptr);
19717   else
19718     return bfd_get_64 (abfd, info_ptr);
19719 }
19720
19721 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19722
19723 static CORE_ADDR
19724 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19725 {
19726   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19727                             cu->addr_base, cu->header.addr_size);
19728 }
19729
19730 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19731
19732 static CORE_ADDR
19733 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19734                              unsigned int *bytes_read)
19735 {
19736   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19737   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19738
19739   return read_addr_index (cu, addr_index);
19740 }
19741
19742 /* Data structure to pass results from dwarf2_read_addr_index_reader
19743    back to dwarf2_read_addr_index.  */
19744
19745 struct dwarf2_read_addr_index_data
19746 {
19747   ULONGEST addr_base;
19748   int addr_size;
19749 };
19750
19751 /* die_reader_func for dwarf2_read_addr_index.  */
19752
19753 static void
19754 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19755                                const gdb_byte *info_ptr,
19756                                struct die_info *comp_unit_die,
19757                                int has_children,
19758                                void *data)
19759 {
19760   struct dwarf2_cu *cu = reader->cu;
19761   struct dwarf2_read_addr_index_data *aidata =
19762     (struct dwarf2_read_addr_index_data *) data;
19763
19764   aidata->addr_base = cu->addr_base;
19765   aidata->addr_size = cu->header.addr_size;
19766 }
19767
19768 /* Given an index in .debug_addr, fetch the value.
19769    NOTE: This can be called during dwarf expression evaluation,
19770    long after the debug information has been read, and thus per_cu->cu
19771    may no longer exist.  */
19772
19773 CORE_ADDR
19774 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19775                         unsigned int addr_index)
19776 {
19777   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19778   struct dwarf2_cu *cu = per_cu->cu;
19779   ULONGEST addr_base;
19780   int addr_size;
19781
19782   /* We need addr_base and addr_size.
19783      If we don't have PER_CU->cu, we have to get it.
19784      Nasty, but the alternative is storing the needed info in PER_CU,
19785      which at this point doesn't seem justified: it's not clear how frequently
19786      it would get used and it would increase the size of every PER_CU.
19787      Entry points like dwarf2_per_cu_addr_size do a similar thing
19788      so we're not in uncharted territory here.
19789      Alas we need to be a bit more complicated as addr_base is contained
19790      in the DIE.
19791
19792      We don't need to read the entire CU(/TU).
19793      We just need the header and top level die.
19794
19795      IWBN to use the aging mechanism to let us lazily later discard the CU.
19796      For now we skip this optimization.  */
19797
19798   if (cu != NULL)
19799     {
19800       addr_base = cu->addr_base;
19801       addr_size = cu->header.addr_size;
19802     }
19803   else
19804     {
19805       struct dwarf2_read_addr_index_data aidata;
19806
19807       /* Note: We can't use init_cutu_and_read_dies_simple here,
19808          we need addr_base.  */
19809       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19810                                dwarf2_read_addr_index_reader, &aidata);
19811       addr_base = aidata.addr_base;
19812       addr_size = aidata.addr_size;
19813     }
19814
19815   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19816                             addr_size);
19817 }
19818
19819 /* Given a DW_FORM_GNU_str_index, fetch the string.
19820    This is only used by the Fission support.  */
19821
19822 static const char *
19823 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19824 {
19825   struct dwarf2_cu *cu = reader->cu;
19826   struct dwarf2_per_objfile *dwarf2_per_objfile
19827     = cu->per_cu->dwarf2_per_objfile;
19828   struct objfile *objfile = dwarf2_per_objfile->objfile;
19829   const char *objf_name = objfile_name (objfile);
19830   bfd *abfd = objfile->obfd;
19831   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19832   struct dwarf2_section_info *str_offsets_section =
19833     &reader->dwo_file->sections.str_offsets;
19834   const gdb_byte *info_ptr;
19835   ULONGEST str_offset;
19836   static const char form_name[] = "DW_FORM_GNU_str_index";
19837
19838   dwarf2_read_section (objfile, str_section);
19839   dwarf2_read_section (objfile, str_offsets_section);
19840   if (str_section->buffer == NULL)
19841     error (_("%s used without .debug_str.dwo section"
19842              " in CU at offset %s [in module %s]"),
19843            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19844   if (str_offsets_section->buffer == NULL)
19845     error (_("%s used without .debug_str_offsets.dwo section"
19846              " in CU at offset %s [in module %s]"),
19847            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19848   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19849     error (_("%s pointing outside of .debug_str_offsets.dwo"
19850              " section in CU at offset %s [in module %s]"),
19851            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19852   info_ptr = (str_offsets_section->buffer
19853               + str_index * cu->header.offset_size);
19854   if (cu->header.offset_size == 4)
19855     str_offset = bfd_get_32 (abfd, info_ptr);
19856   else
19857     str_offset = bfd_get_64 (abfd, info_ptr);
19858   if (str_offset >= str_section->size)
19859     error (_("Offset from %s pointing outside of"
19860              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19861            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19862   return (const char *) (str_section->buffer + str_offset);
19863 }
19864
19865 /* Return the length of an LEB128 number in BUF.  */
19866
19867 static int
19868 leb128_size (const gdb_byte *buf)
19869 {
19870   const gdb_byte *begin = buf;
19871   gdb_byte byte;
19872
19873   while (1)
19874     {
19875       byte = *buf++;
19876       if ((byte & 128) == 0)
19877         return buf - begin;
19878     }
19879 }
19880
19881 static void
19882 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19883 {
19884   switch (lang)
19885     {
19886     case DW_LANG_C89:
19887     case DW_LANG_C99:
19888     case DW_LANG_C11:
19889     case DW_LANG_C:
19890     case DW_LANG_UPC:
19891       cu->language = language_c;
19892       break;
19893     case DW_LANG_Java:
19894     case DW_LANG_C_plus_plus:
19895     case DW_LANG_C_plus_plus_11:
19896     case DW_LANG_C_plus_plus_14:
19897       cu->language = language_cplus;
19898       break;
19899     case DW_LANG_D:
19900       cu->language = language_d;
19901       break;
19902     case DW_LANG_Fortran77:
19903     case DW_LANG_Fortran90:
19904     case DW_LANG_Fortran95:
19905     case DW_LANG_Fortran03:
19906     case DW_LANG_Fortran08:
19907       cu->language = language_fortran;
19908       break;
19909     case DW_LANG_Go:
19910       cu->language = language_go;
19911       break;
19912     case DW_LANG_Mips_Assembler:
19913       cu->language = language_asm;
19914       break;
19915     case DW_LANG_Ada83:
19916     case DW_LANG_Ada95:
19917       cu->language = language_ada;
19918       break;
19919     case DW_LANG_Modula2:
19920       cu->language = language_m2;
19921       break;
19922     case DW_LANG_Pascal83:
19923       cu->language = language_pascal;
19924       break;
19925     case DW_LANG_ObjC:
19926       cu->language = language_objc;
19927       break;
19928     case DW_LANG_Rust:
19929     case DW_LANG_Rust_old:
19930       cu->language = language_rust;
19931       break;
19932     case DW_LANG_Cobol74:
19933     case DW_LANG_Cobol85:
19934     default:
19935       cu->language = language_minimal;
19936       break;
19937     }
19938   cu->language_defn = language_def (cu->language);
19939 }
19940
19941 /* Return the named attribute or NULL if not there.  */
19942
19943 static struct attribute *
19944 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19945 {
19946   for (;;)
19947     {
19948       unsigned int i;
19949       struct attribute *spec = NULL;
19950
19951       for (i = 0; i < die->num_attrs; ++i)
19952         {
19953           if (die->attrs[i].name == name)
19954             return &die->attrs[i];
19955           if (die->attrs[i].name == DW_AT_specification
19956               || die->attrs[i].name == DW_AT_abstract_origin)
19957             spec = &die->attrs[i];
19958         }
19959
19960       if (!spec)
19961         break;
19962
19963       die = follow_die_ref (die, spec, &cu);
19964     }
19965
19966   return NULL;
19967 }
19968
19969 /* Return the named attribute or NULL if not there,
19970    but do not follow DW_AT_specification, etc.
19971    This is for use in contexts where we're reading .debug_types dies.
19972    Following DW_AT_specification, DW_AT_abstract_origin will take us
19973    back up the chain, and we want to go down.  */
19974
19975 static struct attribute *
19976 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19977 {
19978   unsigned int i;
19979
19980   for (i = 0; i < die->num_attrs; ++i)
19981     if (die->attrs[i].name == name)
19982       return &die->attrs[i];
19983
19984   return NULL;
19985 }
19986
19987 /* Return the string associated with a string-typed attribute, or NULL if it
19988    is either not found or is of an incorrect type.  */
19989
19990 static const char *
19991 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19992 {
19993   struct attribute *attr;
19994   const char *str = NULL;
19995
19996   attr = dwarf2_attr (die, name, cu);
19997
19998   if (attr != NULL)
19999     {
20000       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20001           || attr->form == DW_FORM_string
20002           || attr->form == DW_FORM_GNU_str_index
20003           || attr->form == DW_FORM_GNU_strp_alt)
20004         str = DW_STRING (attr);
20005       else
20006         complaint (_("string type expected for attribute %s for "
20007                      "DIE at %s in module %s"),
20008                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
20009                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20010     }
20011
20012   return str;
20013 }
20014
20015 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20016    and holds a non-zero value.  This function should only be used for
20017    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20018
20019 static int
20020 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20021 {
20022   struct attribute *attr = dwarf2_attr (die, name, cu);
20023
20024   return (attr && DW_UNSND (attr));
20025 }
20026
20027 static int
20028 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20029 {
20030   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20031      which value is non-zero.  However, we have to be careful with
20032      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20033      (via dwarf2_flag_true_p) follows this attribute.  So we may
20034      end up accidently finding a declaration attribute that belongs
20035      to a different DIE referenced by the specification attribute,
20036      even though the given DIE does not have a declaration attribute.  */
20037   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20038           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20039 }
20040
20041 /* Return the die giving the specification for DIE, if there is
20042    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20043    containing the return value on output.  If there is no
20044    specification, but there is an abstract origin, that is
20045    returned.  */
20046
20047 static struct die_info *
20048 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20049 {
20050   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20051                                              *spec_cu);
20052
20053   if (spec_attr == NULL)
20054     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20055
20056   if (spec_attr == NULL)
20057     return NULL;
20058   else
20059     return follow_die_ref (die, spec_attr, spec_cu);
20060 }
20061
20062 /* Stub for free_line_header to match void * callback types.  */
20063
20064 static void
20065 free_line_header_voidp (void *arg)
20066 {
20067   struct line_header *lh = (struct line_header *) arg;
20068
20069   delete lh;
20070 }
20071
20072 void
20073 line_header::add_include_dir (const char *include_dir)
20074 {
20075   if (dwarf_line_debug >= 2)
20076     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20077                         include_dirs.size () + 1, include_dir);
20078
20079   include_dirs.push_back (include_dir);
20080 }
20081
20082 void
20083 line_header::add_file_name (const char *name,
20084                             dir_index d_index,
20085                             unsigned int mod_time,
20086                             unsigned int length)
20087 {
20088   if (dwarf_line_debug >= 2)
20089     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20090                         (unsigned) file_names.size () + 1, name);
20091
20092   file_names.emplace_back (name, d_index, mod_time, length);
20093 }
20094
20095 /* A convenience function to find the proper .debug_line section for a CU.  */
20096
20097 static struct dwarf2_section_info *
20098 get_debug_line_section (struct dwarf2_cu *cu)
20099 {
20100   struct dwarf2_section_info *section;
20101   struct dwarf2_per_objfile *dwarf2_per_objfile
20102     = cu->per_cu->dwarf2_per_objfile;
20103
20104   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20105      DWO file.  */
20106   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20107     section = &cu->dwo_unit->dwo_file->sections.line;
20108   else if (cu->per_cu->is_dwz)
20109     {
20110       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20111
20112       section = &dwz->line;
20113     }
20114   else
20115     section = &dwarf2_per_objfile->line;
20116
20117   return section;
20118 }
20119
20120 /* Read directory or file name entry format, starting with byte of
20121    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20122    entries count and the entries themselves in the described entry
20123    format.  */
20124
20125 static void
20126 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20127                         bfd *abfd, const gdb_byte **bufp,
20128                         struct line_header *lh,
20129                         const struct comp_unit_head *cu_header,
20130                         void (*callback) (struct line_header *lh,
20131                                           const char *name,
20132                                           dir_index d_index,
20133                                           unsigned int mod_time,
20134                                           unsigned int length))
20135 {
20136   gdb_byte format_count, formati;
20137   ULONGEST data_count, datai;
20138   const gdb_byte *buf = *bufp;
20139   const gdb_byte *format_header_data;
20140   unsigned int bytes_read;
20141
20142   format_count = read_1_byte (abfd, buf);
20143   buf += 1;
20144   format_header_data = buf;
20145   for (formati = 0; formati < format_count; formati++)
20146     {
20147       read_unsigned_leb128 (abfd, buf, &bytes_read);
20148       buf += bytes_read;
20149       read_unsigned_leb128 (abfd, buf, &bytes_read);
20150       buf += bytes_read;
20151     }
20152
20153   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20154   buf += bytes_read;
20155   for (datai = 0; datai < data_count; datai++)
20156     {
20157       const gdb_byte *format = format_header_data;
20158       struct file_entry fe;
20159
20160       for (formati = 0; formati < format_count; formati++)
20161         {
20162           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20163           format += bytes_read;
20164
20165           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20166           format += bytes_read;
20167
20168           gdb::optional<const char *> string;
20169           gdb::optional<unsigned int> uint;
20170
20171           switch (form)
20172             {
20173             case DW_FORM_string:
20174               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20175               buf += bytes_read;
20176               break;
20177
20178             case DW_FORM_line_strp:
20179               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20180                                                          abfd, buf,
20181                                                          cu_header,
20182                                                          &bytes_read));
20183               buf += bytes_read;
20184               break;
20185
20186             case DW_FORM_data1:
20187               uint.emplace (read_1_byte (abfd, buf));
20188               buf += 1;
20189               break;
20190
20191             case DW_FORM_data2:
20192               uint.emplace (read_2_bytes (abfd, buf));
20193               buf += 2;
20194               break;
20195
20196             case DW_FORM_data4:
20197               uint.emplace (read_4_bytes (abfd, buf));
20198               buf += 4;
20199               break;
20200
20201             case DW_FORM_data8:
20202               uint.emplace (read_8_bytes (abfd, buf));
20203               buf += 8;
20204               break;
20205
20206             case DW_FORM_udata:
20207               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20208               buf += bytes_read;
20209               break;
20210
20211             case DW_FORM_block:
20212               /* It is valid only for DW_LNCT_timestamp which is ignored by
20213                  current GDB.  */
20214               break;
20215             }
20216
20217           switch (content_type)
20218             {
20219             case DW_LNCT_path:
20220               if (string.has_value ())
20221                 fe.name = *string;
20222               break;
20223             case DW_LNCT_directory_index:
20224               if (uint.has_value ())
20225                 fe.d_index = (dir_index) *uint;
20226               break;
20227             case DW_LNCT_timestamp:
20228               if (uint.has_value ())
20229                 fe.mod_time = *uint;
20230               break;
20231             case DW_LNCT_size:
20232               if (uint.has_value ())
20233                 fe.length = *uint;
20234               break;
20235             case DW_LNCT_MD5:
20236               break;
20237             default:
20238               complaint (_("Unknown format content type %s"),
20239                          pulongest (content_type));
20240             }
20241         }
20242
20243       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20244     }
20245
20246   *bufp = buf;
20247 }
20248
20249 /* Read the statement program header starting at OFFSET in
20250    .debug_line, or .debug_line.dwo.  Return a pointer
20251    to a struct line_header, allocated using xmalloc.
20252    Returns NULL if there is a problem reading the header, e.g., if it
20253    has a version we don't understand.
20254
20255    NOTE: the strings in the include directory and file name tables of
20256    the returned object point into the dwarf line section buffer,
20257    and must not be freed.  */
20258
20259 static line_header_up
20260 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20261 {
20262   const gdb_byte *line_ptr;
20263   unsigned int bytes_read, offset_size;
20264   int i;
20265   const char *cur_dir, *cur_file;
20266   struct dwarf2_section_info *section;
20267   bfd *abfd;
20268   struct dwarf2_per_objfile *dwarf2_per_objfile
20269     = cu->per_cu->dwarf2_per_objfile;
20270
20271   section = get_debug_line_section (cu);
20272   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20273   if (section->buffer == NULL)
20274     {
20275       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20276         complaint (_("missing .debug_line.dwo section"));
20277       else
20278         complaint (_("missing .debug_line section"));
20279       return 0;
20280     }
20281
20282   /* We can't do this until we know the section is non-empty.
20283      Only then do we know we have such a section.  */
20284   abfd = get_section_bfd_owner (section);
20285
20286   /* Make sure that at least there's room for the total_length field.
20287      That could be 12 bytes long, but we're just going to fudge that.  */
20288   if (to_underlying (sect_off) + 4 >= section->size)
20289     {
20290       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20291       return 0;
20292     }
20293
20294   line_header_up lh (new line_header ());
20295
20296   lh->sect_off = sect_off;
20297   lh->offset_in_dwz = cu->per_cu->is_dwz;
20298
20299   line_ptr = section->buffer + to_underlying (sect_off);
20300
20301   /* Read in the header.  */
20302   lh->total_length =
20303     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20304                                             &bytes_read, &offset_size);
20305   line_ptr += bytes_read;
20306   if (line_ptr + lh->total_length > (section->buffer + section->size))
20307     {
20308       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20309       return 0;
20310     }
20311   lh->statement_program_end = line_ptr + lh->total_length;
20312   lh->version = read_2_bytes (abfd, line_ptr);
20313   line_ptr += 2;
20314   if (lh->version > 5)
20315     {
20316       /* This is a version we don't understand.  The format could have
20317          changed in ways we don't handle properly so just punt.  */
20318       complaint (_("unsupported version in .debug_line section"));
20319       return NULL;
20320     }
20321   if (lh->version >= 5)
20322     {
20323       gdb_byte segment_selector_size;
20324
20325       /* Skip address size.  */
20326       read_1_byte (abfd, line_ptr);
20327       line_ptr += 1;
20328
20329       segment_selector_size = read_1_byte (abfd, line_ptr);
20330       line_ptr += 1;
20331       if (segment_selector_size != 0)
20332         {
20333           complaint (_("unsupported segment selector size %u "
20334                        "in .debug_line section"),
20335                      segment_selector_size);
20336           return NULL;
20337         }
20338     }
20339   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20340   line_ptr += offset_size;
20341   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20342   line_ptr += 1;
20343   if (lh->version >= 4)
20344     {
20345       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20346       line_ptr += 1;
20347     }
20348   else
20349     lh->maximum_ops_per_instruction = 1;
20350
20351   if (lh->maximum_ops_per_instruction == 0)
20352     {
20353       lh->maximum_ops_per_instruction = 1;
20354       complaint (_("invalid maximum_ops_per_instruction "
20355                    "in `.debug_line' section"));
20356     }
20357
20358   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20359   line_ptr += 1;
20360   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20361   line_ptr += 1;
20362   lh->line_range = read_1_byte (abfd, line_ptr);
20363   line_ptr += 1;
20364   lh->opcode_base = read_1_byte (abfd, line_ptr);
20365   line_ptr += 1;
20366   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20367
20368   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20369   for (i = 1; i < lh->opcode_base; ++i)
20370     {
20371       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20372       line_ptr += 1;
20373     }
20374
20375   if (lh->version >= 5)
20376     {
20377       /* Read directory table.  */
20378       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20379                               &cu->header,
20380                               [] (struct line_header *header, const char *name,
20381                                   dir_index d_index, unsigned int mod_time,
20382                                   unsigned int length)
20383         {
20384           header->add_include_dir (name);
20385         });
20386
20387       /* Read file name table.  */
20388       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20389                               &cu->header,
20390                               [] (struct line_header *header, const char *name,
20391                                   dir_index d_index, unsigned int mod_time,
20392                                   unsigned int length)
20393         {
20394           header->add_file_name (name, d_index, mod_time, length);
20395         });
20396     }
20397   else
20398     {
20399       /* Read directory table.  */
20400       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20401         {
20402           line_ptr += bytes_read;
20403           lh->add_include_dir (cur_dir);
20404         }
20405       line_ptr += bytes_read;
20406
20407       /* Read file name table.  */
20408       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20409         {
20410           unsigned int mod_time, length;
20411           dir_index d_index;
20412
20413           line_ptr += bytes_read;
20414           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20415           line_ptr += bytes_read;
20416           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20417           line_ptr += bytes_read;
20418           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20419           line_ptr += bytes_read;
20420
20421           lh->add_file_name (cur_file, d_index, mod_time, length);
20422         }
20423       line_ptr += bytes_read;
20424     }
20425   lh->statement_program_start = line_ptr;
20426
20427   if (line_ptr > (section->buffer + section->size))
20428     complaint (_("line number info header doesn't "
20429                  "fit in `.debug_line' section"));
20430
20431   return lh;
20432 }
20433
20434 /* Subroutine of dwarf_decode_lines to simplify it.
20435    Return the file name of the psymtab for included file FILE_INDEX
20436    in line header LH of PST.
20437    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20438    If space for the result is malloc'd, *NAME_HOLDER will be set.
20439    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20440
20441 static const char *
20442 psymtab_include_file_name (const struct line_header *lh, int file_index,
20443                            const struct partial_symtab *pst,
20444                            const char *comp_dir,
20445                            gdb::unique_xmalloc_ptr<char> *name_holder)
20446 {
20447   const file_entry &fe = lh->file_names[file_index];
20448   const char *include_name = fe.name;
20449   const char *include_name_to_compare = include_name;
20450   const char *pst_filename;
20451   int file_is_pst;
20452
20453   const char *dir_name = fe.include_dir (lh);
20454
20455   gdb::unique_xmalloc_ptr<char> hold_compare;
20456   if (!IS_ABSOLUTE_PATH (include_name)
20457       && (dir_name != NULL || comp_dir != NULL))
20458     {
20459       /* Avoid creating a duplicate psymtab for PST.
20460          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20461          Before we do the comparison, however, we need to account
20462          for DIR_NAME and COMP_DIR.
20463          First prepend dir_name (if non-NULL).  If we still don't
20464          have an absolute path prepend comp_dir (if non-NULL).
20465          However, the directory we record in the include-file's
20466          psymtab does not contain COMP_DIR (to match the
20467          corresponding symtab(s)).
20468
20469          Example:
20470
20471          bash$ cd /tmp
20472          bash$ gcc -g ./hello.c
20473          include_name = "hello.c"
20474          dir_name = "."
20475          DW_AT_comp_dir = comp_dir = "/tmp"
20476          DW_AT_name = "./hello.c"
20477
20478       */
20479
20480       if (dir_name != NULL)
20481         {
20482           name_holder->reset (concat (dir_name, SLASH_STRING,
20483                                       include_name, (char *) NULL));
20484           include_name = name_holder->get ();
20485           include_name_to_compare = include_name;
20486         }
20487       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20488         {
20489           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20490                                       include_name, (char *) NULL));
20491           include_name_to_compare = hold_compare.get ();
20492         }
20493     }
20494
20495   pst_filename = pst->filename;
20496   gdb::unique_xmalloc_ptr<char> copied_name;
20497   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20498     {
20499       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20500                                  pst_filename, (char *) NULL));
20501       pst_filename = copied_name.get ();
20502     }
20503
20504   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20505
20506   if (file_is_pst)
20507     return NULL;
20508   return include_name;
20509 }
20510
20511 /* State machine to track the state of the line number program.  */
20512
20513 class lnp_state_machine
20514 {
20515 public:
20516   /* Initialize a machine state for the start of a line number
20517      program.  */
20518   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20519                      bool record_lines_p);
20520
20521   file_entry *current_file ()
20522   {
20523     /* lh->file_names is 0-based, but the file name numbers in the
20524        statement program are 1-based.  */
20525     return m_line_header->file_name_at (m_file);
20526   }
20527
20528   /* Record the line in the state machine.  END_SEQUENCE is true if
20529      we're processing the end of a sequence.  */
20530   void record_line (bool end_sequence);
20531
20532   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20533      nop-out rest of the lines in this sequence.  */
20534   void check_line_address (struct dwarf2_cu *cu,
20535                            const gdb_byte *line_ptr,
20536                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20537
20538   void handle_set_discriminator (unsigned int discriminator)
20539   {
20540     m_discriminator = discriminator;
20541     m_line_has_non_zero_discriminator |= discriminator != 0;
20542   }
20543
20544   /* Handle DW_LNE_set_address.  */
20545   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20546   {
20547     m_op_index = 0;
20548     address += baseaddr;
20549     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20550   }
20551
20552   /* Handle DW_LNS_advance_pc.  */
20553   void handle_advance_pc (CORE_ADDR adjust);
20554
20555   /* Handle a special opcode.  */
20556   void handle_special_opcode (unsigned char op_code);
20557
20558   /* Handle DW_LNS_advance_line.  */
20559   void handle_advance_line (int line_delta)
20560   {
20561     advance_line (line_delta);
20562   }
20563
20564   /* Handle DW_LNS_set_file.  */
20565   void handle_set_file (file_name_index file);
20566
20567   /* Handle DW_LNS_negate_stmt.  */
20568   void handle_negate_stmt ()
20569   {
20570     m_is_stmt = !m_is_stmt;
20571   }
20572
20573   /* Handle DW_LNS_const_add_pc.  */
20574   void handle_const_add_pc ();
20575
20576   /* Handle DW_LNS_fixed_advance_pc.  */
20577   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20578   {
20579     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20580     m_op_index = 0;
20581   }
20582
20583   /* Handle DW_LNS_copy.  */
20584   void handle_copy ()
20585   {
20586     record_line (false);
20587     m_discriminator = 0;
20588   }
20589
20590   /* Handle DW_LNE_end_sequence.  */
20591   void handle_end_sequence ()
20592   {
20593     m_currently_recording_lines = true;
20594   }
20595
20596 private:
20597   /* Advance the line by LINE_DELTA.  */
20598   void advance_line (int line_delta)
20599   {
20600     m_line += line_delta;
20601
20602     if (line_delta != 0)
20603       m_line_has_non_zero_discriminator = m_discriminator != 0;
20604   }
20605
20606   struct dwarf2_cu *m_cu;
20607
20608   gdbarch *m_gdbarch;
20609
20610   /* True if we're recording lines.
20611      Otherwise we're building partial symtabs and are just interested in
20612      finding include files mentioned by the line number program.  */
20613   bool m_record_lines_p;
20614
20615   /* The line number header.  */
20616   line_header *m_line_header;
20617
20618   /* These are part of the standard DWARF line number state machine,
20619      and initialized according to the DWARF spec.  */
20620
20621   unsigned char m_op_index = 0;
20622   /* The line table index (1-based) of the current file.  */
20623   file_name_index m_file = (file_name_index) 1;
20624   unsigned int m_line = 1;
20625
20626   /* These are initialized in the constructor.  */
20627
20628   CORE_ADDR m_address;
20629   bool m_is_stmt;
20630   unsigned int m_discriminator;
20631
20632   /* Additional bits of state we need to track.  */
20633
20634   /* The last file that we called dwarf2_start_subfile for.
20635      This is only used for TLLs.  */
20636   unsigned int m_last_file = 0;
20637   /* The last file a line number was recorded for.  */
20638   struct subfile *m_last_subfile = NULL;
20639
20640   /* When true, record the lines we decode.  */
20641   bool m_currently_recording_lines = false;
20642
20643   /* The last line number that was recorded, used to coalesce
20644      consecutive entries for the same line.  This can happen, for
20645      example, when discriminators are present.  PR 17276.  */
20646   unsigned int m_last_line = 0;
20647   bool m_line_has_non_zero_discriminator = false;
20648 };
20649
20650 void
20651 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20652 {
20653   CORE_ADDR addr_adj = (((m_op_index + adjust)
20654                          / m_line_header->maximum_ops_per_instruction)
20655                         * m_line_header->minimum_instruction_length);
20656   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20657   m_op_index = ((m_op_index + adjust)
20658                 % m_line_header->maximum_ops_per_instruction);
20659 }
20660
20661 void
20662 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20663 {
20664   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20665   CORE_ADDR addr_adj = (((m_op_index
20666                           + (adj_opcode / m_line_header->line_range))
20667                          / m_line_header->maximum_ops_per_instruction)
20668                         * m_line_header->minimum_instruction_length);
20669   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20670   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20671                 % m_line_header->maximum_ops_per_instruction);
20672
20673   int line_delta = (m_line_header->line_base
20674                     + (adj_opcode % m_line_header->line_range));
20675   advance_line (line_delta);
20676   record_line (false);
20677   m_discriminator = 0;
20678 }
20679
20680 void
20681 lnp_state_machine::handle_set_file (file_name_index file)
20682 {
20683   m_file = file;
20684
20685   const file_entry *fe = current_file ();
20686   if (fe == NULL)
20687     dwarf2_debug_line_missing_file_complaint ();
20688   else if (m_record_lines_p)
20689     {
20690       const char *dir = fe->include_dir (m_line_header);
20691
20692       m_last_subfile = m_cu->builder->get_current_subfile ();
20693       m_line_has_non_zero_discriminator = m_discriminator != 0;
20694       dwarf2_start_subfile (m_cu, fe->name, dir);
20695     }
20696 }
20697
20698 void
20699 lnp_state_machine::handle_const_add_pc ()
20700 {
20701   CORE_ADDR adjust
20702     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20703
20704   CORE_ADDR addr_adj
20705     = (((m_op_index + adjust)
20706         / m_line_header->maximum_ops_per_instruction)
20707        * m_line_header->minimum_instruction_length);
20708
20709   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20710   m_op_index = ((m_op_index + adjust)
20711                 % m_line_header->maximum_ops_per_instruction);
20712 }
20713
20714 /* Return non-zero if we should add LINE to the line number table.
20715    LINE is the line to add, LAST_LINE is the last line that was added,
20716    LAST_SUBFILE is the subfile for LAST_LINE.
20717    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20718    had a non-zero discriminator.
20719
20720    We have to be careful in the presence of discriminators.
20721    E.g., for this line:
20722
20723      for (i = 0; i < 100000; i++);
20724
20725    clang can emit four line number entries for that one line,
20726    each with a different discriminator.
20727    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20728
20729    However, we want gdb to coalesce all four entries into one.
20730    Otherwise the user could stepi into the middle of the line and
20731    gdb would get confused about whether the pc really was in the
20732    middle of the line.
20733
20734    Things are further complicated by the fact that two consecutive
20735    line number entries for the same line is a heuristic used by gcc
20736    to denote the end of the prologue.  So we can't just discard duplicate
20737    entries, we have to be selective about it.  The heuristic we use is
20738    that we only collapse consecutive entries for the same line if at least
20739    one of those entries has a non-zero discriminator.  PR 17276.
20740
20741    Note: Addresses in the line number state machine can never go backwards
20742    within one sequence, thus this coalescing is ok.  */
20743
20744 static int
20745 dwarf_record_line_p (struct dwarf2_cu *cu,
20746                      unsigned int line, unsigned int last_line,
20747                      int line_has_non_zero_discriminator,
20748                      struct subfile *last_subfile)
20749 {
20750   if (cu->builder->get_current_subfile () != last_subfile)
20751     return 1;
20752   if (line != last_line)
20753     return 1;
20754   /* Same line for the same file that we've seen already.
20755      As a last check, for pr 17276, only record the line if the line
20756      has never had a non-zero discriminator.  */
20757   if (!line_has_non_zero_discriminator)
20758     return 1;
20759   return 0;
20760 }
20761
20762 /* Use the CU's builder to record line number LINE beginning at
20763    address ADDRESS in the line table of subfile SUBFILE.  */
20764
20765 static void
20766 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20767                      unsigned int line, CORE_ADDR address,
20768                      struct dwarf2_cu *cu)
20769 {
20770   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20771
20772   if (dwarf_line_debug)
20773     {
20774       fprintf_unfiltered (gdb_stdlog,
20775                           "Recording line %u, file %s, address %s\n",
20776                           line, lbasename (subfile->name),
20777                           paddress (gdbarch, address));
20778     }
20779
20780   if (cu != nullptr)
20781     cu->builder->record_line (subfile, line, addr);
20782 }
20783
20784 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20785    Mark the end of a set of line number records.
20786    The arguments are the same as for dwarf_record_line_1.
20787    If SUBFILE is NULL the request is ignored.  */
20788
20789 static void
20790 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20791                    CORE_ADDR address, struct dwarf2_cu *cu)
20792 {
20793   if (subfile == NULL)
20794     return;
20795
20796   if (dwarf_line_debug)
20797     {
20798       fprintf_unfiltered (gdb_stdlog,
20799                           "Finishing current line, file %s, address %s\n",
20800                           lbasename (subfile->name),
20801                           paddress (gdbarch, address));
20802     }
20803
20804   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20805 }
20806
20807 void
20808 lnp_state_machine::record_line (bool end_sequence)
20809 {
20810   if (dwarf_line_debug)
20811     {
20812       fprintf_unfiltered (gdb_stdlog,
20813                           "Processing actual line %u: file %u,"
20814                           " address %s, is_stmt %u, discrim %u\n",
20815                           m_line, to_underlying (m_file),
20816                           paddress (m_gdbarch, m_address),
20817                           m_is_stmt, m_discriminator);
20818     }
20819
20820   file_entry *fe = current_file ();
20821
20822   if (fe == NULL)
20823     dwarf2_debug_line_missing_file_complaint ();
20824   /* For now we ignore lines not starting on an instruction boundary.
20825      But not when processing end_sequence for compatibility with the
20826      previous version of the code.  */
20827   else if (m_op_index == 0 || end_sequence)
20828     {
20829       fe->included_p = 1;
20830       if (m_record_lines_p && (producer_is_codewarrior (m_cu) || m_is_stmt))
20831         {
20832           if (m_last_subfile != m_cu->builder->get_current_subfile ()
20833               || end_sequence)
20834             {
20835               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20836                                  m_currently_recording_lines ? m_cu : nullptr);
20837             }
20838
20839           if (!end_sequence)
20840             {
20841               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20842                                        m_line_has_non_zero_discriminator,
20843                                        m_last_subfile))
20844                 {
20845                   dwarf_record_line_1 (m_gdbarch,
20846                                        m_cu->builder->get_current_subfile (),
20847                                        m_line, m_address,
20848                                        m_currently_recording_lines ? m_cu : nullptr);
20849                 }
20850               m_last_subfile = m_cu->builder->get_current_subfile ();
20851               m_last_line = m_line;
20852             }
20853         }
20854     }
20855 }
20856
20857 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20858                                       line_header *lh, bool record_lines_p)
20859 {
20860   m_cu = cu;
20861   m_gdbarch = arch;
20862   m_record_lines_p = record_lines_p;
20863   m_line_header = lh;
20864
20865   m_currently_recording_lines = true;
20866
20867   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20868      was a line entry for it so that the backend has a chance to adjust it
20869      and also record it in case it needs it.  This is currently used by MIPS
20870      code, cf. `mips_adjust_dwarf2_line'.  */
20871   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20872   m_is_stmt = lh->default_is_stmt;
20873   m_discriminator = 0;
20874 }
20875
20876 void
20877 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20878                                        const gdb_byte *line_ptr,
20879                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20880 {
20881   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20882      the pc range of the CU.  However, we restrict the test to only ADDRESS
20883      values of zero to preserve GDB's previous behaviour which is to handle
20884      the specific case of a function being GC'd by the linker.  */
20885
20886   if (address == 0 && address < unrelocated_lowpc)
20887     {
20888       /* This line table is for a function which has been
20889          GCd by the linker.  Ignore it.  PR gdb/12528 */
20890
20891       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20892       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20893
20894       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20895                  line_offset, objfile_name (objfile));
20896       m_currently_recording_lines = false;
20897       /* Note: m_currently_recording_lines is left as false until we see
20898          DW_LNE_end_sequence.  */
20899     }
20900 }
20901
20902 /* Subroutine of dwarf_decode_lines to simplify it.
20903    Process the line number information in LH.
20904    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20905    program in order to set included_p for every referenced header.  */
20906
20907 static void
20908 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20909                       const int decode_for_pst_p, CORE_ADDR lowpc)
20910 {
20911   const gdb_byte *line_ptr, *extended_end;
20912   const gdb_byte *line_end;
20913   unsigned int bytes_read, extended_len;
20914   unsigned char op_code, extended_op;
20915   CORE_ADDR baseaddr;
20916   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20917   bfd *abfd = objfile->obfd;
20918   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20919   /* True if we're recording line info (as opposed to building partial
20920      symtabs and just interested in finding include files mentioned by
20921      the line number program).  */
20922   bool record_lines_p = !decode_for_pst_p;
20923
20924   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20925
20926   line_ptr = lh->statement_program_start;
20927   line_end = lh->statement_program_end;
20928
20929   /* Read the statement sequences until there's nothing left.  */
20930   while (line_ptr < line_end)
20931     {
20932       /* The DWARF line number program state machine.  Reset the state
20933          machine at the start of each sequence.  */
20934       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
20935       bool end_sequence = false;
20936
20937       if (record_lines_p)
20938         {
20939           /* Start a subfile for the current file of the state
20940              machine.  */
20941           const file_entry *fe = state_machine.current_file ();
20942
20943           if (fe != NULL)
20944             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
20945         }
20946
20947       /* Decode the table.  */
20948       while (line_ptr < line_end && !end_sequence)
20949         {
20950           op_code = read_1_byte (abfd, line_ptr);
20951           line_ptr += 1;
20952
20953           if (op_code >= lh->opcode_base)
20954             {
20955               /* Special opcode.  */
20956               state_machine.handle_special_opcode (op_code);
20957             }
20958           else switch (op_code)
20959             {
20960             case DW_LNS_extended_op:
20961               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20962                                                    &bytes_read);
20963               line_ptr += bytes_read;
20964               extended_end = line_ptr + extended_len;
20965               extended_op = read_1_byte (abfd, line_ptr);
20966               line_ptr += 1;
20967               switch (extended_op)
20968                 {
20969                 case DW_LNE_end_sequence:
20970                   state_machine.handle_end_sequence ();
20971                   end_sequence = true;
20972                   break;
20973                 case DW_LNE_set_address:
20974                   {
20975                     CORE_ADDR address
20976                       = read_address (abfd, line_ptr, cu, &bytes_read);
20977                     line_ptr += bytes_read;
20978
20979                     state_machine.check_line_address (cu, line_ptr,
20980                                                       lowpc - baseaddr, address);
20981                     state_machine.handle_set_address (baseaddr, address);
20982                   }
20983                   break;
20984                 case DW_LNE_define_file:
20985                   {
20986                     const char *cur_file;
20987                     unsigned int mod_time, length;
20988                     dir_index dindex;
20989
20990                     cur_file = read_direct_string (abfd, line_ptr,
20991                                                    &bytes_read);
20992                     line_ptr += bytes_read;
20993                     dindex = (dir_index)
20994                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20995                     line_ptr += bytes_read;
20996                     mod_time =
20997                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20998                     line_ptr += bytes_read;
20999                     length =
21000                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21001                     line_ptr += bytes_read;
21002                     lh->add_file_name (cur_file, dindex, mod_time, length);
21003                   }
21004                   break;
21005                 case DW_LNE_set_discriminator:
21006                   {
21007                     /* The discriminator is not interesting to the
21008                        debugger; just ignore it.  We still need to
21009                        check its value though:
21010                        if there are consecutive entries for the same
21011                        (non-prologue) line we want to coalesce them.
21012                        PR 17276.  */
21013                     unsigned int discr
21014                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21015                     line_ptr += bytes_read;
21016
21017                     state_machine.handle_set_discriminator (discr);
21018                   }
21019                   break;
21020                 default:
21021                   complaint (_("mangled .debug_line section"));
21022                   return;
21023                 }
21024               /* Make sure that we parsed the extended op correctly.  If e.g.
21025                  we expected a different address size than the producer used,
21026                  we may have read the wrong number of bytes.  */
21027               if (line_ptr != extended_end)
21028                 {
21029                   complaint (_("mangled .debug_line section"));
21030                   return;
21031                 }
21032               break;
21033             case DW_LNS_copy:
21034               state_machine.handle_copy ();
21035               break;
21036             case DW_LNS_advance_pc:
21037               {
21038                 CORE_ADDR adjust
21039                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21040                 line_ptr += bytes_read;
21041
21042                 state_machine.handle_advance_pc (adjust);
21043               }
21044               break;
21045             case DW_LNS_advance_line:
21046               {
21047                 int line_delta
21048                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21049                 line_ptr += bytes_read;
21050
21051                 state_machine.handle_advance_line (line_delta);
21052               }
21053               break;
21054             case DW_LNS_set_file:
21055               {
21056                 file_name_index file
21057                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21058                                                             &bytes_read);
21059                 line_ptr += bytes_read;
21060
21061                 state_machine.handle_set_file (file);
21062               }
21063               break;
21064             case DW_LNS_set_column:
21065               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21066               line_ptr += bytes_read;
21067               break;
21068             case DW_LNS_negate_stmt:
21069               state_machine.handle_negate_stmt ();
21070               break;
21071             case DW_LNS_set_basic_block:
21072               break;
21073             /* Add to the address register of the state machine the
21074                address increment value corresponding to special opcode
21075                255.  I.e., this value is scaled by the minimum
21076                instruction length since special opcode 255 would have
21077                scaled the increment.  */
21078             case DW_LNS_const_add_pc:
21079               state_machine.handle_const_add_pc ();
21080               break;
21081             case DW_LNS_fixed_advance_pc:
21082               {
21083                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21084                 line_ptr += 2;
21085
21086                 state_machine.handle_fixed_advance_pc (addr_adj);
21087               }
21088               break;
21089             default:
21090               {
21091                 /* Unknown standard opcode, ignore it.  */
21092                 int i;
21093
21094                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21095                   {
21096                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21097                     line_ptr += bytes_read;
21098                   }
21099               }
21100             }
21101         }
21102
21103       if (!end_sequence)
21104         dwarf2_debug_line_missing_end_sequence_complaint ();
21105
21106       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21107          in which case we still finish recording the last line).  */
21108       state_machine.record_line (true);
21109     }
21110 }
21111
21112 /* Decode the Line Number Program (LNP) for the given line_header
21113    structure and CU.  The actual information extracted and the type
21114    of structures created from the LNP depends on the value of PST.
21115
21116    1. If PST is NULL, then this procedure uses the data from the program
21117       to create all necessary symbol tables, and their linetables.
21118
21119    2. If PST is not NULL, this procedure reads the program to determine
21120       the list of files included by the unit represented by PST, and
21121       builds all the associated partial symbol tables.
21122
21123    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21124    It is used for relative paths in the line table.
21125    NOTE: When processing partial symtabs (pst != NULL),
21126    comp_dir == pst->dirname.
21127
21128    NOTE: It is important that psymtabs have the same file name (via strcmp)
21129    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21130    symtab we don't use it in the name of the psymtabs we create.
21131    E.g. expand_line_sal requires this when finding psymtabs to expand.
21132    A good testcase for this is mb-inline.exp.
21133
21134    LOWPC is the lowest address in CU (or 0 if not known).
21135
21136    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21137    for its PC<->lines mapping information.  Otherwise only the filename
21138    table is read in.  */
21139
21140 static void
21141 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21142                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21143                     CORE_ADDR lowpc, int decode_mapping)
21144 {
21145   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21146   const int decode_for_pst_p = (pst != NULL);
21147
21148   if (decode_mapping)
21149     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21150
21151   if (decode_for_pst_p)
21152     {
21153       int file_index;
21154
21155       /* Now that we're done scanning the Line Header Program, we can
21156          create the psymtab of each included file.  */
21157       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21158         if (lh->file_names[file_index].included_p == 1)
21159           {
21160             gdb::unique_xmalloc_ptr<char> name_holder;
21161             const char *include_name =
21162               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21163                                          &name_holder);
21164             if (include_name != NULL)
21165               dwarf2_create_include_psymtab (include_name, pst, objfile);
21166           }
21167     }
21168   else
21169     {
21170       /* Make sure a symtab is created for every file, even files
21171          which contain only variables (i.e. no code with associated
21172          line numbers).  */
21173       struct compunit_symtab *cust = cu->builder->get_compunit_symtab ();
21174       int i;
21175
21176       for (i = 0; i < lh->file_names.size (); i++)
21177         {
21178           file_entry &fe = lh->file_names[i];
21179
21180           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21181
21182           if (cu->builder->get_current_subfile ()->symtab == NULL)
21183             {
21184               cu->builder->get_current_subfile ()->symtab
21185                 = allocate_symtab (cust,
21186                                    cu->builder->get_current_subfile ()->name);
21187             }
21188           fe.symtab = cu->builder->get_current_subfile ()->symtab;
21189         }
21190     }
21191 }
21192
21193 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21194    DIRNAME the name of the source directory which contains FILENAME
21195    or NULL if not known.
21196    This routine tries to keep line numbers from identical absolute and
21197    relative file names in a common subfile.
21198
21199    Using the `list' example from the GDB testsuite, which resides in
21200    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21201    of /srcdir/list0.c yields the following debugging information for list0.c:
21202
21203    DW_AT_name:          /srcdir/list0.c
21204    DW_AT_comp_dir:      /compdir
21205    files.files[0].name: list0.h
21206    files.files[0].dir:  /srcdir
21207    files.files[1].name: list0.c
21208    files.files[1].dir:  /srcdir
21209
21210    The line number information for list0.c has to end up in a single
21211    subfile, so that `break /srcdir/list0.c:1' works as expected.
21212    start_subfile will ensure that this happens provided that we pass the
21213    concatenation of files.files[1].dir and files.files[1].name as the
21214    subfile's name.  */
21215
21216 static void
21217 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21218                       const char *dirname)
21219 {
21220   char *copy = NULL;
21221
21222   /* In order not to lose the line information directory,
21223      we concatenate it to the filename when it makes sense.
21224      Note that the Dwarf3 standard says (speaking of filenames in line
21225      information): ``The directory index is ignored for file names
21226      that represent full path names''.  Thus ignoring dirname in the
21227      `else' branch below isn't an issue.  */
21228
21229   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21230     {
21231       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21232       filename = copy;
21233     }
21234
21235   cu->builder->start_subfile (filename);
21236
21237   if (copy != NULL)
21238     xfree (copy);
21239 }
21240
21241 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21242    buildsym_compunit constructor.  */
21243
21244 static struct compunit_symtab *
21245 dwarf2_start_symtab (struct dwarf2_cu *cu,
21246                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21247 {
21248   gdb_assert (cu->builder == nullptr);
21249
21250   cu->builder.reset (new struct buildsym_compunit
21251                      (cu->per_cu->dwarf2_per_objfile->objfile,
21252                       name, comp_dir, cu->language, low_pc));
21253
21254   cu->list_in_scope = cu->builder->get_file_symbols ();
21255
21256   cu->builder->record_debugformat ("DWARF 2");
21257   cu->builder->record_producer (cu->producer);
21258
21259   cu->processing_has_namespace_info = false;
21260
21261   return cu->builder->get_compunit_symtab ();
21262 }
21263
21264 static void
21265 var_decode_location (struct attribute *attr, struct symbol *sym,
21266                      struct dwarf2_cu *cu)
21267 {
21268   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21269   struct comp_unit_head *cu_header = &cu->header;
21270
21271   /* NOTE drow/2003-01-30: There used to be a comment and some special
21272      code here to turn a symbol with DW_AT_external and a
21273      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21274      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21275      with some versions of binutils) where shared libraries could have
21276      relocations against symbols in their debug information - the
21277      minimal symbol would have the right address, but the debug info
21278      would not.  It's no longer necessary, because we will explicitly
21279      apply relocations when we read in the debug information now.  */
21280
21281   /* A DW_AT_location attribute with no contents indicates that a
21282      variable has been optimized away.  */
21283   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21284     {
21285       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21286       return;
21287     }
21288
21289   /* Handle one degenerate form of location expression specially, to
21290      preserve GDB's previous behavior when section offsets are
21291      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21292      then mark this symbol as LOC_STATIC.  */
21293
21294   if (attr_form_is_block (attr)
21295       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21296            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21297           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21298               && (DW_BLOCK (attr)->size
21299                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21300     {
21301       unsigned int dummy;
21302
21303       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21304         SYMBOL_VALUE_ADDRESS (sym) =
21305           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21306       else
21307         SYMBOL_VALUE_ADDRESS (sym) =
21308           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21309       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21310       fixup_symbol_section (sym, objfile);
21311       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21312                                               SYMBOL_SECTION (sym));
21313       return;
21314     }
21315
21316   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21317      expression evaluator, and use LOC_COMPUTED only when necessary
21318      (i.e. when the value of a register or memory location is
21319      referenced, or a thread-local block, etc.).  Then again, it might
21320      not be worthwhile.  I'm assuming that it isn't unless performance
21321      or memory numbers show me otherwise.  */
21322
21323   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21324
21325   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21326     cu->has_loclist = true;
21327 }
21328
21329 /* Given a pointer to a DWARF information entry, figure out if we need
21330    to make a symbol table entry for it, and if so, create a new entry
21331    and return a pointer to it.
21332    If TYPE is NULL, determine symbol type from the die, otherwise
21333    used the passed type.
21334    If SPACE is not NULL, use it to hold the new symbol.  If it is
21335    NULL, allocate a new symbol on the objfile's obstack.  */
21336
21337 static struct symbol *
21338 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21339             struct symbol *space)
21340 {
21341   struct dwarf2_per_objfile *dwarf2_per_objfile
21342     = cu->per_cu->dwarf2_per_objfile;
21343   struct objfile *objfile = dwarf2_per_objfile->objfile;
21344   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21345   struct symbol *sym = NULL;
21346   const char *name;
21347   struct attribute *attr = NULL;
21348   struct attribute *attr2 = NULL;
21349   CORE_ADDR baseaddr;
21350   struct pending **list_to_add = NULL;
21351
21352   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21353
21354   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21355
21356   name = dwarf2_name (die, cu);
21357   if (name)
21358     {
21359       const char *linkagename;
21360       int suppress_add = 0;
21361
21362       if (space)
21363         sym = space;
21364       else
21365         sym = allocate_symbol (objfile);
21366       OBJSTAT (objfile, n_syms++);
21367
21368       /* Cache this symbol's name and the name's demangled form (if any).  */
21369       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21370       linkagename = dwarf2_physname (name, die, cu);
21371       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21372
21373       /* Fortran does not have mangling standard and the mangling does differ
21374          between gfortran, iFort etc.  */
21375       if (cu->language == language_fortran
21376           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21377         symbol_set_demangled_name (&(sym->ginfo),
21378                                    dwarf2_full_name (name, die, cu),
21379                                    NULL);
21380
21381       /* Default assumptions.
21382          Use the passed type or decode it from the die.  */
21383       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21384       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21385       if (type != NULL)
21386         SYMBOL_TYPE (sym) = type;
21387       else
21388         SYMBOL_TYPE (sym) = die_type (die, cu);
21389       attr = dwarf2_attr (die,
21390                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21391                           cu);
21392       if (attr)
21393         {
21394           SYMBOL_LINE (sym) = DW_UNSND (attr);
21395         }
21396
21397       attr = dwarf2_attr (die,
21398                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21399                           cu);
21400       if (attr)
21401         {
21402           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21403           struct file_entry *fe;
21404
21405           if (cu->line_header != NULL)
21406             fe = cu->line_header->file_name_at (file_index);
21407           else
21408             fe = NULL;
21409
21410           if (fe == NULL)
21411             complaint (_("file index out of range"));
21412           else
21413             symbol_set_symtab (sym, fe->symtab);
21414         }
21415
21416       switch (die->tag)
21417         {
21418         case DW_TAG_label:
21419           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21420           if (attr)
21421             {
21422               CORE_ADDR addr;
21423
21424               addr = attr_value_as_address (attr);
21425               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21426               SYMBOL_VALUE_ADDRESS (sym) = addr;
21427             }
21428           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21429           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21430           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21431           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21432           break;
21433         case DW_TAG_subprogram:
21434           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21435              finish_block.  */
21436           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21437           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21438           if ((attr2 && (DW_UNSND (attr2) != 0))
21439               || cu->language == language_ada)
21440             {
21441               /* Subprograms marked external are stored as a global symbol.
21442                  Ada subprograms, whether marked external or not, are always
21443                  stored as a global symbol, because we want to be able to
21444                  access them globally.  For instance, we want to be able
21445                  to break on a nested subprogram without having to
21446                  specify the context.  */
21447               list_to_add = cu->builder->get_global_symbols ();
21448             }
21449           else
21450             {
21451               list_to_add = cu->list_in_scope;
21452             }
21453           break;
21454         case DW_TAG_inlined_subroutine:
21455           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21456              finish_block.  */
21457           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21458           SYMBOL_INLINED (sym) = 1;
21459           list_to_add = cu->list_in_scope;
21460           break;
21461         case DW_TAG_template_value_param:
21462           suppress_add = 1;
21463           /* Fall through.  */
21464         case DW_TAG_constant:
21465         case DW_TAG_variable:
21466         case DW_TAG_member:
21467           /* Compilation with minimal debug info may result in
21468              variables with missing type entries.  Change the
21469              misleading `void' type to something sensible.  */
21470           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21471             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21472
21473           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21474           /* In the case of DW_TAG_member, we should only be called for
21475              static const members.  */
21476           if (die->tag == DW_TAG_member)
21477             {
21478               /* dwarf2_add_field uses die_is_declaration,
21479                  so we do the same.  */
21480               gdb_assert (die_is_declaration (die, cu));
21481               gdb_assert (attr);
21482             }
21483           if (attr)
21484             {
21485               dwarf2_const_value (attr, sym, cu);
21486               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21487               if (!suppress_add)
21488                 {
21489                   if (attr2 && (DW_UNSND (attr2) != 0))
21490                     list_to_add = cu->builder->get_global_symbols ();
21491                   else
21492                     list_to_add = cu->list_in_scope;
21493                 }
21494               break;
21495             }
21496           attr = dwarf2_attr (die, DW_AT_location, cu);
21497           if (attr)
21498             {
21499               var_decode_location (attr, sym, cu);
21500               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21501
21502               /* Fortran explicitly imports any global symbols to the local
21503                  scope by DW_TAG_common_block.  */
21504               if (cu->language == language_fortran && die->parent
21505                   && die->parent->tag == DW_TAG_common_block)
21506                 attr2 = NULL;
21507
21508               if (SYMBOL_CLASS (sym) == LOC_STATIC
21509                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21510                   && !dwarf2_per_objfile->has_section_at_zero)
21511                 {
21512                   /* When a static variable is eliminated by the linker,
21513                      the corresponding debug information is not stripped
21514                      out, but the variable address is set to null;
21515                      do not add such variables into symbol table.  */
21516                 }
21517               else if (attr2 && (DW_UNSND (attr2) != 0))
21518                 {
21519                   /* Workaround gfortran PR debug/40040 - it uses
21520                      DW_AT_location for variables in -fPIC libraries which may
21521                      get overriden by other libraries/executable and get
21522                      a different address.  Resolve it by the minimal symbol
21523                      which may come from inferior's executable using copy
21524                      relocation.  Make this workaround only for gfortran as for
21525                      other compilers GDB cannot guess the minimal symbol
21526                      Fortran mangling kind.  */
21527                   if (cu->language == language_fortran && die->parent
21528                       && die->parent->tag == DW_TAG_module
21529                       && cu->producer
21530                       && startswith (cu->producer, "GNU Fortran"))
21531                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21532
21533                   /* A variable with DW_AT_external is never static,
21534                      but it may be block-scoped.  */
21535                   list_to_add
21536                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21537                        ? cu->builder->get_global_symbols ()
21538                        : cu->list_in_scope);
21539                 }
21540               else
21541                 list_to_add = cu->list_in_scope;
21542             }
21543           else
21544             {
21545               /* We do not know the address of this symbol.
21546                  If it is an external symbol and we have type information
21547                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21548                  The address of the variable will then be determined from
21549                  the minimal symbol table whenever the variable is
21550                  referenced.  */
21551               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21552
21553               /* Fortran explicitly imports any global symbols to the local
21554                  scope by DW_TAG_common_block.  */
21555               if (cu->language == language_fortran && die->parent
21556                   && die->parent->tag == DW_TAG_common_block)
21557                 {
21558                   /* SYMBOL_CLASS doesn't matter here because
21559                      read_common_block is going to reset it.  */
21560                   if (!suppress_add)
21561                     list_to_add = cu->list_in_scope;
21562                 }
21563               else if (attr2 && (DW_UNSND (attr2) != 0)
21564                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21565                 {
21566                   /* A variable with DW_AT_external is never static, but it
21567                      may be block-scoped.  */
21568                   list_to_add
21569                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21570                        ? cu->builder->get_global_symbols ()
21571                        : cu->list_in_scope);
21572
21573                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21574                 }
21575               else if (!die_is_declaration (die, cu))
21576                 {
21577                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21578                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21579                   if (!suppress_add)
21580                     list_to_add = cu->list_in_scope;
21581                 }
21582             }
21583           break;
21584         case DW_TAG_formal_parameter:
21585           {
21586             /* If we are inside a function, mark this as an argument.  If
21587                not, we might be looking at an argument to an inlined function
21588                when we do not have enough information to show inlined frames;
21589                pretend it's a local variable in that case so that the user can
21590                still see it.  */
21591             struct context_stack *curr
21592               = cu->builder->get_current_context_stack ();
21593             if (curr != nullptr && curr->name != nullptr)
21594               SYMBOL_IS_ARGUMENT (sym) = 1;
21595             attr = dwarf2_attr (die, DW_AT_location, cu);
21596             if (attr)
21597               {
21598                 var_decode_location (attr, sym, cu);
21599               }
21600             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21601             if (attr)
21602               {
21603                 dwarf2_const_value (attr, sym, cu);
21604               }
21605
21606             list_to_add = cu->list_in_scope;
21607           }
21608           break;
21609         case DW_TAG_unspecified_parameters:
21610           /* From varargs functions; gdb doesn't seem to have any
21611              interest in this information, so just ignore it for now.
21612              (FIXME?) */
21613           break;
21614         case DW_TAG_template_type_param:
21615           suppress_add = 1;
21616           /* Fall through.  */
21617         case DW_TAG_class_type:
21618         case DW_TAG_interface_type:
21619         case DW_TAG_structure_type:
21620         case DW_TAG_union_type:
21621         case DW_TAG_set_type:
21622         case DW_TAG_enumeration_type:
21623           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21624           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21625
21626           {
21627             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21628                really ever be static objects: otherwise, if you try
21629                to, say, break of a class's method and you're in a file
21630                which doesn't mention that class, it won't work unless
21631                the check for all static symbols in lookup_symbol_aux
21632                saves you.  See the OtherFileClass tests in
21633                gdb.c++/namespace.exp.  */
21634
21635             if (!suppress_add)
21636               {
21637                 list_to_add
21638                   = (cu->list_in_scope == cu->builder->get_file_symbols ()
21639                      && cu->language == language_cplus
21640                      ? cu->builder->get_global_symbols ()
21641                      : cu->list_in_scope);
21642
21643                 /* The semantics of C++ state that "struct foo {
21644                    ... }" also defines a typedef for "foo".  */
21645                 if (cu->language == language_cplus
21646                     || cu->language == language_ada
21647                     || cu->language == language_d
21648                     || cu->language == language_rust)
21649                   {
21650                     /* The symbol's name is already allocated along
21651                        with this objfile, so we don't need to
21652                        duplicate it for the type.  */
21653                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21654                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21655                   }
21656               }
21657           }
21658           break;
21659         case DW_TAG_typedef:
21660           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21661           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21662           list_to_add = cu->list_in_scope;
21663           break;
21664         case DW_TAG_base_type:
21665         case DW_TAG_subrange_type:
21666           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21667           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21668           list_to_add = cu->list_in_scope;
21669           break;
21670         case DW_TAG_enumerator:
21671           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21672           if (attr)
21673             {
21674               dwarf2_const_value (attr, sym, cu);
21675             }
21676           {
21677             /* NOTE: carlton/2003-11-10: See comment above in the
21678                DW_TAG_class_type, etc. block.  */
21679
21680             list_to_add
21681               = (cu->list_in_scope == cu->builder->get_file_symbols ()
21682                  && cu->language == language_cplus
21683                  ? cu->builder->get_global_symbols ()
21684                  : cu->list_in_scope);
21685           }
21686           break;
21687         case DW_TAG_imported_declaration:
21688         case DW_TAG_namespace:
21689           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21690           list_to_add = cu->builder->get_global_symbols ();
21691           break;
21692         case DW_TAG_module:
21693           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21694           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21695           list_to_add = cu->builder->get_global_symbols ();
21696           break;
21697         case DW_TAG_common_block:
21698           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21699           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21700           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21701           break;
21702         default:
21703           /* Not a tag we recognize.  Hopefully we aren't processing
21704              trash data, but since we must specifically ignore things
21705              we don't recognize, there is nothing else we should do at
21706              this point.  */
21707           complaint (_("unsupported tag: '%s'"),
21708                      dwarf_tag_name (die->tag));
21709           break;
21710         }
21711
21712       if (suppress_add)
21713         {
21714           sym->hash_next = objfile->template_symbols;
21715           objfile->template_symbols = sym;
21716           list_to_add = NULL;
21717         }
21718
21719       if (list_to_add != NULL)
21720         dw2_add_symbol_to_list (sym, list_to_add);
21721
21722       /* For the benefit of old versions of GCC, check for anonymous
21723          namespaces based on the demangled name.  */
21724       if (!cu->processing_has_namespace_info
21725           && cu->language == language_cplus)
21726         cp_scan_for_anonymous_namespaces (cu->builder.get (), sym, objfile);
21727     }
21728   return (sym);
21729 }
21730
21731 /* Given an attr with a DW_FORM_dataN value in host byte order,
21732    zero-extend it as appropriate for the symbol's type.  The DWARF
21733    standard (v4) is not entirely clear about the meaning of using
21734    DW_FORM_dataN for a constant with a signed type, where the type is
21735    wider than the data.  The conclusion of a discussion on the DWARF
21736    list was that this is unspecified.  We choose to always zero-extend
21737    because that is the interpretation long in use by GCC.  */
21738
21739 static gdb_byte *
21740 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21741                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21742 {
21743   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21744   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21745                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21746   LONGEST l = DW_UNSND (attr);
21747
21748   if (bits < sizeof (*value) * 8)
21749     {
21750       l &= ((LONGEST) 1 << bits) - 1;
21751       *value = l;
21752     }
21753   else if (bits == sizeof (*value) * 8)
21754     *value = l;
21755   else
21756     {
21757       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21758       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21759       return bytes;
21760     }
21761
21762   return NULL;
21763 }
21764
21765 /* Read a constant value from an attribute.  Either set *VALUE, or if
21766    the value does not fit in *VALUE, set *BYTES - either already
21767    allocated on the objfile obstack, or newly allocated on OBSTACK,
21768    or, set *BATON, if we translated the constant to a location
21769    expression.  */
21770
21771 static void
21772 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21773                          const char *name, struct obstack *obstack,
21774                          struct dwarf2_cu *cu,
21775                          LONGEST *value, const gdb_byte **bytes,
21776                          struct dwarf2_locexpr_baton **baton)
21777 {
21778   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21779   struct comp_unit_head *cu_header = &cu->header;
21780   struct dwarf_block *blk;
21781   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21782                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21783
21784   *value = 0;
21785   *bytes = NULL;
21786   *baton = NULL;
21787
21788   switch (attr->form)
21789     {
21790     case DW_FORM_addr:
21791     case DW_FORM_GNU_addr_index:
21792       {
21793         gdb_byte *data;
21794
21795         if (TYPE_LENGTH (type) != cu_header->addr_size)
21796           dwarf2_const_value_length_mismatch_complaint (name,
21797                                                         cu_header->addr_size,
21798                                                         TYPE_LENGTH (type));
21799         /* Symbols of this form are reasonably rare, so we just
21800            piggyback on the existing location code rather than writing
21801            a new implementation of symbol_computed_ops.  */
21802         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21803         (*baton)->per_cu = cu->per_cu;
21804         gdb_assert ((*baton)->per_cu);
21805
21806         (*baton)->size = 2 + cu_header->addr_size;
21807         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21808         (*baton)->data = data;
21809
21810         data[0] = DW_OP_addr;
21811         store_unsigned_integer (&data[1], cu_header->addr_size,
21812                                 byte_order, DW_ADDR (attr));
21813         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21814       }
21815       break;
21816     case DW_FORM_string:
21817     case DW_FORM_strp:
21818     case DW_FORM_GNU_str_index:
21819     case DW_FORM_GNU_strp_alt:
21820       /* DW_STRING is already allocated on the objfile obstack, point
21821          directly to it.  */
21822       *bytes = (const gdb_byte *) DW_STRING (attr);
21823       break;
21824     case DW_FORM_block1:
21825     case DW_FORM_block2:
21826     case DW_FORM_block4:
21827     case DW_FORM_block:
21828     case DW_FORM_exprloc:
21829     case DW_FORM_data16:
21830       blk = DW_BLOCK (attr);
21831       if (TYPE_LENGTH (type) != blk->size)
21832         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21833                                                       TYPE_LENGTH (type));
21834       *bytes = blk->data;
21835       break;
21836
21837       /* The DW_AT_const_value attributes are supposed to carry the
21838          symbol's value "represented as it would be on the target
21839          architecture."  By the time we get here, it's already been
21840          converted to host endianness, so we just need to sign- or
21841          zero-extend it as appropriate.  */
21842     case DW_FORM_data1:
21843       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21844       break;
21845     case DW_FORM_data2:
21846       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21847       break;
21848     case DW_FORM_data4:
21849       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21850       break;
21851     case DW_FORM_data8:
21852       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21853       break;
21854
21855     case DW_FORM_sdata:
21856     case DW_FORM_implicit_const:
21857       *value = DW_SND (attr);
21858       break;
21859
21860     case DW_FORM_udata:
21861       *value = DW_UNSND (attr);
21862       break;
21863
21864     default:
21865       complaint (_("unsupported const value attribute form: '%s'"),
21866                  dwarf_form_name (attr->form));
21867       *value = 0;
21868       break;
21869     }
21870 }
21871
21872
21873 /* Copy constant value from an attribute to a symbol.  */
21874
21875 static void
21876 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21877                     struct dwarf2_cu *cu)
21878 {
21879   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21880   LONGEST value;
21881   const gdb_byte *bytes;
21882   struct dwarf2_locexpr_baton *baton;
21883
21884   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21885                            SYMBOL_PRINT_NAME (sym),
21886                            &objfile->objfile_obstack, cu,
21887                            &value, &bytes, &baton);
21888
21889   if (baton != NULL)
21890     {
21891       SYMBOL_LOCATION_BATON (sym) = baton;
21892       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21893     }
21894   else if (bytes != NULL)
21895      {
21896       SYMBOL_VALUE_BYTES (sym) = bytes;
21897       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21898     }
21899   else
21900     {
21901       SYMBOL_VALUE (sym) = value;
21902       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21903     }
21904 }
21905
21906 /* Return the type of the die in question using its DW_AT_type attribute.  */
21907
21908 static struct type *
21909 die_type (struct die_info *die, struct dwarf2_cu *cu)
21910 {
21911   struct attribute *type_attr;
21912
21913   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21914   if (!type_attr)
21915     {
21916       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21917       /* A missing DW_AT_type represents a void type.  */
21918       return objfile_type (objfile)->builtin_void;
21919     }
21920
21921   return lookup_die_type (die, type_attr, cu);
21922 }
21923
21924 /* True iff CU's producer generates GNAT Ada auxiliary information
21925    that allows to find parallel types through that information instead
21926    of having to do expensive parallel lookups by type name.  */
21927
21928 static int
21929 need_gnat_info (struct dwarf2_cu *cu)
21930 {
21931   /* Assume that the Ada compiler was GNAT, which always produces
21932      the auxiliary information.  */
21933   return (cu->language == language_ada);
21934 }
21935
21936 /* Return the auxiliary type of the die in question using its
21937    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21938    attribute is not present.  */
21939
21940 static struct type *
21941 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21942 {
21943   struct attribute *type_attr;
21944
21945   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21946   if (!type_attr)
21947     return NULL;
21948
21949   return lookup_die_type (die, type_attr, cu);
21950 }
21951
21952 /* If DIE has a descriptive_type attribute, then set the TYPE's
21953    descriptive type accordingly.  */
21954
21955 static void
21956 set_descriptive_type (struct type *type, struct die_info *die,
21957                       struct dwarf2_cu *cu)
21958 {
21959   struct type *descriptive_type = die_descriptive_type (die, cu);
21960
21961   if (descriptive_type)
21962     {
21963       ALLOCATE_GNAT_AUX_TYPE (type);
21964       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21965     }
21966 }
21967
21968 /* Return the containing type of the die in question using its
21969    DW_AT_containing_type attribute.  */
21970
21971 static struct type *
21972 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21973 {
21974   struct attribute *type_attr;
21975   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21976
21977   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21978   if (!type_attr)
21979     error (_("Dwarf Error: Problem turning containing type into gdb type "
21980              "[in module %s]"), objfile_name (objfile));
21981
21982   return lookup_die_type (die, type_attr, cu);
21983 }
21984
21985 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21986
21987 static struct type *
21988 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21989 {
21990   struct dwarf2_per_objfile *dwarf2_per_objfile
21991     = cu->per_cu->dwarf2_per_objfile;
21992   struct objfile *objfile = dwarf2_per_objfile->objfile;
21993   char *saved;
21994
21995   std::string message
21996     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
21997                      objfile_name (objfile),
21998                      sect_offset_str (cu->header.sect_off),
21999                      sect_offset_str (die->sect_off));
22000   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22001                                   message.c_str (), message.length ());
22002
22003   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22004 }
22005
22006 /* Look up the type of DIE in CU using its type attribute ATTR.
22007    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22008    DW_AT_containing_type.
22009    If there is no type substitute an error marker.  */
22010
22011 static struct type *
22012 lookup_die_type (struct die_info *die, const struct attribute *attr,
22013                  struct dwarf2_cu *cu)
22014 {
22015   struct dwarf2_per_objfile *dwarf2_per_objfile
22016     = cu->per_cu->dwarf2_per_objfile;
22017   struct objfile *objfile = dwarf2_per_objfile->objfile;
22018   struct type *this_type;
22019
22020   gdb_assert (attr->name == DW_AT_type
22021               || attr->name == DW_AT_GNAT_descriptive_type
22022               || attr->name == DW_AT_containing_type);
22023
22024   /* First see if we have it cached.  */
22025
22026   if (attr->form == DW_FORM_GNU_ref_alt)
22027     {
22028       struct dwarf2_per_cu_data *per_cu;
22029       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22030
22031       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22032                                                  dwarf2_per_objfile);
22033       this_type = get_die_type_at_offset (sect_off, per_cu);
22034     }
22035   else if (attr_form_is_ref (attr))
22036     {
22037       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22038
22039       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22040     }
22041   else if (attr->form == DW_FORM_ref_sig8)
22042     {
22043       ULONGEST signature = DW_SIGNATURE (attr);
22044
22045       return get_signatured_type (die, signature, cu);
22046     }
22047   else
22048     {
22049       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
22050                    " at %s [in module %s]"),
22051                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
22052                  objfile_name (objfile));
22053       return build_error_marker_type (cu, die);
22054     }
22055
22056   /* If not cached we need to read it in.  */
22057
22058   if (this_type == NULL)
22059     {
22060       struct die_info *type_die = NULL;
22061       struct dwarf2_cu *type_cu = cu;
22062
22063       if (attr_form_is_ref (attr))
22064         type_die = follow_die_ref (die, attr, &type_cu);
22065       if (type_die == NULL)
22066         return build_error_marker_type (cu, die);
22067       /* If we find the type now, it's probably because the type came
22068          from an inter-CU reference and the type's CU got expanded before
22069          ours.  */
22070       this_type = read_type_die (type_die, type_cu);
22071     }
22072
22073   /* If we still don't have a type use an error marker.  */
22074
22075   if (this_type == NULL)
22076     return build_error_marker_type (cu, die);
22077
22078   return this_type;
22079 }
22080
22081 /* Return the type in DIE, CU.
22082    Returns NULL for invalid types.
22083
22084    This first does a lookup in die_type_hash,
22085    and only reads the die in if necessary.
22086
22087    NOTE: This can be called when reading in partial or full symbols.  */
22088
22089 static struct type *
22090 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22091 {
22092   struct type *this_type;
22093
22094   this_type = get_die_type (die, cu);
22095   if (this_type)
22096     return this_type;
22097
22098   return read_type_die_1 (die, cu);
22099 }
22100
22101 /* Read the type in DIE, CU.
22102    Returns NULL for invalid types.  */
22103
22104 static struct type *
22105 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22106 {
22107   struct type *this_type = NULL;
22108
22109   switch (die->tag)
22110     {
22111     case DW_TAG_class_type:
22112     case DW_TAG_interface_type:
22113     case DW_TAG_structure_type:
22114     case DW_TAG_union_type:
22115       this_type = read_structure_type (die, cu);
22116       break;
22117     case DW_TAG_enumeration_type:
22118       this_type = read_enumeration_type (die, cu);
22119       break;
22120     case DW_TAG_subprogram:
22121     case DW_TAG_subroutine_type:
22122     case DW_TAG_inlined_subroutine:
22123       this_type = read_subroutine_type (die, cu);
22124       break;
22125     case DW_TAG_array_type:
22126       this_type = read_array_type (die, cu);
22127       break;
22128     case DW_TAG_set_type:
22129       this_type = read_set_type (die, cu);
22130       break;
22131     case DW_TAG_pointer_type:
22132       this_type = read_tag_pointer_type (die, cu);
22133       break;
22134     case DW_TAG_ptr_to_member_type:
22135       this_type = read_tag_ptr_to_member_type (die, cu);
22136       break;
22137     case DW_TAG_reference_type:
22138       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22139       break;
22140     case DW_TAG_rvalue_reference_type:
22141       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22142       break;
22143     case DW_TAG_const_type:
22144       this_type = read_tag_const_type (die, cu);
22145       break;
22146     case DW_TAG_volatile_type:
22147       this_type = read_tag_volatile_type (die, cu);
22148       break;
22149     case DW_TAG_restrict_type:
22150       this_type = read_tag_restrict_type (die, cu);
22151       break;
22152     case DW_TAG_string_type:
22153       this_type = read_tag_string_type (die, cu);
22154       break;
22155     case DW_TAG_typedef:
22156       this_type = read_typedef (die, cu);
22157       break;
22158     case DW_TAG_subrange_type:
22159       this_type = read_subrange_type (die, cu);
22160       break;
22161     case DW_TAG_base_type:
22162       this_type = read_base_type (die, cu);
22163       break;
22164     case DW_TAG_unspecified_type:
22165       this_type = read_unspecified_type (die, cu);
22166       break;
22167     case DW_TAG_namespace:
22168       this_type = read_namespace_type (die, cu);
22169       break;
22170     case DW_TAG_module:
22171       this_type = read_module_type (die, cu);
22172       break;
22173     case DW_TAG_atomic_type:
22174       this_type = read_tag_atomic_type (die, cu);
22175       break;
22176     default:
22177       complaint (_("unexpected tag in read_type_die: '%s'"),
22178                  dwarf_tag_name (die->tag));
22179       break;
22180     }
22181
22182   return this_type;
22183 }
22184
22185 /* See if we can figure out if the class lives in a namespace.  We do
22186    this by looking for a member function; its demangled name will
22187    contain namespace info, if there is any.
22188    Return the computed name or NULL.
22189    Space for the result is allocated on the objfile's obstack.
22190    This is the full-die version of guess_partial_die_structure_name.
22191    In this case we know DIE has no useful parent.  */
22192
22193 static char *
22194 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22195 {
22196   struct die_info *spec_die;
22197   struct dwarf2_cu *spec_cu;
22198   struct die_info *child;
22199   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22200
22201   spec_cu = cu;
22202   spec_die = die_specification (die, &spec_cu);
22203   if (spec_die != NULL)
22204     {
22205       die = spec_die;
22206       cu = spec_cu;
22207     }
22208
22209   for (child = die->child;
22210        child != NULL;
22211        child = child->sibling)
22212     {
22213       if (child->tag == DW_TAG_subprogram)
22214         {
22215           const char *linkage_name = dw2_linkage_name (child, cu);
22216
22217           if (linkage_name != NULL)
22218             {
22219               char *actual_name
22220                 = language_class_name_from_physname (cu->language_defn,
22221                                                      linkage_name);
22222               char *name = NULL;
22223
22224               if (actual_name != NULL)
22225                 {
22226                   const char *die_name = dwarf2_name (die, cu);
22227
22228                   if (die_name != NULL
22229                       && strcmp (die_name, actual_name) != 0)
22230                     {
22231                       /* Strip off the class name from the full name.
22232                          We want the prefix.  */
22233                       int die_name_len = strlen (die_name);
22234                       int actual_name_len = strlen (actual_name);
22235
22236                       /* Test for '::' as a sanity check.  */
22237                       if (actual_name_len > die_name_len + 2
22238                           && actual_name[actual_name_len
22239                                          - die_name_len - 1] == ':')
22240                         name = (char *) obstack_copy0 (
22241                           &objfile->per_bfd->storage_obstack,
22242                           actual_name, actual_name_len - die_name_len - 2);
22243                     }
22244                 }
22245               xfree (actual_name);
22246               return name;
22247             }
22248         }
22249     }
22250
22251   return NULL;
22252 }
22253
22254 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22255    prefix part in such case.  See
22256    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22257
22258 static const char *
22259 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22260 {
22261   struct attribute *attr;
22262   const char *base;
22263
22264   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22265       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22266     return NULL;
22267
22268   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22269     return NULL;
22270
22271   attr = dw2_linkage_name_attr (die, cu);
22272   if (attr == NULL || DW_STRING (attr) == NULL)
22273     return NULL;
22274
22275   /* dwarf2_name had to be already called.  */
22276   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22277
22278   /* Strip the base name, keep any leading namespaces/classes.  */
22279   base = strrchr (DW_STRING (attr), ':');
22280   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22281     return "";
22282
22283   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22284   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22285                                  DW_STRING (attr),
22286                                  &base[-1] - DW_STRING (attr));
22287 }
22288
22289 /* Return the name of the namespace/class that DIE is defined within,
22290    or "" if we can't tell.  The caller should not xfree the result.
22291
22292    For example, if we're within the method foo() in the following
22293    code:
22294
22295    namespace N {
22296      class C {
22297        void foo () {
22298        }
22299      };
22300    }
22301
22302    then determine_prefix on foo's die will return "N::C".  */
22303
22304 static const char *
22305 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22306 {
22307   struct dwarf2_per_objfile *dwarf2_per_objfile
22308     = cu->per_cu->dwarf2_per_objfile;
22309   struct die_info *parent, *spec_die;
22310   struct dwarf2_cu *spec_cu;
22311   struct type *parent_type;
22312   const char *retval;
22313
22314   if (cu->language != language_cplus
22315       && cu->language != language_fortran && cu->language != language_d
22316       && cu->language != language_rust)
22317     return "";
22318
22319   retval = anonymous_struct_prefix (die, cu);
22320   if (retval)
22321     return retval;
22322
22323   /* We have to be careful in the presence of DW_AT_specification.
22324      For example, with GCC 3.4, given the code
22325
22326      namespace N {
22327        void foo() {
22328          // Definition of N::foo.
22329        }
22330      }
22331
22332      then we'll have a tree of DIEs like this:
22333
22334      1: DW_TAG_compile_unit
22335        2: DW_TAG_namespace        // N
22336          3: DW_TAG_subprogram     // declaration of N::foo
22337        4: DW_TAG_subprogram       // definition of N::foo
22338             DW_AT_specification   // refers to die #3
22339
22340      Thus, when processing die #4, we have to pretend that we're in
22341      the context of its DW_AT_specification, namely the contex of die
22342      #3.  */
22343   spec_cu = cu;
22344   spec_die = die_specification (die, &spec_cu);
22345   if (spec_die == NULL)
22346     parent = die->parent;
22347   else
22348     {
22349       parent = spec_die->parent;
22350       cu = spec_cu;
22351     }
22352
22353   if (parent == NULL)
22354     return "";
22355   else if (parent->building_fullname)
22356     {
22357       const char *name;
22358       const char *parent_name;
22359
22360       /* It has been seen on RealView 2.2 built binaries,
22361          DW_TAG_template_type_param types actually _defined_ as
22362          children of the parent class:
22363
22364          enum E {};
22365          template class <class Enum> Class{};
22366          Class<enum E> class_e;
22367
22368          1: DW_TAG_class_type (Class)
22369            2: DW_TAG_enumeration_type (E)
22370              3: DW_TAG_enumerator (enum1:0)
22371              3: DW_TAG_enumerator (enum2:1)
22372              ...
22373            2: DW_TAG_template_type_param
22374               DW_AT_type  DW_FORM_ref_udata (E)
22375
22376          Besides being broken debug info, it can put GDB into an
22377          infinite loop.  Consider:
22378
22379          When we're building the full name for Class<E>, we'll start
22380          at Class, and go look over its template type parameters,
22381          finding E.  We'll then try to build the full name of E, and
22382          reach here.  We're now trying to build the full name of E,
22383          and look over the parent DIE for containing scope.  In the
22384          broken case, if we followed the parent DIE of E, we'd again
22385          find Class, and once again go look at its template type
22386          arguments, etc., etc.  Simply don't consider such parent die
22387          as source-level parent of this die (it can't be, the language
22388          doesn't allow it), and break the loop here.  */
22389       name = dwarf2_name (die, cu);
22390       parent_name = dwarf2_name (parent, cu);
22391       complaint (_("template param type '%s' defined within parent '%s'"),
22392                  name ? name : "<unknown>",
22393                  parent_name ? parent_name : "<unknown>");
22394       return "";
22395     }
22396   else
22397     switch (parent->tag)
22398       {
22399       case DW_TAG_namespace:
22400         parent_type = read_type_die (parent, cu);
22401         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22402            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22403            Work around this problem here.  */
22404         if (cu->language == language_cplus
22405             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22406           return "";
22407         /* We give a name to even anonymous namespaces.  */
22408         return TYPE_NAME (parent_type);
22409       case DW_TAG_class_type:
22410       case DW_TAG_interface_type:
22411       case DW_TAG_structure_type:
22412       case DW_TAG_union_type:
22413       case DW_TAG_module:
22414         parent_type = read_type_die (parent, cu);
22415         if (TYPE_NAME (parent_type) != NULL)
22416           return TYPE_NAME (parent_type);
22417         else
22418           /* An anonymous structure is only allowed non-static data
22419              members; no typedefs, no member functions, et cetera.
22420              So it does not need a prefix.  */
22421           return "";
22422       case DW_TAG_compile_unit:
22423       case DW_TAG_partial_unit:
22424         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22425         if (cu->language == language_cplus
22426             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22427             && die->child != NULL
22428             && (die->tag == DW_TAG_class_type
22429                 || die->tag == DW_TAG_structure_type
22430                 || die->tag == DW_TAG_union_type))
22431           {
22432             char *name = guess_full_die_structure_name (die, cu);
22433             if (name != NULL)
22434               return name;
22435           }
22436         return "";
22437       case DW_TAG_enumeration_type:
22438         parent_type = read_type_die (parent, cu);
22439         if (TYPE_DECLARED_CLASS (parent_type))
22440           {
22441             if (TYPE_NAME (parent_type) != NULL)
22442               return TYPE_NAME (parent_type);
22443             return "";
22444           }
22445         /* Fall through.  */
22446       default:
22447         return determine_prefix (parent, cu);
22448       }
22449 }
22450
22451 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22452    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22453    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22454    an obconcat, otherwise allocate storage for the result.  The CU argument is
22455    used to determine the language and hence, the appropriate separator.  */
22456
22457 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22458
22459 static char *
22460 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22461                  int physname, struct dwarf2_cu *cu)
22462 {
22463   const char *lead = "";
22464   const char *sep;
22465
22466   if (suffix == NULL || suffix[0] == '\0'
22467       || prefix == NULL || prefix[0] == '\0')
22468     sep = "";
22469   else if (cu->language == language_d)
22470     {
22471       /* For D, the 'main' function could be defined in any module, but it
22472          should never be prefixed.  */
22473       if (strcmp (suffix, "D main") == 0)
22474         {
22475           prefix = "";
22476           sep = "";
22477         }
22478       else
22479         sep = ".";
22480     }
22481   else if (cu->language == language_fortran && physname)
22482     {
22483       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22484          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22485
22486       lead = "__";
22487       sep = "_MOD_";
22488     }
22489   else
22490     sep = "::";
22491
22492   if (prefix == NULL)
22493     prefix = "";
22494   if (suffix == NULL)
22495     suffix = "";
22496
22497   if (obs == NULL)
22498     {
22499       char *retval
22500         = ((char *)
22501            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22502
22503       strcpy (retval, lead);
22504       strcat (retval, prefix);
22505       strcat (retval, sep);
22506       strcat (retval, suffix);
22507       return retval;
22508     }
22509   else
22510     {
22511       /* We have an obstack.  */
22512       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22513     }
22514 }
22515
22516 /* Return sibling of die, NULL if no sibling.  */
22517
22518 static struct die_info *
22519 sibling_die (struct die_info *die)
22520 {
22521   return die->sibling;
22522 }
22523
22524 /* Get name of a die, return NULL if not found.  */
22525
22526 static const char *
22527 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22528                           struct obstack *obstack)
22529 {
22530   if (name && cu->language == language_cplus)
22531     {
22532       std::string canon_name = cp_canonicalize_string (name);
22533
22534       if (!canon_name.empty ())
22535         {
22536           if (canon_name != name)
22537             name = (const char *) obstack_copy0 (obstack,
22538                                                  canon_name.c_str (),
22539                                                  canon_name.length ());
22540         }
22541     }
22542
22543   return name;
22544 }
22545
22546 /* Get name of a die, return NULL if not found.
22547    Anonymous namespaces are converted to their magic string.  */
22548
22549 static const char *
22550 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22551 {
22552   struct attribute *attr;
22553   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22554
22555   attr = dwarf2_attr (die, DW_AT_name, cu);
22556   if ((!attr || !DW_STRING (attr))
22557       && die->tag != DW_TAG_namespace
22558       && die->tag != DW_TAG_class_type
22559       && die->tag != DW_TAG_interface_type
22560       && die->tag != DW_TAG_structure_type
22561       && die->tag != DW_TAG_union_type)
22562     return NULL;
22563
22564   switch (die->tag)
22565     {
22566     case DW_TAG_compile_unit:
22567     case DW_TAG_partial_unit:
22568       /* Compilation units have a DW_AT_name that is a filename, not
22569          a source language identifier.  */
22570     case DW_TAG_enumeration_type:
22571     case DW_TAG_enumerator:
22572       /* These tags always have simple identifiers already; no need
22573          to canonicalize them.  */
22574       return DW_STRING (attr);
22575
22576     case DW_TAG_namespace:
22577       if (attr != NULL && DW_STRING (attr) != NULL)
22578         return DW_STRING (attr);
22579       return CP_ANONYMOUS_NAMESPACE_STR;
22580
22581     case DW_TAG_class_type:
22582     case DW_TAG_interface_type:
22583     case DW_TAG_structure_type:
22584     case DW_TAG_union_type:
22585       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22586          structures or unions.  These were of the form "._%d" in GCC 4.1,
22587          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22588          and GCC 4.4.  We work around this problem by ignoring these.  */
22589       if (attr && DW_STRING (attr)
22590           && (startswith (DW_STRING (attr), "._")
22591               || startswith (DW_STRING (attr), "<anonymous")))
22592         return NULL;
22593
22594       /* GCC might emit a nameless typedef that has a linkage name.  See
22595          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22596       if (!attr || DW_STRING (attr) == NULL)
22597         {
22598           char *demangled = NULL;
22599
22600           attr = dw2_linkage_name_attr (die, cu);
22601           if (attr == NULL || DW_STRING (attr) == NULL)
22602             return NULL;
22603
22604           /* Avoid demangling DW_STRING (attr) the second time on a second
22605              call for the same DIE.  */
22606           if (!DW_STRING_IS_CANONICAL (attr))
22607             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22608
22609           if (demangled)
22610             {
22611               const char *base;
22612
22613               /* FIXME: we already did this for the partial symbol... */
22614               DW_STRING (attr)
22615                 = ((const char *)
22616                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22617                                   demangled, strlen (demangled)));
22618               DW_STRING_IS_CANONICAL (attr) = 1;
22619               xfree (demangled);
22620
22621               /* Strip any leading namespaces/classes, keep only the base name.
22622                  DW_AT_name for named DIEs does not contain the prefixes.  */
22623               base = strrchr (DW_STRING (attr), ':');
22624               if (base && base > DW_STRING (attr) && base[-1] == ':')
22625                 return &base[1];
22626               else
22627                 return DW_STRING (attr);
22628             }
22629         }
22630       break;
22631
22632     default:
22633       break;
22634     }
22635
22636   if (!DW_STRING_IS_CANONICAL (attr))
22637     {
22638       DW_STRING (attr)
22639         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22640                                     &objfile->per_bfd->storage_obstack);
22641       DW_STRING_IS_CANONICAL (attr) = 1;
22642     }
22643   return DW_STRING (attr);
22644 }
22645
22646 /* Return the die that this die in an extension of, or NULL if there
22647    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22648    containing the return value on output.  */
22649
22650 static struct die_info *
22651 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22652 {
22653   struct attribute *attr;
22654
22655   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22656   if (attr == NULL)
22657     return NULL;
22658
22659   return follow_die_ref (die, attr, ext_cu);
22660 }
22661
22662 /* Convert a DIE tag into its string name.  */
22663
22664 static const char *
22665 dwarf_tag_name (unsigned tag)
22666 {
22667   const char *name = get_DW_TAG_name (tag);
22668
22669   if (name == NULL)
22670     return "DW_TAG_<unknown>";
22671
22672   return name;
22673 }
22674
22675 /* Convert a DWARF attribute code into its string name.  */
22676
22677 static const char *
22678 dwarf_attr_name (unsigned attr)
22679 {
22680   const char *name;
22681
22682 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22683   if (attr == DW_AT_MIPS_fde)
22684     return "DW_AT_MIPS_fde";
22685 #else
22686   if (attr == DW_AT_HP_block_index)
22687     return "DW_AT_HP_block_index";
22688 #endif
22689
22690   name = get_DW_AT_name (attr);
22691
22692   if (name == NULL)
22693     return "DW_AT_<unknown>";
22694
22695   return name;
22696 }
22697
22698 /* Convert a DWARF value form code into its string name.  */
22699
22700 static const char *
22701 dwarf_form_name (unsigned form)
22702 {
22703   const char *name = get_DW_FORM_name (form);
22704
22705   if (name == NULL)
22706     return "DW_FORM_<unknown>";
22707
22708   return name;
22709 }
22710
22711 static const char *
22712 dwarf_bool_name (unsigned mybool)
22713 {
22714   if (mybool)
22715     return "TRUE";
22716   else
22717     return "FALSE";
22718 }
22719
22720 /* Convert a DWARF type code into its string name.  */
22721
22722 static const char *
22723 dwarf_type_encoding_name (unsigned enc)
22724 {
22725   const char *name = get_DW_ATE_name (enc);
22726
22727   if (name == NULL)
22728     return "DW_ATE_<unknown>";
22729
22730   return name;
22731 }
22732
22733 static void
22734 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22735 {
22736   unsigned int i;
22737
22738   print_spaces (indent, f);
22739   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22740                       dwarf_tag_name (die->tag), die->abbrev,
22741                       sect_offset_str (die->sect_off));
22742
22743   if (die->parent != NULL)
22744     {
22745       print_spaces (indent, f);
22746       fprintf_unfiltered (f, "  parent at offset: %s\n",
22747                           sect_offset_str (die->parent->sect_off));
22748     }
22749
22750   print_spaces (indent, f);
22751   fprintf_unfiltered (f, "  has children: %s\n",
22752            dwarf_bool_name (die->child != NULL));
22753
22754   print_spaces (indent, f);
22755   fprintf_unfiltered (f, "  attributes:\n");
22756
22757   for (i = 0; i < die->num_attrs; ++i)
22758     {
22759       print_spaces (indent, f);
22760       fprintf_unfiltered (f, "    %s (%s) ",
22761                dwarf_attr_name (die->attrs[i].name),
22762                dwarf_form_name (die->attrs[i].form));
22763
22764       switch (die->attrs[i].form)
22765         {
22766         case DW_FORM_addr:
22767         case DW_FORM_GNU_addr_index:
22768           fprintf_unfiltered (f, "address: ");
22769           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22770           break;
22771         case DW_FORM_block2:
22772         case DW_FORM_block4:
22773         case DW_FORM_block:
22774         case DW_FORM_block1:
22775           fprintf_unfiltered (f, "block: size %s",
22776                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22777           break;
22778         case DW_FORM_exprloc:
22779           fprintf_unfiltered (f, "expression: size %s",
22780                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22781           break;
22782         case DW_FORM_data16:
22783           fprintf_unfiltered (f, "constant of 16 bytes");
22784           break;
22785         case DW_FORM_ref_addr:
22786           fprintf_unfiltered (f, "ref address: ");
22787           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22788           break;
22789         case DW_FORM_GNU_ref_alt:
22790           fprintf_unfiltered (f, "alt ref address: ");
22791           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22792           break;
22793         case DW_FORM_ref1:
22794         case DW_FORM_ref2:
22795         case DW_FORM_ref4:
22796         case DW_FORM_ref8:
22797         case DW_FORM_ref_udata:
22798           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22799                               (long) (DW_UNSND (&die->attrs[i])));
22800           break;
22801         case DW_FORM_data1:
22802         case DW_FORM_data2:
22803         case DW_FORM_data4:
22804         case DW_FORM_data8:
22805         case DW_FORM_udata:
22806         case DW_FORM_sdata:
22807           fprintf_unfiltered (f, "constant: %s",
22808                               pulongest (DW_UNSND (&die->attrs[i])));
22809           break;
22810         case DW_FORM_sec_offset:
22811           fprintf_unfiltered (f, "section offset: %s",
22812                               pulongest (DW_UNSND (&die->attrs[i])));
22813           break;
22814         case DW_FORM_ref_sig8:
22815           fprintf_unfiltered (f, "signature: %s",
22816                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22817           break;
22818         case DW_FORM_string:
22819         case DW_FORM_strp:
22820         case DW_FORM_line_strp:
22821         case DW_FORM_GNU_str_index:
22822         case DW_FORM_GNU_strp_alt:
22823           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22824                    DW_STRING (&die->attrs[i])
22825                    ? DW_STRING (&die->attrs[i]) : "",
22826                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22827           break;
22828         case DW_FORM_flag:
22829           if (DW_UNSND (&die->attrs[i]))
22830             fprintf_unfiltered (f, "flag: TRUE");
22831           else
22832             fprintf_unfiltered (f, "flag: FALSE");
22833           break;
22834         case DW_FORM_flag_present:
22835           fprintf_unfiltered (f, "flag: TRUE");
22836           break;
22837         case DW_FORM_indirect:
22838           /* The reader will have reduced the indirect form to
22839              the "base form" so this form should not occur.  */
22840           fprintf_unfiltered (f, 
22841                               "unexpected attribute form: DW_FORM_indirect");
22842           break;
22843         case DW_FORM_implicit_const:
22844           fprintf_unfiltered (f, "constant: %s",
22845                               plongest (DW_SND (&die->attrs[i])));
22846           break;
22847         default:
22848           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22849                    die->attrs[i].form);
22850           break;
22851         }
22852       fprintf_unfiltered (f, "\n");
22853     }
22854 }
22855
22856 static void
22857 dump_die_for_error (struct die_info *die)
22858 {
22859   dump_die_shallow (gdb_stderr, 0, die);
22860 }
22861
22862 static void
22863 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22864 {
22865   int indent = level * 4;
22866
22867   gdb_assert (die != NULL);
22868
22869   if (level >= max_level)
22870     return;
22871
22872   dump_die_shallow (f, indent, die);
22873
22874   if (die->child != NULL)
22875     {
22876       print_spaces (indent, f);
22877       fprintf_unfiltered (f, "  Children:");
22878       if (level + 1 < max_level)
22879         {
22880           fprintf_unfiltered (f, "\n");
22881           dump_die_1 (f, level + 1, max_level, die->child);
22882         }
22883       else
22884         {
22885           fprintf_unfiltered (f,
22886                               " [not printed, max nesting level reached]\n");
22887         }
22888     }
22889
22890   if (die->sibling != NULL && level > 0)
22891     {
22892       dump_die_1 (f, level, max_level, die->sibling);
22893     }
22894 }
22895
22896 /* This is called from the pdie macro in gdbinit.in.
22897    It's not static so gcc will keep a copy callable from gdb.  */
22898
22899 void
22900 dump_die (struct die_info *die, int max_level)
22901 {
22902   dump_die_1 (gdb_stdlog, 0, max_level, die);
22903 }
22904
22905 static void
22906 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22907 {
22908   void **slot;
22909
22910   slot = htab_find_slot_with_hash (cu->die_hash, die,
22911                                    to_underlying (die->sect_off),
22912                                    INSERT);
22913
22914   *slot = die;
22915 }
22916
22917 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22918    required kind.  */
22919
22920 static sect_offset
22921 dwarf2_get_ref_die_offset (const struct attribute *attr)
22922 {
22923   if (attr_form_is_ref (attr))
22924     return (sect_offset) DW_UNSND (attr);
22925
22926   complaint (_("unsupported die ref attribute form: '%s'"),
22927              dwarf_form_name (attr->form));
22928   return {};
22929 }
22930
22931 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22932  * the value held by the attribute is not constant.  */
22933
22934 static LONGEST
22935 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22936 {
22937   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22938     return DW_SND (attr);
22939   else if (attr->form == DW_FORM_udata
22940            || attr->form == DW_FORM_data1
22941            || attr->form == DW_FORM_data2
22942            || attr->form == DW_FORM_data4
22943            || attr->form == DW_FORM_data8)
22944     return DW_UNSND (attr);
22945   else
22946     {
22947       /* For DW_FORM_data16 see attr_form_is_constant.  */
22948       complaint (_("Attribute value is not a constant (%s)"),
22949                  dwarf_form_name (attr->form));
22950       return default_value;
22951     }
22952 }
22953
22954 /* Follow reference or signature attribute ATTR of SRC_DIE.
22955    On entry *REF_CU is the CU of SRC_DIE.
22956    On exit *REF_CU is the CU of the result.  */
22957
22958 static struct die_info *
22959 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22960                        struct dwarf2_cu **ref_cu)
22961 {
22962   struct die_info *die;
22963
22964   if (attr_form_is_ref (attr))
22965     die = follow_die_ref (src_die, attr, ref_cu);
22966   else if (attr->form == DW_FORM_ref_sig8)
22967     die = follow_die_sig (src_die, attr, ref_cu);
22968   else
22969     {
22970       dump_die_for_error (src_die);
22971       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22972              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22973     }
22974
22975   return die;
22976 }
22977
22978 /* Follow reference OFFSET.
22979    On entry *REF_CU is the CU of the source die referencing OFFSET.
22980    On exit *REF_CU is the CU of the result.
22981    Returns NULL if OFFSET is invalid.  */
22982
22983 static struct die_info *
22984 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22985                    struct dwarf2_cu **ref_cu)
22986 {
22987   struct die_info temp_die;
22988   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22989   struct dwarf2_per_objfile *dwarf2_per_objfile
22990     = cu->per_cu->dwarf2_per_objfile;
22991
22992   gdb_assert (cu->per_cu != NULL);
22993
22994   target_cu = cu;
22995
22996   if (cu->per_cu->is_debug_types)
22997     {
22998       /* .debug_types CUs cannot reference anything outside their CU.
22999          If they need to, they have to reference a signatured type via
23000          DW_FORM_ref_sig8.  */
23001       if (!offset_in_cu_p (&cu->header, sect_off))
23002         return NULL;
23003     }
23004   else if (offset_in_dwz != cu->per_cu->is_dwz
23005            || !offset_in_cu_p (&cu->header, sect_off))
23006     {
23007       struct dwarf2_per_cu_data *per_cu;
23008
23009       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23010                                                  dwarf2_per_objfile);
23011
23012       /* If necessary, add it to the queue and load its DIEs.  */
23013       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23014         load_full_comp_unit (per_cu, false, cu->language);
23015
23016       target_cu = per_cu->cu;
23017     }
23018   else if (cu->dies == NULL)
23019     {
23020       /* We're loading full DIEs during partial symbol reading.  */
23021       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23022       load_full_comp_unit (cu->per_cu, false, language_minimal);
23023     }
23024
23025   *ref_cu = target_cu;
23026   temp_die.sect_off = sect_off;
23027   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23028                                                   &temp_die,
23029                                                   to_underlying (sect_off));
23030 }
23031
23032 /* Follow reference attribute ATTR of SRC_DIE.
23033    On entry *REF_CU is the CU of SRC_DIE.
23034    On exit *REF_CU is the CU of the result.  */
23035
23036 static struct die_info *
23037 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23038                 struct dwarf2_cu **ref_cu)
23039 {
23040   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23041   struct dwarf2_cu *cu = *ref_cu;
23042   struct die_info *die;
23043
23044   die = follow_die_offset (sect_off,
23045                            (attr->form == DW_FORM_GNU_ref_alt
23046                             || cu->per_cu->is_dwz),
23047                            ref_cu);
23048   if (!die)
23049     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
23050            "at %s [in module %s]"),
23051            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
23052            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23053
23054   return die;
23055 }
23056
23057 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23058    Returned value is intended for DW_OP_call*.  Returned
23059    dwarf2_locexpr_baton->data has lifetime of
23060    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23061
23062 struct dwarf2_locexpr_baton
23063 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23064                                struct dwarf2_per_cu_data *per_cu,
23065                                CORE_ADDR (*get_frame_pc) (void *baton),
23066                                void *baton, bool resolve_abstract_p)
23067 {
23068   struct dwarf2_cu *cu;
23069   struct die_info *die;
23070   struct attribute *attr;
23071   struct dwarf2_locexpr_baton retval;
23072   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
23073   struct objfile *objfile = dwarf2_per_objfile->objfile;
23074
23075   if (per_cu->cu == NULL)
23076     load_cu (per_cu, false);
23077   cu = per_cu->cu;
23078   if (cu == NULL)
23079     {
23080       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23081          Instead just throw an error, not much else we can do.  */
23082       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23083              sect_offset_str (sect_off), objfile_name (objfile));
23084     }
23085
23086   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23087   if (!die)
23088     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23089            sect_offset_str (sect_off), objfile_name (objfile));
23090
23091   attr = dwarf2_attr (die, DW_AT_location, cu);
23092   if (!attr && resolve_abstract_p
23093       && (dwarf2_per_objfile->abstract_to_concrete.find (die)
23094           != dwarf2_per_objfile->abstract_to_concrete.end ()))
23095     {
23096       CORE_ADDR pc = (*get_frame_pc) (baton);
23097
23098       for (const auto &cand : dwarf2_per_objfile->abstract_to_concrete[die])
23099         {
23100           if (!cand->parent
23101               || cand->parent->tag != DW_TAG_subprogram)
23102             continue;
23103
23104           CORE_ADDR pc_low, pc_high;
23105           get_scope_pc_bounds (cand->parent, &pc_low, &pc_high, cu);
23106           if (pc_low == ((CORE_ADDR) -1)
23107               || !(pc_low <= pc && pc < pc_high))
23108             continue;
23109
23110           die = cand;
23111           attr = dwarf2_attr (die, DW_AT_location, cu);
23112           break;
23113         }
23114     }
23115
23116   if (!attr)
23117     {
23118       /* DWARF: "If there is no such attribute, then there is no effect.".
23119          DATA is ignored if SIZE is 0.  */
23120
23121       retval.data = NULL;
23122       retval.size = 0;
23123     }
23124   else if (attr_form_is_section_offset (attr))
23125     {
23126       struct dwarf2_loclist_baton loclist_baton;
23127       CORE_ADDR pc = (*get_frame_pc) (baton);
23128       size_t size;
23129
23130       fill_in_loclist_baton (cu, &loclist_baton, attr);
23131
23132       retval.data = dwarf2_find_location_expression (&loclist_baton,
23133                                                      &size, pc);
23134       retval.size = size;
23135     }
23136   else
23137     {
23138       if (!attr_form_is_block (attr))
23139         error (_("Dwarf Error: DIE at %s referenced in module %s "
23140                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23141                sect_offset_str (sect_off), objfile_name (objfile));
23142
23143       retval.data = DW_BLOCK (attr)->data;
23144       retval.size = DW_BLOCK (attr)->size;
23145     }
23146   retval.per_cu = cu->per_cu;
23147
23148   age_cached_comp_units (dwarf2_per_objfile);
23149
23150   return retval;
23151 }
23152
23153 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23154    offset.  */
23155
23156 struct dwarf2_locexpr_baton
23157 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23158                              struct dwarf2_per_cu_data *per_cu,
23159                              CORE_ADDR (*get_frame_pc) (void *baton),
23160                              void *baton)
23161 {
23162   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23163
23164   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23165 }
23166
23167 /* Write a constant of a given type as target-ordered bytes into
23168    OBSTACK.  */
23169
23170 static const gdb_byte *
23171 write_constant_as_bytes (struct obstack *obstack,
23172                          enum bfd_endian byte_order,
23173                          struct type *type,
23174                          ULONGEST value,
23175                          LONGEST *len)
23176 {
23177   gdb_byte *result;
23178
23179   *len = TYPE_LENGTH (type);
23180   result = (gdb_byte *) obstack_alloc (obstack, *len);
23181   store_unsigned_integer (result, *len, byte_order, value);
23182
23183   return result;
23184 }
23185
23186 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23187    pointer to the constant bytes and set LEN to the length of the
23188    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23189    does not have a DW_AT_const_value, return NULL.  */
23190
23191 const gdb_byte *
23192 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23193                              struct dwarf2_per_cu_data *per_cu,
23194                              struct obstack *obstack,
23195                              LONGEST *len)
23196 {
23197   struct dwarf2_cu *cu;
23198   struct die_info *die;
23199   struct attribute *attr;
23200   const gdb_byte *result = NULL;
23201   struct type *type;
23202   LONGEST value;
23203   enum bfd_endian byte_order;
23204   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23205
23206   if (per_cu->cu == NULL)
23207     load_cu (per_cu, false);
23208   cu = per_cu->cu;
23209   if (cu == NULL)
23210     {
23211       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23212          Instead just throw an error, not much else we can do.  */
23213       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23214              sect_offset_str (sect_off), objfile_name (objfile));
23215     }
23216
23217   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23218   if (!die)
23219     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23220            sect_offset_str (sect_off), objfile_name (objfile));
23221
23222   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23223   if (attr == NULL)
23224     return NULL;
23225
23226   byte_order = (bfd_big_endian (objfile->obfd)
23227                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23228
23229   switch (attr->form)
23230     {
23231     case DW_FORM_addr:
23232     case DW_FORM_GNU_addr_index:
23233       {
23234         gdb_byte *tem;
23235
23236         *len = cu->header.addr_size;
23237         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23238         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23239         result = tem;
23240       }
23241       break;
23242     case DW_FORM_string:
23243     case DW_FORM_strp:
23244     case DW_FORM_GNU_str_index:
23245     case DW_FORM_GNU_strp_alt:
23246       /* DW_STRING is already allocated on the objfile obstack, point
23247          directly to it.  */
23248       result = (const gdb_byte *) DW_STRING (attr);
23249       *len = strlen (DW_STRING (attr));
23250       break;
23251     case DW_FORM_block1:
23252     case DW_FORM_block2:
23253     case DW_FORM_block4:
23254     case DW_FORM_block:
23255     case DW_FORM_exprloc:
23256     case DW_FORM_data16:
23257       result = DW_BLOCK (attr)->data;
23258       *len = DW_BLOCK (attr)->size;
23259       break;
23260
23261       /* The DW_AT_const_value attributes are supposed to carry the
23262          symbol's value "represented as it would be on the target
23263          architecture."  By the time we get here, it's already been
23264          converted to host endianness, so we just need to sign- or
23265          zero-extend it as appropriate.  */
23266     case DW_FORM_data1:
23267       type = die_type (die, cu);
23268       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23269       if (result == NULL)
23270         result = write_constant_as_bytes (obstack, byte_order,
23271                                           type, value, len);
23272       break;
23273     case DW_FORM_data2:
23274       type = die_type (die, cu);
23275       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23276       if (result == NULL)
23277         result = write_constant_as_bytes (obstack, byte_order,
23278                                           type, value, len);
23279       break;
23280     case DW_FORM_data4:
23281       type = die_type (die, cu);
23282       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23283       if (result == NULL)
23284         result = write_constant_as_bytes (obstack, byte_order,
23285                                           type, value, len);
23286       break;
23287     case DW_FORM_data8:
23288       type = die_type (die, cu);
23289       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23290       if (result == NULL)
23291         result = write_constant_as_bytes (obstack, byte_order,
23292                                           type, value, len);
23293       break;
23294
23295     case DW_FORM_sdata:
23296     case DW_FORM_implicit_const:
23297       type = die_type (die, cu);
23298       result = write_constant_as_bytes (obstack, byte_order,
23299                                         type, DW_SND (attr), len);
23300       break;
23301
23302     case DW_FORM_udata:
23303       type = die_type (die, cu);
23304       result = write_constant_as_bytes (obstack, byte_order,
23305                                         type, DW_UNSND (attr), len);
23306       break;
23307
23308     default:
23309       complaint (_("unsupported const value attribute form: '%s'"),
23310                  dwarf_form_name (attr->form));
23311       break;
23312     }
23313
23314   return result;
23315 }
23316
23317 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23318    valid type for this die is found.  */
23319
23320 struct type *
23321 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23322                                 struct dwarf2_per_cu_data *per_cu)
23323 {
23324   struct dwarf2_cu *cu;
23325   struct die_info *die;
23326
23327   if (per_cu->cu == NULL)
23328     load_cu (per_cu, false);
23329   cu = per_cu->cu;
23330   if (!cu)
23331     return NULL;
23332
23333   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23334   if (!die)
23335     return NULL;
23336
23337   return die_type (die, cu);
23338 }
23339
23340 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23341    PER_CU.  */
23342
23343 struct type *
23344 dwarf2_get_die_type (cu_offset die_offset,
23345                      struct dwarf2_per_cu_data *per_cu)
23346 {
23347   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23348   return get_die_type_at_offset (die_offset_sect, per_cu);
23349 }
23350
23351 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23352    On entry *REF_CU is the CU of SRC_DIE.
23353    On exit *REF_CU is the CU of the result.
23354    Returns NULL if the referenced DIE isn't found.  */
23355
23356 static struct die_info *
23357 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23358                   struct dwarf2_cu **ref_cu)
23359 {
23360   struct die_info temp_die;
23361   struct dwarf2_cu *sig_cu;
23362   struct die_info *die;
23363
23364   /* While it might be nice to assert sig_type->type == NULL here,
23365      we can get here for DW_AT_imported_declaration where we need
23366      the DIE not the type.  */
23367
23368   /* If necessary, add it to the queue and load its DIEs.  */
23369
23370   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23371     read_signatured_type (sig_type);
23372
23373   sig_cu = sig_type->per_cu.cu;
23374   gdb_assert (sig_cu != NULL);
23375   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23376   temp_die.sect_off = sig_type->type_offset_in_section;
23377   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23378                                                  to_underlying (temp_die.sect_off));
23379   if (die)
23380     {
23381       struct dwarf2_per_objfile *dwarf2_per_objfile
23382         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23383
23384       /* For .gdb_index version 7 keep track of included TUs.
23385          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23386       if (dwarf2_per_objfile->index_table != NULL
23387           && dwarf2_per_objfile->index_table->version <= 7)
23388         {
23389           VEC_safe_push (dwarf2_per_cu_ptr,
23390                          (*ref_cu)->per_cu->imported_symtabs,
23391                          sig_cu->per_cu);
23392         }
23393
23394       *ref_cu = sig_cu;
23395       return die;
23396     }
23397
23398   return NULL;
23399 }
23400
23401 /* Follow signatured type referenced by ATTR in SRC_DIE.
23402    On entry *REF_CU is the CU of SRC_DIE.
23403    On exit *REF_CU is the CU of the result.
23404    The result is the DIE of the type.
23405    If the referenced type cannot be found an error is thrown.  */
23406
23407 static struct die_info *
23408 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23409                 struct dwarf2_cu **ref_cu)
23410 {
23411   ULONGEST signature = DW_SIGNATURE (attr);
23412   struct signatured_type *sig_type;
23413   struct die_info *die;
23414
23415   gdb_assert (attr->form == DW_FORM_ref_sig8);
23416
23417   sig_type = lookup_signatured_type (*ref_cu, signature);
23418   /* sig_type will be NULL if the signatured type is missing from
23419      the debug info.  */
23420   if (sig_type == NULL)
23421     {
23422       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23423                " from DIE at %s [in module %s]"),
23424              hex_string (signature), sect_offset_str (src_die->sect_off),
23425              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23426     }
23427
23428   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23429   if (die == NULL)
23430     {
23431       dump_die_for_error (src_die);
23432       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23433                " from DIE at %s [in module %s]"),
23434              hex_string (signature), sect_offset_str (src_die->sect_off),
23435              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23436     }
23437
23438   return die;
23439 }
23440
23441 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23442    reading in and processing the type unit if necessary.  */
23443
23444 static struct type *
23445 get_signatured_type (struct die_info *die, ULONGEST signature,
23446                      struct dwarf2_cu *cu)
23447 {
23448   struct dwarf2_per_objfile *dwarf2_per_objfile
23449     = cu->per_cu->dwarf2_per_objfile;
23450   struct signatured_type *sig_type;
23451   struct dwarf2_cu *type_cu;
23452   struct die_info *type_die;
23453   struct type *type;
23454
23455   sig_type = lookup_signatured_type (cu, signature);
23456   /* sig_type will be NULL if the signatured type is missing from
23457      the debug info.  */
23458   if (sig_type == NULL)
23459     {
23460       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23461                    " from DIE at %s [in module %s]"),
23462                  hex_string (signature), sect_offset_str (die->sect_off),
23463                  objfile_name (dwarf2_per_objfile->objfile));
23464       return build_error_marker_type (cu, die);
23465     }
23466
23467   /* If we already know the type we're done.  */
23468   if (sig_type->type != NULL)
23469     return sig_type->type;
23470
23471   type_cu = cu;
23472   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23473   if (type_die != NULL)
23474     {
23475       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23476          is created.  This is important, for example, because for c++ classes
23477          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23478       type = read_type_die (type_die, type_cu);
23479       if (type == NULL)
23480         {
23481           complaint (_("Dwarf Error: Cannot build signatured type %s"
23482                        " referenced from DIE at %s [in module %s]"),
23483                      hex_string (signature), sect_offset_str (die->sect_off),
23484                      objfile_name (dwarf2_per_objfile->objfile));
23485           type = build_error_marker_type (cu, die);
23486         }
23487     }
23488   else
23489     {
23490       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23491                    " from DIE at %s [in module %s]"),
23492                  hex_string (signature), sect_offset_str (die->sect_off),
23493                  objfile_name (dwarf2_per_objfile->objfile));
23494       type = build_error_marker_type (cu, die);
23495     }
23496   sig_type->type = type;
23497
23498   return type;
23499 }
23500
23501 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23502    reading in and processing the type unit if necessary.  */
23503
23504 static struct type *
23505 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23506                           struct dwarf2_cu *cu) /* ARI: editCase function */
23507 {
23508   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23509   if (attr_form_is_ref (attr))
23510     {
23511       struct dwarf2_cu *type_cu = cu;
23512       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23513
23514       return read_type_die (type_die, type_cu);
23515     }
23516   else if (attr->form == DW_FORM_ref_sig8)
23517     {
23518       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23519     }
23520   else
23521     {
23522       struct dwarf2_per_objfile *dwarf2_per_objfile
23523         = cu->per_cu->dwarf2_per_objfile;
23524
23525       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23526                    " at %s [in module %s]"),
23527                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23528                  objfile_name (dwarf2_per_objfile->objfile));
23529       return build_error_marker_type (cu, die);
23530     }
23531 }
23532
23533 /* Load the DIEs associated with type unit PER_CU into memory.  */
23534
23535 static void
23536 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23537 {
23538   struct signatured_type *sig_type;
23539
23540   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23541   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23542
23543   /* We have the per_cu, but we need the signatured_type.
23544      Fortunately this is an easy translation.  */
23545   gdb_assert (per_cu->is_debug_types);
23546   sig_type = (struct signatured_type *) per_cu;
23547
23548   gdb_assert (per_cu->cu == NULL);
23549
23550   read_signatured_type (sig_type);
23551
23552   gdb_assert (per_cu->cu != NULL);
23553 }
23554
23555 /* die_reader_func for read_signatured_type.
23556    This is identical to load_full_comp_unit_reader,
23557    but is kept separate for now.  */
23558
23559 static void
23560 read_signatured_type_reader (const struct die_reader_specs *reader,
23561                              const gdb_byte *info_ptr,
23562                              struct die_info *comp_unit_die,
23563                              int has_children,
23564                              void *data)
23565 {
23566   struct dwarf2_cu *cu = reader->cu;
23567
23568   gdb_assert (cu->die_hash == NULL);
23569   cu->die_hash =
23570     htab_create_alloc_ex (cu->header.length / 12,
23571                           die_hash,
23572                           die_eq,
23573                           NULL,
23574                           &cu->comp_unit_obstack,
23575                           hashtab_obstack_allocate,
23576                           dummy_obstack_deallocate);
23577
23578   if (has_children)
23579     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23580                                                   &info_ptr, comp_unit_die);
23581   cu->dies = comp_unit_die;
23582   /* comp_unit_die is not stored in die_hash, no need.  */
23583
23584   /* We try not to read any attributes in this function, because not
23585      all CUs needed for references have been loaded yet, and symbol
23586      table processing isn't initialized.  But we have to set the CU language,
23587      or we won't be able to build types correctly.
23588      Similarly, if we do not read the producer, we can not apply
23589      producer-specific interpretation.  */
23590   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23591 }
23592
23593 /* Read in a signatured type and build its CU and DIEs.
23594    If the type is a stub for the real type in a DWO file,
23595    read in the real type from the DWO file as well.  */
23596
23597 static void
23598 read_signatured_type (struct signatured_type *sig_type)
23599 {
23600   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23601
23602   gdb_assert (per_cu->is_debug_types);
23603   gdb_assert (per_cu->cu == NULL);
23604
23605   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23606                            read_signatured_type_reader, NULL);
23607   sig_type->per_cu.tu_read = 1;
23608 }
23609
23610 /* Decode simple location descriptions.
23611    Given a pointer to a dwarf block that defines a location, compute
23612    the location and return the value.
23613
23614    NOTE drow/2003-11-18: This function is called in two situations
23615    now: for the address of static or global variables (partial symbols
23616    only) and for offsets into structures which are expected to be
23617    (more or less) constant.  The partial symbol case should go away,
23618    and only the constant case should remain.  That will let this
23619    function complain more accurately.  A few special modes are allowed
23620    without complaint for global variables (for instance, global
23621    register values and thread-local values).
23622
23623    A location description containing no operations indicates that the
23624    object is optimized out.  The return value is 0 for that case.
23625    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23626    callers will only want a very basic result and this can become a
23627    complaint.
23628
23629    Note that stack[0] is unused except as a default error return.  */
23630
23631 static CORE_ADDR
23632 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23633 {
23634   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23635   size_t i;
23636   size_t size = blk->size;
23637   const gdb_byte *data = blk->data;
23638   CORE_ADDR stack[64];
23639   int stacki;
23640   unsigned int bytes_read, unsnd;
23641   gdb_byte op;
23642
23643   i = 0;
23644   stacki = 0;
23645   stack[stacki] = 0;
23646   stack[++stacki] = 0;
23647
23648   while (i < size)
23649     {
23650       op = data[i++];
23651       switch (op)
23652         {
23653         case DW_OP_lit0:
23654         case DW_OP_lit1:
23655         case DW_OP_lit2:
23656         case DW_OP_lit3:
23657         case DW_OP_lit4:
23658         case DW_OP_lit5:
23659         case DW_OP_lit6:
23660         case DW_OP_lit7:
23661         case DW_OP_lit8:
23662         case DW_OP_lit9:
23663         case DW_OP_lit10:
23664         case DW_OP_lit11:
23665         case DW_OP_lit12:
23666         case DW_OP_lit13:
23667         case DW_OP_lit14:
23668         case DW_OP_lit15:
23669         case DW_OP_lit16:
23670         case DW_OP_lit17:
23671         case DW_OP_lit18:
23672         case DW_OP_lit19:
23673         case DW_OP_lit20:
23674         case DW_OP_lit21:
23675         case DW_OP_lit22:
23676         case DW_OP_lit23:
23677         case DW_OP_lit24:
23678         case DW_OP_lit25:
23679         case DW_OP_lit26:
23680         case DW_OP_lit27:
23681         case DW_OP_lit28:
23682         case DW_OP_lit29:
23683         case DW_OP_lit30:
23684         case DW_OP_lit31:
23685           stack[++stacki] = op - DW_OP_lit0;
23686           break;
23687
23688         case DW_OP_reg0:
23689         case DW_OP_reg1:
23690         case DW_OP_reg2:
23691         case DW_OP_reg3:
23692         case DW_OP_reg4:
23693         case DW_OP_reg5:
23694         case DW_OP_reg6:
23695         case DW_OP_reg7:
23696         case DW_OP_reg8:
23697         case DW_OP_reg9:
23698         case DW_OP_reg10:
23699         case DW_OP_reg11:
23700         case DW_OP_reg12:
23701         case DW_OP_reg13:
23702         case DW_OP_reg14:
23703         case DW_OP_reg15:
23704         case DW_OP_reg16:
23705         case DW_OP_reg17:
23706         case DW_OP_reg18:
23707         case DW_OP_reg19:
23708         case DW_OP_reg20:
23709         case DW_OP_reg21:
23710         case DW_OP_reg22:
23711         case DW_OP_reg23:
23712         case DW_OP_reg24:
23713         case DW_OP_reg25:
23714         case DW_OP_reg26:
23715         case DW_OP_reg27:
23716         case DW_OP_reg28:
23717         case DW_OP_reg29:
23718         case DW_OP_reg30:
23719         case DW_OP_reg31:
23720           stack[++stacki] = op - DW_OP_reg0;
23721           if (i < size)
23722             dwarf2_complex_location_expr_complaint ();
23723           break;
23724
23725         case DW_OP_regx:
23726           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23727           i += bytes_read;
23728           stack[++stacki] = unsnd;
23729           if (i < size)
23730             dwarf2_complex_location_expr_complaint ();
23731           break;
23732
23733         case DW_OP_addr:
23734           stack[++stacki] = read_address (objfile->obfd, &data[i],
23735                                           cu, &bytes_read);
23736           i += bytes_read;
23737           break;
23738
23739         case DW_OP_const1u:
23740           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23741           i += 1;
23742           break;
23743
23744         case DW_OP_const1s:
23745           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23746           i += 1;
23747           break;
23748
23749         case DW_OP_const2u:
23750           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23751           i += 2;
23752           break;
23753
23754         case DW_OP_const2s:
23755           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23756           i += 2;
23757           break;
23758
23759         case DW_OP_const4u:
23760           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23761           i += 4;
23762           break;
23763
23764         case DW_OP_const4s:
23765           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23766           i += 4;
23767           break;
23768
23769         case DW_OP_const8u:
23770           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23771           i += 8;
23772           break;
23773
23774         case DW_OP_constu:
23775           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23776                                                   &bytes_read);
23777           i += bytes_read;
23778           break;
23779
23780         case DW_OP_consts:
23781           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23782           i += bytes_read;
23783           break;
23784
23785         case DW_OP_dup:
23786           stack[stacki + 1] = stack[stacki];
23787           stacki++;
23788           break;
23789
23790         case DW_OP_plus:
23791           stack[stacki - 1] += stack[stacki];
23792           stacki--;
23793           break;
23794
23795         case DW_OP_plus_uconst:
23796           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23797                                                  &bytes_read);
23798           i += bytes_read;
23799           break;
23800
23801         case DW_OP_minus:
23802           stack[stacki - 1] -= stack[stacki];
23803           stacki--;
23804           break;
23805
23806         case DW_OP_deref:
23807           /* If we're not the last op, then we definitely can't encode
23808              this using GDB's address_class enum.  This is valid for partial
23809              global symbols, although the variable's address will be bogus
23810              in the psymtab.  */
23811           if (i < size)
23812             dwarf2_complex_location_expr_complaint ();
23813           break;
23814
23815         case DW_OP_GNU_push_tls_address:
23816         case DW_OP_form_tls_address:
23817           /* The top of the stack has the offset from the beginning
23818              of the thread control block at which the variable is located.  */
23819           /* Nothing should follow this operator, so the top of stack would
23820              be returned.  */
23821           /* This is valid for partial global symbols, but the variable's
23822              address will be bogus in the psymtab.  Make it always at least
23823              non-zero to not look as a variable garbage collected by linker
23824              which have DW_OP_addr 0.  */
23825           if (i < size)
23826             dwarf2_complex_location_expr_complaint ();
23827           stack[stacki]++;
23828           break;
23829
23830         case DW_OP_GNU_uninit:
23831           break;
23832
23833         case DW_OP_GNU_addr_index:
23834         case DW_OP_GNU_const_index:
23835           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23836                                                          &bytes_read);
23837           i += bytes_read;
23838           break;
23839
23840         default:
23841           {
23842             const char *name = get_DW_OP_name (op);
23843
23844             if (name)
23845               complaint (_("unsupported stack op: '%s'"),
23846                          name);
23847             else
23848               complaint (_("unsupported stack op: '%02x'"),
23849                          op);
23850           }
23851
23852           return (stack[stacki]);
23853         }
23854
23855       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23856          outside of the allocated space.  Also enforce minimum>0.  */
23857       if (stacki >= ARRAY_SIZE (stack) - 1)
23858         {
23859           complaint (_("location description stack overflow"));
23860           return 0;
23861         }
23862
23863       if (stacki <= 0)
23864         {
23865           complaint (_("location description stack underflow"));
23866           return 0;
23867         }
23868     }
23869   return (stack[stacki]);
23870 }
23871
23872 /* memory allocation interface */
23873
23874 static struct dwarf_block *
23875 dwarf_alloc_block (struct dwarf2_cu *cu)
23876 {
23877   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23878 }
23879
23880 static struct die_info *
23881 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23882 {
23883   struct die_info *die;
23884   size_t size = sizeof (struct die_info);
23885
23886   if (num_attrs > 1)
23887     size += (num_attrs - 1) * sizeof (struct attribute);
23888
23889   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23890   memset (die, 0, sizeof (struct die_info));
23891   return (die);
23892 }
23893
23894 \f
23895 /* Macro support.  */
23896
23897 /* Return file name relative to the compilation directory of file number I in
23898    *LH's file name table.  The result is allocated using xmalloc; the caller is
23899    responsible for freeing it.  */
23900
23901 static char *
23902 file_file_name (int file, struct line_header *lh)
23903 {
23904   /* Is the file number a valid index into the line header's file name
23905      table?  Remember that file numbers start with one, not zero.  */
23906   if (1 <= file && file <= lh->file_names.size ())
23907     {
23908       const file_entry &fe = lh->file_names[file - 1];
23909
23910       if (!IS_ABSOLUTE_PATH (fe.name))
23911         {
23912           const char *dir = fe.include_dir (lh);
23913           if (dir != NULL)
23914             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23915         }
23916       return xstrdup (fe.name);
23917     }
23918   else
23919     {
23920       /* The compiler produced a bogus file number.  We can at least
23921          record the macro definitions made in the file, even if we
23922          won't be able to find the file by name.  */
23923       char fake_name[80];
23924
23925       xsnprintf (fake_name, sizeof (fake_name),
23926                  "<bad macro file number %d>", file);
23927
23928       complaint (_("bad file number in macro information (%d)"),
23929                  file);
23930
23931       return xstrdup (fake_name);
23932     }
23933 }
23934
23935 /* Return the full name of file number I in *LH's file name table.
23936    Use COMP_DIR as the name of the current directory of the
23937    compilation.  The result is allocated using xmalloc; the caller is
23938    responsible for freeing it.  */
23939 static char *
23940 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23941 {
23942   /* Is the file number a valid index into the line header's file name
23943      table?  Remember that file numbers start with one, not zero.  */
23944   if (1 <= file && file <= lh->file_names.size ())
23945     {
23946       char *relative = file_file_name (file, lh);
23947
23948       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23949         return relative;
23950       return reconcat (relative, comp_dir, SLASH_STRING,
23951                        relative, (char *) NULL);
23952     }
23953   else
23954     return file_file_name (file, lh);
23955 }
23956
23957
23958 static struct macro_source_file *
23959 macro_start_file (struct dwarf2_cu *cu,
23960                   int file, int line,
23961                   struct macro_source_file *current_file,
23962                   struct line_header *lh)
23963 {
23964   /* File name relative to the compilation directory of this source file.  */
23965   char *file_name = file_file_name (file, lh);
23966
23967   if (! current_file)
23968     {
23969       /* Note: We don't create a macro table for this compilation unit
23970          at all until we actually get a filename.  */
23971       struct macro_table *macro_table = cu->builder->get_macro_table ();
23972
23973       /* If we have no current file, then this must be the start_file
23974          directive for the compilation unit's main source file.  */
23975       current_file = macro_set_main (macro_table, file_name);
23976       macro_define_special (macro_table);
23977     }
23978   else
23979     current_file = macro_include (current_file, line, file_name);
23980
23981   xfree (file_name);
23982
23983   return current_file;
23984 }
23985
23986 static const char *
23987 consume_improper_spaces (const char *p, const char *body)
23988 {
23989   if (*p == ' ')
23990     {
23991       complaint (_("macro definition contains spaces "
23992                    "in formal argument list:\n`%s'"),
23993                  body);
23994
23995       while (*p == ' ')
23996         p++;
23997     }
23998
23999   return p;
24000 }
24001
24002
24003 static void
24004 parse_macro_definition (struct macro_source_file *file, int line,
24005                         const char *body)
24006 {
24007   const char *p;
24008
24009   /* The body string takes one of two forms.  For object-like macro
24010      definitions, it should be:
24011
24012         <macro name> " " <definition>
24013
24014      For function-like macro definitions, it should be:
24015
24016         <macro name> "() " <definition>
24017      or
24018         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24019
24020      Spaces may appear only where explicitly indicated, and in the
24021      <definition>.
24022
24023      The Dwarf 2 spec says that an object-like macro's name is always
24024      followed by a space, but versions of GCC around March 2002 omit
24025      the space when the macro's definition is the empty string.
24026
24027      The Dwarf 2 spec says that there should be no spaces between the
24028      formal arguments in a function-like macro's formal argument list,
24029      but versions of GCC around March 2002 include spaces after the
24030      commas.  */
24031
24032
24033   /* Find the extent of the macro name.  The macro name is terminated
24034      by either a space or null character (for an object-like macro) or
24035      an opening paren (for a function-like macro).  */
24036   for (p = body; *p; p++)
24037     if (*p == ' ' || *p == '(')
24038       break;
24039
24040   if (*p == ' ' || *p == '\0')
24041     {
24042       /* It's an object-like macro.  */
24043       int name_len = p - body;
24044       char *name = savestring (body, name_len);
24045       const char *replacement;
24046
24047       if (*p == ' ')
24048         replacement = body + name_len + 1;
24049       else
24050         {
24051           dwarf2_macro_malformed_definition_complaint (body);
24052           replacement = body + name_len;
24053         }
24054
24055       macro_define_object (file, line, name, replacement);
24056
24057       xfree (name);
24058     }
24059   else if (*p == '(')
24060     {
24061       /* It's a function-like macro.  */
24062       char *name = savestring (body, p - body);
24063       int argc = 0;
24064       int argv_size = 1;
24065       char **argv = XNEWVEC (char *, argv_size);
24066
24067       p++;
24068
24069       p = consume_improper_spaces (p, body);
24070
24071       /* Parse the formal argument list.  */
24072       while (*p && *p != ')')
24073         {
24074           /* Find the extent of the current argument name.  */
24075           const char *arg_start = p;
24076
24077           while (*p && *p != ',' && *p != ')' && *p != ' ')
24078             p++;
24079
24080           if (! *p || p == arg_start)
24081             dwarf2_macro_malformed_definition_complaint (body);
24082           else
24083             {
24084               /* Make sure argv has room for the new argument.  */
24085               if (argc >= argv_size)
24086                 {
24087                   argv_size *= 2;
24088                   argv = XRESIZEVEC (char *, argv, argv_size);
24089                 }
24090
24091               argv[argc++] = savestring (arg_start, p - arg_start);
24092             }
24093
24094           p = consume_improper_spaces (p, body);
24095
24096           /* Consume the comma, if present.  */
24097           if (*p == ',')
24098             {
24099               p++;
24100
24101               p = consume_improper_spaces (p, body);
24102             }
24103         }
24104
24105       if (*p == ')')
24106         {
24107           p++;
24108
24109           if (*p == ' ')
24110             /* Perfectly formed definition, no complaints.  */
24111             macro_define_function (file, line, name,
24112                                    argc, (const char **) argv,
24113                                    p + 1);
24114           else if (*p == '\0')
24115             {
24116               /* Complain, but do define it.  */
24117               dwarf2_macro_malformed_definition_complaint (body);
24118               macro_define_function (file, line, name,
24119                                      argc, (const char **) argv,
24120                                      p);
24121             }
24122           else
24123             /* Just complain.  */
24124             dwarf2_macro_malformed_definition_complaint (body);
24125         }
24126       else
24127         /* Just complain.  */
24128         dwarf2_macro_malformed_definition_complaint (body);
24129
24130       xfree (name);
24131       {
24132         int i;
24133
24134         for (i = 0; i < argc; i++)
24135           xfree (argv[i]);
24136       }
24137       xfree (argv);
24138     }
24139   else
24140     dwarf2_macro_malformed_definition_complaint (body);
24141 }
24142
24143 /* Skip some bytes from BYTES according to the form given in FORM.
24144    Returns the new pointer.  */
24145
24146 static const gdb_byte *
24147 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24148                  enum dwarf_form form,
24149                  unsigned int offset_size,
24150                  struct dwarf2_section_info *section)
24151 {
24152   unsigned int bytes_read;
24153
24154   switch (form)
24155     {
24156     case DW_FORM_data1:
24157     case DW_FORM_flag:
24158       ++bytes;
24159       break;
24160
24161     case DW_FORM_data2:
24162       bytes += 2;
24163       break;
24164
24165     case DW_FORM_data4:
24166       bytes += 4;
24167       break;
24168
24169     case DW_FORM_data8:
24170       bytes += 8;
24171       break;
24172
24173     case DW_FORM_data16:
24174       bytes += 16;
24175       break;
24176
24177     case DW_FORM_string:
24178       read_direct_string (abfd, bytes, &bytes_read);
24179       bytes += bytes_read;
24180       break;
24181
24182     case DW_FORM_sec_offset:
24183     case DW_FORM_strp:
24184     case DW_FORM_GNU_strp_alt:
24185       bytes += offset_size;
24186       break;
24187
24188     case DW_FORM_block:
24189       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24190       bytes += bytes_read;
24191       break;
24192
24193     case DW_FORM_block1:
24194       bytes += 1 + read_1_byte (abfd, bytes);
24195       break;
24196     case DW_FORM_block2:
24197       bytes += 2 + read_2_bytes (abfd, bytes);
24198       break;
24199     case DW_FORM_block4:
24200       bytes += 4 + read_4_bytes (abfd, bytes);
24201       break;
24202
24203     case DW_FORM_sdata:
24204     case DW_FORM_udata:
24205     case DW_FORM_GNU_addr_index:
24206     case DW_FORM_GNU_str_index:
24207       bytes = gdb_skip_leb128 (bytes, buffer_end);
24208       if (bytes == NULL)
24209         {
24210           dwarf2_section_buffer_overflow_complaint (section);
24211           return NULL;
24212         }
24213       break;
24214
24215     case DW_FORM_implicit_const:
24216       break;
24217
24218     default:
24219       {
24220         complaint (_("invalid form 0x%x in `%s'"),
24221                    form, get_section_name (section));
24222         return NULL;
24223       }
24224     }
24225
24226   return bytes;
24227 }
24228
24229 /* A helper for dwarf_decode_macros that handles skipping an unknown
24230    opcode.  Returns an updated pointer to the macro data buffer; or,
24231    on error, issues a complaint and returns NULL.  */
24232
24233 static const gdb_byte *
24234 skip_unknown_opcode (unsigned int opcode,
24235                      const gdb_byte **opcode_definitions,
24236                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24237                      bfd *abfd,
24238                      unsigned int offset_size,
24239                      struct dwarf2_section_info *section)
24240 {
24241   unsigned int bytes_read, i;
24242   unsigned long arg;
24243   const gdb_byte *defn;
24244
24245   if (opcode_definitions[opcode] == NULL)
24246     {
24247       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24248                  opcode);
24249       return NULL;
24250     }
24251
24252   defn = opcode_definitions[opcode];
24253   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24254   defn += bytes_read;
24255
24256   for (i = 0; i < arg; ++i)
24257     {
24258       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24259                                  (enum dwarf_form) defn[i], offset_size,
24260                                  section);
24261       if (mac_ptr == NULL)
24262         {
24263           /* skip_form_bytes already issued the complaint.  */
24264           return NULL;
24265         }
24266     }
24267
24268   return mac_ptr;
24269 }
24270
24271 /* A helper function which parses the header of a macro section.
24272    If the macro section is the extended (for now called "GNU") type,
24273    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24274    the header, or issues a complaint and returns NULL on error.  */
24275
24276 static const gdb_byte *
24277 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24278                           bfd *abfd,
24279                           const gdb_byte *mac_ptr,
24280                           unsigned int *offset_size,
24281                           int section_is_gnu)
24282 {
24283   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24284
24285   if (section_is_gnu)
24286     {
24287       unsigned int version, flags;
24288
24289       version = read_2_bytes (abfd, mac_ptr);
24290       if (version != 4 && version != 5)
24291         {
24292           complaint (_("unrecognized version `%d' in .debug_macro section"),
24293                      version);
24294           return NULL;
24295         }
24296       mac_ptr += 2;
24297
24298       flags = read_1_byte (abfd, mac_ptr);
24299       ++mac_ptr;
24300       *offset_size = (flags & 1) ? 8 : 4;
24301
24302       if ((flags & 2) != 0)
24303         /* We don't need the line table offset.  */
24304         mac_ptr += *offset_size;
24305
24306       /* Vendor opcode descriptions.  */
24307       if ((flags & 4) != 0)
24308         {
24309           unsigned int i, count;
24310
24311           count = read_1_byte (abfd, mac_ptr);
24312           ++mac_ptr;
24313           for (i = 0; i < count; ++i)
24314             {
24315               unsigned int opcode, bytes_read;
24316               unsigned long arg;
24317
24318               opcode = read_1_byte (abfd, mac_ptr);
24319               ++mac_ptr;
24320               opcode_definitions[opcode] = mac_ptr;
24321               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24322               mac_ptr += bytes_read;
24323               mac_ptr += arg;
24324             }
24325         }
24326     }
24327
24328   return mac_ptr;
24329 }
24330
24331 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24332    including DW_MACRO_import.  */
24333
24334 static void
24335 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24336                           bfd *abfd,
24337                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24338                           struct macro_source_file *current_file,
24339                           struct line_header *lh,
24340                           struct dwarf2_section_info *section,
24341                           int section_is_gnu, int section_is_dwz,
24342                           unsigned int offset_size,
24343                           htab_t include_hash)
24344 {
24345   struct dwarf2_per_objfile *dwarf2_per_objfile
24346     = cu->per_cu->dwarf2_per_objfile;
24347   struct objfile *objfile = dwarf2_per_objfile->objfile;
24348   enum dwarf_macro_record_type macinfo_type;
24349   int at_commandline;
24350   const gdb_byte *opcode_definitions[256];
24351
24352   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24353                                       &offset_size, section_is_gnu);
24354   if (mac_ptr == NULL)
24355     {
24356       /* We already issued a complaint.  */
24357       return;
24358     }
24359
24360   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24361      GDB is still reading the definitions from command line.  First
24362      DW_MACINFO_start_file will need to be ignored as it was already executed
24363      to create CURRENT_FILE for the main source holding also the command line
24364      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24365      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24366
24367   at_commandline = 1;
24368
24369   do
24370     {
24371       /* Do we at least have room for a macinfo type byte?  */
24372       if (mac_ptr >= mac_end)
24373         {
24374           dwarf2_section_buffer_overflow_complaint (section);
24375           break;
24376         }
24377
24378       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24379       mac_ptr++;
24380
24381       /* Note that we rely on the fact that the corresponding GNU and
24382          DWARF constants are the same.  */
24383       DIAGNOSTIC_PUSH
24384       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24385       switch (macinfo_type)
24386         {
24387           /* A zero macinfo type indicates the end of the macro
24388              information.  */
24389         case 0:
24390           break;
24391
24392         case DW_MACRO_define:
24393         case DW_MACRO_undef:
24394         case DW_MACRO_define_strp:
24395         case DW_MACRO_undef_strp:
24396         case DW_MACRO_define_sup:
24397         case DW_MACRO_undef_sup:
24398           {
24399             unsigned int bytes_read;
24400             int line;
24401             const char *body;
24402             int is_define;
24403
24404             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24405             mac_ptr += bytes_read;
24406
24407             if (macinfo_type == DW_MACRO_define
24408                 || macinfo_type == DW_MACRO_undef)
24409               {
24410                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24411                 mac_ptr += bytes_read;
24412               }
24413             else
24414               {
24415                 LONGEST str_offset;
24416
24417                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24418                 mac_ptr += offset_size;
24419
24420                 if (macinfo_type == DW_MACRO_define_sup
24421                     || macinfo_type == DW_MACRO_undef_sup
24422                     || section_is_dwz)
24423                   {
24424                     struct dwz_file *dwz
24425                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24426
24427                     body = read_indirect_string_from_dwz (objfile,
24428                                                           dwz, str_offset);
24429                   }
24430                 else
24431                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24432                                                          abfd, str_offset);
24433               }
24434
24435             is_define = (macinfo_type == DW_MACRO_define
24436                          || macinfo_type == DW_MACRO_define_strp
24437                          || macinfo_type == DW_MACRO_define_sup);
24438             if (! current_file)
24439               {
24440                 /* DWARF violation as no main source is present.  */
24441                 complaint (_("debug info with no main source gives macro %s "
24442                              "on line %d: %s"),
24443                            is_define ? _("definition") : _("undefinition"),
24444                            line, body);
24445                 break;
24446               }
24447             if ((line == 0 && !at_commandline)
24448                 || (line != 0 && at_commandline))
24449               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24450                          at_commandline ? _("command-line") : _("in-file"),
24451                          is_define ? _("definition") : _("undefinition"),
24452                          line == 0 ? _("zero") : _("non-zero"), line, body);
24453
24454             if (is_define)
24455               parse_macro_definition (current_file, line, body);
24456             else
24457               {
24458                 gdb_assert (macinfo_type == DW_MACRO_undef
24459                             || macinfo_type == DW_MACRO_undef_strp
24460                             || macinfo_type == DW_MACRO_undef_sup);
24461                 macro_undef (current_file, line, body);
24462               }
24463           }
24464           break;
24465
24466         case DW_MACRO_start_file:
24467           {
24468             unsigned int bytes_read;
24469             int line, file;
24470
24471             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24472             mac_ptr += bytes_read;
24473             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24474             mac_ptr += bytes_read;
24475
24476             if ((line == 0 && !at_commandline)
24477                 || (line != 0 && at_commandline))
24478               complaint (_("debug info gives source %d included "
24479                            "from %s at %s line %d"),
24480                          file, at_commandline ? _("command-line") : _("file"),
24481                          line == 0 ? _("zero") : _("non-zero"), line);
24482
24483             if (at_commandline)
24484               {
24485                 /* This DW_MACRO_start_file was executed in the
24486                    pass one.  */
24487                 at_commandline = 0;
24488               }
24489             else
24490               current_file = macro_start_file (cu, file, line, current_file,
24491                                                lh);
24492           }
24493           break;
24494
24495         case DW_MACRO_end_file:
24496           if (! current_file)
24497             complaint (_("macro debug info has an unmatched "
24498                          "`close_file' directive"));
24499           else
24500             {
24501               current_file = current_file->included_by;
24502               if (! current_file)
24503                 {
24504                   enum dwarf_macro_record_type next_type;
24505
24506                   /* GCC circa March 2002 doesn't produce the zero
24507                      type byte marking the end of the compilation
24508                      unit.  Complain if it's not there, but exit no
24509                      matter what.  */
24510
24511                   /* Do we at least have room for a macinfo type byte?  */
24512                   if (mac_ptr >= mac_end)
24513                     {
24514                       dwarf2_section_buffer_overflow_complaint (section);
24515                       return;
24516                     }
24517
24518                   /* We don't increment mac_ptr here, so this is just
24519                      a look-ahead.  */
24520                   next_type
24521                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24522                                                                   mac_ptr);
24523                   if (next_type != 0)
24524                     complaint (_("no terminating 0-type entry for "
24525                                  "macros in `.debug_macinfo' section"));
24526
24527                   return;
24528                 }
24529             }
24530           break;
24531
24532         case DW_MACRO_import:
24533         case DW_MACRO_import_sup:
24534           {
24535             LONGEST offset;
24536             void **slot;
24537             bfd *include_bfd = abfd;
24538             struct dwarf2_section_info *include_section = section;
24539             const gdb_byte *include_mac_end = mac_end;
24540             int is_dwz = section_is_dwz;
24541             const gdb_byte *new_mac_ptr;
24542
24543             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24544             mac_ptr += offset_size;
24545
24546             if (macinfo_type == DW_MACRO_import_sup)
24547               {
24548                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24549
24550                 dwarf2_read_section (objfile, &dwz->macro);
24551
24552                 include_section = &dwz->macro;
24553                 include_bfd = get_section_bfd_owner (include_section);
24554                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24555                 is_dwz = 1;
24556               }
24557
24558             new_mac_ptr = include_section->buffer + offset;
24559             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24560
24561             if (*slot != NULL)
24562               {
24563                 /* This has actually happened; see
24564                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24565                 complaint (_("recursive DW_MACRO_import in "
24566                              ".debug_macro section"));
24567               }
24568             else
24569               {
24570                 *slot = (void *) new_mac_ptr;
24571
24572                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24573                                           include_mac_end, current_file, lh,
24574                                           section, section_is_gnu, is_dwz,
24575                                           offset_size, include_hash);
24576
24577                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24578               }
24579           }
24580           break;
24581
24582         case DW_MACINFO_vendor_ext:
24583           if (!section_is_gnu)
24584             {
24585               unsigned int bytes_read;
24586
24587               /* This reads the constant, but since we don't recognize
24588                  any vendor extensions, we ignore it.  */
24589               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24590               mac_ptr += bytes_read;
24591               read_direct_string (abfd, mac_ptr, &bytes_read);
24592               mac_ptr += bytes_read;
24593
24594               /* We don't recognize any vendor extensions.  */
24595               break;
24596             }
24597           /* FALLTHROUGH */
24598
24599         default:
24600           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24601                                          mac_ptr, mac_end, abfd, offset_size,
24602                                          section);
24603           if (mac_ptr == NULL)
24604             return;
24605           break;
24606         }
24607       DIAGNOSTIC_POP
24608     } while (macinfo_type != 0);
24609 }
24610
24611 static void
24612 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24613                      int section_is_gnu)
24614 {
24615   struct dwarf2_per_objfile *dwarf2_per_objfile
24616     = cu->per_cu->dwarf2_per_objfile;
24617   struct objfile *objfile = dwarf2_per_objfile->objfile;
24618   struct line_header *lh = cu->line_header;
24619   bfd *abfd;
24620   const gdb_byte *mac_ptr, *mac_end;
24621   struct macro_source_file *current_file = 0;
24622   enum dwarf_macro_record_type macinfo_type;
24623   unsigned int offset_size = cu->header.offset_size;
24624   const gdb_byte *opcode_definitions[256];
24625   void **slot;
24626   struct dwarf2_section_info *section;
24627   const char *section_name;
24628
24629   if (cu->dwo_unit != NULL)
24630     {
24631       if (section_is_gnu)
24632         {
24633           section = &cu->dwo_unit->dwo_file->sections.macro;
24634           section_name = ".debug_macro.dwo";
24635         }
24636       else
24637         {
24638           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24639           section_name = ".debug_macinfo.dwo";
24640         }
24641     }
24642   else
24643     {
24644       if (section_is_gnu)
24645         {
24646           section = &dwarf2_per_objfile->macro;
24647           section_name = ".debug_macro";
24648         }
24649       else
24650         {
24651           section = &dwarf2_per_objfile->macinfo;
24652           section_name = ".debug_macinfo";
24653         }
24654     }
24655
24656   dwarf2_read_section (objfile, section);
24657   if (section->buffer == NULL)
24658     {
24659       complaint (_("missing %s section"), section_name);
24660       return;
24661     }
24662   abfd = get_section_bfd_owner (section);
24663
24664   /* First pass: Find the name of the base filename.
24665      This filename is needed in order to process all macros whose definition
24666      (or undefinition) comes from the command line.  These macros are defined
24667      before the first DW_MACINFO_start_file entry, and yet still need to be
24668      associated to the base file.
24669
24670      To determine the base file name, we scan the macro definitions until we
24671      reach the first DW_MACINFO_start_file entry.  We then initialize
24672      CURRENT_FILE accordingly so that any macro definition found before the
24673      first DW_MACINFO_start_file can still be associated to the base file.  */
24674
24675   mac_ptr = section->buffer + offset;
24676   mac_end = section->buffer + section->size;
24677
24678   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24679                                       &offset_size, section_is_gnu);
24680   if (mac_ptr == NULL)
24681     {
24682       /* We already issued a complaint.  */
24683       return;
24684     }
24685
24686   do
24687     {
24688       /* Do we at least have room for a macinfo type byte?  */
24689       if (mac_ptr >= mac_end)
24690         {
24691           /* Complaint is printed during the second pass as GDB will probably
24692              stop the first pass earlier upon finding
24693              DW_MACINFO_start_file.  */
24694           break;
24695         }
24696
24697       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24698       mac_ptr++;
24699
24700       /* Note that we rely on the fact that the corresponding GNU and
24701          DWARF constants are the same.  */
24702       DIAGNOSTIC_PUSH
24703       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24704       switch (macinfo_type)
24705         {
24706           /* A zero macinfo type indicates the end of the macro
24707              information.  */
24708         case 0:
24709           break;
24710
24711         case DW_MACRO_define:
24712         case DW_MACRO_undef:
24713           /* Only skip the data by MAC_PTR.  */
24714           {
24715             unsigned int bytes_read;
24716
24717             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24718             mac_ptr += bytes_read;
24719             read_direct_string (abfd, mac_ptr, &bytes_read);
24720             mac_ptr += bytes_read;
24721           }
24722           break;
24723
24724         case DW_MACRO_start_file:
24725           {
24726             unsigned int bytes_read;
24727             int line, file;
24728
24729             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24730             mac_ptr += bytes_read;
24731             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24732             mac_ptr += bytes_read;
24733
24734             current_file = macro_start_file (cu, file, line, current_file, lh);
24735           }
24736           break;
24737
24738         case DW_MACRO_end_file:
24739           /* No data to skip by MAC_PTR.  */
24740           break;
24741
24742         case DW_MACRO_define_strp:
24743         case DW_MACRO_undef_strp:
24744         case DW_MACRO_define_sup:
24745         case DW_MACRO_undef_sup:
24746           {
24747             unsigned int bytes_read;
24748
24749             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24750             mac_ptr += bytes_read;
24751             mac_ptr += offset_size;
24752           }
24753           break;
24754
24755         case DW_MACRO_import:
24756         case DW_MACRO_import_sup:
24757           /* Note that, according to the spec, a transparent include
24758              chain cannot call DW_MACRO_start_file.  So, we can just
24759              skip this opcode.  */
24760           mac_ptr += offset_size;
24761           break;
24762
24763         case DW_MACINFO_vendor_ext:
24764           /* Only skip the data by MAC_PTR.  */
24765           if (!section_is_gnu)
24766             {
24767               unsigned int bytes_read;
24768
24769               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24770               mac_ptr += bytes_read;
24771               read_direct_string (abfd, mac_ptr, &bytes_read);
24772               mac_ptr += bytes_read;
24773             }
24774           /* FALLTHROUGH */
24775
24776         default:
24777           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24778                                          mac_ptr, mac_end, abfd, offset_size,
24779                                          section);
24780           if (mac_ptr == NULL)
24781             return;
24782           break;
24783         }
24784       DIAGNOSTIC_POP
24785     } while (macinfo_type != 0 && current_file == NULL);
24786
24787   /* Second pass: Process all entries.
24788
24789      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24790      command-line macro definitions/undefinitions.  This flag is unset when we
24791      reach the first DW_MACINFO_start_file entry.  */
24792
24793   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24794                                            htab_eq_pointer,
24795                                            NULL, xcalloc, xfree));
24796   mac_ptr = section->buffer + offset;
24797   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24798   *slot = (void *) mac_ptr;
24799   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24800                             current_file, lh, section,
24801                             section_is_gnu, 0, offset_size,
24802                             include_hash.get ());
24803 }
24804
24805 /* Check if the attribute's form is a DW_FORM_block*
24806    if so return true else false.  */
24807
24808 static int
24809 attr_form_is_block (const struct attribute *attr)
24810 {
24811   return (attr == NULL ? 0 :
24812       attr->form == DW_FORM_block1
24813       || attr->form == DW_FORM_block2
24814       || attr->form == DW_FORM_block4
24815       || attr->form == DW_FORM_block
24816       || attr->form == DW_FORM_exprloc);
24817 }
24818
24819 /* Return non-zero if ATTR's value is a section offset --- classes
24820    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24821    You may use DW_UNSND (attr) to retrieve such offsets.
24822
24823    Section 7.5.4, "Attribute Encodings", explains that no attribute
24824    may have a value that belongs to more than one of these classes; it
24825    would be ambiguous if we did, because we use the same forms for all
24826    of them.  */
24827
24828 static int
24829 attr_form_is_section_offset (const struct attribute *attr)
24830 {
24831   return (attr->form == DW_FORM_data4
24832           || attr->form == DW_FORM_data8
24833           || attr->form == DW_FORM_sec_offset);
24834 }
24835
24836 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24837    zero otherwise.  When this function returns true, you can apply
24838    dwarf2_get_attr_constant_value to it.
24839
24840    However, note that for some attributes you must check
24841    attr_form_is_section_offset before using this test.  DW_FORM_data4
24842    and DW_FORM_data8 are members of both the constant class, and of
24843    the classes that contain offsets into other debug sections
24844    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24845    that, if an attribute's can be either a constant or one of the
24846    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24847    taken as section offsets, not constants.
24848
24849    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24850    cannot handle that.  */
24851
24852 static int
24853 attr_form_is_constant (const struct attribute *attr)
24854 {
24855   switch (attr->form)
24856     {
24857     case DW_FORM_sdata:
24858     case DW_FORM_udata:
24859     case DW_FORM_data1:
24860     case DW_FORM_data2:
24861     case DW_FORM_data4:
24862     case DW_FORM_data8:
24863     case DW_FORM_implicit_const:
24864       return 1;
24865     default:
24866       return 0;
24867     }
24868 }
24869
24870
24871 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24872    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24873
24874 static int
24875 attr_form_is_ref (const struct attribute *attr)
24876 {
24877   switch (attr->form)
24878     {
24879     case DW_FORM_ref_addr:
24880     case DW_FORM_ref1:
24881     case DW_FORM_ref2:
24882     case DW_FORM_ref4:
24883     case DW_FORM_ref8:
24884     case DW_FORM_ref_udata:
24885     case DW_FORM_GNU_ref_alt:
24886       return 1;
24887     default:
24888       return 0;
24889     }
24890 }
24891
24892 /* Return the .debug_loc section to use for CU.
24893    For DWO files use .debug_loc.dwo.  */
24894
24895 static struct dwarf2_section_info *
24896 cu_debug_loc_section (struct dwarf2_cu *cu)
24897 {
24898   struct dwarf2_per_objfile *dwarf2_per_objfile
24899     = cu->per_cu->dwarf2_per_objfile;
24900
24901   if (cu->dwo_unit)
24902     {
24903       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24904       
24905       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24906     }
24907   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24908                                   : &dwarf2_per_objfile->loc);
24909 }
24910
24911 /* A helper function that fills in a dwarf2_loclist_baton.  */
24912
24913 static void
24914 fill_in_loclist_baton (struct dwarf2_cu *cu,
24915                        struct dwarf2_loclist_baton *baton,
24916                        const struct attribute *attr)
24917 {
24918   struct dwarf2_per_objfile *dwarf2_per_objfile
24919     = cu->per_cu->dwarf2_per_objfile;
24920   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24921
24922   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24923
24924   baton->per_cu = cu->per_cu;
24925   gdb_assert (baton->per_cu);
24926   /* We don't know how long the location list is, but make sure we
24927      don't run off the edge of the section.  */
24928   baton->size = section->size - DW_UNSND (attr);
24929   baton->data = section->buffer + DW_UNSND (attr);
24930   baton->base_address = cu->base_address;
24931   baton->from_dwo = cu->dwo_unit != NULL;
24932 }
24933
24934 static void
24935 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24936                              struct dwarf2_cu *cu, int is_block)
24937 {
24938   struct dwarf2_per_objfile *dwarf2_per_objfile
24939     = cu->per_cu->dwarf2_per_objfile;
24940   struct objfile *objfile = dwarf2_per_objfile->objfile;
24941   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24942
24943   if (attr_form_is_section_offset (attr)
24944       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24945          the section.  If so, fall through to the complaint in the
24946          other branch.  */
24947       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24948     {
24949       struct dwarf2_loclist_baton *baton;
24950
24951       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24952
24953       fill_in_loclist_baton (cu, baton, attr);
24954
24955       if (cu->base_known == 0)
24956         complaint (_("Location list used without "
24957                      "specifying the CU base address."));
24958
24959       SYMBOL_ACLASS_INDEX (sym) = (is_block
24960                                    ? dwarf2_loclist_block_index
24961                                    : dwarf2_loclist_index);
24962       SYMBOL_LOCATION_BATON (sym) = baton;
24963     }
24964   else
24965     {
24966       struct dwarf2_locexpr_baton *baton;
24967
24968       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24969       baton->per_cu = cu->per_cu;
24970       gdb_assert (baton->per_cu);
24971
24972       if (attr_form_is_block (attr))
24973         {
24974           /* Note that we're just copying the block's data pointer
24975              here, not the actual data.  We're still pointing into the
24976              info_buffer for SYM's objfile; right now we never release
24977              that buffer, but when we do clean up properly this may
24978              need to change.  */
24979           baton->size = DW_BLOCK (attr)->size;
24980           baton->data = DW_BLOCK (attr)->data;
24981         }
24982       else
24983         {
24984           dwarf2_invalid_attrib_class_complaint ("location description",
24985                                                  SYMBOL_NATURAL_NAME (sym));
24986           baton->size = 0;
24987         }
24988
24989       SYMBOL_ACLASS_INDEX (sym) = (is_block
24990                                    ? dwarf2_locexpr_block_index
24991                                    : dwarf2_locexpr_index);
24992       SYMBOL_LOCATION_BATON (sym) = baton;
24993     }
24994 }
24995
24996 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24997    came from a separate debuginfo file, then the master objfile is
24998    returned.  */
24999
25000 struct objfile *
25001 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25002 {
25003   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25004
25005   /* Return the master objfile, so that we can report and look up the
25006      correct file containing this variable.  */
25007   if (objfile->separate_debug_objfile_backlink)
25008     objfile = objfile->separate_debug_objfile_backlink;
25009
25010   return objfile;
25011 }
25012
25013 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25014    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25015    CU_HEADERP first.  */
25016
25017 static const struct comp_unit_head *
25018 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25019                        struct dwarf2_per_cu_data *per_cu)
25020 {
25021   const gdb_byte *info_ptr;
25022
25023   if (per_cu->cu)
25024     return &per_cu->cu->header;
25025
25026   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25027
25028   memset (cu_headerp, 0, sizeof (*cu_headerp));
25029   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25030                        rcuh_kind::COMPILE);
25031
25032   return cu_headerp;
25033 }
25034
25035 /* Return the address size given in the compilation unit header for CU.  */
25036
25037 int
25038 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25039 {
25040   struct comp_unit_head cu_header_local;
25041   const struct comp_unit_head *cu_headerp;
25042
25043   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25044
25045   return cu_headerp->addr_size;
25046 }
25047
25048 /* Return the offset size given in the compilation unit header for CU.  */
25049
25050 int
25051 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25052 {
25053   struct comp_unit_head cu_header_local;
25054   const struct comp_unit_head *cu_headerp;
25055
25056   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25057
25058   return cu_headerp->offset_size;
25059 }
25060
25061 /* See its dwarf2loc.h declaration.  */
25062
25063 int
25064 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25065 {
25066   struct comp_unit_head cu_header_local;
25067   const struct comp_unit_head *cu_headerp;
25068
25069   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25070
25071   if (cu_headerp->version == 2)
25072     return cu_headerp->addr_size;
25073   else
25074     return cu_headerp->offset_size;
25075 }
25076
25077 /* Return the text offset of the CU.  The returned offset comes from
25078    this CU's objfile.  If this objfile came from a separate debuginfo
25079    file, then the offset may be different from the corresponding
25080    offset in the parent objfile.  */
25081
25082 CORE_ADDR
25083 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25084 {
25085   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25086
25087   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25088 }
25089
25090 /* Return DWARF version number of PER_CU.  */
25091
25092 short
25093 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25094 {
25095   return per_cu->dwarf_version;
25096 }
25097
25098 /* Locate the .debug_info compilation unit from CU's objfile which contains
25099    the DIE at OFFSET.  Raises an error on failure.  */
25100
25101 static struct dwarf2_per_cu_data *
25102 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25103                                   unsigned int offset_in_dwz,
25104                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25105 {
25106   struct dwarf2_per_cu_data *this_cu;
25107   int low, high;
25108
25109   low = 0;
25110   high = dwarf2_per_objfile->all_comp_units.size () - 1;
25111   while (high > low)
25112     {
25113       struct dwarf2_per_cu_data *mid_cu;
25114       int mid = low + (high - low) / 2;
25115
25116       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25117       if (mid_cu->is_dwz > offset_in_dwz
25118           || (mid_cu->is_dwz == offset_in_dwz
25119               && mid_cu->sect_off + mid_cu->length >= sect_off))
25120         high = mid;
25121       else
25122         low = mid + 1;
25123     }
25124   gdb_assert (low == high);
25125   this_cu = dwarf2_per_objfile->all_comp_units[low];
25126   if (this_cu->is_dwz != offset_in_dwz || this_cu->sect_off > sect_off)
25127     {
25128       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25129         error (_("Dwarf Error: could not find partial DIE containing "
25130                "offset %s [in module %s]"),
25131                sect_offset_str (sect_off),
25132                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25133
25134       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25135                   <= sect_off);
25136       return dwarf2_per_objfile->all_comp_units[low-1];
25137     }
25138   else
25139     {
25140       this_cu = dwarf2_per_objfile->all_comp_units[low];
25141       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25142           && sect_off >= this_cu->sect_off + this_cu->length)
25143         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25144       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25145       return this_cu;
25146     }
25147 }
25148
25149 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25150
25151 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25152   : per_cu (per_cu_),
25153     mark (false),
25154     has_loclist (false),
25155     checked_producer (false),
25156     producer_is_gxx_lt_4_6 (false),
25157     producer_is_gcc_lt_4_3 (false),
25158     producer_is_icc (false),
25159     producer_is_icc_lt_14 (false),
25160     producer_is_codewarrior (false),
25161     processing_has_namespace_info (false)
25162 {
25163   per_cu->cu = this;
25164 }
25165
25166 /* Destroy a dwarf2_cu.  */
25167
25168 dwarf2_cu::~dwarf2_cu ()
25169 {
25170   per_cu->cu = NULL;
25171 }
25172
25173 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25174
25175 static void
25176 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25177                        enum language pretend_language)
25178 {
25179   struct attribute *attr;
25180
25181   /* Set the language we're debugging.  */
25182   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25183   if (attr)
25184     set_cu_language (DW_UNSND (attr), cu);
25185   else
25186     {
25187       cu->language = pretend_language;
25188       cu->language_defn = language_def (cu->language);
25189     }
25190
25191   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25192 }
25193
25194 /* Increase the age counter on each cached compilation unit, and free
25195    any that are too old.  */
25196
25197 static void
25198 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25199 {
25200   struct dwarf2_per_cu_data *per_cu, **last_chain;
25201
25202   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25203   per_cu = dwarf2_per_objfile->read_in_chain;
25204   while (per_cu != NULL)
25205     {
25206       per_cu->cu->last_used ++;
25207       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25208         dwarf2_mark (per_cu->cu);
25209       per_cu = per_cu->cu->read_in_chain;
25210     }
25211
25212   per_cu = dwarf2_per_objfile->read_in_chain;
25213   last_chain = &dwarf2_per_objfile->read_in_chain;
25214   while (per_cu != NULL)
25215     {
25216       struct dwarf2_per_cu_data *next_cu;
25217
25218       next_cu = per_cu->cu->read_in_chain;
25219
25220       if (!per_cu->cu->mark)
25221         {
25222           delete per_cu->cu;
25223           *last_chain = next_cu;
25224         }
25225       else
25226         last_chain = &per_cu->cu->read_in_chain;
25227
25228       per_cu = next_cu;
25229     }
25230 }
25231
25232 /* Remove a single compilation unit from the cache.  */
25233
25234 static void
25235 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25236 {
25237   struct dwarf2_per_cu_data *per_cu, **last_chain;
25238   struct dwarf2_per_objfile *dwarf2_per_objfile
25239     = target_per_cu->dwarf2_per_objfile;
25240
25241   per_cu = dwarf2_per_objfile->read_in_chain;
25242   last_chain = &dwarf2_per_objfile->read_in_chain;
25243   while (per_cu != NULL)
25244     {
25245       struct dwarf2_per_cu_data *next_cu;
25246
25247       next_cu = per_cu->cu->read_in_chain;
25248
25249       if (per_cu == target_per_cu)
25250         {
25251           delete per_cu->cu;
25252           per_cu->cu = NULL;
25253           *last_chain = next_cu;
25254           break;
25255         }
25256       else
25257         last_chain = &per_cu->cu->read_in_chain;
25258
25259       per_cu = next_cu;
25260     }
25261 }
25262
25263 /* Cleanup function for the dwarf2_per_objfile data.  */
25264
25265 static void
25266 dwarf2_free_objfile (struct objfile *objfile, void *datum)
25267 {
25268   struct dwarf2_per_objfile *dwarf2_per_objfile
25269     = static_cast<struct dwarf2_per_objfile *> (datum);
25270
25271   delete dwarf2_per_objfile;
25272 }
25273
25274 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25275    We store these in a hash table separate from the DIEs, and preserve them
25276    when the DIEs are flushed out of cache.
25277
25278    The CU "per_cu" pointer is needed because offset alone is not enough to
25279    uniquely identify the type.  A file may have multiple .debug_types sections,
25280    or the type may come from a DWO file.  Furthermore, while it's more logical
25281    to use per_cu->section+offset, with Fission the section with the data is in
25282    the DWO file but we don't know that section at the point we need it.
25283    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25284    because we can enter the lookup routine, get_die_type_at_offset, from
25285    outside this file, and thus won't necessarily have PER_CU->cu.
25286    Fortunately, PER_CU is stable for the life of the objfile.  */
25287
25288 struct dwarf2_per_cu_offset_and_type
25289 {
25290   const struct dwarf2_per_cu_data *per_cu;
25291   sect_offset sect_off;
25292   struct type *type;
25293 };
25294
25295 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25296
25297 static hashval_t
25298 per_cu_offset_and_type_hash (const void *item)
25299 {
25300   const struct dwarf2_per_cu_offset_and_type *ofs
25301     = (const struct dwarf2_per_cu_offset_and_type *) item;
25302
25303   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25304 }
25305
25306 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25307
25308 static int
25309 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25310 {
25311   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25312     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25313   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25314     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25315
25316   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25317           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25318 }
25319
25320 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25321    table if necessary.  For convenience, return TYPE.
25322
25323    The DIEs reading must have careful ordering to:
25324     * Not cause infite loops trying to read in DIEs as a prerequisite for
25325       reading current DIE.
25326     * Not trying to dereference contents of still incompletely read in types
25327       while reading in other DIEs.
25328     * Enable referencing still incompletely read in types just by a pointer to
25329       the type without accessing its fields.
25330
25331    Therefore caller should follow these rules:
25332      * Try to fetch any prerequisite types we may need to build this DIE type
25333        before building the type and calling set_die_type.
25334      * After building type call set_die_type for current DIE as soon as
25335        possible before fetching more types to complete the current type.
25336      * Make the type as complete as possible before fetching more types.  */
25337
25338 static struct type *
25339 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25340 {
25341   struct dwarf2_per_objfile *dwarf2_per_objfile
25342     = cu->per_cu->dwarf2_per_objfile;
25343   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25344   struct objfile *objfile = dwarf2_per_objfile->objfile;
25345   struct attribute *attr;
25346   struct dynamic_prop prop;
25347
25348   /* For Ada types, make sure that the gnat-specific data is always
25349      initialized (if not already set).  There are a few types where
25350      we should not be doing so, because the type-specific area is
25351      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25352      where the type-specific area is used to store the floatformat).
25353      But this is not a problem, because the gnat-specific information
25354      is actually not needed for these types.  */
25355   if (need_gnat_info (cu)
25356       && TYPE_CODE (type) != TYPE_CODE_FUNC
25357       && TYPE_CODE (type) != TYPE_CODE_FLT
25358       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25359       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25360       && TYPE_CODE (type) != TYPE_CODE_METHOD
25361       && !HAVE_GNAT_AUX_INFO (type))
25362     INIT_GNAT_SPECIFIC (type);
25363
25364   /* Read DW_AT_allocated and set in type.  */
25365   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25366   if (attr_form_is_block (attr))
25367     {
25368       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25369         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25370     }
25371   else if (attr != NULL)
25372     {
25373       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25374                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25375                  sect_offset_str (die->sect_off));
25376     }
25377
25378   /* Read DW_AT_associated and set in type.  */
25379   attr = dwarf2_attr (die, DW_AT_associated, cu);
25380   if (attr_form_is_block (attr))
25381     {
25382       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25383         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25384     }
25385   else if (attr != NULL)
25386     {
25387       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25388                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25389                  sect_offset_str (die->sect_off));
25390     }
25391
25392   /* Read DW_AT_data_location and set in type.  */
25393   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25394   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25395     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25396
25397   if (dwarf2_per_objfile->die_type_hash == NULL)
25398     {
25399       dwarf2_per_objfile->die_type_hash =
25400         htab_create_alloc_ex (127,
25401                               per_cu_offset_and_type_hash,
25402                               per_cu_offset_and_type_eq,
25403                               NULL,
25404                               &objfile->objfile_obstack,
25405                               hashtab_obstack_allocate,
25406                               dummy_obstack_deallocate);
25407     }
25408
25409   ofs.per_cu = cu->per_cu;
25410   ofs.sect_off = die->sect_off;
25411   ofs.type = type;
25412   slot = (struct dwarf2_per_cu_offset_and_type **)
25413     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25414   if (*slot)
25415     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25416                sect_offset_str (die->sect_off));
25417   *slot = XOBNEW (&objfile->objfile_obstack,
25418                   struct dwarf2_per_cu_offset_and_type);
25419   **slot = ofs;
25420   return type;
25421 }
25422
25423 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25424    or return NULL if the die does not have a saved type.  */
25425
25426 static struct type *
25427 get_die_type_at_offset (sect_offset sect_off,
25428                         struct dwarf2_per_cu_data *per_cu)
25429 {
25430   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25431   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25432
25433   if (dwarf2_per_objfile->die_type_hash == NULL)
25434     return NULL;
25435
25436   ofs.per_cu = per_cu;
25437   ofs.sect_off = sect_off;
25438   slot = ((struct dwarf2_per_cu_offset_and_type *)
25439           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25440   if (slot)
25441     return slot->type;
25442   else
25443     return NULL;
25444 }
25445
25446 /* Look up the type for DIE in CU in die_type_hash,
25447    or return NULL if DIE does not have a saved type.  */
25448
25449 static struct type *
25450 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25451 {
25452   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25453 }
25454
25455 /* Add a dependence relationship from CU to REF_PER_CU.  */
25456
25457 static void
25458 dwarf2_add_dependence (struct dwarf2_cu *cu,
25459                        struct dwarf2_per_cu_data *ref_per_cu)
25460 {
25461   void **slot;
25462
25463   if (cu->dependencies == NULL)
25464     cu->dependencies
25465       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25466                               NULL, &cu->comp_unit_obstack,
25467                               hashtab_obstack_allocate,
25468                               dummy_obstack_deallocate);
25469
25470   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25471   if (*slot == NULL)
25472     *slot = ref_per_cu;
25473 }
25474
25475 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25476    Set the mark field in every compilation unit in the
25477    cache that we must keep because we are keeping CU.  */
25478
25479 static int
25480 dwarf2_mark_helper (void **slot, void *data)
25481 {
25482   struct dwarf2_per_cu_data *per_cu;
25483
25484   per_cu = (struct dwarf2_per_cu_data *) *slot;
25485
25486   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25487      reading of the chain.  As such dependencies remain valid it is not much
25488      useful to track and undo them during QUIT cleanups.  */
25489   if (per_cu->cu == NULL)
25490     return 1;
25491
25492   if (per_cu->cu->mark)
25493     return 1;
25494   per_cu->cu->mark = true;
25495
25496   if (per_cu->cu->dependencies != NULL)
25497     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25498
25499   return 1;
25500 }
25501
25502 /* Set the mark field in CU and in every other compilation unit in the
25503    cache that we must keep because we are keeping CU.  */
25504
25505 static void
25506 dwarf2_mark (struct dwarf2_cu *cu)
25507 {
25508   if (cu->mark)
25509     return;
25510   cu->mark = true;
25511   if (cu->dependencies != NULL)
25512     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25513 }
25514
25515 static void
25516 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25517 {
25518   while (per_cu)
25519     {
25520       per_cu->cu->mark = false;
25521       per_cu = per_cu->cu->read_in_chain;
25522     }
25523 }
25524
25525 /* Trivial hash function for partial_die_info: the hash value of a DIE
25526    is its offset in .debug_info for this objfile.  */
25527
25528 static hashval_t
25529 partial_die_hash (const void *item)
25530 {
25531   const struct partial_die_info *part_die
25532     = (const struct partial_die_info *) item;
25533
25534   return to_underlying (part_die->sect_off);
25535 }
25536
25537 /* Trivial comparison function for partial_die_info structures: two DIEs
25538    are equal if they have the same offset.  */
25539
25540 static int
25541 partial_die_eq (const void *item_lhs, const void *item_rhs)
25542 {
25543   const struct partial_die_info *part_die_lhs
25544     = (const struct partial_die_info *) item_lhs;
25545   const struct partial_die_info *part_die_rhs
25546     = (const struct partial_die_info *) item_rhs;
25547
25548   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25549 }
25550
25551 struct cmd_list_element *set_dwarf_cmdlist;
25552 struct cmd_list_element *show_dwarf_cmdlist;
25553
25554 static void
25555 set_dwarf_cmd (const char *args, int from_tty)
25556 {
25557   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25558              gdb_stdout);
25559 }
25560
25561 static void
25562 show_dwarf_cmd (const char *args, int from_tty)
25563 {
25564   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25565 }
25566
25567 int dwarf_always_disassemble;
25568
25569 static void
25570 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25571                                struct cmd_list_element *c, const char *value)
25572 {
25573   fprintf_filtered (file,
25574                     _("Whether to always disassemble "
25575                       "DWARF expressions is %s.\n"),
25576                     value);
25577 }
25578
25579 static void
25580 show_check_physname (struct ui_file *file, int from_tty,
25581                      struct cmd_list_element *c, const char *value)
25582 {
25583   fprintf_filtered (file,
25584                     _("Whether to check \"physname\" is %s.\n"),
25585                     value);
25586 }
25587
25588 void
25589 _initialize_dwarf2_read (void)
25590 {
25591   dwarf2_objfile_data_key
25592     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25593
25594   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25595 Set DWARF specific variables.\n\
25596 Configure DWARF variables such as the cache size"),
25597                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25598                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25599
25600   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25601 Show DWARF specific variables\n\
25602 Show DWARF variables such as the cache size"),
25603                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25604                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25605
25606   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25607                             &dwarf_max_cache_age, _("\
25608 Set the upper bound on the age of cached DWARF compilation units."), _("\
25609 Show the upper bound on the age of cached DWARF compilation units."), _("\
25610 A higher limit means that cached compilation units will be stored\n\
25611 in memory longer, and more total memory will be used.  Zero disables\n\
25612 caching, which can slow down startup."),
25613                             NULL,
25614                             show_dwarf_max_cache_age,
25615                             &set_dwarf_cmdlist,
25616                             &show_dwarf_cmdlist);
25617
25618   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25619                            &dwarf_always_disassemble, _("\
25620 Set whether `info address' always disassembles DWARF expressions."), _("\
25621 Show whether `info address' always disassembles DWARF expressions."), _("\
25622 When enabled, DWARF expressions are always printed in an assembly-like\n\
25623 syntax.  When disabled, expressions will be printed in a more\n\
25624 conversational style, when possible."),
25625                            NULL,
25626                            show_dwarf_always_disassemble,
25627                            &set_dwarf_cmdlist,
25628                            &show_dwarf_cmdlist);
25629
25630   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25631 Set debugging of the DWARF reader."), _("\
25632 Show debugging of the DWARF reader."), _("\
25633 When enabled (non-zero), debugging messages are printed during DWARF\n\
25634 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25635 information.  A value greater than 1 provides more verbose information."),
25636                             NULL,
25637                             NULL,
25638                             &setdebuglist, &showdebuglist);
25639
25640   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25641 Set debugging of the DWARF DIE reader."), _("\
25642 Show debugging of the DWARF DIE reader."), _("\
25643 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25644 The value is the maximum depth to print."),
25645                              NULL,
25646                              NULL,
25647                              &setdebuglist, &showdebuglist);
25648
25649   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25650 Set debugging of the dwarf line reader."), _("\
25651 Show debugging of the dwarf line reader."), _("\
25652 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25653 A value of 1 (one) provides basic information.\n\
25654 A value greater than 1 provides more verbose information."),
25655                              NULL,
25656                              NULL,
25657                              &setdebuglist, &showdebuglist);
25658
25659   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25660 Set cross-checking of \"physname\" code against demangler."), _("\
25661 Show cross-checking of \"physname\" code against demangler."), _("\
25662 When enabled, GDB's internal \"physname\" code is checked against\n\
25663 the demangler."),
25664                            NULL, show_check_physname,
25665                            &setdebuglist, &showdebuglist);
25666
25667   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25668                            no_class, &use_deprecated_index_sections, _("\
25669 Set whether to use deprecated gdb_index sections."), _("\
25670 Show whether to use deprecated gdb_index sections."), _("\
25671 When enabled, deprecated .gdb_index sections are used anyway.\n\
25672 Normally they are ignored either because of a missing feature or\n\
25673 performance issue.\n\
25674 Warning: This option must be enabled before gdb reads the file."),
25675                            NULL,
25676                            NULL,
25677                            &setlist, &showlist);
25678
25679   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25680                                                         &dwarf2_locexpr_funcs);
25681   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25682                                                         &dwarf2_loclist_funcs);
25683
25684   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25685                                         &dwarf2_block_frame_base_locexpr_funcs);
25686   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25687                                         &dwarf2_block_frame_base_loclist_funcs);
25688
25689 #if GDB_SELF_TEST
25690   selftests::register_test ("dw2_expand_symtabs_matching",
25691                             selftests::dw2_expand_symtabs_matching::run_test);
25692 #endif
25693 }