Fix for dwz-related crash
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "dwarf2read.h"
33 #include "dwarf-index-common.h"
34 #include "bfd.h"
35 #include "elf-bfd.h"
36 #include "symtab.h"
37 #include "gdbtypes.h"
38 #include "objfiles.h"
39 #include "dwarf2.h"
40 #include "buildsym.h"
41 #include "demangle.h"
42 #include "gdb-demangle.h"
43 #include "expression.h"
44 #include "filenames.h"  /* for DOSish file names */
45 #include "macrotab.h"
46 #include "language.h"
47 #include "complaints.h"
48 #include "bcache.h"
49 #include "dwarf2expr.h"
50 #include "dwarf2loc.h"
51 #include "cp-support.h"
52 #include "hashtab.h"
53 #include "command.h"
54 #include "gdbcmd.h"
55 #include "block.h"
56 #include "addrmap.h"
57 #include "typeprint.h"
58 #include "psympriv.h"
59 #include <sys/stat.h>
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72 #include "build-id.h"
73 #include "namespace.h"
74 #include "common/gdb_unlinker.h"
75 #include "common/function-view.h"
76 #include "common/gdb_optional.h"
77 #include "common/underlying.h"
78 #include "common/byte-vector.h"
79 #include "common/hash_enum.h"
80 #include "filename-seen-cache.h"
81 #include "producer.h"
82 #include <fcntl.h>
83 #include <sys/types.h>
84 #include <algorithm>
85 #include <unordered_set>
86 #include <unordered_map>
87 #include "selftest.h"
88 #include <cmath>
89 #include <set>
90 #include <forward_list>
91 #include "rust-lang.h"
92 #include "common/pathstuff.h"
93
94 /* When == 1, print basic high level tracing messages.
95    When > 1, be more verbose.
96    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
97 static unsigned int dwarf_read_debug = 0;
98
99 /* When non-zero, dump DIEs after they are read in.  */
100 static unsigned int dwarf_die_debug = 0;
101
102 /* When non-zero, dump line number entries as they are read in.  */
103 static unsigned int dwarf_line_debug = 0;
104
105 /* When non-zero, cross-check physname against demangler.  */
106 static int check_physname = 0;
107
108 /* When non-zero, do not reject deprecated .gdb_index sections.  */
109 static int use_deprecated_index_sections = 0;
110
111 static const struct objfile_data *dwarf2_objfile_data_key;
112
113 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
114
115 static int dwarf2_locexpr_index;
116 static int dwarf2_loclist_index;
117 static int dwarf2_locexpr_block_index;
118 static int dwarf2_loclist_block_index;
119
120 /* An index into a (C++) symbol name component in a symbol name as
121    recorded in the mapped_index's symbol table.  For each C++ symbol
122    in the symbol table, we record one entry for the start of each
123    component in the symbol in a table of name components, and then
124    sort the table, in order to be able to binary search symbol names,
125    ignoring leading namespaces, both completion and regular look up.
126    For example, for symbol "A::B::C", we'll have an entry that points
127    to "A::B::C", another that points to "B::C", and another for "C".
128    Note that function symbols in GDB index have no parameter
129    information, just the function/method names.  You can convert a
130    name_component to a "const char *" using the
131    'mapped_index::symbol_name_at(offset_type)' method.  */
132
133 struct name_component
134 {
135   /* Offset in the symbol name where the component starts.  Stored as
136      a (32-bit) offset instead of a pointer to save memory and improve
137      locality on 64-bit architectures.  */
138   offset_type name_offset;
139
140   /* The symbol's index in the symbol and constant pool tables of a
141      mapped_index.  */
142   offset_type idx;
143 };
144
145 /* Base class containing bits shared by both .gdb_index and
146    .debug_name indexes.  */
147
148 struct mapped_index_base
149 {
150   /* The name_component table (a sorted vector).  See name_component's
151      description above.  */
152   std::vector<name_component> name_components;
153
154   /* How NAME_COMPONENTS is sorted.  */
155   enum case_sensitivity name_components_casing;
156
157   /* Return the number of names in the symbol table.  */
158   virtual size_t symbol_name_count () const = 0;
159
160   /* Get the name of the symbol at IDX in the symbol table.  */
161   virtual const char *symbol_name_at (offset_type idx) const = 0;
162
163   /* Return whether the name at IDX in the symbol table should be
164      ignored.  */
165   virtual bool symbol_name_slot_invalid (offset_type idx) const
166   {
167     return false;
168   }
169
170   /* Build the symbol name component sorted vector, if we haven't
171      yet.  */
172   void build_name_components ();
173
174   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
175      possible matches for LN_NO_PARAMS in the name component
176      vector.  */
177   std::pair<std::vector<name_component>::const_iterator,
178             std::vector<name_component>::const_iterator>
179     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
180
181   /* Prevent deleting/destroying via a base class pointer.  */
182 protected:
183   ~mapped_index_base() = default;
184 };
185
186 /* A description of the mapped index.  The file format is described in
187    a comment by the code that writes the index.  */
188 struct mapped_index final : public mapped_index_base
189 {
190   /* A slot/bucket in the symbol table hash.  */
191   struct symbol_table_slot
192   {
193     const offset_type name;
194     const offset_type vec;
195   };
196
197   /* Index data format version.  */
198   int version;
199
200   /* The total length of the buffer.  */
201   off_t total_size;
202
203   /* The address table data.  */
204   gdb::array_view<const gdb_byte> address_table;
205
206   /* The symbol table, implemented as a hash table.  */
207   gdb::array_view<symbol_table_slot> symbol_table;
208
209   /* A pointer to the constant pool.  */
210   const char *constant_pool;
211
212   bool symbol_name_slot_invalid (offset_type idx) const override
213   {
214     const auto &bucket = this->symbol_table[idx];
215     return bucket.name == 0 && bucket.vec;
216   }
217
218   /* Convenience method to get at the name of the symbol at IDX in the
219      symbol table.  */
220   const char *symbol_name_at (offset_type idx) const override
221   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
222
223   size_t symbol_name_count () const override
224   { return this->symbol_table.size (); }
225 };
226
227 /* A description of the mapped .debug_names.
228    Uninitialized map has CU_COUNT 0.  */
229 struct mapped_debug_names final : public mapped_index_base
230 {
231   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
232   : dwarf2_per_objfile (dwarf2_per_objfile_)
233   {}
234
235   struct dwarf2_per_objfile *dwarf2_per_objfile;
236   bfd_endian dwarf5_byte_order;
237   bool dwarf5_is_dwarf64;
238   bool augmentation_is_gdb;
239   uint8_t offset_size;
240   uint32_t cu_count = 0;
241   uint32_t tu_count, bucket_count, name_count;
242   const gdb_byte *cu_table_reordered, *tu_table_reordered;
243   const uint32_t *bucket_table_reordered, *hash_table_reordered;
244   const gdb_byte *name_table_string_offs_reordered;
245   const gdb_byte *name_table_entry_offs_reordered;
246   const gdb_byte *entry_pool;
247
248   struct index_val
249   {
250     ULONGEST dwarf_tag;
251     struct attr
252     {
253       /* Attribute name DW_IDX_*.  */
254       ULONGEST dw_idx;
255
256       /* Attribute form DW_FORM_*.  */
257       ULONGEST form;
258
259       /* Value if FORM is DW_FORM_implicit_const.  */
260       LONGEST implicit_const;
261     };
262     std::vector<attr> attr_vec;
263   };
264
265   std::unordered_map<ULONGEST, index_val> abbrev_map;
266
267   const char *namei_to_name (uint32_t namei) const;
268
269   /* Implementation of the mapped_index_base virtual interface, for
270      the name_components cache.  */
271
272   const char *symbol_name_at (offset_type idx) const override
273   { return namei_to_name (idx); }
274
275   size_t symbol_name_count () const override
276   { return this->name_count; }
277 };
278
279 /* See dwarf2read.h.  */
280
281 dwarf2_per_objfile *
282 get_dwarf2_per_objfile (struct objfile *objfile)
283 {
284   return ((struct dwarf2_per_objfile *)
285           objfile_data (objfile, dwarf2_objfile_data_key));
286 }
287
288 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
289
290 void
291 set_dwarf2_per_objfile (struct objfile *objfile,
292                         struct dwarf2_per_objfile *dwarf2_per_objfile)
293 {
294   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
295   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
296 }
297
298 /* Default names of the debugging sections.  */
299
300 /* Note that if the debugging section has been compressed, it might
301    have a name like .zdebug_info.  */
302
303 static const struct dwarf2_debug_sections dwarf2_elf_names =
304 {
305   { ".debug_info", ".zdebug_info" },
306   { ".debug_abbrev", ".zdebug_abbrev" },
307   { ".debug_line", ".zdebug_line" },
308   { ".debug_loc", ".zdebug_loc" },
309   { ".debug_loclists", ".zdebug_loclists" },
310   { ".debug_macinfo", ".zdebug_macinfo" },
311   { ".debug_macro", ".zdebug_macro" },
312   { ".debug_str", ".zdebug_str" },
313   { ".debug_line_str", ".zdebug_line_str" },
314   { ".debug_ranges", ".zdebug_ranges" },
315   { ".debug_rnglists", ".zdebug_rnglists" },
316   { ".debug_types", ".zdebug_types" },
317   { ".debug_addr", ".zdebug_addr" },
318   { ".debug_frame", ".zdebug_frame" },
319   { ".eh_frame", NULL },
320   { ".gdb_index", ".zgdb_index" },
321   { ".debug_names", ".zdebug_names" },
322   { ".debug_aranges", ".zdebug_aranges" },
323   23
324 };
325
326 /* List of DWO/DWP sections.  */
327
328 static const struct dwop_section_names
329 {
330   struct dwarf2_section_names abbrev_dwo;
331   struct dwarf2_section_names info_dwo;
332   struct dwarf2_section_names line_dwo;
333   struct dwarf2_section_names loc_dwo;
334   struct dwarf2_section_names loclists_dwo;
335   struct dwarf2_section_names macinfo_dwo;
336   struct dwarf2_section_names macro_dwo;
337   struct dwarf2_section_names str_dwo;
338   struct dwarf2_section_names str_offsets_dwo;
339   struct dwarf2_section_names types_dwo;
340   struct dwarf2_section_names cu_index;
341   struct dwarf2_section_names tu_index;
342 }
343 dwop_section_names =
344 {
345   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
346   { ".debug_info.dwo", ".zdebug_info.dwo" },
347   { ".debug_line.dwo", ".zdebug_line.dwo" },
348   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
349   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
350   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
351   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
352   { ".debug_str.dwo", ".zdebug_str.dwo" },
353   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
354   { ".debug_types.dwo", ".zdebug_types.dwo" },
355   { ".debug_cu_index", ".zdebug_cu_index" },
356   { ".debug_tu_index", ".zdebug_tu_index" },
357 };
358
359 /* local data types */
360
361 /* The data in a compilation unit header, after target2host
362    translation, looks like this.  */
363 struct comp_unit_head
364 {
365   unsigned int length;
366   short version;
367   unsigned char addr_size;
368   unsigned char signed_addr_p;
369   sect_offset abbrev_sect_off;
370
371   /* Size of file offsets; either 4 or 8.  */
372   unsigned int offset_size;
373
374   /* Size of the length field; either 4 or 12.  */
375   unsigned int initial_length_size;
376
377   enum dwarf_unit_type unit_type;
378
379   /* Offset to the first byte of this compilation unit header in the
380      .debug_info section, for resolving relative reference dies.  */
381   sect_offset sect_off;
382
383   /* Offset to first die in this cu from the start of the cu.
384      This will be the first byte following the compilation unit header.  */
385   cu_offset first_die_cu_offset;
386
387   /* 64-bit signature of this type unit - it is valid only for
388      UNIT_TYPE DW_UT_type.  */
389   ULONGEST signature;
390
391   /* For types, offset in the type's DIE of the type defined by this TU.  */
392   cu_offset type_cu_offset_in_tu;
393 };
394
395 /* Type used for delaying computation of method physnames.
396    See comments for compute_delayed_physnames.  */
397 struct delayed_method_info
398 {
399   /* The type to which the method is attached, i.e., its parent class.  */
400   struct type *type;
401
402   /* The index of the method in the type's function fieldlists.  */
403   int fnfield_index;
404
405   /* The index of the method in the fieldlist.  */
406   int index;
407
408   /* The name of the DIE.  */
409   const char *name;
410
411   /*  The DIE associated with this method.  */
412   struct die_info *die;
413 };
414
415 /* Internal state when decoding a particular compilation unit.  */
416 struct dwarf2_cu
417 {
418   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
419   ~dwarf2_cu ();
420
421   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
422
423   /* The header of the compilation unit.  */
424   struct comp_unit_head header {};
425
426   /* Base address of this compilation unit.  */
427   CORE_ADDR base_address = 0;
428
429   /* Non-zero if base_address has been set.  */
430   int base_known = 0;
431
432   /* The language we are debugging.  */
433   enum language language = language_unknown;
434   const struct language_defn *language_defn = nullptr;
435
436   const char *producer = nullptr;
437
438   /* The generic symbol table building routines have separate lists for
439      file scope symbols and all all other scopes (local scopes).  So
440      we need to select the right one to pass to add_symbol_to_list().
441      We do it by keeping a pointer to the correct list in list_in_scope.
442
443      FIXME: The original dwarf code just treated the file scope as the
444      first local scope, and all other local scopes as nested local
445      scopes, and worked fine.  Check to see if we really need to
446      distinguish these in buildsym.c.  */
447   struct pending **list_in_scope = nullptr;
448
449   /* Hash table holding all the loaded partial DIEs
450      with partial_die->offset.SECT_OFF as hash.  */
451   htab_t partial_dies = nullptr;
452
453   /* Storage for things with the same lifetime as this read-in compilation
454      unit, including partial DIEs.  */
455   auto_obstack comp_unit_obstack;
456
457   /* When multiple dwarf2_cu structures are living in memory, this field
458      chains them all together, so that they can be released efficiently.
459      We will probably also want a generation counter so that most-recently-used
460      compilation units are cached...  */
461   struct dwarf2_per_cu_data *read_in_chain = nullptr;
462
463   /* Backlink to our per_cu entry.  */
464   struct dwarf2_per_cu_data *per_cu;
465
466   /* How many compilation units ago was this CU last referenced?  */
467   int last_used = 0;
468
469   /* A hash table of DIE cu_offset for following references with
470      die_info->offset.sect_off as hash.  */
471   htab_t die_hash = nullptr;
472
473   /* Full DIEs if read in.  */
474   struct die_info *dies = nullptr;
475
476   /* A set of pointers to dwarf2_per_cu_data objects for compilation
477      units referenced by this one.  Only set during full symbol processing;
478      partial symbol tables do not have dependencies.  */
479   htab_t dependencies = nullptr;
480
481   /* Header data from the line table, during full symbol processing.  */
482   struct line_header *line_header = nullptr;
483   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
484      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
485      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
486      to the line header as long as this DIE is being processed.  See
487      process_die_scope.  */
488   die_info *line_header_die_owner = nullptr;
489
490   /* A list of methods which need to have physnames computed
491      after all type information has been read.  */
492   std::vector<delayed_method_info> method_list;
493
494   /* To be copied to symtab->call_site_htab.  */
495   htab_t call_site_htab = nullptr;
496
497   /* Non-NULL if this CU came from a DWO file.
498      There is an invariant here that is important to remember:
499      Except for attributes copied from the top level DIE in the "main"
500      (or "stub") file in preparation for reading the DWO file
501      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
502      Either there isn't a DWO file (in which case this is NULL and the point
503      is moot), or there is and either we're not going to read it (in which
504      case this is NULL) or there is and we are reading it (in which case this
505      is non-NULL).  */
506   struct dwo_unit *dwo_unit = nullptr;
507
508   /* The DW_AT_addr_base attribute if present, zero otherwise
509      (zero is a valid value though).
510      Note this value comes from the Fission stub CU/TU's DIE.  */
511   ULONGEST addr_base = 0;
512
513   /* The DW_AT_ranges_base attribute if present, zero otherwise
514      (zero is a valid value though).
515      Note this value comes from the Fission stub CU/TU's DIE.
516      Also note that the value is zero in the non-DWO case so this value can
517      be used without needing to know whether DWO files are in use or not.
518      N.B. This does not apply to DW_AT_ranges appearing in
519      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
520      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
521      DW_AT_ranges_base *would* have to be applied, and we'd have to care
522      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
523   ULONGEST ranges_base = 0;
524
525   /* When reading debug info generated by older versions of rustc, we
526      have to rewrite some union types to be struct types with a
527      variant part.  This rewriting must be done after the CU is fully
528      read in, because otherwise at the point of rewriting some struct
529      type might not have been fully processed.  So, we keep a list of
530      all such types here and process them after expansion.  */
531   std::vector<struct type *> rust_unions;
532
533   /* Mark used when releasing cached dies.  */
534   unsigned int mark : 1;
535
536   /* This CU references .debug_loc.  See the symtab->locations_valid field.
537      This test is imperfect as there may exist optimized debug code not using
538      any location list and still facing inlining issues if handled as
539      unoptimized code.  For a future better test see GCC PR other/32998.  */
540   unsigned int has_loclist : 1;
541
542   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
543      if all the producer_is_* fields are valid.  This information is cached
544      because profiling CU expansion showed excessive time spent in
545      producer_is_gxx_lt_4_6.  */
546   unsigned int checked_producer : 1;
547   unsigned int producer_is_gxx_lt_4_6 : 1;
548   unsigned int producer_is_gcc_lt_4_3 : 1;
549   unsigned int producer_is_icc_lt_14 : 1;
550
551   /* When set, the file that we're processing is known to have
552      debugging info for C++ namespaces.  GCC 3.3.x did not produce
553      this information, but later versions do.  */
554
555   unsigned int processing_has_namespace_info : 1;
556
557   struct partial_die_info *find_partial_die (sect_offset sect_off);
558 };
559
560 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
561    This includes type_unit_group and quick_file_names.  */
562
563 struct stmt_list_hash
564 {
565   /* The DWO unit this table is from or NULL if there is none.  */
566   struct dwo_unit *dwo_unit;
567
568   /* Offset in .debug_line or .debug_line.dwo.  */
569   sect_offset line_sect_off;
570 };
571
572 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
573    an object of this type.  */
574
575 struct type_unit_group
576 {
577   /* dwarf2read.c's main "handle" on a TU symtab.
578      To simplify things we create an artificial CU that "includes" all the
579      type units using this stmt_list so that the rest of the code still has
580      a "per_cu" handle on the symtab.
581      This PER_CU is recognized by having no section.  */
582 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
583   struct dwarf2_per_cu_data per_cu;
584
585   /* The TUs that share this DW_AT_stmt_list entry.
586      This is added to while parsing type units to build partial symtabs,
587      and is deleted afterwards and not used again.  */
588   VEC (sig_type_ptr) *tus;
589
590   /* The compunit symtab.
591      Type units in a group needn't all be defined in the same source file,
592      so we create an essentially anonymous symtab as the compunit symtab.  */
593   struct compunit_symtab *compunit_symtab;
594
595   /* The data used to construct the hash key.  */
596   struct stmt_list_hash hash;
597
598   /* The number of symtabs from the line header.
599      The value here must match line_header.num_file_names.  */
600   unsigned int num_symtabs;
601
602   /* The symbol tables for this TU (obtained from the files listed in
603      DW_AT_stmt_list).
604      WARNING: The order of entries here must match the order of entries
605      in the line header.  After the first TU using this type_unit_group, the
606      line header for the subsequent TUs is recreated from this.  This is done
607      because we need to use the same symtabs for each TU using the same
608      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
609      there's no guarantee the line header doesn't have duplicate entries.  */
610   struct symtab **symtabs;
611 };
612
613 /* These sections are what may appear in a (real or virtual) DWO file.  */
614
615 struct dwo_sections
616 {
617   struct dwarf2_section_info abbrev;
618   struct dwarf2_section_info line;
619   struct dwarf2_section_info loc;
620   struct dwarf2_section_info loclists;
621   struct dwarf2_section_info macinfo;
622   struct dwarf2_section_info macro;
623   struct dwarf2_section_info str;
624   struct dwarf2_section_info str_offsets;
625   /* In the case of a virtual DWO file, these two are unused.  */
626   struct dwarf2_section_info info;
627   VEC (dwarf2_section_info_def) *types;
628 };
629
630 /* CUs/TUs in DWP/DWO files.  */
631
632 struct dwo_unit
633 {
634   /* Backlink to the containing struct dwo_file.  */
635   struct dwo_file *dwo_file;
636
637   /* The "id" that distinguishes this CU/TU.
638      .debug_info calls this "dwo_id", .debug_types calls this "signature".
639      Since signatures came first, we stick with it for consistency.  */
640   ULONGEST signature;
641
642   /* The section this CU/TU lives in, in the DWO file.  */
643   struct dwarf2_section_info *section;
644
645   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
646   sect_offset sect_off;
647   unsigned int length;
648
649   /* For types, offset in the type's DIE of the type defined by this TU.  */
650   cu_offset type_offset_in_tu;
651 };
652
653 /* include/dwarf2.h defines the DWP section codes.
654    It defines a max value but it doesn't define a min value, which we
655    use for error checking, so provide one.  */
656
657 enum dwp_v2_section_ids
658 {
659   DW_SECT_MIN = 1
660 };
661
662 /* Data for one DWO file.
663
664    This includes virtual DWO files (a virtual DWO file is a DWO file as it
665    appears in a DWP file).  DWP files don't really have DWO files per se -
666    comdat folding of types "loses" the DWO file they came from, and from
667    a high level view DWP files appear to contain a mass of random types.
668    However, to maintain consistency with the non-DWP case we pretend DWP
669    files contain virtual DWO files, and we assign each TU with one virtual
670    DWO file (generally based on the line and abbrev section offsets -
671    a heuristic that seems to work in practice).  */
672
673 struct dwo_file
674 {
675   /* The DW_AT_GNU_dwo_name attribute.
676      For virtual DWO files the name is constructed from the section offsets
677      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
678      from related CU+TUs.  */
679   const char *dwo_name;
680
681   /* The DW_AT_comp_dir attribute.  */
682   const char *comp_dir;
683
684   /* The bfd, when the file is open.  Otherwise this is NULL.
685      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
686   bfd *dbfd;
687
688   /* The sections that make up this DWO file.
689      Remember that for virtual DWO files in DWP V2, these are virtual
690      sections (for lack of a better name).  */
691   struct dwo_sections sections;
692
693   /* The CUs in the file.
694      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
695      an extension to handle LLVM's Link Time Optimization output (where
696      multiple source files may be compiled into a single object/dwo pair). */
697   htab_t cus;
698
699   /* Table of TUs in the file.
700      Each element is a struct dwo_unit.  */
701   htab_t tus;
702 };
703
704 /* These sections are what may appear in a DWP file.  */
705
706 struct dwp_sections
707 {
708   /* These are used by both DWP version 1 and 2.  */
709   struct dwarf2_section_info str;
710   struct dwarf2_section_info cu_index;
711   struct dwarf2_section_info tu_index;
712
713   /* These are only used by DWP version 2 files.
714      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
715      sections are referenced by section number, and are not recorded here.
716      In DWP version 2 there is at most one copy of all these sections, each
717      section being (effectively) comprised of the concatenation of all of the
718      individual sections that exist in the version 1 format.
719      To keep the code simple we treat each of these concatenated pieces as a
720      section itself (a virtual section?).  */
721   struct dwarf2_section_info abbrev;
722   struct dwarf2_section_info info;
723   struct dwarf2_section_info line;
724   struct dwarf2_section_info loc;
725   struct dwarf2_section_info macinfo;
726   struct dwarf2_section_info macro;
727   struct dwarf2_section_info str_offsets;
728   struct dwarf2_section_info types;
729 };
730
731 /* These sections are what may appear in a virtual DWO file in DWP version 1.
732    A virtual DWO file is a DWO file as it appears in a DWP file.  */
733
734 struct virtual_v1_dwo_sections
735 {
736   struct dwarf2_section_info abbrev;
737   struct dwarf2_section_info line;
738   struct dwarf2_section_info loc;
739   struct dwarf2_section_info macinfo;
740   struct dwarf2_section_info macro;
741   struct dwarf2_section_info str_offsets;
742   /* Each DWP hash table entry records one CU or one TU.
743      That is recorded here, and copied to dwo_unit.section.  */
744   struct dwarf2_section_info info_or_types;
745 };
746
747 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
748    In version 2, the sections of the DWO files are concatenated together
749    and stored in one section of that name.  Thus each ELF section contains
750    several "virtual" sections.  */
751
752 struct virtual_v2_dwo_sections
753 {
754   bfd_size_type abbrev_offset;
755   bfd_size_type abbrev_size;
756
757   bfd_size_type line_offset;
758   bfd_size_type line_size;
759
760   bfd_size_type loc_offset;
761   bfd_size_type loc_size;
762
763   bfd_size_type macinfo_offset;
764   bfd_size_type macinfo_size;
765
766   bfd_size_type macro_offset;
767   bfd_size_type macro_size;
768
769   bfd_size_type str_offsets_offset;
770   bfd_size_type str_offsets_size;
771
772   /* Each DWP hash table entry records one CU or one TU.
773      That is recorded here, and copied to dwo_unit.section.  */
774   bfd_size_type info_or_types_offset;
775   bfd_size_type info_or_types_size;
776 };
777
778 /* Contents of DWP hash tables.  */
779
780 struct dwp_hash_table
781 {
782   uint32_t version, nr_columns;
783   uint32_t nr_units, nr_slots;
784   const gdb_byte *hash_table, *unit_table;
785   union
786   {
787     struct
788     {
789       const gdb_byte *indices;
790     } v1;
791     struct
792     {
793       /* This is indexed by column number and gives the id of the section
794          in that column.  */
795 #define MAX_NR_V2_DWO_SECTIONS \
796   (1 /* .debug_info or .debug_types */ \
797    + 1 /* .debug_abbrev */ \
798    + 1 /* .debug_line */ \
799    + 1 /* .debug_loc */ \
800    + 1 /* .debug_str_offsets */ \
801    + 1 /* .debug_macro or .debug_macinfo */)
802       int section_ids[MAX_NR_V2_DWO_SECTIONS];
803       const gdb_byte *offsets;
804       const gdb_byte *sizes;
805     } v2;
806   } section_pool;
807 };
808
809 /* Data for one DWP file.  */
810
811 struct dwp_file
812 {
813   /* Name of the file.  */
814   const char *name;
815
816   /* File format version.  */
817   int version;
818
819   /* The bfd.  */
820   bfd *dbfd;
821
822   /* Section info for this file.  */
823   struct dwp_sections sections;
824
825   /* Table of CUs in the file.  */
826   const struct dwp_hash_table *cus;
827
828   /* Table of TUs in the file.  */
829   const struct dwp_hash_table *tus;
830
831   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
832   htab_t loaded_cus;
833   htab_t loaded_tus;
834
835   /* Table to map ELF section numbers to their sections.
836      This is only needed for the DWP V1 file format.  */
837   unsigned int num_sections;
838   asection **elf_sections;
839 };
840
841 /* This represents a '.dwz' file.  */
842
843 struct dwz_file
844 {
845   /* A dwz file can only contain a few sections.  */
846   struct dwarf2_section_info abbrev;
847   struct dwarf2_section_info info;
848   struct dwarf2_section_info str;
849   struct dwarf2_section_info line;
850   struct dwarf2_section_info macro;
851   struct dwarf2_section_info gdb_index;
852   struct dwarf2_section_info debug_names;
853
854   /* The dwz's BFD.  */
855   bfd *dwz_bfd;
856 };
857
858 /* Struct used to pass misc. parameters to read_die_and_children, et
859    al.  which are used for both .debug_info and .debug_types dies.
860    All parameters here are unchanging for the life of the call.  This
861    struct exists to abstract away the constant parameters of die reading.  */
862
863 struct die_reader_specs
864 {
865   /* The bfd of die_section.  */
866   bfd* abfd;
867
868   /* The CU of the DIE we are parsing.  */
869   struct dwarf2_cu *cu;
870
871   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
872   struct dwo_file *dwo_file;
873
874   /* The section the die comes from.
875      This is either .debug_info or .debug_types, or the .dwo variants.  */
876   struct dwarf2_section_info *die_section;
877
878   /* die_section->buffer.  */
879   const gdb_byte *buffer;
880
881   /* The end of the buffer.  */
882   const gdb_byte *buffer_end;
883
884   /* The value of the DW_AT_comp_dir attribute.  */
885   const char *comp_dir;
886
887   /* The abbreviation table to use when reading the DIEs.  */
888   struct abbrev_table *abbrev_table;
889 };
890
891 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
892 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
893                                       const gdb_byte *info_ptr,
894                                       struct die_info *comp_unit_die,
895                                       int has_children,
896                                       void *data);
897
898 /* A 1-based directory index.  This is a strong typedef to prevent
899    accidentally using a directory index as a 0-based index into an
900    array/vector.  */
901 enum class dir_index : unsigned int {};
902
903 /* Likewise, a 1-based file name index.  */
904 enum class file_name_index : unsigned int {};
905
906 struct file_entry
907 {
908   file_entry () = default;
909
910   file_entry (const char *name_, dir_index d_index_,
911               unsigned int mod_time_, unsigned int length_)
912     : name (name_),
913       d_index (d_index_),
914       mod_time (mod_time_),
915       length (length_)
916   {}
917
918   /* Return the include directory at D_INDEX stored in LH.  Returns
919      NULL if D_INDEX is out of bounds.  */
920   const char *include_dir (const line_header *lh) const;
921
922   /* The file name.  Note this is an observing pointer.  The memory is
923      owned by debug_line_buffer.  */
924   const char *name {};
925
926   /* The directory index (1-based).  */
927   dir_index d_index {};
928
929   unsigned int mod_time {};
930
931   unsigned int length {};
932
933   /* True if referenced by the Line Number Program.  */
934   bool included_p {};
935
936   /* The associated symbol table, if any.  */
937   struct symtab *symtab {};
938 };
939
940 /* The line number information for a compilation unit (found in the
941    .debug_line section) begins with a "statement program header",
942    which contains the following information.  */
943 struct line_header
944 {
945   line_header ()
946     : offset_in_dwz {}
947   {}
948
949   /* Add an entry to the include directory table.  */
950   void add_include_dir (const char *include_dir);
951
952   /* Add an entry to the file name table.  */
953   void add_file_name (const char *name, dir_index d_index,
954                       unsigned int mod_time, unsigned int length);
955
956   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
957      is out of bounds.  */
958   const char *include_dir_at (dir_index index) const
959   {
960     /* Convert directory index number (1-based) to vector index
961        (0-based).  */
962     size_t vec_index = to_underlying (index) - 1;
963
964     if (vec_index >= include_dirs.size ())
965       return NULL;
966     return include_dirs[vec_index];
967   }
968
969   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
970      is out of bounds.  */
971   file_entry *file_name_at (file_name_index index)
972   {
973     /* Convert file name index number (1-based) to vector index
974        (0-based).  */
975     size_t vec_index = to_underlying (index) - 1;
976
977     if (vec_index >= file_names.size ())
978       return NULL;
979     return &file_names[vec_index];
980   }
981
982   /* Const version of the above.  */
983   const file_entry *file_name_at (unsigned int index) const
984   {
985     if (index >= file_names.size ())
986       return NULL;
987     return &file_names[index];
988   }
989
990   /* Offset of line number information in .debug_line section.  */
991   sect_offset sect_off {};
992
993   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
994   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
995
996   unsigned int total_length {};
997   unsigned short version {};
998   unsigned int header_length {};
999   unsigned char minimum_instruction_length {};
1000   unsigned char maximum_ops_per_instruction {};
1001   unsigned char default_is_stmt {};
1002   int line_base {};
1003   unsigned char line_range {};
1004   unsigned char opcode_base {};
1005
1006   /* standard_opcode_lengths[i] is the number of operands for the
1007      standard opcode whose value is i.  This means that
1008      standard_opcode_lengths[0] is unused, and the last meaningful
1009      element is standard_opcode_lengths[opcode_base - 1].  */
1010   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1011
1012   /* The include_directories table.  Note these are observing
1013      pointers.  The memory is owned by debug_line_buffer.  */
1014   std::vector<const char *> include_dirs;
1015
1016   /* The file_names table.  */
1017   std::vector<file_entry> file_names;
1018
1019   /* The start and end of the statement program following this
1020      header.  These point into dwarf2_per_objfile->line_buffer.  */
1021   const gdb_byte *statement_program_start {}, *statement_program_end {};
1022 };
1023
1024 typedef std::unique_ptr<line_header> line_header_up;
1025
1026 const char *
1027 file_entry::include_dir (const line_header *lh) const
1028 {
1029   return lh->include_dir_at (d_index);
1030 }
1031
1032 /* When we construct a partial symbol table entry we only
1033    need this much information.  */
1034 struct partial_die_info : public allocate_on_obstack
1035   {
1036     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1037
1038     /* Disable assign but still keep copy ctor, which is needed
1039        load_partial_dies.   */
1040     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1041
1042     /* Adjust the partial die before generating a symbol for it.  This
1043        function may set the is_external flag or change the DIE's
1044        name.  */
1045     void fixup (struct dwarf2_cu *cu);
1046
1047     /* Read a minimal amount of information into the minimal die
1048        structure.  */
1049     const gdb_byte *read (const struct die_reader_specs *reader,
1050                           const struct abbrev_info &abbrev,
1051                           const gdb_byte *info_ptr);
1052
1053     /* Offset of this DIE.  */
1054     const sect_offset sect_off;
1055
1056     /* DWARF-2 tag for this DIE.  */
1057     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1058
1059     /* Assorted flags describing the data found in this DIE.  */
1060     const unsigned int has_children : 1;
1061
1062     unsigned int is_external : 1;
1063     unsigned int is_declaration : 1;
1064     unsigned int has_type : 1;
1065     unsigned int has_specification : 1;
1066     unsigned int has_pc_info : 1;
1067     unsigned int may_be_inlined : 1;
1068
1069     /* This DIE has been marked DW_AT_main_subprogram.  */
1070     unsigned int main_subprogram : 1;
1071
1072     /* Flag set if the SCOPE field of this structure has been
1073        computed.  */
1074     unsigned int scope_set : 1;
1075
1076     /* Flag set if the DIE has a byte_size attribute.  */
1077     unsigned int has_byte_size : 1;
1078
1079     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1080     unsigned int has_const_value : 1;
1081
1082     /* Flag set if any of the DIE's children are template arguments.  */
1083     unsigned int has_template_arguments : 1;
1084
1085     /* Flag set if fixup has been called on this die.  */
1086     unsigned int fixup_called : 1;
1087
1088     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1089     unsigned int is_dwz : 1;
1090
1091     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1092     unsigned int spec_is_dwz : 1;
1093
1094     /* The name of this DIE.  Normally the value of DW_AT_name, but
1095        sometimes a default name for unnamed DIEs.  */
1096     const char *name = nullptr;
1097
1098     /* The linkage name, if present.  */
1099     const char *linkage_name = nullptr;
1100
1101     /* The scope to prepend to our children.  This is generally
1102        allocated on the comp_unit_obstack, so will disappear
1103        when this compilation unit leaves the cache.  */
1104     const char *scope = nullptr;
1105
1106     /* Some data associated with the partial DIE.  The tag determines
1107        which field is live.  */
1108     union
1109     {
1110       /* The location description associated with this DIE, if any.  */
1111       struct dwarf_block *locdesc;
1112       /* The offset of an import, for DW_TAG_imported_unit.  */
1113       sect_offset sect_off;
1114     } d {};
1115
1116     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1117     CORE_ADDR lowpc = 0;
1118     CORE_ADDR highpc = 0;
1119
1120     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1121        DW_AT_sibling, if any.  */
1122     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1123        could return DW_AT_sibling values to its caller load_partial_dies.  */
1124     const gdb_byte *sibling = nullptr;
1125
1126     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1127        DW_AT_specification (or DW_AT_abstract_origin or
1128        DW_AT_extension).  */
1129     sect_offset spec_offset {};
1130
1131     /* Pointers to this DIE's parent, first child, and next sibling,
1132        if any.  */
1133     struct partial_die_info *die_parent = nullptr;
1134     struct partial_die_info *die_child = nullptr;
1135     struct partial_die_info *die_sibling = nullptr;
1136
1137     friend struct partial_die_info *
1138     dwarf2_cu::find_partial_die (sect_offset sect_off);
1139
1140   private:
1141     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1142     partial_die_info (sect_offset sect_off)
1143       : partial_die_info (sect_off, DW_TAG_padding, 0)
1144     {
1145     }
1146
1147     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1148                       int has_children_)
1149       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1150     {
1151       is_external = 0;
1152       is_declaration = 0;
1153       has_type = 0;
1154       has_specification = 0;
1155       has_pc_info = 0;
1156       may_be_inlined = 0;
1157       main_subprogram = 0;
1158       scope_set = 0;
1159       has_byte_size = 0;
1160       has_const_value = 0;
1161       has_template_arguments = 0;
1162       fixup_called = 0;
1163       is_dwz = 0;
1164       spec_is_dwz = 0;
1165     }
1166   };
1167
1168 /* This data structure holds the information of an abbrev.  */
1169 struct abbrev_info
1170   {
1171     unsigned int number;        /* number identifying abbrev */
1172     enum dwarf_tag tag;         /* dwarf tag */
1173     unsigned short has_children;                /* boolean */
1174     unsigned short num_attrs;   /* number of attributes */
1175     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1176     struct abbrev_info *next;   /* next in chain */
1177   };
1178
1179 struct attr_abbrev
1180   {
1181     ENUM_BITFIELD(dwarf_attribute) name : 16;
1182     ENUM_BITFIELD(dwarf_form) form : 16;
1183
1184     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1185     LONGEST implicit_const;
1186   };
1187
1188 /* Size of abbrev_table.abbrev_hash_table.  */
1189 #define ABBREV_HASH_SIZE 121
1190
1191 /* Top level data structure to contain an abbreviation table.  */
1192
1193 struct abbrev_table
1194 {
1195   explicit abbrev_table (sect_offset off)
1196     : sect_off (off)
1197   {
1198     m_abbrevs =
1199       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1200     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1201   }
1202
1203   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1204
1205   /* Allocate space for a struct abbrev_info object in
1206      ABBREV_TABLE.  */
1207   struct abbrev_info *alloc_abbrev ();
1208
1209   /* Add an abbreviation to the table.  */
1210   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1211
1212   /* Look up an abbrev in the table.
1213      Returns NULL if the abbrev is not found.  */
1214
1215   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1216
1217
1218   /* Where the abbrev table came from.
1219      This is used as a sanity check when the table is used.  */
1220   const sect_offset sect_off;
1221
1222   /* Storage for the abbrev table.  */
1223   auto_obstack abbrev_obstack;
1224
1225 private:
1226
1227   /* Hash table of abbrevs.
1228      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1229      It could be statically allocated, but the previous code didn't so we
1230      don't either.  */
1231   struct abbrev_info **m_abbrevs;
1232 };
1233
1234 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1235
1236 /* Attributes have a name and a value.  */
1237 struct attribute
1238   {
1239     ENUM_BITFIELD(dwarf_attribute) name : 16;
1240     ENUM_BITFIELD(dwarf_form) form : 15;
1241
1242     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1243        field should be in u.str (existing only for DW_STRING) but it is kept
1244        here for better struct attribute alignment.  */
1245     unsigned int string_is_canonical : 1;
1246
1247     union
1248       {
1249         const char *str;
1250         struct dwarf_block *blk;
1251         ULONGEST unsnd;
1252         LONGEST snd;
1253         CORE_ADDR addr;
1254         ULONGEST signature;
1255       }
1256     u;
1257   };
1258
1259 /* This data structure holds a complete die structure.  */
1260 struct die_info
1261   {
1262     /* DWARF-2 tag for this DIE.  */
1263     ENUM_BITFIELD(dwarf_tag) tag : 16;
1264
1265     /* Number of attributes */
1266     unsigned char num_attrs;
1267
1268     /* True if we're presently building the full type name for the
1269        type derived from this DIE.  */
1270     unsigned char building_fullname : 1;
1271
1272     /* True if this die is in process.  PR 16581.  */
1273     unsigned char in_process : 1;
1274
1275     /* Abbrev number */
1276     unsigned int abbrev;
1277
1278     /* Offset in .debug_info or .debug_types section.  */
1279     sect_offset sect_off;
1280
1281     /* The dies in a compilation unit form an n-ary tree.  PARENT
1282        points to this die's parent; CHILD points to the first child of
1283        this node; and all the children of a given node are chained
1284        together via their SIBLING fields.  */
1285     struct die_info *child;     /* Its first child, if any.  */
1286     struct die_info *sibling;   /* Its next sibling, if any.  */
1287     struct die_info *parent;    /* Its parent, if any.  */
1288
1289     /* An array of attributes, with NUM_ATTRS elements.  There may be
1290        zero, but it's not common and zero-sized arrays are not
1291        sufficiently portable C.  */
1292     struct attribute attrs[1];
1293   };
1294
1295 /* Get at parts of an attribute structure.  */
1296
1297 #define DW_STRING(attr)    ((attr)->u.str)
1298 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1299 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1300 #define DW_BLOCK(attr)     ((attr)->u.blk)
1301 #define DW_SND(attr)       ((attr)->u.snd)
1302 #define DW_ADDR(attr)      ((attr)->u.addr)
1303 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1304
1305 /* Blocks are a bunch of untyped bytes.  */
1306 struct dwarf_block
1307   {
1308     size_t size;
1309
1310     /* Valid only if SIZE is not zero.  */
1311     const gdb_byte *data;
1312   };
1313
1314 #ifndef ATTR_ALLOC_CHUNK
1315 #define ATTR_ALLOC_CHUNK 4
1316 #endif
1317
1318 /* Allocate fields for structs, unions and enums in this size.  */
1319 #ifndef DW_FIELD_ALLOC_CHUNK
1320 #define DW_FIELD_ALLOC_CHUNK 4
1321 #endif
1322
1323 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1324    but this would require a corresponding change in unpack_field_as_long
1325    and friends.  */
1326 static int bits_per_byte = 8;
1327
1328 /* When reading a variant or variant part, we track a bit more
1329    information about the field, and store it in an object of this
1330    type.  */
1331
1332 struct variant_field
1333 {
1334   /* If we see a DW_TAG_variant, then this will be the discriminant
1335      value.  */
1336   ULONGEST discriminant_value;
1337   /* If we see a DW_TAG_variant, then this will be set if this is the
1338      default branch.  */
1339   bool default_branch;
1340   /* While reading a DW_TAG_variant_part, this will be set if this
1341      field is the discriminant.  */
1342   bool is_discriminant;
1343 };
1344
1345 struct nextfield
1346 {
1347   int accessibility = 0;
1348   int virtuality = 0;
1349   /* Extra information to describe a variant or variant part.  */
1350   struct variant_field variant {};
1351   struct field field {};
1352 };
1353
1354 struct fnfieldlist
1355 {
1356   const char *name = nullptr;
1357   std::vector<struct fn_field> fnfields;
1358 };
1359
1360 /* The routines that read and process dies for a C struct or C++ class
1361    pass lists of data member fields and lists of member function fields
1362    in an instance of a field_info structure, as defined below.  */
1363 struct field_info
1364   {
1365     /* List of data member and baseclasses fields.  */
1366     std::vector<struct nextfield> fields;
1367     std::vector<struct nextfield> baseclasses;
1368
1369     /* Number of fields (including baseclasses).  */
1370     int nfields = 0;
1371
1372     /* Set if the accesibility of one of the fields is not public.  */
1373     int non_public_fields = 0;
1374
1375     /* Member function fieldlist array, contains name of possibly overloaded
1376        member function, number of overloaded member functions and a pointer
1377        to the head of the member function field chain.  */
1378     std::vector<struct fnfieldlist> fnfieldlists;
1379
1380     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1381        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1382     std::vector<struct decl_field> typedef_field_list;
1383
1384     /* Nested types defined by this class and the number of elements in this
1385        list.  */
1386     std::vector<struct decl_field> nested_types_list;
1387   };
1388
1389 /* One item on the queue of compilation units to read in full symbols
1390    for.  */
1391 struct dwarf2_queue_item
1392 {
1393   struct dwarf2_per_cu_data *per_cu;
1394   enum language pretend_language;
1395   struct dwarf2_queue_item *next;
1396 };
1397
1398 /* The current queue.  */
1399 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1400
1401 /* Loaded secondary compilation units are kept in memory until they
1402    have not been referenced for the processing of this many
1403    compilation units.  Set this to zero to disable caching.  Cache
1404    sizes of up to at least twenty will improve startup time for
1405    typical inter-CU-reference binaries, at an obvious memory cost.  */
1406 static int dwarf_max_cache_age = 5;
1407 static void
1408 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1409                           struct cmd_list_element *c, const char *value)
1410 {
1411   fprintf_filtered (file, _("The upper bound on the age of cached "
1412                             "DWARF compilation units is %s.\n"),
1413                     value);
1414 }
1415 \f
1416 /* local function prototypes */
1417
1418 static const char *get_section_name (const struct dwarf2_section_info *);
1419
1420 static const char *get_section_file_name (const struct dwarf2_section_info *);
1421
1422 static void dwarf2_find_base_address (struct die_info *die,
1423                                       struct dwarf2_cu *cu);
1424
1425 static struct partial_symtab *create_partial_symtab
1426   (struct dwarf2_per_cu_data *per_cu, const char *name);
1427
1428 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1429                                         const gdb_byte *info_ptr,
1430                                         struct die_info *type_unit_die,
1431                                         int has_children, void *data);
1432
1433 static void dwarf2_build_psymtabs_hard
1434   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1435
1436 static void scan_partial_symbols (struct partial_die_info *,
1437                                   CORE_ADDR *, CORE_ADDR *,
1438                                   int, struct dwarf2_cu *);
1439
1440 static void add_partial_symbol (struct partial_die_info *,
1441                                 struct dwarf2_cu *);
1442
1443 static void add_partial_namespace (struct partial_die_info *pdi,
1444                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1445                                    int set_addrmap, struct dwarf2_cu *cu);
1446
1447 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1448                                 CORE_ADDR *highpc, int set_addrmap,
1449                                 struct dwarf2_cu *cu);
1450
1451 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1452                                      struct dwarf2_cu *cu);
1453
1454 static void add_partial_subprogram (struct partial_die_info *pdi,
1455                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1456                                     int need_pc, struct dwarf2_cu *cu);
1457
1458 static void dwarf2_read_symtab (struct partial_symtab *,
1459                                 struct objfile *);
1460
1461 static void psymtab_to_symtab_1 (struct partial_symtab *);
1462
1463 static abbrev_table_up abbrev_table_read_table
1464   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1465    sect_offset);
1466
1467 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1468
1469 static struct partial_die_info *load_partial_dies
1470   (const struct die_reader_specs *, const gdb_byte *, int);
1471
1472 static struct partial_die_info *find_partial_die (sect_offset, int,
1473                                                   struct dwarf2_cu *);
1474
1475 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1476                                        struct attribute *, struct attr_abbrev *,
1477                                        const gdb_byte *);
1478
1479 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1480
1481 static int read_1_signed_byte (bfd *, const gdb_byte *);
1482
1483 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1484
1485 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1486
1487 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1488
1489 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1490                                unsigned int *);
1491
1492 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1493
1494 static LONGEST read_checked_initial_length_and_offset
1495   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1496    unsigned int *, unsigned int *);
1497
1498 static LONGEST read_offset (bfd *, const gdb_byte *,
1499                             const struct comp_unit_head *,
1500                             unsigned int *);
1501
1502 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1503
1504 static sect_offset read_abbrev_offset
1505   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1506    struct dwarf2_section_info *, sect_offset);
1507
1508 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1509
1510 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1511
1512 static const char *read_indirect_string
1513   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1514    const struct comp_unit_head *, unsigned int *);
1515
1516 static const char *read_indirect_line_string
1517   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1518    const struct comp_unit_head *, unsigned int *);
1519
1520 static const char *read_indirect_string_at_offset
1521   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1522    LONGEST str_offset);
1523
1524 static const char *read_indirect_string_from_dwz
1525   (struct objfile *objfile, struct dwz_file *, LONGEST);
1526
1527 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1528
1529 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1530                                               const gdb_byte *,
1531                                               unsigned int *);
1532
1533 static const char *read_str_index (const struct die_reader_specs *reader,
1534                                    ULONGEST str_index);
1535
1536 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1537
1538 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1539                                       struct dwarf2_cu *);
1540
1541 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1542                                                 unsigned int);
1543
1544 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1545                                        struct dwarf2_cu *cu);
1546
1547 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1548                                struct dwarf2_cu *cu);
1549
1550 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1551
1552 static struct die_info *die_specification (struct die_info *die,
1553                                            struct dwarf2_cu **);
1554
1555 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1556                                                 struct dwarf2_cu *cu);
1557
1558 static void dwarf_decode_lines (struct line_header *, const char *,
1559                                 struct dwarf2_cu *, struct partial_symtab *,
1560                                 CORE_ADDR, int decode_mapping);
1561
1562 static void dwarf2_start_subfile (const char *, const char *);
1563
1564 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1565                                                     const char *, const char *,
1566                                                     CORE_ADDR);
1567
1568 static struct symbol *new_symbol (struct die_info *, struct type *,
1569                                   struct dwarf2_cu *, struct symbol * = NULL);
1570
1571 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1572                                 struct dwarf2_cu *);
1573
1574 static void dwarf2_const_value_attr (const struct attribute *attr,
1575                                      struct type *type,
1576                                      const char *name,
1577                                      struct obstack *obstack,
1578                                      struct dwarf2_cu *cu, LONGEST *value,
1579                                      const gdb_byte **bytes,
1580                                      struct dwarf2_locexpr_baton **baton);
1581
1582 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1583
1584 static int need_gnat_info (struct dwarf2_cu *);
1585
1586 static struct type *die_descriptive_type (struct die_info *,
1587                                           struct dwarf2_cu *);
1588
1589 static void set_descriptive_type (struct type *, struct die_info *,
1590                                   struct dwarf2_cu *);
1591
1592 static struct type *die_containing_type (struct die_info *,
1593                                          struct dwarf2_cu *);
1594
1595 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1596                                      struct dwarf2_cu *);
1597
1598 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1599
1600 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1601
1602 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1603
1604 static char *typename_concat (struct obstack *obs, const char *prefix,
1605                               const char *suffix, int physname,
1606                               struct dwarf2_cu *cu);
1607
1608 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1609
1610 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1611
1612 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1613
1614 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1615
1616 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1617
1618 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1619
1620 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1621                                struct dwarf2_cu *, struct partial_symtab *);
1622
1623 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1624    values.  Keep the items ordered with increasing constraints compliance.  */
1625 enum pc_bounds_kind
1626 {
1627   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1628   PC_BOUNDS_NOT_PRESENT,
1629
1630   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1631      were present but they do not form a valid range of PC addresses.  */
1632   PC_BOUNDS_INVALID,
1633
1634   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1635   PC_BOUNDS_RANGES,
1636
1637   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1638   PC_BOUNDS_HIGH_LOW,
1639 };
1640
1641 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1642                                                  CORE_ADDR *, CORE_ADDR *,
1643                                                  struct dwarf2_cu *,
1644                                                  struct partial_symtab *);
1645
1646 static void get_scope_pc_bounds (struct die_info *,
1647                                  CORE_ADDR *, CORE_ADDR *,
1648                                  struct dwarf2_cu *);
1649
1650 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1651                                         CORE_ADDR, struct dwarf2_cu *);
1652
1653 static void dwarf2_add_field (struct field_info *, struct die_info *,
1654                               struct dwarf2_cu *);
1655
1656 static void dwarf2_attach_fields_to_type (struct field_info *,
1657                                           struct type *, struct dwarf2_cu *);
1658
1659 static void dwarf2_add_member_fn (struct field_info *,
1660                                   struct die_info *, struct type *,
1661                                   struct dwarf2_cu *);
1662
1663 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1664                                              struct type *,
1665                                              struct dwarf2_cu *);
1666
1667 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1668
1669 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1670
1671 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1672
1673 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1674
1675 static struct using_direct **using_directives (enum language);
1676
1677 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1678
1679 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1680
1681 static struct type *read_module_type (struct die_info *die,
1682                                       struct dwarf2_cu *cu);
1683
1684 static const char *namespace_name (struct die_info *die,
1685                                    int *is_anonymous, struct dwarf2_cu *);
1686
1687 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1688
1689 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1690
1691 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1692                                                        struct dwarf2_cu *);
1693
1694 static struct die_info *read_die_and_siblings_1
1695   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1696    struct die_info *);
1697
1698 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1699                                                const gdb_byte *info_ptr,
1700                                                const gdb_byte **new_info_ptr,
1701                                                struct die_info *parent);
1702
1703 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1704                                         struct die_info **, const gdb_byte *,
1705                                         int *, int);
1706
1707 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1708                                       struct die_info **, const gdb_byte *,
1709                                       int *);
1710
1711 static void process_die (struct die_info *, struct dwarf2_cu *);
1712
1713 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1714                                              struct obstack *);
1715
1716 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1717
1718 static const char *dwarf2_full_name (const char *name,
1719                                      struct die_info *die,
1720                                      struct dwarf2_cu *cu);
1721
1722 static const char *dwarf2_physname (const char *name, struct die_info *die,
1723                                     struct dwarf2_cu *cu);
1724
1725 static struct die_info *dwarf2_extension (struct die_info *die,
1726                                           struct dwarf2_cu **);
1727
1728 static const char *dwarf_tag_name (unsigned int);
1729
1730 static const char *dwarf_attr_name (unsigned int);
1731
1732 static const char *dwarf_form_name (unsigned int);
1733
1734 static const char *dwarf_bool_name (unsigned int);
1735
1736 static const char *dwarf_type_encoding_name (unsigned int);
1737
1738 static struct die_info *sibling_die (struct die_info *);
1739
1740 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1741
1742 static void dump_die_for_error (struct die_info *);
1743
1744 static void dump_die_1 (struct ui_file *, int level, int max_level,
1745                         struct die_info *);
1746
1747 /*static*/ void dump_die (struct die_info *, int max_level);
1748
1749 static void store_in_ref_table (struct die_info *,
1750                                 struct dwarf2_cu *);
1751
1752 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1753
1754 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1755
1756 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1757                                                const struct attribute *,
1758                                                struct dwarf2_cu **);
1759
1760 static struct die_info *follow_die_ref (struct die_info *,
1761                                         const struct attribute *,
1762                                         struct dwarf2_cu **);
1763
1764 static struct die_info *follow_die_sig (struct die_info *,
1765                                         const struct attribute *,
1766                                         struct dwarf2_cu **);
1767
1768 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1769                                          struct dwarf2_cu *);
1770
1771 static struct type *get_DW_AT_signature_type (struct die_info *,
1772                                               const struct attribute *,
1773                                               struct dwarf2_cu *);
1774
1775 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1776
1777 static void read_signatured_type (struct signatured_type *);
1778
1779 static int attr_to_dynamic_prop (const struct attribute *attr,
1780                                  struct die_info *die, struct dwarf2_cu *cu,
1781                                  struct dynamic_prop *prop);
1782
1783 /* memory allocation interface */
1784
1785 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1786
1787 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1788
1789 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1790
1791 static int attr_form_is_block (const struct attribute *);
1792
1793 static int attr_form_is_section_offset (const struct attribute *);
1794
1795 static int attr_form_is_constant (const struct attribute *);
1796
1797 static int attr_form_is_ref (const struct attribute *);
1798
1799 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1800                                    struct dwarf2_loclist_baton *baton,
1801                                    const struct attribute *attr);
1802
1803 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1804                                          struct symbol *sym,
1805                                          struct dwarf2_cu *cu,
1806                                          int is_block);
1807
1808 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1809                                      const gdb_byte *info_ptr,
1810                                      struct abbrev_info *abbrev);
1811
1812 static hashval_t partial_die_hash (const void *item);
1813
1814 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1815
1816 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1817   (sect_offset sect_off, unsigned int offset_in_dwz,
1818    struct dwarf2_per_objfile *dwarf2_per_objfile);
1819
1820 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1821                                    struct die_info *comp_unit_die,
1822                                    enum language pretend_language);
1823
1824 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1825
1826 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1827
1828 static struct type *set_die_type (struct die_info *, struct type *,
1829                                   struct dwarf2_cu *);
1830
1831 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1832
1833 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1834
1835 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1836                                  enum language);
1837
1838 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1839                                     enum language);
1840
1841 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1842                                     enum language);
1843
1844 static void dwarf2_add_dependence (struct dwarf2_cu *,
1845                                    struct dwarf2_per_cu_data *);
1846
1847 static void dwarf2_mark (struct dwarf2_cu *);
1848
1849 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1850
1851 static struct type *get_die_type_at_offset (sect_offset,
1852                                             struct dwarf2_per_cu_data *);
1853
1854 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1855
1856 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1857                              enum language pretend_language);
1858
1859 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1860
1861 /* Class, the destructor of which frees all allocated queue entries.  This
1862    will only have work to do if an error was thrown while processing the
1863    dwarf.  If no error was thrown then the queue entries should have all
1864    been processed, and freed, as we went along.  */
1865
1866 class dwarf2_queue_guard
1867 {
1868 public:
1869   dwarf2_queue_guard () = default;
1870
1871   /* Free any entries remaining on the queue.  There should only be
1872      entries left if we hit an error while processing the dwarf.  */
1873   ~dwarf2_queue_guard ()
1874   {
1875     struct dwarf2_queue_item *item, *last;
1876
1877     item = dwarf2_queue;
1878     while (item)
1879       {
1880         /* Anything still marked queued is likely to be in an
1881            inconsistent state, so discard it.  */
1882         if (item->per_cu->queued)
1883           {
1884             if (item->per_cu->cu != NULL)
1885               free_one_cached_comp_unit (item->per_cu);
1886             item->per_cu->queued = 0;
1887           }
1888
1889         last = item;
1890         item = item->next;
1891         xfree (last);
1892       }
1893
1894     dwarf2_queue = dwarf2_queue_tail = NULL;
1895   }
1896 };
1897
1898 /* The return type of find_file_and_directory.  Note, the enclosed
1899    string pointers are only valid while this object is valid.  */
1900
1901 struct file_and_directory
1902 {
1903   /* The filename.  This is never NULL.  */
1904   const char *name;
1905
1906   /* The compilation directory.  NULL if not known.  If we needed to
1907      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1908      points directly to the DW_AT_comp_dir string attribute owned by
1909      the obstack that owns the DIE.  */
1910   const char *comp_dir;
1911
1912   /* If we needed to build a new string for comp_dir, this is what
1913      owns the storage.  */
1914   std::string comp_dir_storage;
1915 };
1916
1917 static file_and_directory find_file_and_directory (struct die_info *die,
1918                                                    struct dwarf2_cu *cu);
1919
1920 static char *file_full_name (int file, struct line_header *lh,
1921                              const char *comp_dir);
1922
1923 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1924 enum class rcuh_kind { COMPILE, TYPE };
1925
1926 static const gdb_byte *read_and_check_comp_unit_head
1927   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1928    struct comp_unit_head *header,
1929    struct dwarf2_section_info *section,
1930    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1931    rcuh_kind section_kind);
1932
1933 static void init_cutu_and_read_dies
1934   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1935    int use_existing_cu, int keep, bool skip_partial,
1936    die_reader_func_ftype *die_reader_func, void *data);
1937
1938 static void init_cutu_and_read_dies_simple
1939   (struct dwarf2_per_cu_data *this_cu,
1940    die_reader_func_ftype *die_reader_func, void *data);
1941
1942 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1943
1944 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1945
1946 static struct dwo_unit *lookup_dwo_unit_in_dwp
1947   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1948    struct dwp_file *dwp_file, const char *comp_dir,
1949    ULONGEST signature, int is_debug_types);
1950
1951 static struct dwp_file *get_dwp_file
1952   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1953
1954 static struct dwo_unit *lookup_dwo_comp_unit
1955   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1956
1957 static struct dwo_unit *lookup_dwo_type_unit
1958   (struct signatured_type *, const char *, const char *);
1959
1960 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1961
1962 static void free_dwo_file (struct dwo_file *);
1963
1964 /* A unique_ptr helper to free a dwo_file.  */
1965
1966 struct dwo_file_deleter
1967 {
1968   void operator() (struct dwo_file *df) const
1969   {
1970     free_dwo_file (df);
1971   }
1972 };
1973
1974 /* A unique pointer to a dwo_file.  */
1975
1976 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
1977
1978 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1979
1980 static void check_producer (struct dwarf2_cu *cu);
1981
1982 static void free_line_header_voidp (void *arg);
1983 \f
1984 /* Various complaints about symbol reading that don't abort the process.  */
1985
1986 static void
1987 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1988 {
1989   complaint (&symfile_complaints,
1990              _("statement list doesn't fit in .debug_line section"));
1991 }
1992
1993 static void
1994 dwarf2_debug_line_missing_file_complaint (void)
1995 {
1996   complaint (&symfile_complaints,
1997              _(".debug_line section has line data without a file"));
1998 }
1999
2000 static void
2001 dwarf2_debug_line_missing_end_sequence_complaint (void)
2002 {
2003   complaint (&symfile_complaints,
2004              _(".debug_line section has line "
2005                "program sequence without an end"));
2006 }
2007
2008 static void
2009 dwarf2_complex_location_expr_complaint (void)
2010 {
2011   complaint (&symfile_complaints, _("location expression too complex"));
2012 }
2013
2014 static void
2015 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2016                                               int arg3)
2017 {
2018   complaint (&symfile_complaints,
2019              _("const value length mismatch for '%s', got %d, expected %d"),
2020              arg1, arg2, arg3);
2021 }
2022
2023 static void
2024 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2025 {
2026   complaint (&symfile_complaints,
2027              _("debug info runs off end of %s section"
2028                " [in module %s]"),
2029              get_section_name (section),
2030              get_section_file_name (section));
2031 }
2032
2033 static void
2034 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2035 {
2036   complaint (&symfile_complaints,
2037              _("macro debug info contains a "
2038                "malformed macro definition:\n`%s'"),
2039              arg1);
2040 }
2041
2042 static void
2043 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2044 {
2045   complaint (&symfile_complaints,
2046              _("invalid attribute class or form for '%s' in '%s'"),
2047              arg1, arg2);
2048 }
2049
2050 /* Hash function for line_header_hash.  */
2051
2052 static hashval_t
2053 line_header_hash (const struct line_header *ofs)
2054 {
2055   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2056 }
2057
2058 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2059
2060 static hashval_t
2061 line_header_hash_voidp (const void *item)
2062 {
2063   const struct line_header *ofs = (const struct line_header *) item;
2064
2065   return line_header_hash (ofs);
2066 }
2067
2068 /* Equality function for line_header_hash.  */
2069
2070 static int
2071 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2072 {
2073   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2074   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2075
2076   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2077           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2078 }
2079
2080 \f
2081
2082 /* Read the given attribute value as an address, taking the attribute's
2083    form into account.  */
2084
2085 static CORE_ADDR
2086 attr_value_as_address (struct attribute *attr)
2087 {
2088   CORE_ADDR addr;
2089
2090   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2091     {
2092       /* Aside from a few clearly defined exceptions, attributes that
2093          contain an address must always be in DW_FORM_addr form.
2094          Unfortunately, some compilers happen to be violating this
2095          requirement by encoding addresses using other forms, such
2096          as DW_FORM_data4 for example.  For those broken compilers,
2097          we try to do our best, without any guarantee of success,
2098          to interpret the address correctly.  It would also be nice
2099          to generate a complaint, but that would require us to maintain
2100          a list of legitimate cases where a non-address form is allowed,
2101          as well as update callers to pass in at least the CU's DWARF
2102          version.  This is more overhead than what we're willing to
2103          expand for a pretty rare case.  */
2104       addr = DW_UNSND (attr);
2105     }
2106   else
2107     addr = DW_ADDR (attr);
2108
2109   return addr;
2110 }
2111
2112 /* See declaration.  */
2113
2114 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2115                                         const dwarf2_debug_sections *names)
2116   : objfile (objfile_)
2117 {
2118   if (names == NULL)
2119     names = &dwarf2_elf_names;
2120
2121   bfd *obfd = objfile->obfd;
2122
2123   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2124     locate_sections (obfd, sec, *names);
2125 }
2126
2127 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2128
2129 dwarf2_per_objfile::~dwarf2_per_objfile ()
2130 {
2131   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2132   free_cached_comp_units ();
2133
2134   if (quick_file_names_table)
2135     htab_delete (quick_file_names_table);
2136
2137   if (line_header_hash)
2138     htab_delete (line_header_hash);
2139
2140   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2141     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2142
2143   for (signatured_type *sig_type : all_type_units)
2144     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2145
2146   VEC_free (dwarf2_section_info_def, types);
2147
2148   if (dwo_files != NULL)
2149     free_dwo_files (dwo_files, objfile);
2150   if (dwp_file != NULL)
2151     gdb_bfd_unref (dwp_file->dbfd);
2152
2153   if (dwz_file != NULL && dwz_file->dwz_bfd)
2154     gdb_bfd_unref (dwz_file->dwz_bfd);
2155
2156   if (index_table != NULL)
2157     index_table->~mapped_index ();
2158
2159   /* Everything else should be on the objfile obstack.  */
2160 }
2161
2162 /* See declaration.  */
2163
2164 void
2165 dwarf2_per_objfile::free_cached_comp_units ()
2166 {
2167   dwarf2_per_cu_data *per_cu = read_in_chain;
2168   dwarf2_per_cu_data **last_chain = &read_in_chain;
2169   while (per_cu != NULL)
2170     {
2171       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2172
2173       delete per_cu->cu;
2174       *last_chain = next_cu;
2175       per_cu = next_cu;
2176     }
2177 }
2178
2179 /* A helper class that calls free_cached_comp_units on
2180    destruction.  */
2181
2182 class free_cached_comp_units
2183 {
2184 public:
2185
2186   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2187     : m_per_objfile (per_objfile)
2188   {
2189   }
2190
2191   ~free_cached_comp_units ()
2192   {
2193     m_per_objfile->free_cached_comp_units ();
2194   }
2195
2196   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2197
2198 private:
2199
2200   dwarf2_per_objfile *m_per_objfile;
2201 };
2202
2203 /* Try to locate the sections we need for DWARF 2 debugging
2204    information and return true if we have enough to do something.
2205    NAMES points to the dwarf2 section names, or is NULL if the standard
2206    ELF names are used.  */
2207
2208 int
2209 dwarf2_has_info (struct objfile *objfile,
2210                  const struct dwarf2_debug_sections *names)
2211 {
2212   if (objfile->flags & OBJF_READNEVER)
2213     return 0;
2214
2215   struct dwarf2_per_objfile *dwarf2_per_objfile
2216     = get_dwarf2_per_objfile (objfile);
2217
2218   if (dwarf2_per_objfile == NULL)
2219     {
2220       /* Initialize per-objfile state.  */
2221       dwarf2_per_objfile
2222         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2223                                                                      names);
2224       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2225     }
2226   return (!dwarf2_per_objfile->info.is_virtual
2227           && dwarf2_per_objfile->info.s.section != NULL
2228           && !dwarf2_per_objfile->abbrev.is_virtual
2229           && dwarf2_per_objfile->abbrev.s.section != NULL);
2230 }
2231
2232 /* Return the containing section of virtual section SECTION.  */
2233
2234 static struct dwarf2_section_info *
2235 get_containing_section (const struct dwarf2_section_info *section)
2236 {
2237   gdb_assert (section->is_virtual);
2238   return section->s.containing_section;
2239 }
2240
2241 /* Return the bfd owner of SECTION.  */
2242
2243 static struct bfd *
2244 get_section_bfd_owner (const struct dwarf2_section_info *section)
2245 {
2246   if (section->is_virtual)
2247     {
2248       section = get_containing_section (section);
2249       gdb_assert (!section->is_virtual);
2250     }
2251   return section->s.section->owner;
2252 }
2253
2254 /* Return the bfd section of SECTION.
2255    Returns NULL if the section is not present.  */
2256
2257 static asection *
2258 get_section_bfd_section (const struct dwarf2_section_info *section)
2259 {
2260   if (section->is_virtual)
2261     {
2262       section = get_containing_section (section);
2263       gdb_assert (!section->is_virtual);
2264     }
2265   return section->s.section;
2266 }
2267
2268 /* Return the name of SECTION.  */
2269
2270 static const char *
2271 get_section_name (const struct dwarf2_section_info *section)
2272 {
2273   asection *sectp = get_section_bfd_section (section);
2274
2275   gdb_assert (sectp != NULL);
2276   return bfd_section_name (get_section_bfd_owner (section), sectp);
2277 }
2278
2279 /* Return the name of the file SECTION is in.  */
2280
2281 static const char *
2282 get_section_file_name (const struct dwarf2_section_info *section)
2283 {
2284   bfd *abfd = get_section_bfd_owner (section);
2285
2286   return bfd_get_filename (abfd);
2287 }
2288
2289 /* Return the id of SECTION.
2290    Returns 0 if SECTION doesn't exist.  */
2291
2292 static int
2293 get_section_id (const struct dwarf2_section_info *section)
2294 {
2295   asection *sectp = get_section_bfd_section (section);
2296
2297   if (sectp == NULL)
2298     return 0;
2299   return sectp->id;
2300 }
2301
2302 /* Return the flags of SECTION.
2303    SECTION (or containing section if this is a virtual section) must exist.  */
2304
2305 static int
2306 get_section_flags (const struct dwarf2_section_info *section)
2307 {
2308   asection *sectp = get_section_bfd_section (section);
2309
2310   gdb_assert (sectp != NULL);
2311   return bfd_get_section_flags (sectp->owner, sectp);
2312 }
2313
2314 /* When loading sections, we look either for uncompressed section or for
2315    compressed section names.  */
2316
2317 static int
2318 section_is_p (const char *section_name,
2319               const struct dwarf2_section_names *names)
2320 {
2321   if (names->normal != NULL
2322       && strcmp (section_name, names->normal) == 0)
2323     return 1;
2324   if (names->compressed != NULL
2325       && strcmp (section_name, names->compressed) == 0)
2326     return 1;
2327   return 0;
2328 }
2329
2330 /* See declaration.  */
2331
2332 void
2333 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2334                                      const dwarf2_debug_sections &names)
2335 {
2336   flagword aflag = bfd_get_section_flags (abfd, sectp);
2337
2338   if ((aflag & SEC_HAS_CONTENTS) == 0)
2339     {
2340     }
2341   else if (section_is_p (sectp->name, &names.info))
2342     {
2343       this->info.s.section = sectp;
2344       this->info.size = bfd_get_section_size (sectp);
2345     }
2346   else if (section_is_p (sectp->name, &names.abbrev))
2347     {
2348       this->abbrev.s.section = sectp;
2349       this->abbrev.size = bfd_get_section_size (sectp);
2350     }
2351   else if (section_is_p (sectp->name, &names.line))
2352     {
2353       this->line.s.section = sectp;
2354       this->line.size = bfd_get_section_size (sectp);
2355     }
2356   else if (section_is_p (sectp->name, &names.loc))
2357     {
2358       this->loc.s.section = sectp;
2359       this->loc.size = bfd_get_section_size (sectp);
2360     }
2361   else if (section_is_p (sectp->name, &names.loclists))
2362     {
2363       this->loclists.s.section = sectp;
2364       this->loclists.size = bfd_get_section_size (sectp);
2365     }
2366   else if (section_is_p (sectp->name, &names.macinfo))
2367     {
2368       this->macinfo.s.section = sectp;
2369       this->macinfo.size = bfd_get_section_size (sectp);
2370     }
2371   else if (section_is_p (sectp->name, &names.macro))
2372     {
2373       this->macro.s.section = sectp;
2374       this->macro.size = bfd_get_section_size (sectp);
2375     }
2376   else if (section_is_p (sectp->name, &names.str))
2377     {
2378       this->str.s.section = sectp;
2379       this->str.size = bfd_get_section_size (sectp);
2380     }
2381   else if (section_is_p (sectp->name, &names.line_str))
2382     {
2383       this->line_str.s.section = sectp;
2384       this->line_str.size = bfd_get_section_size (sectp);
2385     }
2386   else if (section_is_p (sectp->name, &names.addr))
2387     {
2388       this->addr.s.section = sectp;
2389       this->addr.size = bfd_get_section_size (sectp);
2390     }
2391   else if (section_is_p (sectp->name, &names.frame))
2392     {
2393       this->frame.s.section = sectp;
2394       this->frame.size = bfd_get_section_size (sectp);
2395     }
2396   else if (section_is_p (sectp->name, &names.eh_frame))
2397     {
2398       this->eh_frame.s.section = sectp;
2399       this->eh_frame.size = bfd_get_section_size (sectp);
2400     }
2401   else if (section_is_p (sectp->name, &names.ranges))
2402     {
2403       this->ranges.s.section = sectp;
2404       this->ranges.size = bfd_get_section_size (sectp);
2405     }
2406   else if (section_is_p (sectp->name, &names.rnglists))
2407     {
2408       this->rnglists.s.section = sectp;
2409       this->rnglists.size = bfd_get_section_size (sectp);
2410     }
2411   else if (section_is_p (sectp->name, &names.types))
2412     {
2413       struct dwarf2_section_info type_section;
2414
2415       memset (&type_section, 0, sizeof (type_section));
2416       type_section.s.section = sectp;
2417       type_section.size = bfd_get_section_size (sectp);
2418
2419       VEC_safe_push (dwarf2_section_info_def, this->types,
2420                      &type_section);
2421     }
2422   else if (section_is_p (sectp->name, &names.gdb_index))
2423     {
2424       this->gdb_index.s.section = sectp;
2425       this->gdb_index.size = bfd_get_section_size (sectp);
2426     }
2427   else if (section_is_p (sectp->name, &names.debug_names))
2428     {
2429       this->debug_names.s.section = sectp;
2430       this->debug_names.size = bfd_get_section_size (sectp);
2431     }
2432   else if (section_is_p (sectp->name, &names.debug_aranges))
2433     {
2434       this->debug_aranges.s.section = sectp;
2435       this->debug_aranges.size = bfd_get_section_size (sectp);
2436     }
2437
2438   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2439       && bfd_section_vma (abfd, sectp) == 0)
2440     this->has_section_at_zero = true;
2441 }
2442
2443 /* A helper function that decides whether a section is empty,
2444    or not present.  */
2445
2446 static int
2447 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2448 {
2449   if (section->is_virtual)
2450     return section->size == 0;
2451   return section->s.section == NULL || section->size == 0;
2452 }
2453
2454 /* See dwarf2read.h.  */
2455
2456 void
2457 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2458 {
2459   asection *sectp;
2460   bfd *abfd;
2461   gdb_byte *buf, *retbuf;
2462
2463   if (info->readin)
2464     return;
2465   info->buffer = NULL;
2466   info->readin = 1;
2467
2468   if (dwarf2_section_empty_p (info))
2469     return;
2470
2471   sectp = get_section_bfd_section (info);
2472
2473   /* If this is a virtual section we need to read in the real one first.  */
2474   if (info->is_virtual)
2475     {
2476       struct dwarf2_section_info *containing_section =
2477         get_containing_section (info);
2478
2479       gdb_assert (sectp != NULL);
2480       if ((sectp->flags & SEC_RELOC) != 0)
2481         {
2482           error (_("Dwarf Error: DWP format V2 with relocations is not"
2483                    " supported in section %s [in module %s]"),
2484                  get_section_name (info), get_section_file_name (info));
2485         }
2486       dwarf2_read_section (objfile, containing_section);
2487       /* Other code should have already caught virtual sections that don't
2488          fit.  */
2489       gdb_assert (info->virtual_offset + info->size
2490                   <= containing_section->size);
2491       /* If the real section is empty or there was a problem reading the
2492          section we shouldn't get here.  */
2493       gdb_assert (containing_section->buffer != NULL);
2494       info->buffer = containing_section->buffer + info->virtual_offset;
2495       return;
2496     }
2497
2498   /* If the section has relocations, we must read it ourselves.
2499      Otherwise we attach it to the BFD.  */
2500   if ((sectp->flags & SEC_RELOC) == 0)
2501     {
2502       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2503       return;
2504     }
2505
2506   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2507   info->buffer = buf;
2508
2509   /* When debugging .o files, we may need to apply relocations; see
2510      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2511      We never compress sections in .o files, so we only need to
2512      try this when the section is not compressed.  */
2513   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2514   if (retbuf != NULL)
2515     {
2516       info->buffer = retbuf;
2517       return;
2518     }
2519
2520   abfd = get_section_bfd_owner (info);
2521   gdb_assert (abfd != NULL);
2522
2523   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2524       || bfd_bread (buf, info->size, abfd) != info->size)
2525     {
2526       error (_("Dwarf Error: Can't read DWARF data"
2527                " in section %s [in module %s]"),
2528              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2529     }
2530 }
2531
2532 /* A helper function that returns the size of a section in a safe way.
2533    If you are positive that the section has been read before using the
2534    size, then it is safe to refer to the dwarf2_section_info object's
2535    "size" field directly.  In other cases, you must call this
2536    function, because for compressed sections the size field is not set
2537    correctly until the section has been read.  */
2538
2539 static bfd_size_type
2540 dwarf2_section_size (struct objfile *objfile,
2541                      struct dwarf2_section_info *info)
2542 {
2543   if (!info->readin)
2544     dwarf2_read_section (objfile, info);
2545   return info->size;
2546 }
2547
2548 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2549    SECTION_NAME.  */
2550
2551 void
2552 dwarf2_get_section_info (struct objfile *objfile,
2553                          enum dwarf2_section_enum sect,
2554                          asection **sectp, const gdb_byte **bufp,
2555                          bfd_size_type *sizep)
2556 {
2557   struct dwarf2_per_objfile *data
2558     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2559                                                   dwarf2_objfile_data_key);
2560   struct dwarf2_section_info *info;
2561
2562   /* We may see an objfile without any DWARF, in which case we just
2563      return nothing.  */
2564   if (data == NULL)
2565     {
2566       *sectp = NULL;
2567       *bufp = NULL;
2568       *sizep = 0;
2569       return;
2570     }
2571   switch (sect)
2572     {
2573     case DWARF2_DEBUG_FRAME:
2574       info = &data->frame;
2575       break;
2576     case DWARF2_EH_FRAME:
2577       info = &data->eh_frame;
2578       break;
2579     default:
2580       gdb_assert_not_reached ("unexpected section");
2581     }
2582
2583   dwarf2_read_section (objfile, info);
2584
2585   *sectp = get_section_bfd_section (info);
2586   *bufp = info->buffer;
2587   *sizep = info->size;
2588 }
2589
2590 /* A helper function to find the sections for a .dwz file.  */
2591
2592 static void
2593 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2594 {
2595   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2596
2597   /* Note that we only support the standard ELF names, because .dwz
2598      is ELF-only (at the time of writing).  */
2599   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2600     {
2601       dwz_file->abbrev.s.section = sectp;
2602       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2603     }
2604   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2605     {
2606       dwz_file->info.s.section = sectp;
2607       dwz_file->info.size = bfd_get_section_size (sectp);
2608     }
2609   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2610     {
2611       dwz_file->str.s.section = sectp;
2612       dwz_file->str.size = bfd_get_section_size (sectp);
2613     }
2614   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2615     {
2616       dwz_file->line.s.section = sectp;
2617       dwz_file->line.size = bfd_get_section_size (sectp);
2618     }
2619   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2620     {
2621       dwz_file->macro.s.section = sectp;
2622       dwz_file->macro.size = bfd_get_section_size (sectp);
2623     }
2624   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2625     {
2626       dwz_file->gdb_index.s.section = sectp;
2627       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2628     }
2629   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2630     {
2631       dwz_file->debug_names.s.section = sectp;
2632       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2633     }
2634 }
2635
2636 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2637    there is no .gnu_debugaltlink section in the file.  Error if there
2638    is such a section but the file cannot be found.  */
2639
2640 static struct dwz_file *
2641 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2642 {
2643   const char *filename;
2644   struct dwz_file *result;
2645   bfd_size_type buildid_len_arg;
2646   size_t buildid_len;
2647   bfd_byte *buildid;
2648
2649   if (dwarf2_per_objfile->dwz_file != NULL)
2650     return dwarf2_per_objfile->dwz_file;
2651
2652   bfd_set_error (bfd_error_no_error);
2653   gdb::unique_xmalloc_ptr<char> data
2654     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2655                                   &buildid_len_arg, &buildid));
2656   if (data == NULL)
2657     {
2658       if (bfd_get_error () == bfd_error_no_error)
2659         return NULL;
2660       error (_("could not read '.gnu_debugaltlink' section: %s"),
2661              bfd_errmsg (bfd_get_error ()));
2662     }
2663
2664   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2665
2666   buildid_len = (size_t) buildid_len_arg;
2667
2668   filename = data.get ();
2669
2670   std::string abs_storage;
2671   if (!IS_ABSOLUTE_PATH (filename))
2672     {
2673       gdb::unique_xmalloc_ptr<char> abs
2674         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2675
2676       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2677       filename = abs_storage.c_str ();
2678     }
2679
2680   /* First try the file name given in the section.  If that doesn't
2681      work, try to use the build-id instead.  */
2682   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2683   if (dwz_bfd != NULL)
2684     {
2685       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2686         dwz_bfd.release ();
2687     }
2688
2689   if (dwz_bfd == NULL)
2690     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2691
2692   if (dwz_bfd == NULL)
2693     error (_("could not find '.gnu_debugaltlink' file for %s"),
2694            objfile_name (dwarf2_per_objfile->objfile));
2695
2696   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2697                            struct dwz_file);
2698   result->dwz_bfd = dwz_bfd.release ();
2699
2700   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2701
2702   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2703   dwarf2_per_objfile->dwz_file = result;
2704   return result;
2705 }
2706 \f
2707 /* DWARF quick_symbols_functions support.  */
2708
2709 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2710    unique line tables, so we maintain a separate table of all .debug_line
2711    derived entries to support the sharing.
2712    All the quick functions need is the list of file names.  We discard the
2713    line_header when we're done and don't need to record it here.  */
2714 struct quick_file_names
2715 {
2716   /* The data used to construct the hash key.  */
2717   struct stmt_list_hash hash;
2718
2719   /* The number of entries in file_names, real_names.  */
2720   unsigned int num_file_names;
2721
2722   /* The file names from the line table, after being run through
2723      file_full_name.  */
2724   const char **file_names;
2725
2726   /* The file names from the line table after being run through
2727      gdb_realpath.  These are computed lazily.  */
2728   const char **real_names;
2729 };
2730
2731 /* When using the index (and thus not using psymtabs), each CU has an
2732    object of this type.  This is used to hold information needed by
2733    the various "quick" methods.  */
2734 struct dwarf2_per_cu_quick_data
2735 {
2736   /* The file table.  This can be NULL if there was no file table
2737      or it's currently not read in.
2738      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2739   struct quick_file_names *file_names;
2740
2741   /* The corresponding symbol table.  This is NULL if symbols for this
2742      CU have not yet been read.  */
2743   struct compunit_symtab *compunit_symtab;
2744
2745   /* A temporary mark bit used when iterating over all CUs in
2746      expand_symtabs_matching.  */
2747   unsigned int mark : 1;
2748
2749   /* True if we've tried to read the file table and found there isn't one.
2750      There will be no point in trying to read it again next time.  */
2751   unsigned int no_file_data : 1;
2752 };
2753
2754 /* Utility hash function for a stmt_list_hash.  */
2755
2756 static hashval_t
2757 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2758 {
2759   hashval_t v = 0;
2760
2761   if (stmt_list_hash->dwo_unit != NULL)
2762     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2763   v += to_underlying (stmt_list_hash->line_sect_off);
2764   return v;
2765 }
2766
2767 /* Utility equality function for a stmt_list_hash.  */
2768
2769 static int
2770 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2771                     const struct stmt_list_hash *rhs)
2772 {
2773   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2774     return 0;
2775   if (lhs->dwo_unit != NULL
2776       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2777     return 0;
2778
2779   return lhs->line_sect_off == rhs->line_sect_off;
2780 }
2781
2782 /* Hash function for a quick_file_names.  */
2783
2784 static hashval_t
2785 hash_file_name_entry (const void *e)
2786 {
2787   const struct quick_file_names *file_data
2788     = (const struct quick_file_names *) e;
2789
2790   return hash_stmt_list_entry (&file_data->hash);
2791 }
2792
2793 /* Equality function for a quick_file_names.  */
2794
2795 static int
2796 eq_file_name_entry (const void *a, const void *b)
2797 {
2798   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2799   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2800
2801   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2802 }
2803
2804 /* Delete function for a quick_file_names.  */
2805
2806 static void
2807 delete_file_name_entry (void *e)
2808 {
2809   struct quick_file_names *file_data = (struct quick_file_names *) e;
2810   int i;
2811
2812   for (i = 0; i < file_data->num_file_names; ++i)
2813     {
2814       xfree ((void*) file_data->file_names[i]);
2815       if (file_data->real_names)
2816         xfree ((void*) file_data->real_names[i]);
2817     }
2818
2819   /* The space for the struct itself lives on objfile_obstack,
2820      so we don't free it here.  */
2821 }
2822
2823 /* Create a quick_file_names hash table.  */
2824
2825 static htab_t
2826 create_quick_file_names_table (unsigned int nr_initial_entries)
2827 {
2828   return htab_create_alloc (nr_initial_entries,
2829                             hash_file_name_entry, eq_file_name_entry,
2830                             delete_file_name_entry, xcalloc, xfree);
2831 }
2832
2833 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2834    have to be created afterwards.  You should call age_cached_comp_units after
2835    processing PER_CU->CU.  dw2_setup must have been already called.  */
2836
2837 static void
2838 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2839 {
2840   if (per_cu->is_debug_types)
2841     load_full_type_unit (per_cu);
2842   else
2843     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2844
2845   if (per_cu->cu == NULL)
2846     return;  /* Dummy CU.  */
2847
2848   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2849 }
2850
2851 /* Read in the symbols for PER_CU.  */
2852
2853 static void
2854 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2855 {
2856   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2857
2858   /* Skip type_unit_groups, reading the type units they contain
2859      is handled elsewhere.  */
2860   if (IS_TYPE_UNIT_GROUP (per_cu))
2861     return;
2862
2863   /* The destructor of dwarf2_queue_guard frees any entries left on
2864      the queue.  After this point we're guaranteed to leave this function
2865      with the dwarf queue empty.  */
2866   dwarf2_queue_guard q_guard;
2867
2868   if (dwarf2_per_objfile->using_index
2869       ? per_cu->v.quick->compunit_symtab == NULL
2870       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2871     {
2872       queue_comp_unit (per_cu, language_minimal);
2873       load_cu (per_cu, skip_partial);
2874
2875       /* If we just loaded a CU from a DWO, and we're working with an index
2876          that may badly handle TUs, load all the TUs in that DWO as well.
2877          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2878       if (!per_cu->is_debug_types
2879           && per_cu->cu != NULL
2880           && per_cu->cu->dwo_unit != NULL
2881           && dwarf2_per_objfile->index_table != NULL
2882           && dwarf2_per_objfile->index_table->version <= 7
2883           /* DWP files aren't supported yet.  */
2884           && get_dwp_file (dwarf2_per_objfile) == NULL)
2885         queue_and_load_all_dwo_tus (per_cu);
2886     }
2887
2888   process_queue (dwarf2_per_objfile);
2889
2890   /* Age the cache, releasing compilation units that have not
2891      been used recently.  */
2892   age_cached_comp_units (dwarf2_per_objfile);
2893 }
2894
2895 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2896    the objfile from which this CU came.  Returns the resulting symbol
2897    table.  */
2898
2899 static struct compunit_symtab *
2900 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2901 {
2902   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2903
2904   gdb_assert (dwarf2_per_objfile->using_index);
2905   if (!per_cu->v.quick->compunit_symtab)
2906     {
2907       free_cached_comp_units freer (dwarf2_per_objfile);
2908       scoped_restore decrementer = increment_reading_symtab ();
2909       dw2_do_instantiate_symtab (per_cu, skip_partial);
2910       process_cu_includes (dwarf2_per_objfile);
2911     }
2912
2913   return per_cu->v.quick->compunit_symtab;
2914 }
2915
2916 /* See declaration.  */
2917
2918 dwarf2_per_cu_data *
2919 dwarf2_per_objfile::get_cutu (int index)
2920 {
2921   if (index >= this->all_comp_units.size ())
2922     {
2923       index -= this->all_comp_units.size ();
2924       gdb_assert (index < this->all_type_units.size ());
2925       return &this->all_type_units[index]->per_cu;
2926     }
2927
2928   return this->all_comp_units[index];
2929 }
2930
2931 /* See declaration.  */
2932
2933 dwarf2_per_cu_data *
2934 dwarf2_per_objfile::get_cu (int index)
2935 {
2936   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2937
2938   return this->all_comp_units[index];
2939 }
2940
2941 /* See declaration.  */
2942
2943 signatured_type *
2944 dwarf2_per_objfile::get_tu (int index)
2945 {
2946   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2947
2948   return this->all_type_units[index];
2949 }
2950
2951 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2952    objfile_obstack, and constructed with the specified field
2953    values.  */
2954
2955 static dwarf2_per_cu_data *
2956 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2957                           struct dwarf2_section_info *section,
2958                           int is_dwz,
2959                           sect_offset sect_off, ULONGEST length)
2960 {
2961   struct objfile *objfile = dwarf2_per_objfile->objfile;
2962   dwarf2_per_cu_data *the_cu
2963     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2964                      struct dwarf2_per_cu_data);
2965   the_cu->sect_off = sect_off;
2966   the_cu->length = length;
2967   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2968   the_cu->section = section;
2969   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2970                                    struct dwarf2_per_cu_quick_data);
2971   the_cu->is_dwz = is_dwz;
2972   return the_cu;
2973 }
2974
2975 /* A helper for create_cus_from_index that handles a given list of
2976    CUs.  */
2977
2978 static void
2979 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2980                             const gdb_byte *cu_list, offset_type n_elements,
2981                             struct dwarf2_section_info *section,
2982                             int is_dwz)
2983 {
2984   for (offset_type i = 0; i < n_elements; i += 2)
2985     {
2986       gdb_static_assert (sizeof (ULONGEST) >= 8);
2987
2988       sect_offset sect_off
2989         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2990       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2991       cu_list += 2 * 8;
2992
2993       dwarf2_per_cu_data *per_cu
2994         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2995                                      sect_off, length);
2996       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2997     }
2998 }
2999
3000 /* Read the CU list from the mapped index, and use it to create all
3001    the CU objects for this objfile.  */
3002
3003 static void
3004 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3005                        const gdb_byte *cu_list, offset_type cu_list_elements,
3006                        const gdb_byte *dwz_list, offset_type dwz_elements)
3007 {
3008   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3009   dwarf2_per_objfile->all_comp_units.reserve
3010     ((cu_list_elements + dwz_elements) / 2);
3011
3012   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3013                               &dwarf2_per_objfile->info, 0);
3014
3015   if (dwz_elements == 0)
3016     return;
3017
3018   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3019   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3020                               &dwz->info, 1);
3021 }
3022
3023 /* Create the signatured type hash table from the index.  */
3024
3025 static void
3026 create_signatured_type_table_from_index
3027   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3028    struct dwarf2_section_info *section,
3029    const gdb_byte *bytes,
3030    offset_type elements)
3031 {
3032   struct objfile *objfile = dwarf2_per_objfile->objfile;
3033
3034   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3035   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3036
3037   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3038
3039   for (offset_type i = 0; i < elements; i += 3)
3040     {
3041       struct signatured_type *sig_type;
3042       ULONGEST signature;
3043       void **slot;
3044       cu_offset type_offset_in_tu;
3045
3046       gdb_static_assert (sizeof (ULONGEST) >= 8);
3047       sect_offset sect_off
3048         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3049       type_offset_in_tu
3050         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3051                                                 BFD_ENDIAN_LITTLE);
3052       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3053       bytes += 3 * 8;
3054
3055       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3056                                  struct signatured_type);
3057       sig_type->signature = signature;
3058       sig_type->type_offset_in_tu = type_offset_in_tu;
3059       sig_type->per_cu.is_debug_types = 1;
3060       sig_type->per_cu.section = section;
3061       sig_type->per_cu.sect_off = sect_off;
3062       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3063       sig_type->per_cu.v.quick
3064         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3065                           struct dwarf2_per_cu_quick_data);
3066
3067       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3068       *slot = sig_type;
3069
3070       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3071     }
3072
3073   dwarf2_per_objfile->signatured_types = sig_types_hash;
3074 }
3075
3076 /* Create the signatured type hash table from .debug_names.  */
3077
3078 static void
3079 create_signatured_type_table_from_debug_names
3080   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3081    const mapped_debug_names &map,
3082    struct dwarf2_section_info *section,
3083    struct dwarf2_section_info *abbrev_section)
3084 {
3085   struct objfile *objfile = dwarf2_per_objfile->objfile;
3086
3087   dwarf2_read_section (objfile, section);
3088   dwarf2_read_section (objfile, abbrev_section);
3089
3090   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3091   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3092
3093   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3094
3095   for (uint32_t i = 0; i < map.tu_count; ++i)
3096     {
3097       struct signatured_type *sig_type;
3098       void **slot;
3099
3100       sect_offset sect_off
3101         = (sect_offset) (extract_unsigned_integer
3102                          (map.tu_table_reordered + i * map.offset_size,
3103                           map.offset_size,
3104                           map.dwarf5_byte_order));
3105
3106       comp_unit_head cu_header;
3107       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3108                                      abbrev_section,
3109                                      section->buffer + to_underlying (sect_off),
3110                                      rcuh_kind::TYPE);
3111
3112       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3113                                  struct signatured_type);
3114       sig_type->signature = cu_header.signature;
3115       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3116       sig_type->per_cu.is_debug_types = 1;
3117       sig_type->per_cu.section = section;
3118       sig_type->per_cu.sect_off = sect_off;
3119       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3120       sig_type->per_cu.v.quick
3121         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3122                           struct dwarf2_per_cu_quick_data);
3123
3124       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3125       *slot = sig_type;
3126
3127       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3128     }
3129
3130   dwarf2_per_objfile->signatured_types = sig_types_hash;
3131 }
3132
3133 /* Read the address map data from the mapped index, and use it to
3134    populate the objfile's psymtabs_addrmap.  */
3135
3136 static void
3137 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3138                            struct mapped_index *index)
3139 {
3140   struct objfile *objfile = dwarf2_per_objfile->objfile;
3141   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3142   const gdb_byte *iter, *end;
3143   struct addrmap *mutable_map;
3144   CORE_ADDR baseaddr;
3145
3146   auto_obstack temp_obstack;
3147
3148   mutable_map = addrmap_create_mutable (&temp_obstack);
3149
3150   iter = index->address_table.data ();
3151   end = iter + index->address_table.size ();
3152
3153   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3154
3155   while (iter < end)
3156     {
3157       ULONGEST hi, lo, cu_index;
3158       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3159       iter += 8;
3160       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3161       iter += 8;
3162       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3163       iter += 4;
3164
3165       if (lo > hi)
3166         {
3167           complaint (&symfile_complaints,
3168                      _(".gdb_index address table has invalid range (%s - %s)"),
3169                      hex_string (lo), hex_string (hi));
3170           continue;
3171         }
3172
3173       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3174         {
3175           complaint (&symfile_complaints,
3176                      _(".gdb_index address table has invalid CU number %u"),
3177                      (unsigned) cu_index);
3178           continue;
3179         }
3180
3181       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3182       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3183       addrmap_set_empty (mutable_map, lo, hi - 1,
3184                          dwarf2_per_objfile->get_cu (cu_index));
3185     }
3186
3187   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3188                                                     &objfile->objfile_obstack);
3189 }
3190
3191 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3192    populate the objfile's psymtabs_addrmap.  */
3193
3194 static void
3195 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3196                              struct dwarf2_section_info *section)
3197 {
3198   struct objfile *objfile = dwarf2_per_objfile->objfile;
3199   bfd *abfd = objfile->obfd;
3200   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3201   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3202                                        SECT_OFF_TEXT (objfile));
3203
3204   auto_obstack temp_obstack;
3205   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3206
3207   std::unordered_map<sect_offset,
3208                      dwarf2_per_cu_data *,
3209                      gdb::hash_enum<sect_offset>>
3210     debug_info_offset_to_per_cu;
3211   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3212     {
3213       const auto insertpair
3214         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3215       if (!insertpair.second)
3216         {
3217           warning (_("Section .debug_aranges in %s has duplicate "
3218                      "debug_info_offset %s, ignoring .debug_aranges."),
3219                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3220           return;
3221         }
3222     }
3223
3224   dwarf2_read_section (objfile, section);
3225
3226   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3227
3228   const gdb_byte *addr = section->buffer;
3229
3230   while (addr < section->buffer + section->size)
3231     {
3232       const gdb_byte *const entry_addr = addr;
3233       unsigned int bytes_read;
3234
3235       const LONGEST entry_length = read_initial_length (abfd, addr,
3236                                                         &bytes_read);
3237       addr += bytes_read;
3238
3239       const gdb_byte *const entry_end = addr + entry_length;
3240       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3241       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3242       if (addr + entry_length > section->buffer + section->size)
3243         {
3244           warning (_("Section .debug_aranges in %s entry at offset %zu "
3245                      "length %s exceeds section length %s, "
3246                      "ignoring .debug_aranges."),
3247                    objfile_name (objfile), entry_addr - section->buffer,
3248                    plongest (bytes_read + entry_length),
3249                    pulongest (section->size));
3250           return;
3251         }
3252
3253       /* The version number.  */
3254       const uint16_t version = read_2_bytes (abfd, addr);
3255       addr += 2;
3256       if (version != 2)
3257         {
3258           warning (_("Section .debug_aranges in %s entry at offset %zu "
3259                      "has unsupported version %d, ignoring .debug_aranges."),
3260                    objfile_name (objfile), entry_addr - section->buffer,
3261                    version);
3262           return;
3263         }
3264
3265       const uint64_t debug_info_offset
3266         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3267       addr += offset_size;
3268       const auto per_cu_it
3269         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3270       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3271         {
3272           warning (_("Section .debug_aranges in %s entry at offset %zu "
3273                      "debug_info_offset %s does not exists, "
3274                      "ignoring .debug_aranges."),
3275                    objfile_name (objfile), entry_addr - section->buffer,
3276                    pulongest (debug_info_offset));
3277           return;
3278         }
3279       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3280
3281       const uint8_t address_size = *addr++;
3282       if (address_size < 1 || address_size > 8)
3283         {
3284           warning (_("Section .debug_aranges in %s entry at offset %zu "
3285                      "address_size %u is invalid, ignoring .debug_aranges."),
3286                    objfile_name (objfile), entry_addr - section->buffer,
3287                    address_size);
3288           return;
3289         }
3290
3291       const uint8_t segment_selector_size = *addr++;
3292       if (segment_selector_size != 0)
3293         {
3294           warning (_("Section .debug_aranges in %s entry at offset %zu "
3295                      "segment_selector_size %u is not supported, "
3296                      "ignoring .debug_aranges."),
3297                    objfile_name (objfile), entry_addr - section->buffer,
3298                    segment_selector_size);
3299           return;
3300         }
3301
3302       /* Must pad to an alignment boundary that is twice the address
3303          size.  It is undocumented by the DWARF standard but GCC does
3304          use it.  */
3305       for (size_t padding = ((-(addr - section->buffer))
3306                              & (2 * address_size - 1));
3307            padding > 0; padding--)
3308         if (*addr++ != 0)
3309           {
3310             warning (_("Section .debug_aranges in %s entry at offset %zu "
3311                        "padding is not zero, ignoring .debug_aranges."),
3312                      objfile_name (objfile), entry_addr - section->buffer);
3313             return;
3314           }
3315
3316       for (;;)
3317         {
3318           if (addr + 2 * address_size > entry_end)
3319             {
3320               warning (_("Section .debug_aranges in %s entry at offset %zu "
3321                          "address list is not properly terminated, "
3322                          "ignoring .debug_aranges."),
3323                        objfile_name (objfile), entry_addr - section->buffer);
3324               return;
3325             }
3326           ULONGEST start = extract_unsigned_integer (addr, address_size,
3327                                                      dwarf5_byte_order);
3328           addr += address_size;
3329           ULONGEST length = extract_unsigned_integer (addr, address_size,
3330                                                       dwarf5_byte_order);
3331           addr += address_size;
3332           if (start == 0 && length == 0)
3333             break;
3334           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3335             {
3336               /* Symbol was eliminated due to a COMDAT group.  */
3337               continue;
3338             }
3339           ULONGEST end = start + length;
3340           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3341           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3342           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3343         }
3344     }
3345
3346   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3347                                                     &objfile->objfile_obstack);
3348 }
3349
3350 /* Find a slot in the mapped index INDEX for the object named NAME.
3351    If NAME is found, set *VEC_OUT to point to the CU vector in the
3352    constant pool and return true.  If NAME cannot be found, return
3353    false.  */
3354
3355 static bool
3356 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3357                           offset_type **vec_out)
3358 {
3359   offset_type hash;
3360   offset_type slot, step;
3361   int (*cmp) (const char *, const char *);
3362
3363   gdb::unique_xmalloc_ptr<char> without_params;
3364   if (current_language->la_language == language_cplus
3365       || current_language->la_language == language_fortran
3366       || current_language->la_language == language_d)
3367     {
3368       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3369          not contain any.  */
3370
3371       if (strchr (name, '(') != NULL)
3372         {
3373           without_params = cp_remove_params (name);
3374
3375           if (without_params != NULL)
3376             name = without_params.get ();
3377         }
3378     }
3379
3380   /* Index version 4 did not support case insensitive searches.  But the
3381      indices for case insensitive languages are built in lowercase, therefore
3382      simulate our NAME being searched is also lowercased.  */
3383   hash = mapped_index_string_hash ((index->version == 4
3384                                     && case_sensitivity == case_sensitive_off
3385                                     ? 5 : index->version),
3386                                    name);
3387
3388   slot = hash & (index->symbol_table.size () - 1);
3389   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3390   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3391
3392   for (;;)
3393     {
3394       const char *str;
3395
3396       const auto &bucket = index->symbol_table[slot];
3397       if (bucket.name == 0 && bucket.vec == 0)
3398         return false;
3399
3400       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3401       if (!cmp (name, str))
3402         {
3403           *vec_out = (offset_type *) (index->constant_pool
3404                                       + MAYBE_SWAP (bucket.vec));
3405           return true;
3406         }
3407
3408       slot = (slot + step) & (index->symbol_table.size () - 1);
3409     }
3410 }
3411
3412 /* A helper function that reads the .gdb_index from SECTION and fills
3413    in MAP.  FILENAME is the name of the file containing the section;
3414    it is used for error reporting.  DEPRECATED_OK is true if it is
3415    ok to use deprecated sections.
3416
3417    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3418    out parameters that are filled in with information about the CU and
3419    TU lists in the section.
3420
3421    Returns 1 if all went well, 0 otherwise.  */
3422
3423 static bool
3424 read_index_from_section (struct objfile *objfile,
3425                          const char *filename,
3426                          bool deprecated_ok,
3427                          struct dwarf2_section_info *section,
3428                          struct mapped_index *map,
3429                          const gdb_byte **cu_list,
3430                          offset_type *cu_list_elements,
3431                          const gdb_byte **types_list,
3432                          offset_type *types_list_elements)
3433 {
3434   const gdb_byte *addr;
3435   offset_type version;
3436   offset_type *metadata;
3437   int i;
3438
3439   if (dwarf2_section_empty_p (section))
3440     return 0;
3441
3442   /* Older elfutils strip versions could keep the section in the main
3443      executable while splitting it for the separate debug info file.  */
3444   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3445     return 0;
3446
3447   dwarf2_read_section (objfile, section);
3448
3449   addr = section->buffer;
3450   /* Version check.  */
3451   version = MAYBE_SWAP (*(offset_type *) addr);
3452   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3453      causes the index to behave very poorly for certain requests.  Version 3
3454      contained incomplete addrmap.  So, it seems better to just ignore such
3455      indices.  */
3456   if (version < 4)
3457     {
3458       static int warning_printed = 0;
3459       if (!warning_printed)
3460         {
3461           warning (_("Skipping obsolete .gdb_index section in %s."),
3462                    filename);
3463           warning_printed = 1;
3464         }
3465       return 0;
3466     }
3467   /* Index version 4 uses a different hash function than index version
3468      5 and later.
3469
3470      Versions earlier than 6 did not emit psymbols for inlined
3471      functions.  Using these files will cause GDB not to be able to
3472      set breakpoints on inlined functions by name, so we ignore these
3473      indices unless the user has done
3474      "set use-deprecated-index-sections on".  */
3475   if (version < 6 && !deprecated_ok)
3476     {
3477       static int warning_printed = 0;
3478       if (!warning_printed)
3479         {
3480           warning (_("\
3481 Skipping deprecated .gdb_index section in %s.\n\
3482 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3483 to use the section anyway."),
3484                    filename);
3485           warning_printed = 1;
3486         }
3487       return 0;
3488     }
3489   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3490      of the TU (for symbols coming from TUs),
3491      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3492      Plus gold-generated indices can have duplicate entries for global symbols,
3493      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3494      These are just performance bugs, and we can't distinguish gdb-generated
3495      indices from gold-generated ones, so issue no warning here.  */
3496
3497   /* Indexes with higher version than the one supported by GDB may be no
3498      longer backward compatible.  */
3499   if (version > 8)
3500     return 0;
3501
3502   map->version = version;
3503   map->total_size = section->size;
3504
3505   metadata = (offset_type *) (addr + sizeof (offset_type));
3506
3507   i = 0;
3508   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3509   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3510                        / 8);
3511   ++i;
3512
3513   *types_list = addr + MAYBE_SWAP (metadata[i]);
3514   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3515                            - MAYBE_SWAP (metadata[i]))
3516                           / 8);
3517   ++i;
3518
3519   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3520   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3521   map->address_table
3522     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3523   ++i;
3524
3525   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3526   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3527   map->symbol_table
3528     = gdb::array_view<mapped_index::symbol_table_slot>
3529        ((mapped_index::symbol_table_slot *) symbol_table,
3530         (mapped_index::symbol_table_slot *) symbol_table_end);
3531
3532   ++i;
3533   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3534
3535   return 1;
3536 }
3537
3538 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3539    elements of all the CUs and return 1.  Otherwise, return 0.  */
3540
3541 static int
3542 dwarf2_read_index (struct dwarf2_per_objfile *dwarf2_per_objfile)
3543 {
3544   struct mapped_index local_map, *map;
3545   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3546   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3547   struct dwz_file *dwz;
3548   struct objfile *objfile = dwarf2_per_objfile->objfile;
3549
3550   if (!read_index_from_section (objfile, objfile_name (objfile),
3551                                 use_deprecated_index_sections,
3552                                 &dwarf2_per_objfile->gdb_index, &local_map,
3553                                 &cu_list, &cu_list_elements,
3554                                 &types_list, &types_list_elements))
3555     return 0;
3556
3557   /* Don't use the index if it's empty.  */
3558   if (local_map.symbol_table.empty ())
3559     return 0;
3560
3561   /* If there is a .dwz file, read it so we can get its CU list as
3562      well.  */
3563   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3564   if (dwz != NULL)
3565     {
3566       struct mapped_index dwz_map;
3567       const gdb_byte *dwz_types_ignore;
3568       offset_type dwz_types_elements_ignore;
3569
3570       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3571                                     1,
3572                                     &dwz->gdb_index, &dwz_map,
3573                                     &dwz_list, &dwz_list_elements,
3574                                     &dwz_types_ignore,
3575                                     &dwz_types_elements_ignore))
3576         {
3577           warning (_("could not read '.gdb_index' section from %s; skipping"),
3578                    bfd_get_filename (dwz->dwz_bfd));
3579           return 0;
3580         }
3581     }
3582
3583   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3584                          dwz_list, dwz_list_elements);
3585
3586   if (types_list_elements)
3587     {
3588       struct dwarf2_section_info *section;
3589
3590       /* We can only handle a single .debug_types when we have an
3591          index.  */
3592       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3593         return 0;
3594
3595       section = VEC_index (dwarf2_section_info_def,
3596                            dwarf2_per_objfile->types, 0);
3597
3598       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3599                                                types_list, types_list_elements);
3600     }
3601
3602   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3603
3604   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3605   map = new (map) mapped_index ();
3606   *map = local_map;
3607
3608   dwarf2_per_objfile->index_table = map;
3609   dwarf2_per_objfile->using_index = 1;
3610   dwarf2_per_objfile->quick_file_names_table =
3611     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3612
3613   return 1;
3614 }
3615
3616 /* die_reader_func for dw2_get_file_names.  */
3617
3618 static void
3619 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3620                            const gdb_byte *info_ptr,
3621                            struct die_info *comp_unit_die,
3622                            int has_children,
3623                            void *data)
3624 {
3625   struct dwarf2_cu *cu = reader->cu;
3626   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3627   struct dwarf2_per_objfile *dwarf2_per_objfile
3628     = cu->per_cu->dwarf2_per_objfile;
3629   struct objfile *objfile = dwarf2_per_objfile->objfile;
3630   struct dwarf2_per_cu_data *lh_cu;
3631   struct attribute *attr;
3632   int i;
3633   void **slot;
3634   struct quick_file_names *qfn;
3635
3636   gdb_assert (! this_cu->is_debug_types);
3637
3638   /* Our callers never want to match partial units -- instead they
3639      will match the enclosing full CU.  */
3640   if (comp_unit_die->tag == DW_TAG_partial_unit)
3641     {
3642       this_cu->v.quick->no_file_data = 1;
3643       return;
3644     }
3645
3646   lh_cu = this_cu;
3647   slot = NULL;
3648
3649   line_header_up lh;
3650   sect_offset line_offset {};
3651
3652   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3653   if (attr)
3654     {
3655       struct quick_file_names find_entry;
3656
3657       line_offset = (sect_offset) DW_UNSND (attr);
3658
3659       /* We may have already read in this line header (TU line header sharing).
3660          If we have we're done.  */
3661       find_entry.hash.dwo_unit = cu->dwo_unit;
3662       find_entry.hash.line_sect_off = line_offset;
3663       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3664                              &find_entry, INSERT);
3665       if (*slot != NULL)
3666         {
3667           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3668           return;
3669         }
3670
3671       lh = dwarf_decode_line_header (line_offset, cu);
3672     }
3673   if (lh == NULL)
3674     {
3675       lh_cu->v.quick->no_file_data = 1;
3676       return;
3677     }
3678
3679   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3680   qfn->hash.dwo_unit = cu->dwo_unit;
3681   qfn->hash.line_sect_off = line_offset;
3682   gdb_assert (slot != NULL);
3683   *slot = qfn;
3684
3685   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3686
3687   qfn->num_file_names = lh->file_names.size ();
3688   qfn->file_names =
3689     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3690   for (i = 0; i < lh->file_names.size (); ++i)
3691     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3692   qfn->real_names = NULL;
3693
3694   lh_cu->v.quick->file_names = qfn;
3695 }
3696
3697 /* A helper for the "quick" functions which attempts to read the line
3698    table for THIS_CU.  */
3699
3700 static struct quick_file_names *
3701 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3702 {
3703   /* This should never be called for TUs.  */
3704   gdb_assert (! this_cu->is_debug_types);
3705   /* Nor type unit groups.  */
3706   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3707
3708   if (this_cu->v.quick->file_names != NULL)
3709     return this_cu->v.quick->file_names;
3710   /* If we know there is no line data, no point in looking again.  */
3711   if (this_cu->v.quick->no_file_data)
3712     return NULL;
3713
3714   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3715
3716   if (this_cu->v.quick->no_file_data)
3717     return NULL;
3718   return this_cu->v.quick->file_names;
3719 }
3720
3721 /* A helper for the "quick" functions which computes and caches the
3722    real path for a given file name from the line table.  */
3723
3724 static const char *
3725 dw2_get_real_path (struct objfile *objfile,
3726                    struct quick_file_names *qfn, int index)
3727 {
3728   if (qfn->real_names == NULL)
3729     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3730                                       qfn->num_file_names, const char *);
3731
3732   if (qfn->real_names[index] == NULL)
3733     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3734
3735   return qfn->real_names[index];
3736 }
3737
3738 static struct symtab *
3739 dw2_find_last_source_symtab (struct objfile *objfile)
3740 {
3741   struct dwarf2_per_objfile *dwarf2_per_objfile
3742     = get_dwarf2_per_objfile (objfile);
3743   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3744   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3745
3746   if (cust == NULL)
3747     return NULL;
3748
3749   return compunit_primary_filetab (cust);
3750 }
3751
3752 /* Traversal function for dw2_forget_cached_source_info.  */
3753
3754 static int
3755 dw2_free_cached_file_names (void **slot, void *info)
3756 {
3757   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3758
3759   if (file_data->real_names)
3760     {
3761       int i;
3762
3763       for (i = 0; i < file_data->num_file_names; ++i)
3764         {
3765           xfree ((void*) file_data->real_names[i]);
3766           file_data->real_names[i] = NULL;
3767         }
3768     }
3769
3770   return 1;
3771 }
3772
3773 static void
3774 dw2_forget_cached_source_info (struct objfile *objfile)
3775 {
3776   struct dwarf2_per_objfile *dwarf2_per_objfile
3777     = get_dwarf2_per_objfile (objfile);
3778
3779   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3780                           dw2_free_cached_file_names, NULL);
3781 }
3782
3783 /* Helper function for dw2_map_symtabs_matching_filename that expands
3784    the symtabs and calls the iterator.  */
3785
3786 static int
3787 dw2_map_expand_apply (struct objfile *objfile,
3788                       struct dwarf2_per_cu_data *per_cu,
3789                       const char *name, const char *real_path,
3790                       gdb::function_view<bool (symtab *)> callback)
3791 {
3792   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3793
3794   /* Don't visit already-expanded CUs.  */
3795   if (per_cu->v.quick->compunit_symtab)
3796     return 0;
3797
3798   /* This may expand more than one symtab, and we want to iterate over
3799      all of them.  */
3800   dw2_instantiate_symtab (per_cu, false);
3801
3802   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3803                                     last_made, callback);
3804 }
3805
3806 /* Implementation of the map_symtabs_matching_filename method.  */
3807
3808 static bool
3809 dw2_map_symtabs_matching_filename
3810   (struct objfile *objfile, const char *name, const char *real_path,
3811    gdb::function_view<bool (symtab *)> callback)
3812 {
3813   const char *name_basename = lbasename (name);
3814   struct dwarf2_per_objfile *dwarf2_per_objfile
3815     = get_dwarf2_per_objfile (objfile);
3816
3817   /* The rule is CUs specify all the files, including those used by
3818      any TU, so there's no need to scan TUs here.  */
3819
3820   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3821     {
3822       /* We only need to look at symtabs not already expanded.  */
3823       if (per_cu->v.quick->compunit_symtab)
3824         continue;
3825
3826       quick_file_names *file_data = dw2_get_file_names (per_cu);
3827       if (file_data == NULL)
3828         continue;
3829
3830       for (int j = 0; j < file_data->num_file_names; ++j)
3831         {
3832           const char *this_name = file_data->file_names[j];
3833           const char *this_real_name;
3834
3835           if (compare_filenames_for_search (this_name, name))
3836             {
3837               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3838                                         callback))
3839                 return true;
3840               continue;
3841             }
3842
3843           /* Before we invoke realpath, which can get expensive when many
3844              files are involved, do a quick comparison of the basenames.  */
3845           if (! basenames_may_differ
3846               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3847             continue;
3848
3849           this_real_name = dw2_get_real_path (objfile, file_data, j);
3850           if (compare_filenames_for_search (this_real_name, name))
3851             {
3852               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3853                                         callback))
3854                 return true;
3855               continue;
3856             }
3857
3858           if (real_path != NULL)
3859             {
3860               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3861               gdb_assert (IS_ABSOLUTE_PATH (name));
3862               if (this_real_name != NULL
3863                   && FILENAME_CMP (real_path, this_real_name) == 0)
3864                 {
3865                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3866                                             callback))
3867                     return true;
3868                   continue;
3869                 }
3870             }
3871         }
3872     }
3873
3874   return false;
3875 }
3876
3877 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3878
3879 struct dw2_symtab_iterator
3880 {
3881   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3882   struct dwarf2_per_objfile *dwarf2_per_objfile;
3883   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3884   int want_specific_block;
3885   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3886      Unused if !WANT_SPECIFIC_BLOCK.  */
3887   int block_index;
3888   /* The kind of symbol we're looking for.  */
3889   domain_enum domain;
3890   /* The list of CUs from the index entry of the symbol,
3891      or NULL if not found.  */
3892   offset_type *vec;
3893   /* The next element in VEC to look at.  */
3894   int next;
3895   /* The number of elements in VEC, or zero if there is no match.  */
3896   int length;
3897   /* Have we seen a global version of the symbol?
3898      If so we can ignore all further global instances.
3899      This is to work around gold/15646, inefficient gold-generated
3900      indices.  */
3901   int global_seen;
3902 };
3903
3904 /* Initialize the index symtab iterator ITER.
3905    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3906    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3907
3908 static void
3909 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3910                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3911                       int want_specific_block,
3912                       int block_index,
3913                       domain_enum domain,
3914                       const char *name)
3915 {
3916   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3917   iter->want_specific_block = want_specific_block;
3918   iter->block_index = block_index;
3919   iter->domain = domain;
3920   iter->next = 0;
3921   iter->global_seen = 0;
3922
3923   mapped_index *index = dwarf2_per_objfile->index_table;
3924
3925   /* index is NULL if OBJF_READNOW.  */
3926   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3927     iter->length = MAYBE_SWAP (*iter->vec);
3928   else
3929     {
3930       iter->vec = NULL;
3931       iter->length = 0;
3932     }
3933 }
3934
3935 /* Return the next matching CU or NULL if there are no more.  */
3936
3937 static struct dwarf2_per_cu_data *
3938 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3939 {
3940   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3941
3942   for ( ; iter->next < iter->length; ++iter->next)
3943     {
3944       offset_type cu_index_and_attrs =
3945         MAYBE_SWAP (iter->vec[iter->next + 1]);
3946       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3947       int want_static = iter->block_index != GLOBAL_BLOCK;
3948       /* This value is only valid for index versions >= 7.  */
3949       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3950       gdb_index_symbol_kind symbol_kind =
3951         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3952       /* Only check the symbol attributes if they're present.
3953          Indices prior to version 7 don't record them,
3954          and indices >= 7 may elide them for certain symbols
3955          (gold does this).  */
3956       int attrs_valid =
3957         (dwarf2_per_objfile->index_table->version >= 7
3958          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3959
3960       /* Don't crash on bad data.  */
3961       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3962                        + dwarf2_per_objfile->all_type_units.size ()))
3963         {
3964           complaint (&symfile_complaints,
3965                      _(".gdb_index entry has bad CU index"
3966                        " [in module %s]"),
3967                      objfile_name (dwarf2_per_objfile->objfile));
3968           continue;
3969         }
3970
3971       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3972
3973       /* Skip if already read in.  */
3974       if (per_cu->v.quick->compunit_symtab)
3975         continue;
3976
3977       /* Check static vs global.  */
3978       if (attrs_valid)
3979         {
3980           if (iter->want_specific_block
3981               && want_static != is_static)
3982             continue;
3983           /* Work around gold/15646.  */
3984           if (!is_static && iter->global_seen)
3985             continue;
3986           if (!is_static)
3987             iter->global_seen = 1;
3988         }
3989
3990       /* Only check the symbol's kind if it has one.  */
3991       if (attrs_valid)
3992         {
3993           switch (iter->domain)
3994             {
3995             case VAR_DOMAIN:
3996               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3997                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3998                   /* Some types are also in VAR_DOMAIN.  */
3999                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4000                 continue;
4001               break;
4002             case STRUCT_DOMAIN:
4003               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4004                 continue;
4005               break;
4006             case LABEL_DOMAIN:
4007               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4008                 continue;
4009               break;
4010             default:
4011               break;
4012             }
4013         }
4014
4015       ++iter->next;
4016       return per_cu;
4017     }
4018
4019   return NULL;
4020 }
4021
4022 static struct compunit_symtab *
4023 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4024                    const char *name, domain_enum domain)
4025 {
4026   struct compunit_symtab *stab_best = NULL;
4027   struct dwarf2_per_objfile *dwarf2_per_objfile
4028     = get_dwarf2_per_objfile (objfile);
4029
4030   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4031
4032   struct dw2_symtab_iterator iter;
4033   struct dwarf2_per_cu_data *per_cu;
4034
4035   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4036
4037   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4038     {
4039       struct symbol *sym, *with_opaque = NULL;
4040       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4041       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4042       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4043
4044       sym = block_find_symbol (block, name, domain,
4045                                block_find_non_opaque_type_preferred,
4046                                &with_opaque);
4047
4048       /* Some caution must be observed with overloaded functions
4049          and methods, since the index will not contain any overload
4050          information (but NAME might contain it).  */
4051
4052       if (sym != NULL
4053           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4054         return stab;
4055       if (with_opaque != NULL
4056           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4057         stab_best = stab;
4058
4059       /* Keep looking through other CUs.  */
4060     }
4061
4062   return stab_best;
4063 }
4064
4065 static void
4066 dw2_print_stats (struct objfile *objfile)
4067 {
4068   struct dwarf2_per_objfile *dwarf2_per_objfile
4069     = get_dwarf2_per_objfile (objfile);
4070   int total = (dwarf2_per_objfile->all_comp_units.size ()
4071                + dwarf2_per_objfile->all_type_units.size ());
4072   int count = 0;
4073
4074   for (int i = 0; i < total; ++i)
4075     {
4076       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4077
4078       if (!per_cu->v.quick->compunit_symtab)
4079         ++count;
4080     }
4081   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4082   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4083 }
4084
4085 /* This dumps minimal information about the index.
4086    It is called via "mt print objfiles".
4087    One use is to verify .gdb_index has been loaded by the
4088    gdb.dwarf2/gdb-index.exp testcase.  */
4089
4090 static void
4091 dw2_dump (struct objfile *objfile)
4092 {
4093   struct dwarf2_per_objfile *dwarf2_per_objfile
4094     = get_dwarf2_per_objfile (objfile);
4095
4096   gdb_assert (dwarf2_per_objfile->using_index);
4097   printf_filtered (".gdb_index:");
4098   if (dwarf2_per_objfile->index_table != NULL)
4099     {
4100       printf_filtered (" version %d\n",
4101                        dwarf2_per_objfile->index_table->version);
4102     }
4103   else
4104     printf_filtered (" faked for \"readnow\"\n");
4105   printf_filtered ("\n");
4106 }
4107
4108 static void
4109 dw2_relocate (struct objfile *objfile,
4110               const struct section_offsets *new_offsets,
4111               const struct section_offsets *delta)
4112 {
4113   /* There's nothing to relocate here.  */
4114 }
4115
4116 static void
4117 dw2_expand_symtabs_for_function (struct objfile *objfile,
4118                                  const char *func_name)
4119 {
4120   struct dwarf2_per_objfile *dwarf2_per_objfile
4121     = get_dwarf2_per_objfile (objfile);
4122
4123   struct dw2_symtab_iterator iter;
4124   struct dwarf2_per_cu_data *per_cu;
4125
4126   /* Note: It doesn't matter what we pass for block_index here.  */
4127   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4128                         func_name);
4129
4130   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4131     dw2_instantiate_symtab (per_cu, false);
4132
4133 }
4134
4135 static void
4136 dw2_expand_all_symtabs (struct objfile *objfile)
4137 {
4138   struct dwarf2_per_objfile *dwarf2_per_objfile
4139     = get_dwarf2_per_objfile (objfile);
4140   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4141                      + dwarf2_per_objfile->all_type_units.size ());
4142
4143   for (int i = 0; i < total_units; ++i)
4144     {
4145       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4146
4147       /* We don't want to directly expand a partial CU, because if we
4148          read it with the wrong language, then assertion failures can
4149          be triggered later on.  See PR symtab/23010.  So, tell
4150          dw2_instantiate_symtab to skip partial CUs -- any important
4151          partial CU will be read via DW_TAG_imported_unit anyway.  */
4152       dw2_instantiate_symtab (per_cu, true);
4153     }
4154 }
4155
4156 static void
4157 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4158                                   const char *fullname)
4159 {
4160   struct dwarf2_per_objfile *dwarf2_per_objfile
4161     = get_dwarf2_per_objfile (objfile);
4162
4163   /* We don't need to consider type units here.
4164      This is only called for examining code, e.g. expand_line_sal.
4165      There can be an order of magnitude (or more) more type units
4166      than comp units, and we avoid them if we can.  */
4167
4168   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4169     {
4170       /* We only need to look at symtabs not already expanded.  */
4171       if (per_cu->v.quick->compunit_symtab)
4172         continue;
4173
4174       quick_file_names *file_data = dw2_get_file_names (per_cu);
4175       if (file_data == NULL)
4176         continue;
4177
4178       for (int j = 0; j < file_data->num_file_names; ++j)
4179         {
4180           const char *this_fullname = file_data->file_names[j];
4181
4182           if (filename_cmp (this_fullname, fullname) == 0)
4183             {
4184               dw2_instantiate_symtab (per_cu, false);
4185               break;
4186             }
4187         }
4188     }
4189 }
4190
4191 static void
4192 dw2_map_matching_symbols (struct objfile *objfile,
4193                           const char * name, domain_enum domain,
4194                           int global,
4195                           int (*callback) (struct block *,
4196                                            struct symbol *, void *),
4197                           void *data, symbol_name_match_type match,
4198                           symbol_compare_ftype *ordered_compare)
4199 {
4200   /* Currently unimplemented; used for Ada.  The function can be called if the
4201      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4202      does not look for non-Ada symbols this function should just return.  */
4203 }
4204
4205 /* Symbol name matcher for .gdb_index names.
4206
4207    Symbol names in .gdb_index have a few particularities:
4208
4209    - There's no indication of which is the language of each symbol.
4210
4211      Since each language has its own symbol name matching algorithm,
4212      and we don't know which language is the right one, we must match
4213      each symbol against all languages.  This would be a potential
4214      performance problem if it were not mitigated by the
4215      mapped_index::name_components lookup table, which significantly
4216      reduces the number of times we need to call into this matcher,
4217      making it a non-issue.
4218
4219    - Symbol names in the index have no overload (parameter)
4220      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4221      appear as "foo" in the index, for example.
4222
4223      This means that the lookup names passed to the symbol name
4224      matcher functions must have no parameter information either
4225      because (e.g.) symbol search name "foo" does not match
4226      lookup-name "foo(int)" [while swapping search name for lookup
4227      name would match].
4228 */
4229 class gdb_index_symbol_name_matcher
4230 {
4231 public:
4232   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4233   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4234
4235   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4236      Returns true if any matcher matches.  */
4237   bool matches (const char *symbol_name);
4238
4239 private:
4240   /* A reference to the lookup name we're matching against.  */
4241   const lookup_name_info &m_lookup_name;
4242
4243   /* A vector holding all the different symbol name matchers, for all
4244      languages.  */
4245   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4246 };
4247
4248 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4249   (const lookup_name_info &lookup_name)
4250     : m_lookup_name (lookup_name)
4251 {
4252   /* Prepare the vector of comparison functions upfront, to avoid
4253      doing the same work for each symbol.  Care is taken to avoid
4254      matching with the same matcher more than once if/when multiple
4255      languages use the same matcher function.  */
4256   auto &matchers = m_symbol_name_matcher_funcs;
4257   matchers.reserve (nr_languages);
4258
4259   matchers.push_back (default_symbol_name_matcher);
4260
4261   for (int i = 0; i < nr_languages; i++)
4262     {
4263       const language_defn *lang = language_def ((enum language) i);
4264       symbol_name_matcher_ftype *name_matcher
4265         = get_symbol_name_matcher (lang, m_lookup_name);
4266
4267       /* Don't insert the same comparison routine more than once.
4268          Note that we do this linear walk instead of a seemingly
4269          cheaper sorted insert, or use a std::set or something like
4270          that, because relative order of function addresses is not
4271          stable.  This is not a problem in practice because the number
4272          of supported languages is low, and the cost here is tiny
4273          compared to the number of searches we'll do afterwards using
4274          this object.  */
4275       if (name_matcher != default_symbol_name_matcher
4276           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4277               == matchers.end ()))
4278         matchers.push_back (name_matcher);
4279     }
4280 }
4281
4282 bool
4283 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4284 {
4285   for (auto matches_name : m_symbol_name_matcher_funcs)
4286     if (matches_name (symbol_name, m_lookup_name, NULL))
4287       return true;
4288
4289   return false;
4290 }
4291
4292 /* Starting from a search name, return the string that finds the upper
4293    bound of all strings that start with SEARCH_NAME in a sorted name
4294    list.  Returns the empty string to indicate that the upper bound is
4295    the end of the list.  */
4296
4297 static std::string
4298 make_sort_after_prefix_name (const char *search_name)
4299 {
4300   /* When looking to complete "func", we find the upper bound of all
4301      symbols that start with "func" by looking for where we'd insert
4302      the closest string that would follow "func" in lexicographical
4303      order.  Usually, that's "func"-with-last-character-incremented,
4304      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4305      will be UTF-8 multi-byte sequences, but we can't be certain.
4306      Especially mind the 0xff character, which is a valid character in
4307      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4308      rule out compilers allowing it in identifiers.  Note that
4309      conveniently, strcmp/strcasecmp are specified to compare
4310      characters interpreted as unsigned char.  So what we do is treat
4311      the whole string as a base 256 number composed of a sequence of
4312      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4313      to 0, and carries 1 to the following more-significant position.
4314      If the very first character in SEARCH_NAME ends up incremented
4315      and carries/overflows, then the upper bound is the end of the
4316      list.  The string after the empty string is also the empty
4317      string.
4318
4319      Some examples of this operation:
4320
4321        SEARCH_NAME  => "+1" RESULT
4322
4323        "abc"              => "abd"
4324        "ab\xff"           => "ac"
4325        "\xff" "a" "\xff"  => "\xff" "b"
4326        "\xff"             => ""
4327        "\xff\xff"         => ""
4328        ""                 => ""
4329
4330      Then, with these symbols for example:
4331
4332       func
4333       func1
4334       fund
4335
4336      completing "func" looks for symbols between "func" and
4337      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4338      which finds "func" and "func1", but not "fund".
4339
4340      And with:
4341
4342       funcÿ     (Latin1 'ÿ' [0xff])
4343       funcÿ1
4344       fund
4345
4346      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4347      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4348
4349      And with:
4350
4351       ÿÿ        (Latin1 'ÿ' [0xff])
4352       ÿÿ1
4353
4354      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4355      the end of the list.
4356   */
4357   std::string after = search_name;
4358   while (!after.empty () && (unsigned char) after.back () == 0xff)
4359     after.pop_back ();
4360   if (!after.empty ())
4361     after.back () = (unsigned char) after.back () + 1;
4362   return after;
4363 }
4364
4365 /* See declaration.  */
4366
4367 std::pair<std::vector<name_component>::const_iterator,
4368           std::vector<name_component>::const_iterator>
4369 mapped_index_base::find_name_components_bounds
4370   (const lookup_name_info &lookup_name_without_params) const
4371 {
4372   auto *name_cmp
4373     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4374
4375   const char *cplus
4376     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4377
4378   /* Comparison function object for lower_bound that matches against a
4379      given symbol name.  */
4380   auto lookup_compare_lower = [&] (const name_component &elem,
4381                                    const char *name)
4382     {
4383       const char *elem_qualified = this->symbol_name_at (elem.idx);
4384       const char *elem_name = elem_qualified + elem.name_offset;
4385       return name_cmp (elem_name, name) < 0;
4386     };
4387
4388   /* Comparison function object for upper_bound that matches against a
4389      given symbol name.  */
4390   auto lookup_compare_upper = [&] (const char *name,
4391                                    const name_component &elem)
4392     {
4393       const char *elem_qualified = this->symbol_name_at (elem.idx);
4394       const char *elem_name = elem_qualified + elem.name_offset;
4395       return name_cmp (name, elem_name) < 0;
4396     };
4397
4398   auto begin = this->name_components.begin ();
4399   auto end = this->name_components.end ();
4400
4401   /* Find the lower bound.  */
4402   auto lower = [&] ()
4403     {
4404       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4405         return begin;
4406       else
4407         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4408     } ();
4409
4410   /* Find the upper bound.  */
4411   auto upper = [&] ()
4412     {
4413       if (lookup_name_without_params.completion_mode ())
4414         {
4415           /* In completion mode, we want UPPER to point past all
4416              symbols names that have the same prefix.  I.e., with
4417              these symbols, and completing "func":
4418
4419               function        << lower bound
4420               function1
4421               other_function  << upper bound
4422
4423              We find the upper bound by looking for the insertion
4424              point of "func"-with-last-character-incremented,
4425              i.e. "fund".  */
4426           std::string after = make_sort_after_prefix_name (cplus);
4427           if (after.empty ())
4428             return end;
4429           return std::lower_bound (lower, end, after.c_str (),
4430                                    lookup_compare_lower);
4431         }
4432       else
4433         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4434     } ();
4435
4436   return {lower, upper};
4437 }
4438
4439 /* See declaration.  */
4440
4441 void
4442 mapped_index_base::build_name_components ()
4443 {
4444   if (!this->name_components.empty ())
4445     return;
4446
4447   this->name_components_casing = case_sensitivity;
4448   auto *name_cmp
4449     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4450
4451   /* The code below only knows how to break apart components of C++
4452      symbol names (and other languages that use '::' as
4453      namespace/module separator).  If we add support for wild matching
4454      to some language that uses some other operator (E.g., Ada, Go and
4455      D use '.'), then we'll need to try splitting the symbol name
4456      according to that language too.  Note that Ada does support wild
4457      matching, but doesn't currently support .gdb_index.  */
4458   auto count = this->symbol_name_count ();
4459   for (offset_type idx = 0; idx < count; idx++)
4460     {
4461       if (this->symbol_name_slot_invalid (idx))
4462         continue;
4463
4464       const char *name = this->symbol_name_at (idx);
4465
4466       /* Add each name component to the name component table.  */
4467       unsigned int previous_len = 0;
4468       for (unsigned int current_len = cp_find_first_component (name);
4469            name[current_len] != '\0';
4470            current_len += cp_find_first_component (name + current_len))
4471         {
4472           gdb_assert (name[current_len] == ':');
4473           this->name_components.push_back ({previous_len, idx});
4474           /* Skip the '::'.  */
4475           current_len += 2;
4476           previous_len = current_len;
4477         }
4478       this->name_components.push_back ({previous_len, idx});
4479     }
4480
4481   /* Sort name_components elements by name.  */
4482   auto name_comp_compare = [&] (const name_component &left,
4483                                 const name_component &right)
4484     {
4485       const char *left_qualified = this->symbol_name_at (left.idx);
4486       const char *right_qualified = this->symbol_name_at (right.idx);
4487
4488       const char *left_name = left_qualified + left.name_offset;
4489       const char *right_name = right_qualified + right.name_offset;
4490
4491       return name_cmp (left_name, right_name) < 0;
4492     };
4493
4494   std::sort (this->name_components.begin (),
4495              this->name_components.end (),
4496              name_comp_compare);
4497 }
4498
4499 /* Helper for dw2_expand_symtabs_matching that works with a
4500    mapped_index_base instead of the containing objfile.  This is split
4501    to a separate function in order to be able to unit test the
4502    name_components matching using a mock mapped_index_base.  For each
4503    symbol name that matches, calls MATCH_CALLBACK, passing it the
4504    symbol's index in the mapped_index_base symbol table.  */
4505
4506 static void
4507 dw2_expand_symtabs_matching_symbol
4508   (mapped_index_base &index,
4509    const lookup_name_info &lookup_name_in,
4510    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4511    enum search_domain kind,
4512    gdb::function_view<void (offset_type)> match_callback)
4513 {
4514   lookup_name_info lookup_name_without_params
4515     = lookup_name_in.make_ignore_params ();
4516   gdb_index_symbol_name_matcher lookup_name_matcher
4517     (lookup_name_without_params);
4518
4519   /* Build the symbol name component sorted vector, if we haven't
4520      yet.  */
4521   index.build_name_components ();
4522
4523   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4524
4525   /* Now for each symbol name in range, check to see if we have a name
4526      match, and if so, call the MATCH_CALLBACK callback.  */
4527
4528   /* The same symbol may appear more than once in the range though.
4529      E.g., if we're looking for symbols that complete "w", and we have
4530      a symbol named "w1::w2", we'll find the two name components for
4531      that same symbol in the range.  To be sure we only call the
4532      callback once per symbol, we first collect the symbol name
4533      indexes that matched in a temporary vector and ignore
4534      duplicates.  */
4535   std::vector<offset_type> matches;
4536   matches.reserve (std::distance (bounds.first, bounds.second));
4537
4538   for (; bounds.first != bounds.second; ++bounds.first)
4539     {
4540       const char *qualified = index.symbol_name_at (bounds.first->idx);
4541
4542       if (!lookup_name_matcher.matches (qualified)
4543           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4544         continue;
4545
4546       matches.push_back (bounds.first->idx);
4547     }
4548
4549   std::sort (matches.begin (), matches.end ());
4550
4551   /* Finally call the callback, once per match.  */
4552   ULONGEST prev = -1;
4553   for (offset_type idx : matches)
4554     {
4555       if (prev != idx)
4556         {
4557           match_callback (idx);
4558           prev = idx;
4559         }
4560     }
4561
4562   /* Above we use a type wider than idx's for 'prev', since 0 and
4563      (offset_type)-1 are both possible values.  */
4564   static_assert (sizeof (prev) > sizeof (offset_type), "");
4565 }
4566
4567 #if GDB_SELF_TEST
4568
4569 namespace selftests { namespace dw2_expand_symtabs_matching {
4570
4571 /* A mock .gdb_index/.debug_names-like name index table, enough to
4572    exercise dw2_expand_symtabs_matching_symbol, which works with the
4573    mapped_index_base interface.  Builds an index from the symbol list
4574    passed as parameter to the constructor.  */
4575 class mock_mapped_index : public mapped_index_base
4576 {
4577 public:
4578   mock_mapped_index (gdb::array_view<const char *> symbols)
4579     : m_symbol_table (symbols)
4580   {}
4581
4582   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4583
4584   /* Return the number of names in the symbol table.  */
4585   size_t symbol_name_count () const override
4586   {
4587     return m_symbol_table.size ();
4588   }
4589
4590   /* Get the name of the symbol at IDX in the symbol table.  */
4591   const char *symbol_name_at (offset_type idx) const override
4592   {
4593     return m_symbol_table[idx];
4594   }
4595
4596 private:
4597   gdb::array_view<const char *> m_symbol_table;
4598 };
4599
4600 /* Convenience function that converts a NULL pointer to a "<null>"
4601    string, to pass to print routines.  */
4602
4603 static const char *
4604 string_or_null (const char *str)
4605 {
4606   return str != NULL ? str : "<null>";
4607 }
4608
4609 /* Check if a lookup_name_info built from
4610    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4611    index.  EXPECTED_LIST is the list of expected matches, in expected
4612    matching order.  If no match expected, then an empty list is
4613    specified.  Returns true on success.  On failure prints a warning
4614    indicating the file:line that failed, and returns false.  */
4615
4616 static bool
4617 check_match (const char *file, int line,
4618              mock_mapped_index &mock_index,
4619              const char *name, symbol_name_match_type match_type,
4620              bool completion_mode,
4621              std::initializer_list<const char *> expected_list)
4622 {
4623   lookup_name_info lookup_name (name, match_type, completion_mode);
4624
4625   bool matched = true;
4626
4627   auto mismatch = [&] (const char *expected_str,
4628                        const char *got)
4629   {
4630     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4631                "expected=\"%s\", got=\"%s\"\n"),
4632              file, line,
4633              (match_type == symbol_name_match_type::FULL
4634               ? "FULL" : "WILD"),
4635              name, string_or_null (expected_str), string_or_null (got));
4636     matched = false;
4637   };
4638
4639   auto expected_it = expected_list.begin ();
4640   auto expected_end = expected_list.end ();
4641
4642   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4643                                       NULL, ALL_DOMAIN,
4644                                       [&] (offset_type idx)
4645   {
4646     const char *matched_name = mock_index.symbol_name_at (idx);
4647     const char *expected_str
4648       = expected_it == expected_end ? NULL : *expected_it++;
4649
4650     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4651       mismatch (expected_str, matched_name);
4652   });
4653
4654   const char *expected_str
4655   = expected_it == expected_end ? NULL : *expected_it++;
4656   if (expected_str != NULL)
4657     mismatch (expected_str, NULL);
4658
4659   return matched;
4660 }
4661
4662 /* The symbols added to the mock mapped_index for testing (in
4663    canonical form).  */
4664 static const char *test_symbols[] = {
4665   "function",
4666   "std::bar",
4667   "std::zfunction",
4668   "std::zfunction2",
4669   "w1::w2",
4670   "ns::foo<char*>",
4671   "ns::foo<int>",
4672   "ns::foo<long>",
4673   "ns2::tmpl<int>::foo2",
4674   "(anonymous namespace)::A::B::C",
4675
4676   /* These are used to check that the increment-last-char in the
4677      matching algorithm for completion doesn't match "t1_fund" when
4678      completing "t1_func".  */
4679   "t1_func",
4680   "t1_func1",
4681   "t1_fund",
4682   "t1_fund1",
4683
4684   /* A UTF-8 name with multi-byte sequences to make sure that
4685      cp-name-parser understands this as a single identifier ("função"
4686      is "function" in PT).  */
4687   u8"u8função",
4688
4689   /* \377 (0xff) is Latin1 'ÿ'.  */
4690   "yfunc\377",
4691
4692   /* \377 (0xff) is Latin1 'ÿ'.  */
4693   "\377",
4694   "\377\377123",
4695
4696   /* A name with all sorts of complications.  Starts with "z" to make
4697      it easier for the completion tests below.  */
4698 #define Z_SYM_NAME \
4699   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4700     "::tuple<(anonymous namespace)::ui*, " \
4701     "std::default_delete<(anonymous namespace)::ui>, void>"
4702
4703   Z_SYM_NAME
4704 };
4705
4706 /* Returns true if the mapped_index_base::find_name_component_bounds
4707    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4708    in completion mode.  */
4709
4710 static bool
4711 check_find_bounds_finds (mapped_index_base &index,
4712                          const char *search_name,
4713                          gdb::array_view<const char *> expected_syms)
4714 {
4715   lookup_name_info lookup_name (search_name,
4716                                 symbol_name_match_type::FULL, true);
4717
4718   auto bounds = index.find_name_components_bounds (lookup_name);
4719
4720   size_t distance = std::distance (bounds.first, bounds.second);
4721   if (distance != expected_syms.size ())
4722     return false;
4723
4724   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4725     {
4726       auto nc_elem = bounds.first + exp_elem;
4727       const char *qualified = index.symbol_name_at (nc_elem->idx);
4728       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4729         return false;
4730     }
4731
4732   return true;
4733 }
4734
4735 /* Test the lower-level mapped_index::find_name_component_bounds
4736    method.  */
4737
4738 static void
4739 test_mapped_index_find_name_component_bounds ()
4740 {
4741   mock_mapped_index mock_index (test_symbols);
4742
4743   mock_index.build_name_components ();
4744
4745   /* Test the lower-level mapped_index::find_name_component_bounds
4746      method in completion mode.  */
4747   {
4748     static const char *expected_syms[] = {
4749       "t1_func",
4750       "t1_func1",
4751     };
4752
4753     SELF_CHECK (check_find_bounds_finds (mock_index,
4754                                          "t1_func", expected_syms));
4755   }
4756
4757   /* Check that the increment-last-char in the name matching algorithm
4758      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4759   {
4760     static const char *expected_syms1[] = {
4761       "\377",
4762       "\377\377123",
4763     };
4764     SELF_CHECK (check_find_bounds_finds (mock_index,
4765                                          "\377", expected_syms1));
4766
4767     static const char *expected_syms2[] = {
4768       "\377\377123",
4769     };
4770     SELF_CHECK (check_find_bounds_finds (mock_index,
4771                                          "\377\377", expected_syms2));
4772   }
4773 }
4774
4775 /* Test dw2_expand_symtabs_matching_symbol.  */
4776
4777 static void
4778 test_dw2_expand_symtabs_matching_symbol ()
4779 {
4780   mock_mapped_index mock_index (test_symbols);
4781
4782   /* We let all tests run until the end even if some fails, for debug
4783      convenience.  */
4784   bool any_mismatch = false;
4785
4786   /* Create the expected symbols list (an initializer_list).  Needed
4787      because lists have commas, and we need to pass them to CHECK,
4788      which is a macro.  */
4789 #define EXPECT(...) { __VA_ARGS__ }
4790
4791   /* Wrapper for check_match that passes down the current
4792      __FILE__/__LINE__.  */
4793 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4794   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4795                                 mock_index,                             \
4796                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4797                                 EXPECTED_LIST)
4798
4799   /* Identity checks.  */
4800   for (const char *sym : test_symbols)
4801     {
4802       /* Should be able to match all existing symbols.  */
4803       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4804                    EXPECT (sym));
4805
4806       /* Should be able to match all existing symbols with
4807          parameters.  */
4808       std::string with_params = std::string (sym) + "(int)";
4809       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4810                    EXPECT (sym));
4811
4812       /* Should be able to match all existing symbols with
4813          parameters and qualifiers.  */
4814       with_params = std::string (sym) + " ( int ) const";
4815       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4816                    EXPECT (sym));
4817
4818       /* This should really find sym, but cp-name-parser.y doesn't
4819          know about lvalue/rvalue qualifiers yet.  */
4820       with_params = std::string (sym) + " ( int ) &&";
4821       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4822                    {});
4823     }
4824
4825   /* Check that the name matching algorithm for completion doesn't get
4826      confused with Latin1 'ÿ' / 0xff.  */
4827   {
4828     static const char str[] = "\377";
4829     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4830                  EXPECT ("\377", "\377\377123"));
4831   }
4832
4833   /* Check that the increment-last-char in the matching algorithm for
4834      completion doesn't match "t1_fund" when completing "t1_func".  */
4835   {
4836     static const char str[] = "t1_func";
4837     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4838                  EXPECT ("t1_func", "t1_func1"));
4839   }
4840
4841   /* Check that completion mode works at each prefix of the expected
4842      symbol name.  */
4843   {
4844     static const char str[] = "function(int)";
4845     size_t len = strlen (str);
4846     std::string lookup;
4847
4848     for (size_t i = 1; i < len; i++)
4849       {
4850         lookup.assign (str, i);
4851         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4852                      EXPECT ("function"));
4853       }
4854   }
4855
4856   /* While "w" is a prefix of both components, the match function
4857      should still only be called once.  */
4858   {
4859     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4860                  EXPECT ("w1::w2"));
4861     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4862                  EXPECT ("w1::w2"));
4863   }
4864
4865   /* Same, with a "complicated" symbol.  */
4866   {
4867     static const char str[] = Z_SYM_NAME;
4868     size_t len = strlen (str);
4869     std::string lookup;
4870
4871     for (size_t i = 1; i < len; i++)
4872       {
4873         lookup.assign (str, i);
4874         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4875                      EXPECT (Z_SYM_NAME));
4876       }
4877   }
4878
4879   /* In FULL mode, an incomplete symbol doesn't match.  */
4880   {
4881     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4882                  {});
4883   }
4884
4885   /* A complete symbol with parameters matches any overload, since the
4886      index has no overload info.  */
4887   {
4888     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4889                  EXPECT ("std::zfunction", "std::zfunction2"));
4890     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4891                  EXPECT ("std::zfunction", "std::zfunction2"));
4892     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4893                  EXPECT ("std::zfunction", "std::zfunction2"));
4894   }
4895
4896   /* Check that whitespace is ignored appropriately.  A symbol with a
4897      template argument list. */
4898   {
4899     static const char expected[] = "ns::foo<int>";
4900     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4901                  EXPECT (expected));
4902     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4903                  EXPECT (expected));
4904   }
4905
4906   /* Check that whitespace is ignored appropriately.  A symbol with a
4907      template argument list that includes a pointer.  */
4908   {
4909     static const char expected[] = "ns::foo<char*>";
4910     /* Try both completion and non-completion modes.  */
4911     static const bool completion_mode[2] = {false, true};
4912     for (size_t i = 0; i < 2; i++)
4913       {
4914         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4915                      completion_mode[i], EXPECT (expected));
4916         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4917                      completion_mode[i], EXPECT (expected));
4918
4919         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4920                      completion_mode[i], EXPECT (expected));
4921         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4922                      completion_mode[i], EXPECT (expected));
4923       }
4924   }
4925
4926   {
4927     /* Check method qualifiers are ignored.  */
4928     static const char expected[] = "ns::foo<char*>";
4929     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4930                  symbol_name_match_type::FULL, true, EXPECT (expected));
4931     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4932                  symbol_name_match_type::FULL, true, EXPECT (expected));
4933     CHECK_MATCH ("foo < char * >  ( int ) const",
4934                  symbol_name_match_type::WILD, true, EXPECT (expected));
4935     CHECK_MATCH ("foo < char * >  ( int ) &&",
4936                  symbol_name_match_type::WILD, true, EXPECT (expected));
4937   }
4938
4939   /* Test lookup names that don't match anything.  */
4940   {
4941     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4942                  {});
4943
4944     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4945                  {});
4946   }
4947
4948   /* Some wild matching tests, exercising "(anonymous namespace)",
4949      which should not be confused with a parameter list.  */
4950   {
4951     static const char *syms[] = {
4952       "A::B::C",
4953       "B::C",
4954       "C",
4955       "A :: B :: C ( int )",
4956       "B :: C ( int )",
4957       "C ( int )",
4958     };
4959
4960     for (const char *s : syms)
4961       {
4962         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4963                      EXPECT ("(anonymous namespace)::A::B::C"));
4964       }
4965   }
4966
4967   {
4968     static const char expected[] = "ns2::tmpl<int>::foo2";
4969     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4970                  EXPECT (expected));
4971     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4972                  EXPECT (expected));
4973   }
4974
4975   SELF_CHECK (!any_mismatch);
4976
4977 #undef EXPECT
4978 #undef CHECK_MATCH
4979 }
4980
4981 static void
4982 run_test ()
4983 {
4984   test_mapped_index_find_name_component_bounds ();
4985   test_dw2_expand_symtabs_matching_symbol ();
4986 }
4987
4988 }} // namespace selftests::dw2_expand_symtabs_matching
4989
4990 #endif /* GDB_SELF_TEST */
4991
4992 /* If FILE_MATCHER is NULL or if PER_CU has
4993    dwarf2_per_cu_quick_data::MARK set (see
4994    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4995    EXPANSION_NOTIFY on it.  */
4996
4997 static void
4998 dw2_expand_symtabs_matching_one
4999   (struct dwarf2_per_cu_data *per_cu,
5000    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5001    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5002 {
5003   if (file_matcher == NULL || per_cu->v.quick->mark)
5004     {
5005       bool symtab_was_null
5006         = (per_cu->v.quick->compunit_symtab == NULL);
5007
5008       dw2_instantiate_symtab (per_cu, false);
5009
5010       if (expansion_notify != NULL
5011           && symtab_was_null
5012           && per_cu->v.quick->compunit_symtab != NULL)
5013         expansion_notify (per_cu->v.quick->compunit_symtab);
5014     }
5015 }
5016
5017 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5018    matched, to expand corresponding CUs that were marked.  IDX is the
5019    index of the symbol name that matched.  */
5020
5021 static void
5022 dw2_expand_marked_cus
5023   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5024    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5025    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5026    search_domain kind)
5027 {
5028   offset_type *vec, vec_len, vec_idx;
5029   bool global_seen = false;
5030   mapped_index &index = *dwarf2_per_objfile->index_table;
5031
5032   vec = (offset_type *) (index.constant_pool
5033                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5034   vec_len = MAYBE_SWAP (vec[0]);
5035   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5036     {
5037       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5038       /* This value is only valid for index versions >= 7.  */
5039       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5040       gdb_index_symbol_kind symbol_kind =
5041         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5042       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5043       /* Only check the symbol attributes if they're present.
5044          Indices prior to version 7 don't record them,
5045          and indices >= 7 may elide them for certain symbols
5046          (gold does this).  */
5047       int attrs_valid =
5048         (index.version >= 7
5049          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5050
5051       /* Work around gold/15646.  */
5052       if (attrs_valid)
5053         {
5054           if (!is_static && global_seen)
5055             continue;
5056           if (!is_static)
5057             global_seen = true;
5058         }
5059
5060       /* Only check the symbol's kind if it has one.  */
5061       if (attrs_valid)
5062         {
5063           switch (kind)
5064             {
5065             case VARIABLES_DOMAIN:
5066               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5067                 continue;
5068               break;
5069             case FUNCTIONS_DOMAIN:
5070               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5071                 continue;
5072               break;
5073             case TYPES_DOMAIN:
5074               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5075                 continue;
5076               break;
5077             default:
5078               break;
5079             }
5080         }
5081
5082       /* Don't crash on bad data.  */
5083       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5084                        + dwarf2_per_objfile->all_type_units.size ()))
5085         {
5086           complaint (&symfile_complaints,
5087                      _(".gdb_index entry has bad CU index"
5088                        " [in module %s]"),
5089                        objfile_name (dwarf2_per_objfile->objfile));
5090           continue;
5091         }
5092
5093       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5094       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5095                                        expansion_notify);
5096     }
5097 }
5098
5099 /* If FILE_MATCHER is non-NULL, set all the
5100    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5101    that match FILE_MATCHER.  */
5102
5103 static void
5104 dw_expand_symtabs_matching_file_matcher
5105   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5106    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5107 {
5108   if (file_matcher == NULL)
5109     return;
5110
5111   objfile *const objfile = dwarf2_per_objfile->objfile;
5112
5113   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5114                                             htab_eq_pointer,
5115                                             NULL, xcalloc, xfree));
5116   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5117                                                 htab_eq_pointer,
5118                                                 NULL, xcalloc, xfree));
5119
5120   /* The rule is CUs specify all the files, including those used by
5121      any TU, so there's no need to scan TUs here.  */
5122
5123   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5124     {
5125       QUIT;
5126
5127       per_cu->v.quick->mark = 0;
5128
5129       /* We only need to look at symtabs not already expanded.  */
5130       if (per_cu->v.quick->compunit_symtab)
5131         continue;
5132
5133       quick_file_names *file_data = dw2_get_file_names (per_cu);
5134       if (file_data == NULL)
5135         continue;
5136
5137       if (htab_find (visited_not_found.get (), file_data) != NULL)
5138         continue;
5139       else if (htab_find (visited_found.get (), file_data) != NULL)
5140         {
5141           per_cu->v.quick->mark = 1;
5142           continue;
5143         }
5144
5145       for (int j = 0; j < file_data->num_file_names; ++j)
5146         {
5147           const char *this_real_name;
5148
5149           if (file_matcher (file_data->file_names[j], false))
5150             {
5151               per_cu->v.quick->mark = 1;
5152               break;
5153             }
5154
5155           /* Before we invoke realpath, which can get expensive when many
5156              files are involved, do a quick comparison of the basenames.  */
5157           if (!basenames_may_differ
5158               && !file_matcher (lbasename (file_data->file_names[j]),
5159                                 true))
5160             continue;
5161
5162           this_real_name = dw2_get_real_path (objfile, file_data, j);
5163           if (file_matcher (this_real_name, false))
5164             {
5165               per_cu->v.quick->mark = 1;
5166               break;
5167             }
5168         }
5169
5170       void **slot = htab_find_slot (per_cu->v.quick->mark
5171                                     ? visited_found.get ()
5172                                     : visited_not_found.get (),
5173                                     file_data, INSERT);
5174       *slot = file_data;
5175     }
5176 }
5177
5178 static void
5179 dw2_expand_symtabs_matching
5180   (struct objfile *objfile,
5181    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5182    const lookup_name_info &lookup_name,
5183    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5184    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5185    enum search_domain kind)
5186 {
5187   struct dwarf2_per_objfile *dwarf2_per_objfile
5188     = get_dwarf2_per_objfile (objfile);
5189
5190   /* index_table is NULL if OBJF_READNOW.  */
5191   if (!dwarf2_per_objfile->index_table)
5192     return;
5193
5194   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5195
5196   mapped_index &index = *dwarf2_per_objfile->index_table;
5197
5198   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5199                                       symbol_matcher,
5200                                       kind, [&] (offset_type idx)
5201     {
5202       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5203                              expansion_notify, kind);
5204     });
5205 }
5206
5207 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5208    symtab.  */
5209
5210 static struct compunit_symtab *
5211 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5212                                           CORE_ADDR pc)
5213 {
5214   int i;
5215
5216   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5217       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5218     return cust;
5219
5220   if (cust->includes == NULL)
5221     return NULL;
5222
5223   for (i = 0; cust->includes[i]; ++i)
5224     {
5225       struct compunit_symtab *s = cust->includes[i];
5226
5227       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5228       if (s != NULL)
5229         return s;
5230     }
5231
5232   return NULL;
5233 }
5234
5235 static struct compunit_symtab *
5236 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5237                                   struct bound_minimal_symbol msymbol,
5238                                   CORE_ADDR pc,
5239                                   struct obj_section *section,
5240                                   int warn_if_readin)
5241 {
5242   struct dwarf2_per_cu_data *data;
5243   struct compunit_symtab *result;
5244
5245   if (!objfile->psymtabs_addrmap)
5246     return NULL;
5247
5248   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5249                                                      pc);
5250   if (!data)
5251     return NULL;
5252
5253   if (warn_if_readin && data->v.quick->compunit_symtab)
5254     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5255              paddress (get_objfile_arch (objfile), pc));
5256
5257   result
5258     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5259                                                                         false),
5260                                                 pc);
5261   gdb_assert (result != NULL);
5262   return result;
5263 }
5264
5265 static void
5266 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5267                           void *data, int need_fullname)
5268 {
5269   struct dwarf2_per_objfile *dwarf2_per_objfile
5270     = get_dwarf2_per_objfile (objfile);
5271
5272   if (!dwarf2_per_objfile->filenames_cache)
5273     {
5274       dwarf2_per_objfile->filenames_cache.emplace ();
5275
5276       htab_up visited (htab_create_alloc (10,
5277                                           htab_hash_pointer, htab_eq_pointer,
5278                                           NULL, xcalloc, xfree));
5279
5280       /* The rule is CUs specify all the files, including those used
5281          by any TU, so there's no need to scan TUs here.  We can
5282          ignore file names coming from already-expanded CUs.  */
5283
5284       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5285         {
5286           if (per_cu->v.quick->compunit_symtab)
5287             {
5288               void **slot = htab_find_slot (visited.get (),
5289                                             per_cu->v.quick->file_names,
5290                                             INSERT);
5291
5292               *slot = per_cu->v.quick->file_names;
5293             }
5294         }
5295
5296       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5297         {
5298           /* We only need to look at symtabs not already expanded.  */
5299           if (per_cu->v.quick->compunit_symtab)
5300             continue;
5301
5302           quick_file_names *file_data = dw2_get_file_names (per_cu);
5303           if (file_data == NULL)
5304             continue;
5305
5306           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5307           if (*slot)
5308             {
5309               /* Already visited.  */
5310               continue;
5311             }
5312           *slot = file_data;
5313
5314           for (int j = 0; j < file_data->num_file_names; ++j)
5315             {
5316               const char *filename = file_data->file_names[j];
5317               dwarf2_per_objfile->filenames_cache->seen (filename);
5318             }
5319         }
5320     }
5321
5322   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5323     {
5324       gdb::unique_xmalloc_ptr<char> this_real_name;
5325
5326       if (need_fullname)
5327         this_real_name = gdb_realpath (filename);
5328       (*fun) (filename, this_real_name.get (), data);
5329     });
5330 }
5331
5332 static int
5333 dw2_has_symbols (struct objfile *objfile)
5334 {
5335   return 1;
5336 }
5337
5338 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5339 {
5340   dw2_has_symbols,
5341   dw2_find_last_source_symtab,
5342   dw2_forget_cached_source_info,
5343   dw2_map_symtabs_matching_filename,
5344   dw2_lookup_symbol,
5345   dw2_print_stats,
5346   dw2_dump,
5347   dw2_relocate,
5348   dw2_expand_symtabs_for_function,
5349   dw2_expand_all_symtabs,
5350   dw2_expand_symtabs_with_fullname,
5351   dw2_map_matching_symbols,
5352   dw2_expand_symtabs_matching,
5353   dw2_find_pc_sect_compunit_symtab,
5354   NULL,
5355   dw2_map_symbol_filenames
5356 };
5357
5358 /* DWARF-5 debug_names reader.  */
5359
5360 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5361 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5362
5363 /* A helper function that reads the .debug_names section in SECTION
5364    and fills in MAP.  FILENAME is the name of the file containing the
5365    section; it is used for error reporting.
5366
5367    Returns true if all went well, false otherwise.  */
5368
5369 static bool
5370 read_debug_names_from_section (struct objfile *objfile,
5371                                const char *filename,
5372                                struct dwarf2_section_info *section,
5373                                mapped_debug_names &map)
5374 {
5375   if (dwarf2_section_empty_p (section))
5376     return false;
5377
5378   /* Older elfutils strip versions could keep the section in the main
5379      executable while splitting it for the separate debug info file.  */
5380   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5381     return false;
5382
5383   dwarf2_read_section (objfile, section);
5384
5385   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5386
5387   const gdb_byte *addr = section->buffer;
5388
5389   bfd *const abfd = get_section_bfd_owner (section);
5390
5391   unsigned int bytes_read;
5392   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5393   addr += bytes_read;
5394
5395   map.dwarf5_is_dwarf64 = bytes_read != 4;
5396   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5397   if (bytes_read + length != section->size)
5398     {
5399       /* There may be multiple per-CU indices.  */
5400       warning (_("Section .debug_names in %s length %s does not match "
5401                  "section length %s, ignoring .debug_names."),
5402                filename, plongest (bytes_read + length),
5403                pulongest (section->size));
5404       return false;
5405     }
5406
5407   /* The version number.  */
5408   uint16_t version = read_2_bytes (abfd, addr);
5409   addr += 2;
5410   if (version != 5)
5411     {
5412       warning (_("Section .debug_names in %s has unsupported version %d, "
5413                  "ignoring .debug_names."),
5414                filename, version);
5415       return false;
5416     }
5417
5418   /* Padding.  */
5419   uint16_t padding = read_2_bytes (abfd, addr);
5420   addr += 2;
5421   if (padding != 0)
5422     {
5423       warning (_("Section .debug_names in %s has unsupported padding %d, "
5424                  "ignoring .debug_names."),
5425                filename, padding);
5426       return false;
5427     }
5428
5429   /* comp_unit_count - The number of CUs in the CU list.  */
5430   map.cu_count = read_4_bytes (abfd, addr);
5431   addr += 4;
5432
5433   /* local_type_unit_count - The number of TUs in the local TU
5434      list.  */
5435   map.tu_count = read_4_bytes (abfd, addr);
5436   addr += 4;
5437
5438   /* foreign_type_unit_count - The number of TUs in the foreign TU
5439      list.  */
5440   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5441   addr += 4;
5442   if (foreign_tu_count != 0)
5443     {
5444       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5445                  "ignoring .debug_names."),
5446                filename, static_cast<unsigned long> (foreign_tu_count));
5447       return false;
5448     }
5449
5450   /* bucket_count - The number of hash buckets in the hash lookup
5451      table.  */
5452   map.bucket_count = read_4_bytes (abfd, addr);
5453   addr += 4;
5454
5455   /* name_count - The number of unique names in the index.  */
5456   map.name_count = read_4_bytes (abfd, addr);
5457   addr += 4;
5458
5459   /* abbrev_table_size - The size in bytes of the abbreviations
5460      table.  */
5461   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5462   addr += 4;
5463
5464   /* augmentation_string_size - The size in bytes of the augmentation
5465      string.  This value is rounded up to a multiple of 4.  */
5466   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5467   addr += 4;
5468   map.augmentation_is_gdb = ((augmentation_string_size
5469                               == sizeof (dwarf5_augmentation))
5470                              && memcmp (addr, dwarf5_augmentation,
5471                                         sizeof (dwarf5_augmentation)) == 0);
5472   augmentation_string_size += (-augmentation_string_size) & 3;
5473   addr += augmentation_string_size;
5474
5475   /* List of CUs */
5476   map.cu_table_reordered = addr;
5477   addr += map.cu_count * map.offset_size;
5478
5479   /* List of Local TUs */
5480   map.tu_table_reordered = addr;
5481   addr += map.tu_count * map.offset_size;
5482
5483   /* Hash Lookup Table */
5484   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5485   addr += map.bucket_count * 4;
5486   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5487   addr += map.name_count * 4;
5488
5489   /* Name Table */
5490   map.name_table_string_offs_reordered = addr;
5491   addr += map.name_count * map.offset_size;
5492   map.name_table_entry_offs_reordered = addr;
5493   addr += map.name_count * map.offset_size;
5494
5495   const gdb_byte *abbrev_table_start = addr;
5496   for (;;)
5497     {
5498       unsigned int bytes_read;
5499       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5500       addr += bytes_read;
5501       if (index_num == 0)
5502         break;
5503
5504       const auto insertpair
5505         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5506       if (!insertpair.second)
5507         {
5508           warning (_("Section .debug_names in %s has duplicate index %s, "
5509                      "ignoring .debug_names."),
5510                    filename, pulongest (index_num));
5511           return false;
5512         }
5513       mapped_debug_names::index_val &indexval = insertpair.first->second;
5514       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5515       addr += bytes_read;
5516
5517       for (;;)
5518         {
5519           mapped_debug_names::index_val::attr attr;
5520           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5521           addr += bytes_read;
5522           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5523           addr += bytes_read;
5524           if (attr.form == DW_FORM_implicit_const)
5525             {
5526               attr.implicit_const = read_signed_leb128 (abfd, addr,
5527                                                         &bytes_read);
5528               addr += bytes_read;
5529             }
5530           if (attr.dw_idx == 0 && attr.form == 0)
5531             break;
5532           indexval.attr_vec.push_back (std::move (attr));
5533         }
5534     }
5535   if (addr != abbrev_table_start + abbrev_table_size)
5536     {
5537       warning (_("Section .debug_names in %s has abbreviation_table "
5538                  "of size %zu vs. written as %u, ignoring .debug_names."),
5539                filename, addr - abbrev_table_start, abbrev_table_size);
5540       return false;
5541     }
5542   map.entry_pool = addr;
5543
5544   return true;
5545 }
5546
5547 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5548    list.  */
5549
5550 static void
5551 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5552                                   const mapped_debug_names &map,
5553                                   dwarf2_section_info &section,
5554                                   bool is_dwz)
5555 {
5556   sect_offset sect_off_prev;
5557   for (uint32_t i = 0; i <= map.cu_count; ++i)
5558     {
5559       sect_offset sect_off_next;
5560       if (i < map.cu_count)
5561         {
5562           sect_off_next
5563             = (sect_offset) (extract_unsigned_integer
5564                              (map.cu_table_reordered + i * map.offset_size,
5565                               map.offset_size,
5566                               map.dwarf5_byte_order));
5567         }
5568       else
5569         sect_off_next = (sect_offset) section.size;
5570       if (i >= 1)
5571         {
5572           const ULONGEST length = sect_off_next - sect_off_prev;
5573           dwarf2_per_cu_data *per_cu
5574             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5575                                          sect_off_prev, length);
5576           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5577         }
5578       sect_off_prev = sect_off_next;
5579     }
5580 }
5581
5582 /* Read the CU list from the mapped index, and use it to create all
5583    the CU objects for this dwarf2_per_objfile.  */
5584
5585 static void
5586 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5587                              const mapped_debug_names &map,
5588                              const mapped_debug_names &dwz_map)
5589 {
5590   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5591   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5592
5593   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5594                                     dwarf2_per_objfile->info,
5595                                     false /* is_dwz */);
5596
5597   if (dwz_map.cu_count == 0)
5598     return;
5599
5600   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5601   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5602                                     true /* is_dwz */);
5603 }
5604
5605 /* Read .debug_names.  If everything went ok, initialize the "quick"
5606    elements of all the CUs and return true.  Otherwise, return false.  */
5607
5608 static bool
5609 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5610 {
5611   mapped_debug_names local_map (dwarf2_per_objfile);
5612   mapped_debug_names dwz_map (dwarf2_per_objfile);
5613   struct objfile *objfile = dwarf2_per_objfile->objfile;
5614
5615   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5616                                       &dwarf2_per_objfile->debug_names,
5617                                       local_map))
5618     return false;
5619
5620   /* Don't use the index if it's empty.  */
5621   if (local_map.name_count == 0)
5622     return false;
5623
5624   /* If there is a .dwz file, read it so we can get its CU list as
5625      well.  */
5626   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5627   if (dwz != NULL)
5628     {
5629       if (!read_debug_names_from_section (objfile,
5630                                           bfd_get_filename (dwz->dwz_bfd),
5631                                           &dwz->debug_names, dwz_map))
5632         {
5633           warning (_("could not read '.debug_names' section from %s; skipping"),
5634                    bfd_get_filename (dwz->dwz_bfd));
5635           return false;
5636         }
5637     }
5638
5639   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5640
5641   if (local_map.tu_count != 0)
5642     {
5643       /* We can only handle a single .debug_types when we have an
5644          index.  */
5645       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5646         return false;
5647
5648       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5649                                                 dwarf2_per_objfile->types, 0);
5650
5651       create_signatured_type_table_from_debug_names
5652         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5653     }
5654
5655   create_addrmap_from_aranges (dwarf2_per_objfile,
5656                                &dwarf2_per_objfile->debug_aranges);
5657
5658   dwarf2_per_objfile->debug_names_table.reset
5659     (new mapped_debug_names (dwarf2_per_objfile));
5660   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5661   dwarf2_per_objfile->using_index = 1;
5662   dwarf2_per_objfile->quick_file_names_table =
5663     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5664
5665   return true;
5666 }
5667
5668 /* Type used to manage iterating over all CUs looking for a symbol for
5669    .debug_names.  */
5670
5671 class dw2_debug_names_iterator
5672 {
5673 public:
5674   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5675      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5676   dw2_debug_names_iterator (const mapped_debug_names &map,
5677                             bool want_specific_block,
5678                             block_enum block_index, domain_enum domain,
5679                             const char *name)
5680     : m_map (map), m_want_specific_block (want_specific_block),
5681       m_block_index (block_index), m_domain (domain),
5682       m_addr (find_vec_in_debug_names (map, name))
5683   {}
5684
5685   dw2_debug_names_iterator (const mapped_debug_names &map,
5686                             search_domain search, uint32_t namei)
5687     : m_map (map),
5688       m_search (search),
5689       m_addr (find_vec_in_debug_names (map, namei))
5690   {}
5691
5692   /* Return the next matching CU or NULL if there are no more.  */
5693   dwarf2_per_cu_data *next ();
5694
5695 private:
5696   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5697                                                   const char *name);
5698   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5699                                                   uint32_t namei);
5700
5701   /* The internalized form of .debug_names.  */
5702   const mapped_debug_names &m_map;
5703
5704   /* If true, only look for symbols that match BLOCK_INDEX.  */
5705   const bool m_want_specific_block = false;
5706
5707   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5708      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5709      value.  */
5710   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5711
5712   /* The kind of symbol we're looking for.  */
5713   const domain_enum m_domain = UNDEF_DOMAIN;
5714   const search_domain m_search = ALL_DOMAIN;
5715
5716   /* The list of CUs from the index entry of the symbol, or NULL if
5717      not found.  */
5718   const gdb_byte *m_addr;
5719 };
5720
5721 const char *
5722 mapped_debug_names::namei_to_name (uint32_t namei) const
5723 {
5724   const ULONGEST namei_string_offs
5725     = extract_unsigned_integer ((name_table_string_offs_reordered
5726                                  + namei * offset_size),
5727                                 offset_size,
5728                                 dwarf5_byte_order);
5729   return read_indirect_string_at_offset
5730     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5731 }
5732
5733 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5734    found, return pointer to its pool data.  If NAME cannot be found,
5735    return NULL.  */
5736
5737 const gdb_byte *
5738 dw2_debug_names_iterator::find_vec_in_debug_names
5739   (const mapped_debug_names &map, const char *name)
5740 {
5741   int (*cmp) (const char *, const char *);
5742
5743   if (current_language->la_language == language_cplus
5744       || current_language->la_language == language_fortran
5745       || current_language->la_language == language_d)
5746     {
5747       /* NAME is already canonical.  Drop any qualifiers as
5748          .debug_names does not contain any.  */
5749
5750       if (strchr (name, '(') != NULL)
5751         {
5752           gdb::unique_xmalloc_ptr<char> without_params
5753             = cp_remove_params (name);
5754
5755           if (without_params != NULL)
5756             {
5757               name = without_params.get();
5758             }
5759         }
5760     }
5761
5762   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5763
5764   const uint32_t full_hash = dwarf5_djb_hash (name);
5765   uint32_t namei
5766     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5767                                 (map.bucket_table_reordered
5768                                  + (full_hash % map.bucket_count)), 4,
5769                                 map.dwarf5_byte_order);
5770   if (namei == 0)
5771     return NULL;
5772   --namei;
5773   if (namei >= map.name_count)
5774     {
5775       complaint (&symfile_complaints,
5776                  _("Wrong .debug_names with name index %u but name_count=%u "
5777                    "[in module %s]"),
5778                  namei, map.name_count,
5779                  objfile_name (map.dwarf2_per_objfile->objfile));
5780       return NULL;
5781     }
5782
5783   for (;;)
5784     {
5785       const uint32_t namei_full_hash
5786         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5787                                     (map.hash_table_reordered + namei), 4,
5788                                     map.dwarf5_byte_order);
5789       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5790         return NULL;
5791
5792       if (full_hash == namei_full_hash)
5793         {
5794           const char *const namei_string = map.namei_to_name (namei);
5795
5796 #if 0 /* An expensive sanity check.  */
5797           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5798             {
5799               complaint (&symfile_complaints,
5800                          _("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 (&symfile_complaints,
5830                  _("Wrong .debug_names with name index %u but name_count=%u "
5831                    "[in module %s]"),
5832                  namei, map.name_count,
5833                  objfile_name (map.dwarf2_per_objfile->objfile));
5834       return NULL;
5835     }
5836
5837   const ULONGEST namei_entry_offs
5838     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5839                                  + namei * map.offset_size),
5840                                 map.offset_size, map.dwarf5_byte_order);
5841   return map.entry_pool + namei_entry_offs;
5842 }
5843
5844 /* See dw2_debug_names_iterator.  */
5845
5846 dwarf2_per_cu_data *
5847 dw2_debug_names_iterator::next ()
5848 {
5849   if (m_addr == NULL)
5850     return NULL;
5851
5852   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5853   struct objfile *objfile = dwarf2_per_objfile->objfile;
5854   bfd *const abfd = objfile->obfd;
5855
5856  again:
5857
5858   unsigned int bytes_read;
5859   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5860   m_addr += bytes_read;
5861   if (abbrev == 0)
5862     return NULL;
5863
5864   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5865   if (indexval_it == m_map.abbrev_map.cend ())
5866     {
5867       complaint (&symfile_complaints,
5868                  _("Wrong .debug_names undefined abbrev code %s "
5869                    "[in module %s]"),
5870                  pulongest (abbrev), objfile_name (objfile));
5871       return NULL;
5872     }
5873   const mapped_debug_names::index_val &indexval = indexval_it->second;
5874   bool have_is_static = false;
5875   bool is_static;
5876   dwarf2_per_cu_data *per_cu = NULL;
5877   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5878     {
5879       ULONGEST ull;
5880       switch (attr.form)
5881         {
5882         case DW_FORM_implicit_const:
5883           ull = attr.implicit_const;
5884           break;
5885         case DW_FORM_flag_present:
5886           ull = 1;
5887           break;
5888         case DW_FORM_udata:
5889           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5890           m_addr += bytes_read;
5891           break;
5892         default:
5893           complaint (&symfile_complaints,
5894                      _("Unsupported .debug_names form %s [in module %s]"),
5895                      dwarf_form_name (attr.form),
5896                      objfile_name (objfile));
5897           return NULL;
5898         }
5899       switch (attr.dw_idx)
5900         {
5901         case DW_IDX_compile_unit:
5902           /* Don't crash on bad data.  */
5903           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5904             {
5905               complaint (&symfile_complaints,
5906                          _(".debug_names entry has bad CU index %s"
5907                            " [in module %s]"),
5908                          pulongest (ull),
5909                          objfile_name (dwarf2_per_objfile->objfile));
5910               continue;
5911             }
5912           per_cu = dwarf2_per_objfile->get_cutu (ull);
5913           break;
5914         case DW_IDX_type_unit:
5915           /* Don't crash on bad data.  */
5916           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5917             {
5918               complaint (&symfile_complaints,
5919                          _(".debug_names entry has bad TU index %s"
5920                            " [in module %s]"),
5921                          pulongest (ull),
5922                          objfile_name (dwarf2_per_objfile->objfile));
5923               continue;
5924             }
5925           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5926           break;
5927         case DW_IDX_GNU_internal:
5928           if (!m_map.augmentation_is_gdb)
5929             break;
5930           have_is_static = true;
5931           is_static = true;
5932           break;
5933         case DW_IDX_GNU_external:
5934           if (!m_map.augmentation_is_gdb)
5935             break;
5936           have_is_static = true;
5937           is_static = false;
5938           break;
5939         }
5940     }
5941
5942   /* Skip if already read in.  */
5943   if (per_cu->v.quick->compunit_symtab)
5944     goto again;
5945
5946   /* Check static vs global.  */
5947   if (have_is_static)
5948     {
5949       const bool want_static = m_block_index != GLOBAL_BLOCK;
5950       if (m_want_specific_block && want_static != is_static)
5951         goto again;
5952     }
5953
5954   /* Match dw2_symtab_iter_next, symbol_kind
5955      and debug_names::psymbol_tag.  */
5956   switch (m_domain)
5957     {
5958     case VAR_DOMAIN:
5959       switch (indexval.dwarf_tag)
5960         {
5961         case DW_TAG_variable:
5962         case DW_TAG_subprogram:
5963         /* Some types are also in VAR_DOMAIN.  */
5964         case DW_TAG_typedef:
5965         case DW_TAG_structure_type:
5966           break;
5967         default:
5968           goto again;
5969         }
5970       break;
5971     case STRUCT_DOMAIN:
5972       switch (indexval.dwarf_tag)
5973         {
5974         case DW_TAG_typedef:
5975         case DW_TAG_structure_type:
5976           break;
5977         default:
5978           goto again;
5979         }
5980       break;
5981     case LABEL_DOMAIN:
5982       switch (indexval.dwarf_tag)
5983         {
5984         case 0:
5985         case DW_TAG_variable:
5986           break;
5987         default:
5988           goto again;
5989         }
5990       break;
5991     default:
5992       break;
5993     }
5994
5995   /* Match dw2_expand_symtabs_matching, symbol_kind and
5996      debug_names::psymbol_tag.  */
5997   switch (m_search)
5998     {
5999     case VARIABLES_DOMAIN:
6000       switch (indexval.dwarf_tag)
6001         {
6002         case DW_TAG_variable:
6003           break;
6004         default:
6005           goto again;
6006         }
6007       break;
6008     case FUNCTIONS_DOMAIN:
6009       switch (indexval.dwarf_tag)
6010         {
6011         case DW_TAG_subprogram:
6012           break;
6013         default:
6014           goto again;
6015         }
6016       break;
6017     case TYPES_DOMAIN:
6018       switch (indexval.dwarf_tag)
6019         {
6020         case DW_TAG_typedef:
6021         case DW_TAG_structure_type:
6022           break;
6023         default:
6024           goto again;
6025         }
6026       break;
6027     default:
6028       break;
6029     }
6030
6031   return per_cu;
6032 }
6033
6034 static struct compunit_symtab *
6035 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6036                                const char *name, domain_enum domain)
6037 {
6038   const block_enum block_index = static_cast<block_enum> (block_index_int);
6039   struct dwarf2_per_objfile *dwarf2_per_objfile
6040     = get_dwarf2_per_objfile (objfile);
6041
6042   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6043   if (!mapp)
6044     {
6045       /* index is NULL if OBJF_READNOW.  */
6046       return NULL;
6047     }
6048   const auto &map = *mapp;
6049
6050   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6051                                  block_index, domain, name);
6052
6053   struct compunit_symtab *stab_best = NULL;
6054   struct dwarf2_per_cu_data *per_cu;
6055   while ((per_cu = iter.next ()) != NULL)
6056     {
6057       struct symbol *sym, *with_opaque = NULL;
6058       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6059       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6060       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6061
6062       sym = block_find_symbol (block, name, domain,
6063                                block_find_non_opaque_type_preferred,
6064                                &with_opaque);
6065
6066       /* Some caution must be observed with overloaded functions and
6067          methods, since the index will not contain any overload
6068          information (but NAME might contain it).  */
6069
6070       if (sym != NULL
6071           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6072         return stab;
6073       if (with_opaque != NULL
6074           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6075         stab_best = stab;
6076
6077       /* Keep looking through other CUs.  */
6078     }
6079
6080   return stab_best;
6081 }
6082
6083 /* This dumps minimal information about .debug_names.  It is called
6084    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6085    uses this to verify that .debug_names has been loaded.  */
6086
6087 static void
6088 dw2_debug_names_dump (struct objfile *objfile)
6089 {
6090   struct dwarf2_per_objfile *dwarf2_per_objfile
6091     = get_dwarf2_per_objfile (objfile);
6092
6093   gdb_assert (dwarf2_per_objfile->using_index);
6094   printf_filtered (".debug_names:");
6095   if (dwarf2_per_objfile->debug_names_table)
6096     printf_filtered (" exists\n");
6097   else
6098     printf_filtered (" faked for \"readnow\"\n");
6099   printf_filtered ("\n");
6100 }
6101
6102 static void
6103 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6104                                              const char *func_name)
6105 {
6106   struct dwarf2_per_objfile *dwarf2_per_objfile
6107     = get_dwarf2_per_objfile (objfile);
6108
6109   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6110   if (dwarf2_per_objfile->debug_names_table)
6111     {
6112       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6113
6114       /* Note: It doesn't matter what we pass for block_index here.  */
6115       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6116                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6117
6118       struct dwarf2_per_cu_data *per_cu;
6119       while ((per_cu = iter.next ()) != NULL)
6120         dw2_instantiate_symtab (per_cu, false);
6121     }
6122 }
6123
6124 static void
6125 dw2_debug_names_expand_symtabs_matching
6126   (struct objfile *objfile,
6127    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6128    const lookup_name_info &lookup_name,
6129    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6130    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6131    enum search_domain kind)
6132 {
6133   struct dwarf2_per_objfile *dwarf2_per_objfile
6134     = get_dwarf2_per_objfile (objfile);
6135
6136   /* debug_names_table is NULL if OBJF_READNOW.  */
6137   if (!dwarf2_per_objfile->debug_names_table)
6138     return;
6139
6140   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6141
6142   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6143
6144   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6145                                       symbol_matcher,
6146                                       kind, [&] (offset_type namei)
6147     {
6148       /* The name was matched, now expand corresponding CUs that were
6149          marked.  */
6150       dw2_debug_names_iterator iter (map, kind, namei);
6151
6152       struct dwarf2_per_cu_data *per_cu;
6153       while ((per_cu = iter.next ()) != NULL)
6154         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6155                                          expansion_notify);
6156     });
6157 }
6158
6159 const struct quick_symbol_functions dwarf2_debug_names_functions =
6160 {
6161   dw2_has_symbols,
6162   dw2_find_last_source_symtab,
6163   dw2_forget_cached_source_info,
6164   dw2_map_symtabs_matching_filename,
6165   dw2_debug_names_lookup_symbol,
6166   dw2_print_stats,
6167   dw2_debug_names_dump,
6168   dw2_relocate,
6169   dw2_debug_names_expand_symtabs_for_function,
6170   dw2_expand_all_symtabs,
6171   dw2_expand_symtabs_with_fullname,
6172   dw2_map_matching_symbols,
6173   dw2_debug_names_expand_symtabs_matching,
6174   dw2_find_pc_sect_compunit_symtab,
6175   NULL,
6176   dw2_map_symbol_filenames
6177 };
6178
6179 /* See symfile.h.  */
6180
6181 bool
6182 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6183 {
6184   struct dwarf2_per_objfile *dwarf2_per_objfile
6185     = get_dwarf2_per_objfile (objfile);
6186
6187   /* If we're about to read full symbols, don't bother with the
6188      indices.  In this case we also don't care if some other debug
6189      format is making psymtabs, because they are all about to be
6190      expanded anyway.  */
6191   if ((objfile->flags & OBJF_READNOW))
6192     {
6193       dwarf2_per_objfile->using_index = 1;
6194       create_all_comp_units (dwarf2_per_objfile);
6195       create_all_type_units (dwarf2_per_objfile);
6196       dwarf2_per_objfile->quick_file_names_table
6197         = create_quick_file_names_table
6198             (dwarf2_per_objfile->all_comp_units.size ());
6199
6200       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6201                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6202         {
6203           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6204
6205           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6206                                             struct dwarf2_per_cu_quick_data);
6207         }
6208
6209       /* Return 1 so that gdb sees the "quick" functions.  However,
6210          these functions will be no-ops because we will have expanded
6211          all symtabs.  */
6212       *index_kind = dw_index_kind::GDB_INDEX;
6213       return true;
6214     }
6215
6216   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6217     {
6218       *index_kind = dw_index_kind::DEBUG_NAMES;
6219       return true;
6220     }
6221
6222   if (dwarf2_read_index (dwarf2_per_objfile))
6223     {
6224       *index_kind = dw_index_kind::GDB_INDEX;
6225       return true;
6226     }
6227
6228   return false;
6229 }
6230
6231 \f
6232
6233 /* Build a partial symbol table.  */
6234
6235 void
6236 dwarf2_build_psymtabs (struct objfile *objfile)
6237 {
6238   struct dwarf2_per_objfile *dwarf2_per_objfile
6239     = get_dwarf2_per_objfile (objfile);
6240
6241   if (objfile->global_psymbols.capacity () == 0
6242       && objfile->static_psymbols.capacity () == 0)
6243     init_psymbol_list (objfile, 1024);
6244
6245   TRY
6246     {
6247       /* This isn't really ideal: all the data we allocate on the
6248          objfile's obstack is still uselessly kept around.  However,
6249          freeing it seems unsafe.  */
6250       psymtab_discarder psymtabs (objfile);
6251       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6252       psymtabs.keep ();
6253     }
6254   CATCH (except, RETURN_MASK_ERROR)
6255     {
6256       exception_print (gdb_stderr, except);
6257     }
6258   END_CATCH
6259 }
6260
6261 /* Return the total length of the CU described by HEADER.  */
6262
6263 static unsigned int
6264 get_cu_length (const struct comp_unit_head *header)
6265 {
6266   return header->initial_length_size + header->length;
6267 }
6268
6269 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6270
6271 static inline bool
6272 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6273 {
6274   sect_offset bottom = cu_header->sect_off;
6275   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6276
6277   return sect_off >= bottom && sect_off < top;
6278 }
6279
6280 /* Find the base address of the compilation unit for range lists and
6281    location lists.  It will normally be specified by DW_AT_low_pc.
6282    In DWARF-3 draft 4, the base address could be overridden by
6283    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6284    compilation units with discontinuous ranges.  */
6285
6286 static void
6287 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6288 {
6289   struct attribute *attr;
6290
6291   cu->base_known = 0;
6292   cu->base_address = 0;
6293
6294   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6295   if (attr)
6296     {
6297       cu->base_address = attr_value_as_address (attr);
6298       cu->base_known = 1;
6299     }
6300   else
6301     {
6302       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6303       if (attr)
6304         {
6305           cu->base_address = attr_value_as_address (attr);
6306           cu->base_known = 1;
6307         }
6308     }
6309 }
6310
6311 /* Read in the comp unit header information from the debug_info at info_ptr.
6312    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6313    NOTE: This leaves members offset, first_die_offset to be filled in
6314    by the caller.  */
6315
6316 static const gdb_byte *
6317 read_comp_unit_head (struct comp_unit_head *cu_header,
6318                      const gdb_byte *info_ptr,
6319                      struct dwarf2_section_info *section,
6320                      rcuh_kind section_kind)
6321 {
6322   int signed_addr;
6323   unsigned int bytes_read;
6324   const char *filename = get_section_file_name (section);
6325   bfd *abfd = get_section_bfd_owner (section);
6326
6327   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6328   cu_header->initial_length_size = bytes_read;
6329   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6330   info_ptr += bytes_read;
6331   cu_header->version = read_2_bytes (abfd, info_ptr);
6332   info_ptr += 2;
6333   if (cu_header->version < 5)
6334     switch (section_kind)
6335       {
6336       case rcuh_kind::COMPILE:
6337         cu_header->unit_type = DW_UT_compile;
6338         break;
6339       case rcuh_kind::TYPE:
6340         cu_header->unit_type = DW_UT_type;
6341         break;
6342       default:
6343         internal_error (__FILE__, __LINE__,
6344                         _("read_comp_unit_head: invalid section_kind"));
6345       }
6346   else
6347     {
6348       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6349                                                  (read_1_byte (abfd, info_ptr));
6350       info_ptr += 1;
6351       switch (cu_header->unit_type)
6352         {
6353         case DW_UT_compile:
6354           if (section_kind != rcuh_kind::COMPILE)
6355             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6356                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6357                    filename);
6358           break;
6359         case DW_UT_type:
6360           section_kind = rcuh_kind::TYPE;
6361           break;
6362         default:
6363           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6364                  "(is %d, should be %d or %d) [in module %s]"),
6365                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6366         }
6367
6368       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6369       info_ptr += 1;
6370     }
6371   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6372                                                           cu_header,
6373                                                           &bytes_read);
6374   info_ptr += bytes_read;
6375   if (cu_header->version < 5)
6376     {
6377       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6378       info_ptr += 1;
6379     }
6380   signed_addr = bfd_get_sign_extend_vma (abfd);
6381   if (signed_addr < 0)
6382     internal_error (__FILE__, __LINE__,
6383                     _("read_comp_unit_head: dwarf from non elf file"));
6384   cu_header->signed_addr_p = signed_addr;
6385
6386   if (section_kind == rcuh_kind::TYPE)
6387     {
6388       LONGEST type_offset;
6389
6390       cu_header->signature = read_8_bytes (abfd, info_ptr);
6391       info_ptr += 8;
6392
6393       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6394       info_ptr += bytes_read;
6395       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6396       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6397         error (_("Dwarf Error: Too big type_offset in compilation unit "
6398                "header (is %s) [in module %s]"), plongest (type_offset),
6399                filename);
6400     }
6401
6402   return info_ptr;
6403 }
6404
6405 /* Helper function that returns the proper abbrev section for
6406    THIS_CU.  */
6407
6408 static struct dwarf2_section_info *
6409 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6410 {
6411   struct dwarf2_section_info *abbrev;
6412   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6413
6414   if (this_cu->is_dwz)
6415     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6416   else
6417     abbrev = &dwarf2_per_objfile->abbrev;
6418
6419   return abbrev;
6420 }
6421
6422 /* Subroutine of read_and_check_comp_unit_head and
6423    read_and_check_type_unit_head to simplify them.
6424    Perform various error checking on the header.  */
6425
6426 static void
6427 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6428                             struct comp_unit_head *header,
6429                             struct dwarf2_section_info *section,
6430                             struct dwarf2_section_info *abbrev_section)
6431 {
6432   const char *filename = get_section_file_name (section);
6433
6434   if (header->version < 2 || header->version > 5)
6435     error (_("Dwarf Error: wrong version in compilation unit header "
6436            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6437            filename);
6438
6439   if (to_underlying (header->abbrev_sect_off)
6440       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6441     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6442            "(offset %s + 6) [in module %s]"),
6443            sect_offset_str (header->abbrev_sect_off),
6444            sect_offset_str (header->sect_off),
6445            filename);
6446
6447   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6448      avoid potential 32-bit overflow.  */
6449   if (((ULONGEST) header->sect_off + get_cu_length (header))
6450       > section->size)
6451     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6452            "(offset %s + 0) [in module %s]"),
6453            header->length, sect_offset_str (header->sect_off),
6454            filename);
6455 }
6456
6457 /* Read in a CU/TU header and perform some basic error checking.
6458    The contents of the header are stored in HEADER.
6459    The result is a pointer to the start of the first DIE.  */
6460
6461 static const gdb_byte *
6462 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6463                                struct comp_unit_head *header,
6464                                struct dwarf2_section_info *section,
6465                                struct dwarf2_section_info *abbrev_section,
6466                                const gdb_byte *info_ptr,
6467                                rcuh_kind section_kind)
6468 {
6469   const gdb_byte *beg_of_comp_unit = info_ptr;
6470
6471   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6472
6473   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6474
6475   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6476
6477   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6478                               abbrev_section);
6479
6480   return info_ptr;
6481 }
6482
6483 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6484
6485 static sect_offset
6486 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6487                     struct dwarf2_section_info *section,
6488                     sect_offset sect_off)
6489 {
6490   bfd *abfd = get_section_bfd_owner (section);
6491   const gdb_byte *info_ptr;
6492   unsigned int initial_length_size, offset_size;
6493   uint16_t version;
6494
6495   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6496   info_ptr = section->buffer + to_underlying (sect_off);
6497   read_initial_length (abfd, info_ptr, &initial_length_size);
6498   offset_size = initial_length_size == 4 ? 4 : 8;
6499   info_ptr += initial_length_size;
6500
6501   version = read_2_bytes (abfd, info_ptr);
6502   info_ptr += 2;
6503   if (version >= 5)
6504     {
6505       /* Skip unit type and address size.  */
6506       info_ptr += 2;
6507     }
6508
6509   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6510 }
6511
6512 /* Allocate a new partial symtab for file named NAME and mark this new
6513    partial symtab as being an include of PST.  */
6514
6515 static void
6516 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6517                                struct objfile *objfile)
6518 {
6519   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6520
6521   if (!IS_ABSOLUTE_PATH (subpst->filename))
6522     {
6523       /* It shares objfile->objfile_obstack.  */
6524       subpst->dirname = pst->dirname;
6525     }
6526
6527   subpst->textlow = 0;
6528   subpst->texthigh = 0;
6529
6530   subpst->dependencies
6531     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6532   subpst->dependencies[0] = pst;
6533   subpst->number_of_dependencies = 1;
6534
6535   subpst->globals_offset = 0;
6536   subpst->n_global_syms = 0;
6537   subpst->statics_offset = 0;
6538   subpst->n_static_syms = 0;
6539   subpst->compunit_symtab = NULL;
6540   subpst->read_symtab = pst->read_symtab;
6541   subpst->readin = 0;
6542
6543   /* No private part is necessary for include psymtabs.  This property
6544      can be used to differentiate between such include psymtabs and
6545      the regular ones.  */
6546   subpst->read_symtab_private = NULL;
6547 }
6548
6549 /* Read the Line Number Program data and extract the list of files
6550    included by the source file represented by PST.  Build an include
6551    partial symtab for each of these included files.  */
6552
6553 static void
6554 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6555                                struct die_info *die,
6556                                struct partial_symtab *pst)
6557 {
6558   line_header_up lh;
6559   struct attribute *attr;
6560
6561   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6562   if (attr)
6563     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6564   if (lh == NULL)
6565     return;  /* No linetable, so no includes.  */
6566
6567   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6568   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6569 }
6570
6571 static hashval_t
6572 hash_signatured_type (const void *item)
6573 {
6574   const struct signatured_type *sig_type
6575     = (const struct signatured_type *) item;
6576
6577   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6578   return sig_type->signature;
6579 }
6580
6581 static int
6582 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6583 {
6584   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6585   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6586
6587   return lhs->signature == rhs->signature;
6588 }
6589
6590 /* Allocate a hash table for signatured types.  */
6591
6592 static htab_t
6593 allocate_signatured_type_table (struct objfile *objfile)
6594 {
6595   return htab_create_alloc_ex (41,
6596                                hash_signatured_type,
6597                                eq_signatured_type,
6598                                NULL,
6599                                &objfile->objfile_obstack,
6600                                hashtab_obstack_allocate,
6601                                dummy_obstack_deallocate);
6602 }
6603
6604 /* A helper function to add a signatured type CU to a table.  */
6605
6606 static int
6607 add_signatured_type_cu_to_table (void **slot, void *datum)
6608 {
6609   struct signatured_type *sigt = (struct signatured_type *) *slot;
6610   std::vector<signatured_type *> *all_type_units
6611     = (std::vector<signatured_type *> *) datum;
6612
6613   all_type_units->push_back (sigt);
6614
6615   return 1;
6616 }
6617
6618 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6619    and fill them into TYPES_HTAB.  It will process only type units,
6620    therefore DW_UT_type.  */
6621
6622 static void
6623 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6624                               struct dwo_file *dwo_file,
6625                               dwarf2_section_info *section, htab_t &types_htab,
6626                               rcuh_kind section_kind)
6627 {
6628   struct objfile *objfile = dwarf2_per_objfile->objfile;
6629   struct dwarf2_section_info *abbrev_section;
6630   bfd *abfd;
6631   const gdb_byte *info_ptr, *end_ptr;
6632
6633   abbrev_section = (dwo_file != NULL
6634                     ? &dwo_file->sections.abbrev
6635                     : &dwarf2_per_objfile->abbrev);
6636
6637   if (dwarf_read_debug)
6638     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6639                         get_section_name (section),
6640                         get_section_file_name (abbrev_section));
6641
6642   dwarf2_read_section (objfile, section);
6643   info_ptr = section->buffer;
6644
6645   if (info_ptr == NULL)
6646     return;
6647
6648   /* We can't set abfd until now because the section may be empty or
6649      not present, in which case the bfd is unknown.  */
6650   abfd = get_section_bfd_owner (section);
6651
6652   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6653      because we don't need to read any dies: the signature is in the
6654      header.  */
6655
6656   end_ptr = info_ptr + section->size;
6657   while (info_ptr < end_ptr)
6658     {
6659       struct signatured_type *sig_type;
6660       struct dwo_unit *dwo_tu;
6661       void **slot;
6662       const gdb_byte *ptr = info_ptr;
6663       struct comp_unit_head header;
6664       unsigned int length;
6665
6666       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6667
6668       /* Initialize it due to a false compiler warning.  */
6669       header.signature = -1;
6670       header.type_cu_offset_in_tu = (cu_offset) -1;
6671
6672       /* We need to read the type's signature in order to build the hash
6673          table, but we don't need anything else just yet.  */
6674
6675       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6676                                            abbrev_section, ptr, section_kind);
6677
6678       length = get_cu_length (&header);
6679
6680       /* Skip dummy type units.  */
6681       if (ptr >= info_ptr + length
6682           || peek_abbrev_code (abfd, ptr) == 0
6683           || header.unit_type != DW_UT_type)
6684         {
6685           info_ptr += length;
6686           continue;
6687         }
6688
6689       if (types_htab == NULL)
6690         {
6691           if (dwo_file)
6692             types_htab = allocate_dwo_unit_table (objfile);
6693           else
6694             types_htab = allocate_signatured_type_table (objfile);
6695         }
6696
6697       if (dwo_file)
6698         {
6699           sig_type = NULL;
6700           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6701                                    struct dwo_unit);
6702           dwo_tu->dwo_file = dwo_file;
6703           dwo_tu->signature = header.signature;
6704           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6705           dwo_tu->section = section;
6706           dwo_tu->sect_off = sect_off;
6707           dwo_tu->length = length;
6708         }
6709       else
6710         {
6711           /* N.B.: type_offset is not usable if this type uses a DWO file.
6712              The real type_offset is in the DWO file.  */
6713           dwo_tu = NULL;
6714           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6715                                      struct signatured_type);
6716           sig_type->signature = header.signature;
6717           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6718           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6719           sig_type->per_cu.is_debug_types = 1;
6720           sig_type->per_cu.section = section;
6721           sig_type->per_cu.sect_off = sect_off;
6722           sig_type->per_cu.length = length;
6723         }
6724
6725       slot = htab_find_slot (types_htab,
6726                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6727                              INSERT);
6728       gdb_assert (slot != NULL);
6729       if (*slot != NULL)
6730         {
6731           sect_offset dup_sect_off;
6732
6733           if (dwo_file)
6734             {
6735               const struct dwo_unit *dup_tu
6736                 = (const struct dwo_unit *) *slot;
6737
6738               dup_sect_off = dup_tu->sect_off;
6739             }
6740           else
6741             {
6742               const struct signatured_type *dup_tu
6743                 = (const struct signatured_type *) *slot;
6744
6745               dup_sect_off = dup_tu->per_cu.sect_off;
6746             }
6747
6748           complaint (&symfile_complaints,
6749                      _("debug type entry at offset %s is duplicate to"
6750                        " the entry at offset %s, signature %s"),
6751                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6752                      hex_string (header.signature));
6753         }
6754       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6755
6756       if (dwarf_read_debug > 1)
6757         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6758                             sect_offset_str (sect_off),
6759                             hex_string (header.signature));
6760
6761       info_ptr += length;
6762     }
6763 }
6764
6765 /* Create the hash table of all entries in the .debug_types
6766    (or .debug_types.dwo) section(s).
6767    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6768    otherwise it is NULL.
6769
6770    The result is a pointer to the hash table or NULL if there are no types.
6771
6772    Note: This function processes DWO files only, not DWP files.  */
6773
6774 static void
6775 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6776                                struct dwo_file *dwo_file,
6777                                VEC (dwarf2_section_info_def) *types,
6778                                htab_t &types_htab)
6779 {
6780   int ix;
6781   struct dwarf2_section_info *section;
6782
6783   if (VEC_empty (dwarf2_section_info_def, types))
6784     return;
6785
6786   for (ix = 0;
6787        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6788        ++ix)
6789     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6790                                   types_htab, rcuh_kind::TYPE);
6791 }
6792
6793 /* Create the hash table of all entries in the .debug_types section,
6794    and initialize all_type_units.
6795    The result is zero if there is an error (e.g. missing .debug_types section),
6796    otherwise non-zero.  */
6797
6798 static int
6799 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6800 {
6801   htab_t types_htab = NULL;
6802
6803   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6804                                 &dwarf2_per_objfile->info, types_htab,
6805                                 rcuh_kind::COMPILE);
6806   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6807                                  dwarf2_per_objfile->types, types_htab);
6808   if (types_htab == NULL)
6809     {
6810       dwarf2_per_objfile->signatured_types = NULL;
6811       return 0;
6812     }
6813
6814   dwarf2_per_objfile->signatured_types = types_htab;
6815
6816   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6817   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6818
6819   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6820                           &dwarf2_per_objfile->all_type_units);
6821
6822   return 1;
6823 }
6824
6825 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6826    If SLOT is non-NULL, it is the entry to use in the hash table.
6827    Otherwise we find one.  */
6828
6829 static struct signatured_type *
6830 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6831                void **slot)
6832 {
6833   struct objfile *objfile = dwarf2_per_objfile->objfile;
6834
6835   if (dwarf2_per_objfile->all_type_units.size ()
6836       == dwarf2_per_objfile->all_type_units.capacity ())
6837     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6838
6839   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6840                                               struct signatured_type);
6841
6842   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6843   sig_type->signature = sig;
6844   sig_type->per_cu.is_debug_types = 1;
6845   if (dwarf2_per_objfile->using_index)
6846     {
6847       sig_type->per_cu.v.quick =
6848         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6849                         struct dwarf2_per_cu_quick_data);
6850     }
6851
6852   if (slot == NULL)
6853     {
6854       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6855                              sig_type, INSERT);
6856     }
6857   gdb_assert (*slot == NULL);
6858   *slot = sig_type;
6859   /* The rest of sig_type must be filled in by the caller.  */
6860   return sig_type;
6861 }
6862
6863 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6864    Fill in SIG_ENTRY with DWO_ENTRY.  */
6865
6866 static void
6867 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6868                                   struct signatured_type *sig_entry,
6869                                   struct dwo_unit *dwo_entry)
6870 {
6871   /* Make sure we're not clobbering something we don't expect to.  */
6872   gdb_assert (! sig_entry->per_cu.queued);
6873   gdb_assert (sig_entry->per_cu.cu == NULL);
6874   if (dwarf2_per_objfile->using_index)
6875     {
6876       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6877       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6878     }
6879   else
6880       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6881   gdb_assert (sig_entry->signature == dwo_entry->signature);
6882   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6883   gdb_assert (sig_entry->type_unit_group == NULL);
6884   gdb_assert (sig_entry->dwo_unit == NULL);
6885
6886   sig_entry->per_cu.section = dwo_entry->section;
6887   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6888   sig_entry->per_cu.length = dwo_entry->length;
6889   sig_entry->per_cu.reading_dwo_directly = 1;
6890   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6891   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6892   sig_entry->dwo_unit = dwo_entry;
6893 }
6894
6895 /* Subroutine of lookup_signatured_type.
6896    If we haven't read the TU yet, create the signatured_type data structure
6897    for a TU to be read in directly from a DWO file, bypassing the stub.
6898    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6899    using .gdb_index, then when reading a CU we want to stay in the DWO file
6900    containing that CU.  Otherwise we could end up reading several other DWO
6901    files (due to comdat folding) to process the transitive closure of all the
6902    mentioned TUs, and that can be slow.  The current DWO file will have every
6903    type signature that it needs.
6904    We only do this for .gdb_index because in the psymtab case we already have
6905    to read all the DWOs to build the type unit groups.  */
6906
6907 static struct signatured_type *
6908 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6909 {
6910   struct dwarf2_per_objfile *dwarf2_per_objfile
6911     = cu->per_cu->dwarf2_per_objfile;
6912   struct objfile *objfile = dwarf2_per_objfile->objfile;
6913   struct dwo_file *dwo_file;
6914   struct dwo_unit find_dwo_entry, *dwo_entry;
6915   struct signatured_type find_sig_entry, *sig_entry;
6916   void **slot;
6917
6918   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6919
6920   /* If TU skeletons have been removed then we may not have read in any
6921      TUs yet.  */
6922   if (dwarf2_per_objfile->signatured_types == NULL)
6923     {
6924       dwarf2_per_objfile->signatured_types
6925         = allocate_signatured_type_table (objfile);
6926     }
6927
6928   /* We only ever need to read in one copy of a signatured type.
6929      Use the global signatured_types array to do our own comdat-folding
6930      of types.  If this is the first time we're reading this TU, and
6931      the TU has an entry in .gdb_index, replace the recorded data from
6932      .gdb_index with this TU.  */
6933
6934   find_sig_entry.signature = sig;
6935   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6936                          &find_sig_entry, INSERT);
6937   sig_entry = (struct signatured_type *) *slot;
6938
6939   /* We can get here with the TU already read, *or* in the process of being
6940      read.  Don't reassign the global entry to point to this DWO if that's
6941      the case.  Also note that if the TU is already being read, it may not
6942      have come from a DWO, the program may be a mix of Fission-compiled
6943      code and non-Fission-compiled code.  */
6944
6945   /* Have we already tried to read this TU?
6946      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6947      needn't exist in the global table yet).  */
6948   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6949     return sig_entry;
6950
6951   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6952      dwo_unit of the TU itself.  */
6953   dwo_file = cu->dwo_unit->dwo_file;
6954
6955   /* Ok, this is the first time we're reading this TU.  */
6956   if (dwo_file->tus == NULL)
6957     return NULL;
6958   find_dwo_entry.signature = sig;
6959   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6960   if (dwo_entry == NULL)
6961     return NULL;
6962
6963   /* If the global table doesn't have an entry for this TU, add one.  */
6964   if (sig_entry == NULL)
6965     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6966
6967   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6968   sig_entry->per_cu.tu_read = 1;
6969   return sig_entry;
6970 }
6971
6972 /* Subroutine of lookup_signatured_type.
6973    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6974    then try the DWP file.  If the TU stub (skeleton) has been removed then
6975    it won't be in .gdb_index.  */
6976
6977 static struct signatured_type *
6978 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6979 {
6980   struct dwarf2_per_objfile *dwarf2_per_objfile
6981     = cu->per_cu->dwarf2_per_objfile;
6982   struct objfile *objfile = dwarf2_per_objfile->objfile;
6983   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6984   struct dwo_unit *dwo_entry;
6985   struct signatured_type find_sig_entry, *sig_entry;
6986   void **slot;
6987
6988   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6989   gdb_assert (dwp_file != NULL);
6990
6991   /* If TU skeletons have been removed then we may not have read in any
6992      TUs yet.  */
6993   if (dwarf2_per_objfile->signatured_types == NULL)
6994     {
6995       dwarf2_per_objfile->signatured_types
6996         = allocate_signatured_type_table (objfile);
6997     }
6998
6999   find_sig_entry.signature = sig;
7000   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7001                          &find_sig_entry, INSERT);
7002   sig_entry = (struct signatured_type *) *slot;
7003
7004   /* Have we already tried to read this TU?
7005      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7006      needn't exist in the global table yet).  */
7007   if (sig_entry != NULL)
7008     return sig_entry;
7009
7010   if (dwp_file->tus == NULL)
7011     return NULL;
7012   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7013                                       sig, 1 /* is_debug_types */);
7014   if (dwo_entry == NULL)
7015     return NULL;
7016
7017   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7018   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7019
7020   return sig_entry;
7021 }
7022
7023 /* Lookup a signature based type for DW_FORM_ref_sig8.
7024    Returns NULL if signature SIG is not present in the table.
7025    It is up to the caller to complain about this.  */
7026
7027 static struct signatured_type *
7028 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7029 {
7030   struct dwarf2_per_objfile *dwarf2_per_objfile
7031     = cu->per_cu->dwarf2_per_objfile;
7032
7033   if (cu->dwo_unit
7034       && dwarf2_per_objfile->using_index)
7035     {
7036       /* We're in a DWO/DWP file, and we're using .gdb_index.
7037          These cases require special processing.  */
7038       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7039         return lookup_dwo_signatured_type (cu, sig);
7040       else
7041         return lookup_dwp_signatured_type (cu, sig);
7042     }
7043   else
7044     {
7045       struct signatured_type find_entry, *entry;
7046
7047       if (dwarf2_per_objfile->signatured_types == NULL)
7048         return NULL;
7049       find_entry.signature = sig;
7050       entry = ((struct signatured_type *)
7051                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7052       return entry;
7053     }
7054 }
7055 \f
7056 /* Low level DIE reading support.  */
7057
7058 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7059
7060 static void
7061 init_cu_die_reader (struct die_reader_specs *reader,
7062                     struct dwarf2_cu *cu,
7063                     struct dwarf2_section_info *section,
7064                     struct dwo_file *dwo_file,
7065                     struct abbrev_table *abbrev_table)
7066 {
7067   gdb_assert (section->readin && section->buffer != NULL);
7068   reader->abfd = get_section_bfd_owner (section);
7069   reader->cu = cu;
7070   reader->dwo_file = dwo_file;
7071   reader->die_section = section;
7072   reader->buffer = section->buffer;
7073   reader->buffer_end = section->buffer + section->size;
7074   reader->comp_dir = NULL;
7075   reader->abbrev_table = abbrev_table;
7076 }
7077
7078 /* Subroutine of init_cutu_and_read_dies to simplify it.
7079    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7080    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7081    already.
7082
7083    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7084    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7085    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7086    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7087    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7088    STUB_COMP_DIR may be non-NULL.
7089    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7090    are filled in with the info of the DIE from the DWO file.
7091    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7092    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7093    kept around for at least as long as *RESULT_READER.
7094
7095    The result is non-zero if a valid (non-dummy) DIE was found.  */
7096
7097 static int
7098 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7099                         struct dwo_unit *dwo_unit,
7100                         struct die_info *stub_comp_unit_die,
7101                         const char *stub_comp_dir,
7102                         struct die_reader_specs *result_reader,
7103                         const gdb_byte **result_info_ptr,
7104                         struct die_info **result_comp_unit_die,
7105                         int *result_has_children,
7106                         abbrev_table_up *result_dwo_abbrev_table)
7107 {
7108   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7109   struct objfile *objfile = dwarf2_per_objfile->objfile;
7110   struct dwarf2_cu *cu = this_cu->cu;
7111   bfd *abfd;
7112   const gdb_byte *begin_info_ptr, *info_ptr;
7113   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7114   int i,num_extra_attrs;
7115   struct dwarf2_section_info *dwo_abbrev_section;
7116   struct attribute *attr;
7117   struct die_info *comp_unit_die;
7118
7119   /* At most one of these may be provided.  */
7120   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7121
7122   /* These attributes aren't processed until later:
7123      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7124      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7125      referenced later.  However, these attributes are found in the stub
7126      which we won't have later.  In order to not impose this complication
7127      on the rest of the code, we read them here and copy them to the
7128      DWO CU/TU die.  */
7129
7130   stmt_list = NULL;
7131   low_pc = NULL;
7132   high_pc = NULL;
7133   ranges = NULL;
7134   comp_dir = NULL;
7135
7136   if (stub_comp_unit_die != NULL)
7137     {
7138       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7139          DWO file.  */
7140       if (! this_cu->is_debug_types)
7141         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7142       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7143       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7144       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7145       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7146
7147       /* There should be a DW_AT_addr_base attribute here (if needed).
7148          We need the value before we can process DW_FORM_GNU_addr_index.  */
7149       cu->addr_base = 0;
7150       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7151       if (attr)
7152         cu->addr_base = DW_UNSND (attr);
7153
7154       /* There should be a DW_AT_ranges_base attribute here (if needed).
7155          We need the value before we can process DW_AT_ranges.  */
7156       cu->ranges_base = 0;
7157       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7158       if (attr)
7159         cu->ranges_base = DW_UNSND (attr);
7160     }
7161   else if (stub_comp_dir != NULL)
7162     {
7163       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7164       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7165       comp_dir->name = DW_AT_comp_dir;
7166       comp_dir->form = DW_FORM_string;
7167       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7168       DW_STRING (comp_dir) = stub_comp_dir;
7169     }
7170
7171   /* Set up for reading the DWO CU/TU.  */
7172   cu->dwo_unit = dwo_unit;
7173   dwarf2_section_info *section = dwo_unit->section;
7174   dwarf2_read_section (objfile, section);
7175   abfd = get_section_bfd_owner (section);
7176   begin_info_ptr = info_ptr = (section->buffer
7177                                + to_underlying (dwo_unit->sect_off));
7178   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7179
7180   if (this_cu->is_debug_types)
7181     {
7182       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7183
7184       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7185                                                 &cu->header, section,
7186                                                 dwo_abbrev_section,
7187                                                 info_ptr, rcuh_kind::TYPE);
7188       /* This is not an assert because it can be caused by bad debug info.  */
7189       if (sig_type->signature != cu->header.signature)
7190         {
7191           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7192                    " TU at offset %s [in module %s]"),
7193                  hex_string (sig_type->signature),
7194                  hex_string (cu->header.signature),
7195                  sect_offset_str (dwo_unit->sect_off),
7196                  bfd_get_filename (abfd));
7197         }
7198       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7199       /* For DWOs coming from DWP files, we don't know the CU length
7200          nor the type's offset in the TU until now.  */
7201       dwo_unit->length = get_cu_length (&cu->header);
7202       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7203
7204       /* Establish the type offset that can be used to lookup the type.
7205          For DWO files, we don't know it until now.  */
7206       sig_type->type_offset_in_section
7207         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7208     }
7209   else
7210     {
7211       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7212                                                 &cu->header, section,
7213                                                 dwo_abbrev_section,
7214                                                 info_ptr, rcuh_kind::COMPILE);
7215       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7216       /* For DWOs coming from DWP files, we don't know the CU length
7217          until now.  */
7218       dwo_unit->length = get_cu_length (&cu->header);
7219     }
7220
7221   *result_dwo_abbrev_table
7222     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7223                                cu->header.abbrev_sect_off);
7224   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7225                       result_dwo_abbrev_table->get ());
7226
7227   /* Read in the die, but leave space to copy over the attributes
7228      from the stub.  This has the benefit of simplifying the rest of
7229      the code - all the work to maintain the illusion of a single
7230      DW_TAG_{compile,type}_unit DIE is done here.  */
7231   num_extra_attrs = ((stmt_list != NULL)
7232                      + (low_pc != NULL)
7233                      + (high_pc != NULL)
7234                      + (ranges != NULL)
7235                      + (comp_dir != NULL));
7236   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7237                               result_has_children, num_extra_attrs);
7238
7239   /* Copy over the attributes from the stub to the DIE we just read in.  */
7240   comp_unit_die = *result_comp_unit_die;
7241   i = comp_unit_die->num_attrs;
7242   if (stmt_list != NULL)
7243     comp_unit_die->attrs[i++] = *stmt_list;
7244   if (low_pc != NULL)
7245     comp_unit_die->attrs[i++] = *low_pc;
7246   if (high_pc != NULL)
7247     comp_unit_die->attrs[i++] = *high_pc;
7248   if (ranges != NULL)
7249     comp_unit_die->attrs[i++] = *ranges;
7250   if (comp_dir != NULL)
7251     comp_unit_die->attrs[i++] = *comp_dir;
7252   comp_unit_die->num_attrs += num_extra_attrs;
7253
7254   if (dwarf_die_debug)
7255     {
7256       fprintf_unfiltered (gdb_stdlog,
7257                           "Read die from %s@0x%x of %s:\n",
7258                           get_section_name (section),
7259                           (unsigned) (begin_info_ptr - section->buffer),
7260                           bfd_get_filename (abfd));
7261       dump_die (comp_unit_die, dwarf_die_debug);
7262     }
7263
7264   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7265      TUs by skipping the stub and going directly to the entry in the DWO file.
7266      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7267      to get it via circuitous means.  Blech.  */
7268   if (comp_dir != NULL)
7269     result_reader->comp_dir = DW_STRING (comp_dir);
7270
7271   /* Skip dummy compilation units.  */
7272   if (info_ptr >= begin_info_ptr + dwo_unit->length
7273       || peek_abbrev_code (abfd, info_ptr) == 0)
7274     return 0;
7275
7276   *result_info_ptr = info_ptr;
7277   return 1;
7278 }
7279
7280 /* Subroutine of init_cutu_and_read_dies to simplify it.
7281    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7282    Returns NULL if the specified DWO unit cannot be found.  */
7283
7284 static struct dwo_unit *
7285 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7286                  struct die_info *comp_unit_die)
7287 {
7288   struct dwarf2_cu *cu = this_cu->cu;
7289   ULONGEST signature;
7290   struct dwo_unit *dwo_unit;
7291   const char *comp_dir, *dwo_name;
7292
7293   gdb_assert (cu != NULL);
7294
7295   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7296   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7297   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7298
7299   if (this_cu->is_debug_types)
7300     {
7301       struct signatured_type *sig_type;
7302
7303       /* Since this_cu is the first member of struct signatured_type,
7304          we can go from a pointer to one to a pointer to the other.  */
7305       sig_type = (struct signatured_type *) this_cu;
7306       signature = sig_type->signature;
7307       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7308     }
7309   else
7310     {
7311       struct attribute *attr;
7312
7313       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7314       if (! attr)
7315         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7316                  " [in module %s]"),
7317                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7318       signature = DW_UNSND (attr);
7319       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7320                                        signature);
7321     }
7322
7323   return dwo_unit;
7324 }
7325
7326 /* Subroutine of init_cutu_and_read_dies to simplify it.
7327    See it for a description of the parameters.
7328    Read a TU directly from a DWO file, bypassing the stub.  */
7329
7330 static void
7331 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7332                            int use_existing_cu, int keep,
7333                            die_reader_func_ftype *die_reader_func,
7334                            void *data)
7335 {
7336   std::unique_ptr<dwarf2_cu> new_cu;
7337   struct signatured_type *sig_type;
7338   struct die_reader_specs reader;
7339   const gdb_byte *info_ptr;
7340   struct die_info *comp_unit_die;
7341   int has_children;
7342   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7343
7344   /* Verify we can do the following downcast, and that we have the
7345      data we need.  */
7346   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7347   sig_type = (struct signatured_type *) this_cu;
7348   gdb_assert (sig_type->dwo_unit != NULL);
7349
7350   if (use_existing_cu && this_cu->cu != NULL)
7351     {
7352       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7353       /* There's no need to do the rereading_dwo_cu handling that
7354          init_cutu_and_read_dies does since we don't read the stub.  */
7355     }
7356   else
7357     {
7358       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7359       gdb_assert (this_cu->cu == NULL);
7360       new_cu.reset (new dwarf2_cu (this_cu));
7361     }
7362
7363   /* A future optimization, if needed, would be to use an existing
7364      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7365      could share abbrev tables.  */
7366
7367   /* The abbreviation table used by READER, this must live at least as long as
7368      READER.  */
7369   abbrev_table_up dwo_abbrev_table;
7370
7371   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7372                               NULL /* stub_comp_unit_die */,
7373                               sig_type->dwo_unit->dwo_file->comp_dir,
7374                               &reader, &info_ptr,
7375                               &comp_unit_die, &has_children,
7376                               &dwo_abbrev_table) == 0)
7377     {
7378       /* Dummy die.  */
7379       return;
7380     }
7381
7382   /* All the "real" work is done here.  */
7383   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7384
7385   /* This duplicates the code in init_cutu_and_read_dies,
7386      but the alternative is making the latter more complex.
7387      This function is only for the special case of using DWO files directly:
7388      no point in overly complicating the general case just to handle this.  */
7389   if (new_cu != NULL && keep)
7390     {
7391       /* Link this CU into read_in_chain.  */
7392       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7393       dwarf2_per_objfile->read_in_chain = this_cu;
7394       /* The chain owns it now.  */
7395       new_cu.release ();
7396     }
7397 }
7398
7399 /* Initialize a CU (or TU) and read its DIEs.
7400    If the CU defers to a DWO file, read the DWO file as well.
7401
7402    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7403    Otherwise the table specified in the comp unit header is read in and used.
7404    This is an optimization for when we already have the abbrev table.
7405
7406    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7407    Otherwise, a new CU is allocated with xmalloc.
7408
7409    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7410    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7411
7412    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7413    linker) then DIE_READER_FUNC will not get called.  */
7414
7415 static void
7416 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7417                          struct abbrev_table *abbrev_table,
7418                          int use_existing_cu, int keep,
7419                          bool skip_partial,
7420                          die_reader_func_ftype *die_reader_func,
7421                          void *data)
7422 {
7423   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7424   struct objfile *objfile = dwarf2_per_objfile->objfile;
7425   struct dwarf2_section_info *section = this_cu->section;
7426   bfd *abfd = get_section_bfd_owner (section);
7427   struct dwarf2_cu *cu;
7428   const gdb_byte *begin_info_ptr, *info_ptr;
7429   struct die_reader_specs reader;
7430   struct die_info *comp_unit_die;
7431   int has_children;
7432   struct attribute *attr;
7433   struct signatured_type *sig_type = NULL;
7434   struct dwarf2_section_info *abbrev_section;
7435   /* Non-zero if CU currently points to a DWO file and we need to
7436      reread it.  When this happens we need to reread the skeleton die
7437      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7438   int rereading_dwo_cu = 0;
7439
7440   if (dwarf_die_debug)
7441     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7442                         this_cu->is_debug_types ? "type" : "comp",
7443                         sect_offset_str (this_cu->sect_off));
7444
7445   if (use_existing_cu)
7446     gdb_assert (keep);
7447
7448   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7449      file (instead of going through the stub), short-circuit all of this.  */
7450   if (this_cu->reading_dwo_directly)
7451     {
7452       /* Narrow down the scope of possibilities to have to understand.  */
7453       gdb_assert (this_cu->is_debug_types);
7454       gdb_assert (abbrev_table == NULL);
7455       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7456                                  die_reader_func, data);
7457       return;
7458     }
7459
7460   /* This is cheap if the section is already read in.  */
7461   dwarf2_read_section (objfile, section);
7462
7463   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7464
7465   abbrev_section = get_abbrev_section_for_cu (this_cu);
7466
7467   std::unique_ptr<dwarf2_cu> new_cu;
7468   if (use_existing_cu && this_cu->cu != NULL)
7469     {
7470       cu = this_cu->cu;
7471       /* If this CU is from a DWO file we need to start over, we need to
7472          refetch the attributes from the skeleton CU.
7473          This could be optimized by retrieving those attributes from when we
7474          were here the first time: the previous comp_unit_die was stored in
7475          comp_unit_obstack.  But there's no data yet that we need this
7476          optimization.  */
7477       if (cu->dwo_unit != NULL)
7478         rereading_dwo_cu = 1;
7479     }
7480   else
7481     {
7482       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7483       gdb_assert (this_cu->cu == NULL);
7484       new_cu.reset (new dwarf2_cu (this_cu));
7485       cu = new_cu.get ();
7486     }
7487
7488   /* Get the header.  */
7489   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7490     {
7491       /* We already have the header, there's no need to read it in again.  */
7492       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7493     }
7494   else
7495     {
7496       if (this_cu->is_debug_types)
7497         {
7498           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7499                                                     &cu->header, section,
7500                                                     abbrev_section, info_ptr,
7501                                                     rcuh_kind::TYPE);
7502
7503           /* Since per_cu is the first member of struct signatured_type,
7504              we can go from a pointer to one to a pointer to the other.  */
7505           sig_type = (struct signatured_type *) this_cu;
7506           gdb_assert (sig_type->signature == cu->header.signature);
7507           gdb_assert (sig_type->type_offset_in_tu
7508                       == cu->header.type_cu_offset_in_tu);
7509           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7510
7511           /* LENGTH has not been set yet for type units if we're
7512              using .gdb_index.  */
7513           this_cu->length = get_cu_length (&cu->header);
7514
7515           /* Establish the type offset that can be used to lookup the type.  */
7516           sig_type->type_offset_in_section =
7517             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7518
7519           this_cu->dwarf_version = cu->header.version;
7520         }
7521       else
7522         {
7523           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7524                                                     &cu->header, section,
7525                                                     abbrev_section,
7526                                                     info_ptr,
7527                                                     rcuh_kind::COMPILE);
7528
7529           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7530           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7531           this_cu->dwarf_version = cu->header.version;
7532         }
7533     }
7534
7535   /* Skip dummy compilation units.  */
7536   if (info_ptr >= begin_info_ptr + this_cu->length
7537       || peek_abbrev_code (abfd, info_ptr) == 0)
7538     return;
7539
7540   /* If we don't have them yet, read the abbrevs for this compilation unit.
7541      And if we need to read them now, make sure they're freed when we're
7542      done (own the table through ABBREV_TABLE_HOLDER).  */
7543   abbrev_table_up abbrev_table_holder;
7544   if (abbrev_table != NULL)
7545     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7546   else
7547     {
7548       abbrev_table_holder
7549         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7550                                    cu->header.abbrev_sect_off);
7551       abbrev_table = abbrev_table_holder.get ();
7552     }
7553
7554   /* Read the top level CU/TU die.  */
7555   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7556   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7557
7558   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7559     return;
7560
7561   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7562      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7563      table from the DWO file and pass the ownership over to us.  It will be
7564      referenced from READER, so we must make sure to free it after we're done
7565      with READER.
7566
7567      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7568      DWO CU, that this test will fail (the attribute will not be present).  */
7569   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7570   abbrev_table_up dwo_abbrev_table;
7571   if (attr)
7572     {
7573       struct dwo_unit *dwo_unit;
7574       struct die_info *dwo_comp_unit_die;
7575
7576       if (has_children)
7577         {
7578           complaint (&symfile_complaints,
7579                      _("compilation unit with DW_AT_GNU_dwo_name"
7580                        " has children (offset %s) [in module %s]"),
7581                      sect_offset_str (this_cu->sect_off),
7582                      bfd_get_filename (abfd));
7583         }
7584       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7585       if (dwo_unit != NULL)
7586         {
7587           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7588                                       comp_unit_die, NULL,
7589                                       &reader, &info_ptr,
7590                                       &dwo_comp_unit_die, &has_children,
7591                                       &dwo_abbrev_table) == 0)
7592             {
7593               /* Dummy die.  */
7594               return;
7595             }
7596           comp_unit_die = dwo_comp_unit_die;
7597         }
7598       else
7599         {
7600           /* Yikes, we couldn't find the rest of the DIE, we only have
7601              the stub.  A complaint has already been logged.  There's
7602              not much more we can do except pass on the stub DIE to
7603              die_reader_func.  We don't want to throw an error on bad
7604              debug info.  */
7605         }
7606     }
7607
7608   /* All of the above is setup for this call.  Yikes.  */
7609   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7610
7611   /* Done, clean up.  */
7612   if (new_cu != NULL && keep)
7613     {
7614       /* Link this CU into read_in_chain.  */
7615       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7616       dwarf2_per_objfile->read_in_chain = this_cu;
7617       /* The chain owns it now.  */
7618       new_cu.release ();
7619     }
7620 }
7621
7622 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7623    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7624    to have already done the lookup to find the DWO file).
7625
7626    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7627    THIS_CU->is_debug_types, but nothing else.
7628
7629    We fill in THIS_CU->length.
7630
7631    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7632    linker) then DIE_READER_FUNC will not get called.
7633
7634    THIS_CU->cu is always freed when done.
7635    This is done in order to not leave THIS_CU->cu in a state where we have
7636    to care whether it refers to the "main" CU or the DWO CU.  */
7637
7638 static void
7639 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7640                                    struct dwo_file *dwo_file,
7641                                    die_reader_func_ftype *die_reader_func,
7642                                    void *data)
7643 {
7644   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7645   struct objfile *objfile = dwarf2_per_objfile->objfile;
7646   struct dwarf2_section_info *section = this_cu->section;
7647   bfd *abfd = get_section_bfd_owner (section);
7648   struct dwarf2_section_info *abbrev_section;
7649   const gdb_byte *begin_info_ptr, *info_ptr;
7650   struct die_reader_specs reader;
7651   struct die_info *comp_unit_die;
7652   int has_children;
7653
7654   if (dwarf_die_debug)
7655     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7656                         this_cu->is_debug_types ? "type" : "comp",
7657                         sect_offset_str (this_cu->sect_off));
7658
7659   gdb_assert (this_cu->cu == NULL);
7660
7661   abbrev_section = (dwo_file != NULL
7662                     ? &dwo_file->sections.abbrev
7663                     : get_abbrev_section_for_cu (this_cu));
7664
7665   /* This is cheap if the section is already read in.  */
7666   dwarf2_read_section (objfile, section);
7667
7668   struct dwarf2_cu cu (this_cu);
7669
7670   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7671   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7672                                             &cu.header, section,
7673                                             abbrev_section, info_ptr,
7674                                             (this_cu->is_debug_types
7675                                              ? rcuh_kind::TYPE
7676                                              : rcuh_kind::COMPILE));
7677
7678   this_cu->length = get_cu_length (&cu.header);
7679
7680   /* Skip dummy compilation units.  */
7681   if (info_ptr >= begin_info_ptr + this_cu->length
7682       || peek_abbrev_code (abfd, info_ptr) == 0)
7683     return;
7684
7685   abbrev_table_up abbrev_table
7686     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7687                                cu.header.abbrev_sect_off);
7688
7689   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7690   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7691
7692   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7693 }
7694
7695 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7696    does not lookup the specified DWO file.
7697    This cannot be used to read DWO files.
7698
7699    THIS_CU->cu is always freed when done.
7700    This is done in order to not leave THIS_CU->cu in a state where we have
7701    to care whether it refers to the "main" CU or the DWO CU.
7702    We can revisit this if the data shows there's a performance issue.  */
7703
7704 static void
7705 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7706                                 die_reader_func_ftype *die_reader_func,
7707                                 void *data)
7708 {
7709   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7710 }
7711 \f
7712 /* Type Unit Groups.
7713
7714    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7715    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7716    so that all types coming from the same compilation (.o file) are grouped
7717    together.  A future step could be to put the types in the same symtab as
7718    the CU the types ultimately came from.  */
7719
7720 static hashval_t
7721 hash_type_unit_group (const void *item)
7722 {
7723   const struct type_unit_group *tu_group
7724     = (const struct type_unit_group *) item;
7725
7726   return hash_stmt_list_entry (&tu_group->hash);
7727 }
7728
7729 static int
7730 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7731 {
7732   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7733   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7734
7735   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7736 }
7737
7738 /* Allocate a hash table for type unit groups.  */
7739
7740 static htab_t
7741 allocate_type_unit_groups_table (struct objfile *objfile)
7742 {
7743   return htab_create_alloc_ex (3,
7744                                hash_type_unit_group,
7745                                eq_type_unit_group,
7746                                NULL,
7747                                &objfile->objfile_obstack,
7748                                hashtab_obstack_allocate,
7749                                dummy_obstack_deallocate);
7750 }
7751
7752 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7753    partial symtabs.  We combine several TUs per psymtab to not let the size
7754    of any one psymtab grow too big.  */
7755 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7756 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7757
7758 /* Helper routine for get_type_unit_group.
7759    Create the type_unit_group object used to hold one or more TUs.  */
7760
7761 static struct type_unit_group *
7762 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7763 {
7764   struct dwarf2_per_objfile *dwarf2_per_objfile
7765     = cu->per_cu->dwarf2_per_objfile;
7766   struct objfile *objfile = dwarf2_per_objfile->objfile;
7767   struct dwarf2_per_cu_data *per_cu;
7768   struct type_unit_group *tu_group;
7769
7770   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7771                              struct type_unit_group);
7772   per_cu = &tu_group->per_cu;
7773   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7774
7775   if (dwarf2_per_objfile->using_index)
7776     {
7777       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7778                                         struct dwarf2_per_cu_quick_data);
7779     }
7780   else
7781     {
7782       unsigned int line_offset = to_underlying (line_offset_struct);
7783       struct partial_symtab *pst;
7784       char *name;
7785
7786       /* Give the symtab a useful name for debug purposes.  */
7787       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7788         name = xstrprintf ("<type_units_%d>",
7789                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7790       else
7791         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
7792
7793       pst = create_partial_symtab (per_cu, name);
7794       pst->anonymous = 1;
7795
7796       xfree (name);
7797     }
7798
7799   tu_group->hash.dwo_unit = cu->dwo_unit;
7800   tu_group->hash.line_sect_off = line_offset_struct;
7801
7802   return tu_group;
7803 }
7804
7805 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7806    STMT_LIST is a DW_AT_stmt_list attribute.  */
7807
7808 static struct type_unit_group *
7809 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7810 {
7811   struct dwarf2_per_objfile *dwarf2_per_objfile
7812     = cu->per_cu->dwarf2_per_objfile;
7813   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7814   struct type_unit_group *tu_group;
7815   void **slot;
7816   unsigned int line_offset;
7817   struct type_unit_group type_unit_group_for_lookup;
7818
7819   if (dwarf2_per_objfile->type_unit_groups == NULL)
7820     {
7821       dwarf2_per_objfile->type_unit_groups =
7822         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7823     }
7824
7825   /* Do we need to create a new group, or can we use an existing one?  */
7826
7827   if (stmt_list)
7828     {
7829       line_offset = DW_UNSND (stmt_list);
7830       ++tu_stats->nr_symtab_sharers;
7831     }
7832   else
7833     {
7834       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7835          We can do various things here like create one group per TU or
7836          spread them over multiple groups to split up the expansion work.
7837          To avoid worst case scenarios (too many groups or too large groups)
7838          we, umm, group them in bunches.  */
7839       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7840                      | (tu_stats->nr_stmt_less_type_units
7841                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7842       ++tu_stats->nr_stmt_less_type_units;
7843     }
7844
7845   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7846   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7847   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7848                          &type_unit_group_for_lookup, INSERT);
7849   if (*slot != NULL)
7850     {
7851       tu_group = (struct type_unit_group *) *slot;
7852       gdb_assert (tu_group != NULL);
7853     }
7854   else
7855     {
7856       sect_offset line_offset_struct = (sect_offset) line_offset;
7857       tu_group = create_type_unit_group (cu, line_offset_struct);
7858       *slot = tu_group;
7859       ++tu_stats->nr_symtabs;
7860     }
7861
7862   return tu_group;
7863 }
7864 \f
7865 /* Partial symbol tables.  */
7866
7867 /* Create a psymtab named NAME and assign it to PER_CU.
7868
7869    The caller must fill in the following details:
7870    dirname, textlow, texthigh.  */
7871
7872 static struct partial_symtab *
7873 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7874 {
7875   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7876   struct partial_symtab *pst;
7877
7878   pst = start_psymtab_common (objfile, name, 0,
7879                               objfile->global_psymbols,
7880                               objfile->static_psymbols);
7881
7882   pst->psymtabs_addrmap_supported = 1;
7883
7884   /* This is the glue that links PST into GDB's symbol API.  */
7885   pst->read_symtab_private = per_cu;
7886   pst->read_symtab = dwarf2_read_symtab;
7887   per_cu->v.psymtab = pst;
7888
7889   return pst;
7890 }
7891
7892 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7893    type.  */
7894
7895 struct process_psymtab_comp_unit_data
7896 {
7897   /* True if we are reading a DW_TAG_partial_unit.  */
7898
7899   int want_partial_unit;
7900
7901   /* The "pretend" language that is used if the CU doesn't declare a
7902      language.  */
7903
7904   enum language pretend_language;
7905 };
7906
7907 /* die_reader_func for process_psymtab_comp_unit.  */
7908
7909 static void
7910 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7911                                   const gdb_byte *info_ptr,
7912                                   struct die_info *comp_unit_die,
7913                                   int has_children,
7914                                   void *data)
7915 {
7916   struct dwarf2_cu *cu = reader->cu;
7917   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7918   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7919   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7920   CORE_ADDR baseaddr;
7921   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7922   struct partial_symtab *pst;
7923   enum pc_bounds_kind cu_bounds_kind;
7924   const char *filename;
7925   struct process_psymtab_comp_unit_data *info
7926     = (struct process_psymtab_comp_unit_data *) data;
7927
7928   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7929     return;
7930
7931   gdb_assert (! per_cu->is_debug_types);
7932
7933   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7934
7935   cu->list_in_scope = &file_symbols;
7936
7937   /* Allocate a new partial symbol table structure.  */
7938   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7939   if (filename == NULL)
7940     filename = "";
7941
7942   pst = create_partial_symtab (per_cu, filename);
7943
7944   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7945   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7946
7947   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7948
7949   dwarf2_find_base_address (comp_unit_die, cu);
7950
7951   /* Possibly set the default values of LOWPC and HIGHPC from
7952      `DW_AT_ranges'.  */
7953   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7954                                          &best_highpc, cu, pst);
7955   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7956     /* Store the contiguous range if it is not empty; it can be empty for
7957        CUs with no code.  */
7958     addrmap_set_empty (objfile->psymtabs_addrmap,
7959                        gdbarch_adjust_dwarf2_addr (gdbarch,
7960                                                    best_lowpc + baseaddr),
7961                        gdbarch_adjust_dwarf2_addr (gdbarch,
7962                                                    best_highpc + baseaddr) - 1,
7963                        pst);
7964
7965   /* Check if comp unit has_children.
7966      If so, read the rest of the partial symbols from this comp unit.
7967      If not, there's no more debug_info for this comp unit.  */
7968   if (has_children)
7969     {
7970       struct partial_die_info *first_die;
7971       CORE_ADDR lowpc, highpc;
7972
7973       lowpc = ((CORE_ADDR) -1);
7974       highpc = ((CORE_ADDR) 0);
7975
7976       first_die = load_partial_dies (reader, info_ptr, 1);
7977
7978       scan_partial_symbols (first_die, &lowpc, &highpc,
7979                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7980
7981       /* If we didn't find a lowpc, set it to highpc to avoid
7982          complaints from `maint check'.  */
7983       if (lowpc == ((CORE_ADDR) -1))
7984         lowpc = highpc;
7985
7986       /* If the compilation unit didn't have an explicit address range,
7987          then use the information extracted from its child dies.  */
7988       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7989         {
7990           best_lowpc = lowpc;
7991           best_highpc = highpc;
7992         }
7993     }
7994   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7995   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7996
7997   end_psymtab_common (objfile, pst);
7998
7999   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8000     {
8001       int i;
8002       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8003       struct dwarf2_per_cu_data *iter;
8004
8005       /* Fill in 'dependencies' here; we fill in 'users' in a
8006          post-pass.  */
8007       pst->number_of_dependencies = len;
8008       pst->dependencies =
8009         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8010       for (i = 0;
8011            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8012                         i, iter);
8013            ++i)
8014         pst->dependencies[i] = iter->v.psymtab;
8015
8016       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8017     }
8018
8019   /* Get the list of files included in the current compilation unit,
8020      and build a psymtab for each of them.  */
8021   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8022
8023   if (dwarf_read_debug)
8024     {
8025       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8026
8027       fprintf_unfiltered (gdb_stdlog,
8028                           "Psymtab for %s unit @%s: %s - %s"
8029                           ", %d global, %d static syms\n",
8030                           per_cu->is_debug_types ? "type" : "comp",
8031                           sect_offset_str (per_cu->sect_off),
8032                           paddress (gdbarch, pst->textlow),
8033                           paddress (gdbarch, pst->texthigh),
8034                           pst->n_global_syms, pst->n_static_syms);
8035     }
8036 }
8037
8038 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8039    Process compilation unit THIS_CU for a psymtab.  */
8040
8041 static void
8042 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8043                            int want_partial_unit,
8044                            enum language pretend_language)
8045 {
8046   /* If this compilation unit was already read in, free the
8047      cached copy in order to read it in again.  This is
8048      necessary because we skipped some symbols when we first
8049      read in the compilation unit (see load_partial_dies).
8050      This problem could be avoided, but the benefit is unclear.  */
8051   if (this_cu->cu != NULL)
8052     free_one_cached_comp_unit (this_cu);
8053
8054   if (this_cu->is_debug_types)
8055     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8056                              build_type_psymtabs_reader, NULL);
8057   else
8058     {
8059       process_psymtab_comp_unit_data info;
8060       info.want_partial_unit = want_partial_unit;
8061       info.pretend_language = pretend_language;
8062       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8063                                process_psymtab_comp_unit_reader, &info);
8064     }
8065
8066   /* Age out any secondary CUs.  */
8067   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8068 }
8069
8070 /* Reader function for build_type_psymtabs.  */
8071
8072 static void
8073 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8074                             const gdb_byte *info_ptr,
8075                             struct die_info *type_unit_die,
8076                             int has_children,
8077                             void *data)
8078 {
8079   struct dwarf2_per_objfile *dwarf2_per_objfile
8080     = reader->cu->per_cu->dwarf2_per_objfile;
8081   struct objfile *objfile = dwarf2_per_objfile->objfile;
8082   struct dwarf2_cu *cu = reader->cu;
8083   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8084   struct signatured_type *sig_type;
8085   struct type_unit_group *tu_group;
8086   struct attribute *attr;
8087   struct partial_die_info *first_die;
8088   CORE_ADDR lowpc, highpc;
8089   struct partial_symtab *pst;
8090
8091   gdb_assert (data == NULL);
8092   gdb_assert (per_cu->is_debug_types);
8093   sig_type = (struct signatured_type *) per_cu;
8094
8095   if (! has_children)
8096     return;
8097
8098   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8099   tu_group = get_type_unit_group (cu, attr);
8100
8101   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8102
8103   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8104   cu->list_in_scope = &file_symbols;
8105   pst = create_partial_symtab (per_cu, "");
8106   pst->anonymous = 1;
8107
8108   first_die = load_partial_dies (reader, info_ptr, 1);
8109
8110   lowpc = (CORE_ADDR) -1;
8111   highpc = (CORE_ADDR) 0;
8112   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8113
8114   end_psymtab_common (objfile, pst);
8115 }
8116
8117 /* Struct used to sort TUs by their abbreviation table offset.  */
8118
8119 struct tu_abbrev_offset
8120 {
8121   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8122   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8123   {}
8124
8125   signatured_type *sig_type;
8126   sect_offset abbrev_offset;
8127 };
8128
8129 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8130
8131 static bool
8132 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8133                           const struct tu_abbrev_offset &b)
8134 {
8135   return a.abbrev_offset < b.abbrev_offset;
8136 }
8137
8138 /* Efficiently read all the type units.
8139    This does the bulk of the work for build_type_psymtabs.
8140
8141    The efficiency is because we sort TUs by the abbrev table they use and
8142    only read each abbrev table once.  In one program there are 200K TUs
8143    sharing 8K abbrev tables.
8144
8145    The main purpose of this function is to support building the
8146    dwarf2_per_objfile->type_unit_groups table.
8147    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8148    can collapse the search space by grouping them by stmt_list.
8149    The savings can be significant, in the same program from above the 200K TUs
8150    share 8K stmt_list tables.
8151
8152    FUNC is expected to call get_type_unit_group, which will create the
8153    struct type_unit_group if necessary and add it to
8154    dwarf2_per_objfile->type_unit_groups.  */
8155
8156 static void
8157 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8158 {
8159   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8160   abbrev_table_up abbrev_table;
8161   sect_offset abbrev_offset;
8162
8163   /* It's up to the caller to not call us multiple times.  */
8164   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8165
8166   if (dwarf2_per_objfile->all_type_units.empty ())
8167     return;
8168
8169   /* TUs typically share abbrev tables, and there can be way more TUs than
8170      abbrev tables.  Sort by abbrev table to reduce the number of times we
8171      read each abbrev table in.
8172      Alternatives are to punt or to maintain a cache of abbrev tables.
8173      This is simpler and efficient enough for now.
8174
8175      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8176      symtab to use).  Typically TUs with the same abbrev offset have the same
8177      stmt_list value too so in practice this should work well.
8178
8179      The basic algorithm here is:
8180
8181       sort TUs by abbrev table
8182       for each TU with same abbrev table:
8183         read abbrev table if first user
8184         read TU top level DIE
8185           [IWBN if DWO skeletons had DW_AT_stmt_list]
8186         call FUNC  */
8187
8188   if (dwarf_read_debug)
8189     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8190
8191   /* Sort in a separate table to maintain the order of all_type_units
8192      for .gdb_index: TU indices directly index all_type_units.  */
8193   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8194   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8195
8196   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8197     sorted_by_abbrev.emplace_back
8198       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8199                                      sig_type->per_cu.section,
8200                                      sig_type->per_cu.sect_off));
8201
8202   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8203              sort_tu_by_abbrev_offset);
8204
8205   abbrev_offset = (sect_offset) ~(unsigned) 0;
8206
8207   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8208     {
8209       /* Switch to the next abbrev table if necessary.  */
8210       if (abbrev_table == NULL
8211           || tu.abbrev_offset != abbrev_offset)
8212         {
8213           abbrev_offset = tu.abbrev_offset;
8214           abbrev_table =
8215             abbrev_table_read_table (dwarf2_per_objfile,
8216                                      &dwarf2_per_objfile->abbrev,
8217                                      abbrev_offset);
8218           ++tu_stats->nr_uniq_abbrev_tables;
8219         }
8220
8221       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8222                                0, 0, false, build_type_psymtabs_reader, NULL);
8223     }
8224 }
8225
8226 /* Print collected type unit statistics.  */
8227
8228 static void
8229 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8230 {
8231   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8232
8233   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8234   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8235                       dwarf2_per_objfile->all_type_units.size ());
8236   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8237                       tu_stats->nr_uniq_abbrev_tables);
8238   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8239                       tu_stats->nr_symtabs);
8240   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8241                       tu_stats->nr_symtab_sharers);
8242   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8243                       tu_stats->nr_stmt_less_type_units);
8244   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8245                       tu_stats->nr_all_type_units_reallocs);
8246 }
8247
8248 /* Traversal function for build_type_psymtabs.  */
8249
8250 static int
8251 build_type_psymtab_dependencies (void **slot, void *info)
8252 {
8253   struct dwarf2_per_objfile *dwarf2_per_objfile
8254     = (struct dwarf2_per_objfile *) info;
8255   struct objfile *objfile = dwarf2_per_objfile->objfile;
8256   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8257   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8258   struct partial_symtab *pst = per_cu->v.psymtab;
8259   int len = VEC_length (sig_type_ptr, tu_group->tus);
8260   struct signatured_type *iter;
8261   int i;
8262
8263   gdb_assert (len > 0);
8264   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8265
8266   pst->number_of_dependencies = len;
8267   pst->dependencies =
8268     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8269   for (i = 0;
8270        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8271        ++i)
8272     {
8273       gdb_assert (iter->per_cu.is_debug_types);
8274       pst->dependencies[i] = iter->per_cu.v.psymtab;
8275       iter->type_unit_group = tu_group;
8276     }
8277
8278   VEC_free (sig_type_ptr, tu_group->tus);
8279
8280   return 1;
8281 }
8282
8283 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8284    Build partial symbol tables for the .debug_types comp-units.  */
8285
8286 static void
8287 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8288 {
8289   if (! create_all_type_units (dwarf2_per_objfile))
8290     return;
8291
8292   build_type_psymtabs_1 (dwarf2_per_objfile);
8293 }
8294
8295 /* Traversal function for process_skeletonless_type_unit.
8296    Read a TU in a DWO file and build partial symbols for it.  */
8297
8298 static int
8299 process_skeletonless_type_unit (void **slot, void *info)
8300 {
8301   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8302   struct dwarf2_per_objfile *dwarf2_per_objfile
8303     = (struct dwarf2_per_objfile *) info;
8304   struct signatured_type find_entry, *entry;
8305
8306   /* If this TU doesn't exist in the global table, add it and read it in.  */
8307
8308   if (dwarf2_per_objfile->signatured_types == NULL)
8309     {
8310       dwarf2_per_objfile->signatured_types
8311         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8312     }
8313
8314   find_entry.signature = dwo_unit->signature;
8315   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8316                          INSERT);
8317   /* If we've already seen this type there's nothing to do.  What's happening
8318      is we're doing our own version of comdat-folding here.  */
8319   if (*slot != NULL)
8320     return 1;
8321
8322   /* This does the job that create_all_type_units would have done for
8323      this TU.  */
8324   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8325   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8326   *slot = entry;
8327
8328   /* This does the job that build_type_psymtabs_1 would have done.  */
8329   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8330                            build_type_psymtabs_reader, NULL);
8331
8332   return 1;
8333 }
8334
8335 /* Traversal function for process_skeletonless_type_units.  */
8336
8337 static int
8338 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8339 {
8340   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8341
8342   if (dwo_file->tus != NULL)
8343     {
8344       htab_traverse_noresize (dwo_file->tus,
8345                               process_skeletonless_type_unit, info);
8346     }
8347
8348   return 1;
8349 }
8350
8351 /* Scan all TUs of DWO files, verifying we've processed them.
8352    This is needed in case a TU was emitted without its skeleton.
8353    Note: This can't be done until we know what all the DWO files are.  */
8354
8355 static void
8356 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8357 {
8358   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8359   if (get_dwp_file (dwarf2_per_objfile) == NULL
8360       && dwarf2_per_objfile->dwo_files != NULL)
8361     {
8362       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8363                               process_dwo_file_for_skeletonless_type_units,
8364                               dwarf2_per_objfile);
8365     }
8366 }
8367
8368 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8369
8370 static void
8371 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8372 {
8373   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8374     {
8375       struct partial_symtab *pst = per_cu->v.psymtab;
8376
8377       if (pst == NULL)
8378         continue;
8379
8380       for (int j = 0; j < pst->number_of_dependencies; ++j)
8381         {
8382           /* Set the 'user' field only if it is not already set.  */
8383           if (pst->dependencies[j]->user == NULL)
8384             pst->dependencies[j]->user = pst;
8385         }
8386     }
8387 }
8388
8389 /* Build the partial symbol table by doing a quick pass through the
8390    .debug_info and .debug_abbrev sections.  */
8391
8392 static void
8393 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8394 {
8395   struct objfile *objfile = dwarf2_per_objfile->objfile;
8396
8397   if (dwarf_read_debug)
8398     {
8399       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8400                           objfile_name (objfile));
8401     }
8402
8403   dwarf2_per_objfile->reading_partial_symbols = 1;
8404
8405   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8406
8407   /* Any cached compilation units will be linked by the per-objfile
8408      read_in_chain.  Make sure to free them when we're done.  */
8409   free_cached_comp_units freer (dwarf2_per_objfile);
8410
8411   build_type_psymtabs (dwarf2_per_objfile);
8412
8413   create_all_comp_units (dwarf2_per_objfile);
8414
8415   /* Create a temporary address map on a temporary obstack.  We later
8416      copy this to the final obstack.  */
8417   auto_obstack temp_obstack;
8418
8419   scoped_restore save_psymtabs_addrmap
8420     = make_scoped_restore (&objfile->psymtabs_addrmap,
8421                            addrmap_create_mutable (&temp_obstack));
8422
8423   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8424     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8425
8426   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8427   process_skeletonless_type_units (dwarf2_per_objfile);
8428
8429   /* Now that all TUs have been processed we can fill in the dependencies.  */
8430   if (dwarf2_per_objfile->type_unit_groups != NULL)
8431     {
8432       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8433                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8434     }
8435
8436   if (dwarf_read_debug)
8437     print_tu_stats (dwarf2_per_objfile);
8438
8439   set_partial_user (dwarf2_per_objfile);
8440
8441   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8442                                                     &objfile->objfile_obstack);
8443   /* At this point we want to keep the address map.  */
8444   save_psymtabs_addrmap.release ();
8445
8446   if (dwarf_read_debug)
8447     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8448                         objfile_name (objfile));
8449 }
8450
8451 /* die_reader_func for load_partial_comp_unit.  */
8452
8453 static void
8454 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8455                                const gdb_byte *info_ptr,
8456                                struct die_info *comp_unit_die,
8457                                int has_children,
8458                                void *data)
8459 {
8460   struct dwarf2_cu *cu = reader->cu;
8461
8462   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8463
8464   /* Check if comp unit has_children.
8465      If so, read the rest of the partial symbols from this comp unit.
8466      If not, there's no more debug_info for this comp unit.  */
8467   if (has_children)
8468     load_partial_dies (reader, info_ptr, 0);
8469 }
8470
8471 /* Load the partial DIEs for a secondary CU into memory.
8472    This is also used when rereading a primary CU with load_all_dies.  */
8473
8474 static void
8475 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8476 {
8477   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8478                            load_partial_comp_unit_reader, NULL);
8479 }
8480
8481 static void
8482 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8483                               struct dwarf2_section_info *section,
8484                               struct dwarf2_section_info *abbrev_section,
8485                               unsigned int is_dwz)
8486 {
8487   const gdb_byte *info_ptr;
8488   struct objfile *objfile = dwarf2_per_objfile->objfile;
8489
8490   if (dwarf_read_debug)
8491     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8492                         get_section_name (section),
8493                         get_section_file_name (section));
8494
8495   dwarf2_read_section (objfile, section);
8496
8497   info_ptr = section->buffer;
8498
8499   while (info_ptr < section->buffer + section->size)
8500     {
8501       struct dwarf2_per_cu_data *this_cu;
8502
8503       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8504
8505       comp_unit_head cu_header;
8506       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8507                                      abbrev_section, info_ptr,
8508                                      rcuh_kind::COMPILE);
8509
8510       /* Save the compilation unit for later lookup.  */
8511       if (cu_header.unit_type != DW_UT_type)
8512         {
8513           this_cu = XOBNEW (&objfile->objfile_obstack,
8514                             struct dwarf2_per_cu_data);
8515           memset (this_cu, 0, sizeof (*this_cu));
8516         }
8517       else
8518         {
8519           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8520                                   struct signatured_type);
8521           memset (sig_type, 0, sizeof (*sig_type));
8522           sig_type->signature = cu_header.signature;
8523           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8524           this_cu = &sig_type->per_cu;
8525         }
8526       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8527       this_cu->sect_off = sect_off;
8528       this_cu->length = cu_header.length + cu_header.initial_length_size;
8529       this_cu->is_dwz = is_dwz;
8530       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8531       this_cu->section = section;
8532
8533       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8534
8535       info_ptr = info_ptr + this_cu->length;
8536     }
8537 }
8538
8539 /* Create a list of all compilation units in OBJFILE.
8540    This is only done for -readnow and building partial symtabs.  */
8541
8542 static void
8543 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8544 {
8545   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8546   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8547                                 &dwarf2_per_objfile->abbrev, 0);
8548
8549   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8550   if (dwz != NULL)
8551     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8552                                   1);
8553 }
8554
8555 /* Process all loaded DIEs for compilation unit CU, starting at
8556    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8557    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8558    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8559    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8560
8561 static void
8562 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8563                       CORE_ADDR *highpc, int set_addrmap,
8564                       struct dwarf2_cu *cu)
8565 {
8566   struct partial_die_info *pdi;
8567
8568   /* Now, march along the PDI's, descending into ones which have
8569      interesting children but skipping the children of the other ones,
8570      until we reach the end of the compilation unit.  */
8571
8572   pdi = first_die;
8573
8574   while (pdi != NULL)
8575     {
8576       pdi->fixup (cu);
8577
8578       /* Anonymous namespaces or modules have no name but have interesting
8579          children, so we need to look at them.  Ditto for anonymous
8580          enums.  */
8581
8582       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8583           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8584           || pdi->tag == DW_TAG_imported_unit
8585           || pdi->tag == DW_TAG_inlined_subroutine)
8586         {
8587           switch (pdi->tag)
8588             {
8589             case DW_TAG_subprogram:
8590             case DW_TAG_inlined_subroutine:
8591               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8592               break;
8593             case DW_TAG_constant:
8594             case DW_TAG_variable:
8595             case DW_TAG_typedef:
8596             case DW_TAG_union_type:
8597               if (!pdi->is_declaration)
8598                 {
8599                   add_partial_symbol (pdi, cu);
8600                 }
8601               break;
8602             case DW_TAG_class_type:
8603             case DW_TAG_interface_type:
8604             case DW_TAG_structure_type:
8605               if (!pdi->is_declaration)
8606                 {
8607                   add_partial_symbol (pdi, cu);
8608                 }
8609               if ((cu->language == language_rust
8610                    || cu->language == language_cplus) && pdi->has_children)
8611                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8612                                       set_addrmap, cu);
8613               break;
8614             case DW_TAG_enumeration_type:
8615               if (!pdi->is_declaration)
8616                 add_partial_enumeration (pdi, cu);
8617               break;
8618             case DW_TAG_base_type:
8619             case DW_TAG_subrange_type:
8620               /* File scope base type definitions are added to the partial
8621                  symbol table.  */
8622               add_partial_symbol (pdi, cu);
8623               break;
8624             case DW_TAG_namespace:
8625               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8626               break;
8627             case DW_TAG_module:
8628               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8629               break;
8630             case DW_TAG_imported_unit:
8631               {
8632                 struct dwarf2_per_cu_data *per_cu;
8633
8634                 /* For now we don't handle imported units in type units.  */
8635                 if (cu->per_cu->is_debug_types)
8636                   {
8637                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8638                              " supported in type units [in module %s]"),
8639                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8640                   }
8641
8642                 per_cu = dwarf2_find_containing_comp_unit
8643                            (pdi->d.sect_off, pdi->is_dwz,
8644                             cu->per_cu->dwarf2_per_objfile);
8645
8646                 /* Go read the partial unit, if needed.  */
8647                 if (per_cu->v.psymtab == NULL)
8648                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8649
8650                 VEC_safe_push (dwarf2_per_cu_ptr,
8651                                cu->per_cu->imported_symtabs, per_cu);
8652               }
8653               break;
8654             case DW_TAG_imported_declaration:
8655               add_partial_symbol (pdi, cu);
8656               break;
8657             default:
8658               break;
8659             }
8660         }
8661
8662       /* If the die has a sibling, skip to the sibling.  */
8663
8664       pdi = pdi->die_sibling;
8665     }
8666 }
8667
8668 /* Functions used to compute the fully scoped name of a partial DIE.
8669
8670    Normally, this is simple.  For C++, the parent DIE's fully scoped
8671    name is concatenated with "::" and the partial DIE's name.
8672    Enumerators are an exception; they use the scope of their parent
8673    enumeration type, i.e. the name of the enumeration type is not
8674    prepended to the enumerator.
8675
8676    There are two complexities.  One is DW_AT_specification; in this
8677    case "parent" means the parent of the target of the specification,
8678    instead of the direct parent of the DIE.  The other is compilers
8679    which do not emit DW_TAG_namespace; in this case we try to guess
8680    the fully qualified name of structure types from their members'
8681    linkage names.  This must be done using the DIE's children rather
8682    than the children of any DW_AT_specification target.  We only need
8683    to do this for structures at the top level, i.e. if the target of
8684    any DW_AT_specification (if any; otherwise the DIE itself) does not
8685    have a parent.  */
8686
8687 /* Compute the scope prefix associated with PDI's parent, in
8688    compilation unit CU.  The result will be allocated on CU's
8689    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8690    field.  NULL is returned if no prefix is necessary.  */
8691 static const char *
8692 partial_die_parent_scope (struct partial_die_info *pdi,
8693                           struct dwarf2_cu *cu)
8694 {
8695   const char *grandparent_scope;
8696   struct partial_die_info *parent, *real_pdi;
8697
8698   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8699      then this means the parent of the specification DIE.  */
8700
8701   real_pdi = pdi;
8702   while (real_pdi->has_specification)
8703     real_pdi = find_partial_die (real_pdi->spec_offset,
8704                                  real_pdi->spec_is_dwz, cu);
8705
8706   parent = real_pdi->die_parent;
8707   if (parent == NULL)
8708     return NULL;
8709
8710   if (parent->scope_set)
8711     return parent->scope;
8712
8713   parent->fixup (cu);
8714
8715   grandparent_scope = partial_die_parent_scope (parent, cu);
8716
8717   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8718      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8719      Work around this problem here.  */
8720   if (cu->language == language_cplus
8721       && parent->tag == DW_TAG_namespace
8722       && strcmp (parent->name, "::") == 0
8723       && grandparent_scope == NULL)
8724     {
8725       parent->scope = NULL;
8726       parent->scope_set = 1;
8727       return NULL;
8728     }
8729
8730   if (pdi->tag == DW_TAG_enumerator)
8731     /* Enumerators should not get the name of the enumeration as a prefix.  */
8732     parent->scope = grandparent_scope;
8733   else if (parent->tag == DW_TAG_namespace
8734       || parent->tag == DW_TAG_module
8735       || parent->tag == DW_TAG_structure_type
8736       || parent->tag == DW_TAG_class_type
8737       || parent->tag == DW_TAG_interface_type
8738       || parent->tag == DW_TAG_union_type
8739       || parent->tag == DW_TAG_enumeration_type)
8740     {
8741       if (grandparent_scope == NULL)
8742         parent->scope = parent->name;
8743       else
8744         parent->scope = typename_concat (&cu->comp_unit_obstack,
8745                                          grandparent_scope,
8746                                          parent->name, 0, cu);
8747     }
8748   else
8749     {
8750       /* FIXME drow/2004-04-01: What should we be doing with
8751          function-local names?  For partial symbols, we should probably be
8752          ignoring them.  */
8753       complaint (&symfile_complaints,
8754                  _("unhandled containing DIE tag %d for DIE at %s"),
8755                  parent->tag, sect_offset_str (pdi->sect_off));
8756       parent->scope = grandparent_scope;
8757     }
8758
8759   parent->scope_set = 1;
8760   return parent->scope;
8761 }
8762
8763 /* Return the fully scoped name associated with PDI, from compilation unit
8764    CU.  The result will be allocated with malloc.  */
8765
8766 static char *
8767 partial_die_full_name (struct partial_die_info *pdi,
8768                        struct dwarf2_cu *cu)
8769 {
8770   const char *parent_scope;
8771
8772   /* If this is a template instantiation, we can not work out the
8773      template arguments from partial DIEs.  So, unfortunately, we have
8774      to go through the full DIEs.  At least any work we do building
8775      types here will be reused if full symbols are loaded later.  */
8776   if (pdi->has_template_arguments)
8777     {
8778       pdi->fixup (cu);
8779
8780       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8781         {
8782           struct die_info *die;
8783           struct attribute attr;
8784           struct dwarf2_cu *ref_cu = cu;
8785
8786           /* DW_FORM_ref_addr is using section offset.  */
8787           attr.name = (enum dwarf_attribute) 0;
8788           attr.form = DW_FORM_ref_addr;
8789           attr.u.unsnd = to_underlying (pdi->sect_off);
8790           die = follow_die_ref (NULL, &attr, &ref_cu);
8791
8792           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8793         }
8794     }
8795
8796   parent_scope = partial_die_parent_scope (pdi, cu);
8797   if (parent_scope == NULL)
8798     return NULL;
8799   else
8800     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8801 }
8802
8803 static void
8804 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8805 {
8806   struct dwarf2_per_objfile *dwarf2_per_objfile
8807     = cu->per_cu->dwarf2_per_objfile;
8808   struct objfile *objfile = dwarf2_per_objfile->objfile;
8809   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8810   CORE_ADDR addr = 0;
8811   const char *actual_name = NULL;
8812   CORE_ADDR baseaddr;
8813   char *built_actual_name;
8814
8815   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8816
8817   built_actual_name = partial_die_full_name (pdi, cu);
8818   if (built_actual_name != NULL)
8819     actual_name = built_actual_name;
8820
8821   if (actual_name == NULL)
8822     actual_name = pdi->name;
8823
8824   switch (pdi->tag)
8825     {
8826     case DW_TAG_inlined_subroutine:
8827     case DW_TAG_subprogram:
8828       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8829       if (pdi->is_external || cu->language == language_ada)
8830         {
8831           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8832              of the global scope.  But in Ada, we want to be able to access
8833              nested procedures globally.  So all Ada subprograms are stored
8834              in the global scope.  */
8835           add_psymbol_to_list (actual_name, strlen (actual_name),
8836                                built_actual_name != NULL,
8837                                VAR_DOMAIN, LOC_BLOCK,
8838                                &objfile->global_psymbols,
8839                                addr, cu->language, objfile);
8840         }
8841       else
8842         {
8843           add_psymbol_to_list (actual_name, strlen (actual_name),
8844                                built_actual_name != NULL,
8845                                VAR_DOMAIN, LOC_BLOCK,
8846                                &objfile->static_psymbols,
8847                                addr, cu->language, objfile);
8848         }
8849
8850       if (pdi->main_subprogram && actual_name != NULL)
8851         set_objfile_main_name (objfile, actual_name, cu->language);
8852       break;
8853     case DW_TAG_constant:
8854       {
8855         std::vector<partial_symbol *> *list;
8856
8857         if (pdi->is_external)
8858           list = &objfile->global_psymbols;
8859         else
8860           list = &objfile->static_psymbols;
8861         add_psymbol_to_list (actual_name, strlen (actual_name),
8862                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8863                              list, 0, cu->language, objfile);
8864       }
8865       break;
8866     case DW_TAG_variable:
8867       if (pdi->d.locdesc)
8868         addr = decode_locdesc (pdi->d.locdesc, cu);
8869
8870       if (pdi->d.locdesc
8871           && addr == 0
8872           && !dwarf2_per_objfile->has_section_at_zero)
8873         {
8874           /* A global or static variable may also have been stripped
8875              out by the linker if unused, in which case its address
8876              will be nullified; do not add such variables into partial
8877              symbol table then.  */
8878         }
8879       else if (pdi->is_external)
8880         {
8881           /* Global Variable.
8882              Don't enter into the minimal symbol tables as there is
8883              a minimal symbol table entry from the ELF symbols already.
8884              Enter into partial symbol table if it has a location
8885              descriptor or a type.
8886              If the location descriptor is missing, new_symbol will create
8887              a LOC_UNRESOLVED symbol, the address of the variable will then
8888              be determined from the minimal symbol table whenever the variable
8889              is referenced.
8890              The address for the partial symbol table entry is not
8891              used by GDB, but it comes in handy for debugging partial symbol
8892              table building.  */
8893
8894           if (pdi->d.locdesc || pdi->has_type)
8895             add_psymbol_to_list (actual_name, strlen (actual_name),
8896                                  built_actual_name != NULL,
8897                                  VAR_DOMAIN, LOC_STATIC,
8898                                  &objfile->global_psymbols,
8899                                  addr + baseaddr,
8900                                  cu->language, objfile);
8901         }
8902       else
8903         {
8904           int has_loc = pdi->d.locdesc != NULL;
8905
8906           /* Static Variable.  Skip symbols whose value we cannot know (those
8907              without location descriptors or constant values).  */
8908           if (!has_loc && !pdi->has_const_value)
8909             {
8910               xfree (built_actual_name);
8911               return;
8912             }
8913
8914           add_psymbol_to_list (actual_name, strlen (actual_name),
8915                                built_actual_name != NULL,
8916                                VAR_DOMAIN, LOC_STATIC,
8917                                &objfile->static_psymbols,
8918                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8919                                cu->language, objfile);
8920         }
8921       break;
8922     case DW_TAG_typedef:
8923     case DW_TAG_base_type:
8924     case DW_TAG_subrange_type:
8925       add_psymbol_to_list (actual_name, strlen (actual_name),
8926                            built_actual_name != NULL,
8927                            VAR_DOMAIN, LOC_TYPEDEF,
8928                            &objfile->static_psymbols,
8929                            0, cu->language, objfile);
8930       break;
8931     case DW_TAG_imported_declaration:
8932     case DW_TAG_namespace:
8933       add_psymbol_to_list (actual_name, strlen (actual_name),
8934                            built_actual_name != NULL,
8935                            VAR_DOMAIN, LOC_TYPEDEF,
8936                            &objfile->global_psymbols,
8937                            0, cu->language, objfile);
8938       break;
8939     case DW_TAG_module:
8940       add_psymbol_to_list (actual_name, strlen (actual_name),
8941                            built_actual_name != NULL,
8942                            MODULE_DOMAIN, LOC_TYPEDEF,
8943                            &objfile->global_psymbols,
8944                            0, cu->language, objfile);
8945       break;
8946     case DW_TAG_class_type:
8947     case DW_TAG_interface_type:
8948     case DW_TAG_structure_type:
8949     case DW_TAG_union_type:
8950     case DW_TAG_enumeration_type:
8951       /* Skip external references.  The DWARF standard says in the section
8952          about "Structure, Union, and Class Type Entries": "An incomplete
8953          structure, union or class type is represented by a structure,
8954          union or class entry that does not have a byte size attribute
8955          and that has a DW_AT_declaration attribute."  */
8956       if (!pdi->has_byte_size && pdi->is_declaration)
8957         {
8958           xfree (built_actual_name);
8959           return;
8960         }
8961
8962       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8963          static vs. global.  */
8964       add_psymbol_to_list (actual_name, strlen (actual_name),
8965                            built_actual_name != NULL,
8966                            STRUCT_DOMAIN, LOC_TYPEDEF,
8967                            cu->language == language_cplus
8968                            ? &objfile->global_psymbols
8969                            : &objfile->static_psymbols,
8970                            0, cu->language, objfile);
8971
8972       break;
8973     case DW_TAG_enumerator:
8974       add_psymbol_to_list (actual_name, strlen (actual_name),
8975                            built_actual_name != NULL,
8976                            VAR_DOMAIN, LOC_CONST,
8977                            cu->language == language_cplus
8978                            ? &objfile->global_psymbols
8979                            : &objfile->static_psymbols,
8980                            0, cu->language, objfile);
8981       break;
8982     default:
8983       break;
8984     }
8985
8986   xfree (built_actual_name);
8987 }
8988
8989 /* Read a partial die corresponding to a namespace; also, add a symbol
8990    corresponding to that namespace to the symbol table.  NAMESPACE is
8991    the name of the enclosing namespace.  */
8992
8993 static void
8994 add_partial_namespace (struct partial_die_info *pdi,
8995                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8996                        int set_addrmap, struct dwarf2_cu *cu)
8997 {
8998   /* Add a symbol for the namespace.  */
8999
9000   add_partial_symbol (pdi, cu);
9001
9002   /* Now scan partial symbols in that namespace.  */
9003
9004   if (pdi->has_children)
9005     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9006 }
9007
9008 /* Read a partial die corresponding to a Fortran module.  */
9009
9010 static void
9011 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9012                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9013 {
9014   /* Add a symbol for the namespace.  */
9015
9016   add_partial_symbol (pdi, cu);
9017
9018   /* Now scan partial symbols in that module.  */
9019
9020   if (pdi->has_children)
9021     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9022 }
9023
9024 /* Read a partial die corresponding to a subprogram or an inlined
9025    subprogram and create a partial symbol for that subprogram.
9026    When the CU language allows it, this routine also defines a partial
9027    symbol for each nested subprogram that this subprogram contains.
9028    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9029    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9030
9031    PDI may also be a lexical block, in which case we simply search
9032    recursively for subprograms defined inside that lexical block.
9033    Again, this is only performed when the CU language allows this
9034    type of definitions.  */
9035
9036 static void
9037 add_partial_subprogram (struct partial_die_info *pdi,
9038                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9039                         int set_addrmap, struct dwarf2_cu *cu)
9040 {
9041   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9042     {
9043       if (pdi->has_pc_info)
9044         {
9045           if (pdi->lowpc < *lowpc)
9046             *lowpc = pdi->lowpc;
9047           if (pdi->highpc > *highpc)
9048             *highpc = pdi->highpc;
9049           if (set_addrmap)
9050             {
9051               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9052               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9053               CORE_ADDR baseaddr;
9054               CORE_ADDR highpc;
9055               CORE_ADDR lowpc;
9056
9057               baseaddr = ANOFFSET (objfile->section_offsets,
9058                                    SECT_OFF_TEXT (objfile));
9059               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9060                                                   pdi->lowpc + baseaddr);
9061               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9062                                                    pdi->highpc + baseaddr);
9063               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9064                                  cu->per_cu->v.psymtab);
9065             }
9066         }
9067
9068       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9069         {
9070           if (!pdi->is_declaration)
9071             /* Ignore subprogram DIEs that do not have a name, they are
9072                illegal.  Do not emit a complaint at this point, we will
9073                do so when we convert this psymtab into a symtab.  */
9074             if (pdi->name)
9075               add_partial_symbol (pdi, cu);
9076         }
9077     }
9078
9079   if (! pdi->has_children)
9080     return;
9081
9082   if (cu->language == language_ada)
9083     {
9084       pdi = pdi->die_child;
9085       while (pdi != NULL)
9086         {
9087           pdi->fixup (cu);
9088           if (pdi->tag == DW_TAG_subprogram
9089               || pdi->tag == DW_TAG_inlined_subroutine
9090               || pdi->tag == DW_TAG_lexical_block)
9091             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9092           pdi = pdi->die_sibling;
9093         }
9094     }
9095 }
9096
9097 /* Read a partial die corresponding to an enumeration type.  */
9098
9099 static void
9100 add_partial_enumeration (struct partial_die_info *enum_pdi,
9101                          struct dwarf2_cu *cu)
9102 {
9103   struct partial_die_info *pdi;
9104
9105   if (enum_pdi->name != NULL)
9106     add_partial_symbol (enum_pdi, cu);
9107
9108   pdi = enum_pdi->die_child;
9109   while (pdi)
9110     {
9111       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9112         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9113       else
9114         add_partial_symbol (pdi, cu);
9115       pdi = pdi->die_sibling;
9116     }
9117 }
9118
9119 /* Return the initial uleb128 in the die at INFO_PTR.  */
9120
9121 static unsigned int
9122 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9123 {
9124   unsigned int bytes_read;
9125
9126   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9127 }
9128
9129 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9130    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9131
9132    Return the corresponding abbrev, or NULL if the number is zero (indicating
9133    an empty DIE).  In either case *BYTES_READ will be set to the length of
9134    the initial number.  */
9135
9136 static struct abbrev_info *
9137 peek_die_abbrev (const die_reader_specs &reader,
9138                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9139 {
9140   dwarf2_cu *cu = reader.cu;
9141   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9142   unsigned int abbrev_number
9143     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9144
9145   if (abbrev_number == 0)
9146     return NULL;
9147
9148   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9149   if (!abbrev)
9150     {
9151       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9152                " at offset %s [in module %s]"),
9153              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9154              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9155     }
9156
9157   return abbrev;
9158 }
9159
9160 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9161    Returns a pointer to the end of a series of DIEs, terminated by an empty
9162    DIE.  Any children of the skipped DIEs will also be skipped.  */
9163
9164 static const gdb_byte *
9165 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9166 {
9167   while (1)
9168     {
9169       unsigned int bytes_read;
9170       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9171
9172       if (abbrev == NULL)
9173         return info_ptr + bytes_read;
9174       else
9175         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9176     }
9177 }
9178
9179 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9180    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9181    abbrev corresponding to that skipped uleb128 should be passed in
9182    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9183    children.  */
9184
9185 static const gdb_byte *
9186 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9187               struct abbrev_info *abbrev)
9188 {
9189   unsigned int bytes_read;
9190   struct attribute attr;
9191   bfd *abfd = reader->abfd;
9192   struct dwarf2_cu *cu = reader->cu;
9193   const gdb_byte *buffer = reader->buffer;
9194   const gdb_byte *buffer_end = reader->buffer_end;
9195   unsigned int form, i;
9196
9197   for (i = 0; i < abbrev->num_attrs; i++)
9198     {
9199       /* The only abbrev we care about is DW_AT_sibling.  */
9200       if (abbrev->attrs[i].name == DW_AT_sibling)
9201         {
9202           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9203           if (attr.form == DW_FORM_ref_addr)
9204             complaint (&symfile_complaints,
9205                        _("ignoring absolute DW_AT_sibling"));
9206           else
9207             {
9208               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9209               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9210
9211               if (sibling_ptr < info_ptr)
9212                 complaint (&symfile_complaints,
9213                            _("DW_AT_sibling points backwards"));
9214               else if (sibling_ptr > reader->buffer_end)
9215                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9216               else
9217                 return sibling_ptr;
9218             }
9219         }
9220
9221       /* If it isn't DW_AT_sibling, skip this attribute.  */
9222       form = abbrev->attrs[i].form;
9223     skip_attribute:
9224       switch (form)
9225         {
9226         case DW_FORM_ref_addr:
9227           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9228              and later it is offset sized.  */
9229           if (cu->header.version == 2)
9230             info_ptr += cu->header.addr_size;
9231           else
9232             info_ptr += cu->header.offset_size;
9233           break;
9234         case DW_FORM_GNU_ref_alt:
9235           info_ptr += cu->header.offset_size;
9236           break;
9237         case DW_FORM_addr:
9238           info_ptr += cu->header.addr_size;
9239           break;
9240         case DW_FORM_data1:
9241         case DW_FORM_ref1:
9242         case DW_FORM_flag:
9243           info_ptr += 1;
9244           break;
9245         case DW_FORM_flag_present:
9246         case DW_FORM_implicit_const:
9247           break;
9248         case DW_FORM_data2:
9249         case DW_FORM_ref2:
9250           info_ptr += 2;
9251           break;
9252         case DW_FORM_data4:
9253         case DW_FORM_ref4:
9254           info_ptr += 4;
9255           break;
9256         case DW_FORM_data8:
9257         case DW_FORM_ref8:
9258         case DW_FORM_ref_sig8:
9259           info_ptr += 8;
9260           break;
9261         case DW_FORM_data16:
9262           info_ptr += 16;
9263           break;
9264         case DW_FORM_string:
9265           read_direct_string (abfd, info_ptr, &bytes_read);
9266           info_ptr += bytes_read;
9267           break;
9268         case DW_FORM_sec_offset:
9269         case DW_FORM_strp:
9270         case DW_FORM_GNU_strp_alt:
9271           info_ptr += cu->header.offset_size;
9272           break;
9273         case DW_FORM_exprloc:
9274         case DW_FORM_block:
9275           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9276           info_ptr += bytes_read;
9277           break;
9278         case DW_FORM_block1:
9279           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9280           break;
9281         case DW_FORM_block2:
9282           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9283           break;
9284         case DW_FORM_block4:
9285           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9286           break;
9287         case DW_FORM_sdata:
9288         case DW_FORM_udata:
9289         case DW_FORM_ref_udata:
9290         case DW_FORM_GNU_addr_index:
9291         case DW_FORM_GNU_str_index:
9292           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9293           break;
9294         case DW_FORM_indirect:
9295           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9296           info_ptr += bytes_read;
9297           /* We need to continue parsing from here, so just go back to
9298              the top.  */
9299           goto skip_attribute;
9300
9301         default:
9302           error (_("Dwarf Error: Cannot handle %s "
9303                    "in DWARF reader [in module %s]"),
9304                  dwarf_form_name (form),
9305                  bfd_get_filename (abfd));
9306         }
9307     }
9308
9309   if (abbrev->has_children)
9310     return skip_children (reader, info_ptr);
9311   else
9312     return info_ptr;
9313 }
9314
9315 /* Locate ORIG_PDI's sibling.
9316    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9317
9318 static const gdb_byte *
9319 locate_pdi_sibling (const struct die_reader_specs *reader,
9320                     struct partial_die_info *orig_pdi,
9321                     const gdb_byte *info_ptr)
9322 {
9323   /* Do we know the sibling already?  */
9324
9325   if (orig_pdi->sibling)
9326     return orig_pdi->sibling;
9327
9328   /* Are there any children to deal with?  */
9329
9330   if (!orig_pdi->has_children)
9331     return info_ptr;
9332
9333   /* Skip the children the long way.  */
9334
9335   return skip_children (reader, info_ptr);
9336 }
9337
9338 /* Expand this partial symbol table into a full symbol table.  SELF is
9339    not NULL.  */
9340
9341 static void
9342 dwarf2_read_symtab (struct partial_symtab *self,
9343                     struct objfile *objfile)
9344 {
9345   struct dwarf2_per_objfile *dwarf2_per_objfile
9346     = get_dwarf2_per_objfile (objfile);
9347
9348   if (self->readin)
9349     {
9350       warning (_("bug: psymtab for %s is already read in."),
9351                self->filename);
9352     }
9353   else
9354     {
9355       if (info_verbose)
9356         {
9357           printf_filtered (_("Reading in symbols for %s..."),
9358                            self->filename);
9359           gdb_flush (gdb_stdout);
9360         }
9361
9362       /* If this psymtab is constructed from a debug-only objfile, the
9363          has_section_at_zero flag will not necessarily be correct.  We
9364          can get the correct value for this flag by looking at the data
9365          associated with the (presumably stripped) associated objfile.  */
9366       if (objfile->separate_debug_objfile_backlink)
9367         {
9368           struct dwarf2_per_objfile *dpo_backlink
9369             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9370
9371           dwarf2_per_objfile->has_section_at_zero
9372             = dpo_backlink->has_section_at_zero;
9373         }
9374
9375       dwarf2_per_objfile->reading_partial_symbols = 0;
9376
9377       psymtab_to_symtab_1 (self);
9378
9379       /* Finish up the debug error message.  */
9380       if (info_verbose)
9381         printf_filtered (_("done.\n"));
9382     }
9383
9384   process_cu_includes (dwarf2_per_objfile);
9385 }
9386 \f
9387 /* Reading in full CUs.  */
9388
9389 /* Add PER_CU to the queue.  */
9390
9391 static void
9392 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9393                  enum language pretend_language)
9394 {
9395   struct dwarf2_queue_item *item;
9396
9397   per_cu->queued = 1;
9398   item = XNEW (struct dwarf2_queue_item);
9399   item->per_cu = per_cu;
9400   item->pretend_language = pretend_language;
9401   item->next = NULL;
9402
9403   if (dwarf2_queue == NULL)
9404     dwarf2_queue = item;
9405   else
9406     dwarf2_queue_tail->next = item;
9407
9408   dwarf2_queue_tail = item;
9409 }
9410
9411 /* If PER_CU is not yet queued, add it to the queue.
9412    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9413    dependency.
9414    The result is non-zero if PER_CU was queued, otherwise the result is zero
9415    meaning either PER_CU is already queued or it is already loaded.
9416
9417    N.B. There is an invariant here that if a CU is queued then it is loaded.
9418    The caller is required to load PER_CU if we return non-zero.  */
9419
9420 static int
9421 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9422                        struct dwarf2_per_cu_data *per_cu,
9423                        enum language pretend_language)
9424 {
9425   /* We may arrive here during partial symbol reading, if we need full
9426      DIEs to process an unusual case (e.g. template arguments).  Do
9427      not queue PER_CU, just tell our caller to load its DIEs.  */
9428   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9429     {
9430       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9431         return 1;
9432       return 0;
9433     }
9434
9435   /* Mark the dependence relation so that we don't flush PER_CU
9436      too early.  */
9437   if (dependent_cu != NULL)
9438     dwarf2_add_dependence (dependent_cu, per_cu);
9439
9440   /* If it's already on the queue, we have nothing to do.  */
9441   if (per_cu->queued)
9442     return 0;
9443
9444   /* If the compilation unit is already loaded, just mark it as
9445      used.  */
9446   if (per_cu->cu != NULL)
9447     {
9448       per_cu->cu->last_used = 0;
9449       return 0;
9450     }
9451
9452   /* Add it to the queue.  */
9453   queue_comp_unit (per_cu, pretend_language);
9454
9455   return 1;
9456 }
9457
9458 /* Process the queue.  */
9459
9460 static void
9461 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9462 {
9463   struct dwarf2_queue_item *item, *next_item;
9464
9465   if (dwarf_read_debug)
9466     {
9467       fprintf_unfiltered (gdb_stdlog,
9468                           "Expanding one or more symtabs of objfile %s ...\n",
9469                           objfile_name (dwarf2_per_objfile->objfile));
9470     }
9471
9472   /* The queue starts out with one item, but following a DIE reference
9473      may load a new CU, adding it to the end of the queue.  */
9474   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9475     {
9476       if ((dwarf2_per_objfile->using_index
9477            ? !item->per_cu->v.quick->compunit_symtab
9478            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9479           /* Skip dummy CUs.  */
9480           && item->per_cu->cu != NULL)
9481         {
9482           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9483           unsigned int debug_print_threshold;
9484           char buf[100];
9485
9486           if (per_cu->is_debug_types)
9487             {
9488               struct signatured_type *sig_type =
9489                 (struct signatured_type *) per_cu;
9490
9491               sprintf (buf, "TU %s at offset %s",
9492                        hex_string (sig_type->signature),
9493                        sect_offset_str (per_cu->sect_off));
9494               /* There can be 100s of TUs.
9495                  Only print them in verbose mode.  */
9496               debug_print_threshold = 2;
9497             }
9498           else
9499             {
9500               sprintf (buf, "CU at offset %s",
9501                        sect_offset_str (per_cu->sect_off));
9502               debug_print_threshold = 1;
9503             }
9504
9505           if (dwarf_read_debug >= debug_print_threshold)
9506             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9507
9508           if (per_cu->is_debug_types)
9509             process_full_type_unit (per_cu, item->pretend_language);
9510           else
9511             process_full_comp_unit (per_cu, item->pretend_language);
9512
9513           if (dwarf_read_debug >= debug_print_threshold)
9514             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9515         }
9516
9517       item->per_cu->queued = 0;
9518       next_item = item->next;
9519       xfree (item);
9520     }
9521
9522   dwarf2_queue_tail = NULL;
9523
9524   if (dwarf_read_debug)
9525     {
9526       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9527                           objfile_name (dwarf2_per_objfile->objfile));
9528     }
9529 }
9530
9531 /* Read in full symbols for PST, and anything it depends on.  */
9532
9533 static void
9534 psymtab_to_symtab_1 (struct partial_symtab *pst)
9535 {
9536   struct dwarf2_per_cu_data *per_cu;
9537   int i;
9538
9539   if (pst->readin)
9540     return;
9541
9542   for (i = 0; i < pst->number_of_dependencies; i++)
9543     if (!pst->dependencies[i]->readin
9544         && pst->dependencies[i]->user == NULL)
9545       {
9546         /* Inform about additional files that need to be read in.  */
9547         if (info_verbose)
9548           {
9549             /* FIXME: i18n: Need to make this a single string.  */
9550             fputs_filtered (" ", gdb_stdout);
9551             wrap_here ("");
9552             fputs_filtered ("and ", gdb_stdout);
9553             wrap_here ("");
9554             printf_filtered ("%s...", pst->dependencies[i]->filename);
9555             wrap_here ("");     /* Flush output.  */
9556             gdb_flush (gdb_stdout);
9557           }
9558         psymtab_to_symtab_1 (pst->dependencies[i]);
9559       }
9560
9561   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9562
9563   if (per_cu == NULL)
9564     {
9565       /* It's an include file, no symbols to read for it.
9566          Everything is in the parent symtab.  */
9567       pst->readin = 1;
9568       return;
9569     }
9570
9571   dw2_do_instantiate_symtab (per_cu, false);
9572 }
9573
9574 /* Trivial hash function for die_info: the hash value of a DIE
9575    is its offset in .debug_info for this objfile.  */
9576
9577 static hashval_t
9578 die_hash (const void *item)
9579 {
9580   const struct die_info *die = (const struct die_info *) item;
9581
9582   return to_underlying (die->sect_off);
9583 }
9584
9585 /* Trivial comparison function for die_info structures: two DIEs
9586    are equal if they have the same offset.  */
9587
9588 static int
9589 die_eq (const void *item_lhs, const void *item_rhs)
9590 {
9591   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9592   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9593
9594   return die_lhs->sect_off == die_rhs->sect_off;
9595 }
9596
9597 /* die_reader_func for load_full_comp_unit.
9598    This is identical to read_signatured_type_reader,
9599    but is kept separate for now.  */
9600
9601 static void
9602 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9603                             const gdb_byte *info_ptr,
9604                             struct die_info *comp_unit_die,
9605                             int has_children,
9606                             void *data)
9607 {
9608   struct dwarf2_cu *cu = reader->cu;
9609   enum language *language_ptr = (enum language *) data;
9610
9611   gdb_assert (cu->die_hash == NULL);
9612   cu->die_hash =
9613     htab_create_alloc_ex (cu->header.length / 12,
9614                           die_hash,
9615                           die_eq,
9616                           NULL,
9617                           &cu->comp_unit_obstack,
9618                           hashtab_obstack_allocate,
9619                           dummy_obstack_deallocate);
9620
9621   if (has_children)
9622     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9623                                                   &info_ptr, comp_unit_die);
9624   cu->dies = comp_unit_die;
9625   /* comp_unit_die is not stored in die_hash, no need.  */
9626
9627   /* We try not to read any attributes in this function, because not
9628      all CUs needed for references have been loaded yet, and symbol
9629      table processing isn't initialized.  But we have to set the CU language,
9630      or we won't be able to build types correctly.
9631      Similarly, if we do not read the producer, we can not apply
9632      producer-specific interpretation.  */
9633   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9634 }
9635
9636 /* Load the DIEs associated with PER_CU into memory.  */
9637
9638 static void
9639 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9640                      bool skip_partial,
9641                      enum language pretend_language)
9642 {
9643   gdb_assert (! this_cu->is_debug_types);
9644
9645   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9646                            load_full_comp_unit_reader, &pretend_language);
9647 }
9648
9649 /* Add a DIE to the delayed physname list.  */
9650
9651 static void
9652 add_to_method_list (struct type *type, int fnfield_index, int index,
9653                     const char *name, struct die_info *die,
9654                     struct dwarf2_cu *cu)
9655 {
9656   struct delayed_method_info mi;
9657   mi.type = type;
9658   mi.fnfield_index = fnfield_index;
9659   mi.index = index;
9660   mi.name = name;
9661   mi.die = die;
9662   cu->method_list.push_back (mi);
9663 }
9664
9665 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9666    "const" / "volatile".  If so, decrements LEN by the length of the
9667    modifier and return true.  Otherwise return false.  */
9668
9669 template<size_t N>
9670 static bool
9671 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9672 {
9673   size_t mod_len = sizeof (mod) - 1;
9674   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9675     {
9676       len -= mod_len;
9677       return true;
9678     }
9679   return false;
9680 }
9681
9682 /* Compute the physnames of any methods on the CU's method list.
9683
9684    The computation of method physnames is delayed in order to avoid the
9685    (bad) condition that one of the method's formal parameters is of an as yet
9686    incomplete type.  */
9687
9688 static void
9689 compute_delayed_physnames (struct dwarf2_cu *cu)
9690 {
9691   /* Only C++ delays computing physnames.  */
9692   if (cu->method_list.empty ())
9693     return;
9694   gdb_assert (cu->language == language_cplus);
9695
9696   for (struct delayed_method_info &mi : cu->method_list)
9697     {
9698       const char *physname;
9699       struct fn_fieldlist *fn_flp
9700         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9701       physname = dwarf2_physname (mi.name, mi.die, cu);
9702       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9703         = physname ? physname : "";
9704
9705       /* Since there's no tag to indicate whether a method is a
9706          const/volatile overload, extract that information out of the
9707          demangled name.  */
9708       if (physname != NULL)
9709         {
9710           size_t len = strlen (physname);
9711
9712           while (1)
9713             {
9714               if (physname[len] == ')') /* shortcut */
9715                 break;
9716               else if (check_modifier (physname, len, " const"))
9717                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9718               else if (check_modifier (physname, len, " volatile"))
9719                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9720               else
9721                 break;
9722             }
9723         }
9724     }
9725
9726   /* The list is no longer needed.  */
9727   cu->method_list.clear ();
9728 }
9729
9730 /* Go objects should be embedded in a DW_TAG_module DIE,
9731    and it's not clear if/how imported objects will appear.
9732    To keep Go support simple until that's worked out,
9733    go back through what we've read and create something usable.
9734    We could do this while processing each DIE, and feels kinda cleaner,
9735    but that way is more invasive.
9736    This is to, for example, allow the user to type "p var" or "b main"
9737    without having to specify the package name, and allow lookups
9738    of module.object to work in contexts that use the expression
9739    parser.  */
9740
9741 static void
9742 fixup_go_packaging (struct dwarf2_cu *cu)
9743 {
9744   char *package_name = NULL;
9745   struct pending *list;
9746   int i;
9747
9748   for (list = global_symbols; list != NULL; list = list->next)
9749     {
9750       for (i = 0; i < list->nsyms; ++i)
9751         {
9752           struct symbol *sym = list->symbol[i];
9753
9754           if (SYMBOL_LANGUAGE (sym) == language_go
9755               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9756             {
9757               char *this_package_name = go_symbol_package_name (sym);
9758
9759               if (this_package_name == NULL)
9760                 continue;
9761               if (package_name == NULL)
9762                 package_name = this_package_name;
9763               else
9764                 {
9765                   struct objfile *objfile
9766                     = cu->per_cu->dwarf2_per_objfile->objfile;
9767                   if (strcmp (package_name, this_package_name) != 0)
9768                     complaint (&symfile_complaints,
9769                                _("Symtab %s has objects from two different Go packages: %s and %s"),
9770                                (symbol_symtab (sym) != NULL
9771                                 ? symtab_to_filename_for_display
9772                                     (symbol_symtab (sym))
9773                                 : objfile_name (objfile)),
9774                                this_package_name, package_name);
9775                   xfree (this_package_name);
9776                 }
9777             }
9778         }
9779     }
9780
9781   if (package_name != NULL)
9782     {
9783       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9784       const char *saved_package_name
9785         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9786                                         package_name,
9787                                         strlen (package_name));
9788       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9789                                      saved_package_name);
9790       struct symbol *sym;
9791
9792       TYPE_TAG_NAME (type) = TYPE_NAME (type);
9793
9794       sym = allocate_symbol (objfile);
9795       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9796       SYMBOL_SET_NAMES (sym, saved_package_name,
9797                         strlen (saved_package_name), 0, objfile);
9798       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9799          e.g., "main" finds the "main" module and not C's main().  */
9800       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9801       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9802       SYMBOL_TYPE (sym) = type;
9803
9804       add_symbol_to_list (sym, &global_symbols);
9805
9806       xfree (package_name);
9807     }
9808 }
9809
9810 /* Allocate a fully-qualified name consisting of the two parts on the
9811    obstack.  */
9812
9813 static const char *
9814 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9815 {
9816   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9817 }
9818
9819 /* A helper that allocates a struct discriminant_info to attach to a
9820    union type.  */
9821
9822 static struct discriminant_info *
9823 alloc_discriminant_info (struct type *type, int discriminant_index,
9824                          int default_index)
9825 {
9826   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9827   gdb_assert (discriminant_index == -1
9828               || (discriminant_index >= 0
9829                   && discriminant_index < TYPE_NFIELDS (type)));
9830   gdb_assert (default_index == -1
9831               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9832
9833   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9834
9835   struct discriminant_info *disc
9836     = ((struct discriminant_info *)
9837        TYPE_ZALLOC (type,
9838                     offsetof (struct discriminant_info, discriminants)
9839                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9840   disc->default_index = default_index;
9841   disc->discriminant_index = discriminant_index;
9842
9843   struct dynamic_prop prop;
9844   prop.kind = PROP_UNDEFINED;
9845   prop.data.baton = disc;
9846
9847   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9848
9849   return disc;
9850 }
9851
9852 /* Some versions of rustc emitted enums in an unusual way.
9853
9854    Ordinary enums were emitted as unions.  The first element of each
9855    structure in the union was named "RUST$ENUM$DISR".  This element
9856    held the discriminant.
9857
9858    These versions of Rust also implemented the "non-zero"
9859    optimization.  When the enum had two values, and one is empty and
9860    the other holds a pointer that cannot be zero, the pointer is used
9861    as the discriminant, with a zero value meaning the empty variant.
9862    Here, the union's first member is of the form
9863    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9864    where the fieldnos are the indices of the fields that should be
9865    traversed in order to find the field (which may be several fields deep)
9866    and the variantname is the name of the variant of the case when the
9867    field is zero.
9868
9869    This function recognizes whether TYPE is of one of these forms,
9870    and, if so, smashes it to be a variant type.  */
9871
9872 static void
9873 quirk_rust_enum (struct type *type, struct objfile *objfile)
9874 {
9875   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9876
9877   /* We don't need to deal with empty enums.  */
9878   if (TYPE_NFIELDS (type) == 0)
9879     return;
9880
9881 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9882   if (TYPE_NFIELDS (type) == 1
9883       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9884     {
9885       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9886
9887       /* Decode the field name to find the offset of the
9888          discriminant.  */
9889       ULONGEST bit_offset = 0;
9890       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9891       while (name[0] >= '0' && name[0] <= '9')
9892         {
9893           char *tail;
9894           unsigned long index = strtoul (name, &tail, 10);
9895           name = tail;
9896           if (*name != '$'
9897               || index >= TYPE_NFIELDS (field_type)
9898               || (TYPE_FIELD_LOC_KIND (field_type, index)
9899                   != FIELD_LOC_KIND_BITPOS))
9900             {
9901               complaint (&symfile_complaints,
9902                          _("Could not parse Rust enum encoding string \"%s\""
9903                            "[in module %s]"),
9904                          TYPE_FIELD_NAME (type, 0),
9905                          objfile_name (objfile));
9906               return;
9907             }
9908           ++name;
9909
9910           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9911           field_type = TYPE_FIELD_TYPE (field_type, index);
9912         }
9913
9914       /* Make a union to hold the variants.  */
9915       struct type *union_type = alloc_type (objfile);
9916       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9917       TYPE_NFIELDS (union_type) = 3;
9918       TYPE_FIELDS (union_type)
9919         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9920       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9921       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9922
9923       /* Put the discriminant must at index 0.  */
9924       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9925       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9926       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9927       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9928
9929       /* The order of fields doesn't really matter, so put the real
9930          field at index 1 and the data-less field at index 2.  */
9931       struct discriminant_info *disc
9932         = alloc_discriminant_info (union_type, 0, 1);
9933       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9934       TYPE_FIELD_NAME (union_type, 1)
9935         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9936       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9937         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9938                               TYPE_FIELD_NAME (union_type, 1));
9939
9940       const char *dataless_name
9941         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9942                               name);
9943       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9944                                               dataless_name);
9945       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9946       /* NAME points into the original discriminant name, which
9947          already has the correct lifetime.  */
9948       TYPE_FIELD_NAME (union_type, 2) = name;
9949       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9950       disc->discriminants[2] = 0;
9951
9952       /* Smash this type to be a structure type.  We have to do this
9953          because the type has already been recorded.  */
9954       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9955       TYPE_NFIELDS (type) = 1;
9956       TYPE_FIELDS (type)
9957         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9958
9959       /* Install the variant part.  */
9960       TYPE_FIELD_TYPE (type, 0) = union_type;
9961       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9962       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9963     }
9964   else if (TYPE_NFIELDS (type) == 1)
9965     {
9966       /* We assume that a union with a single field is a univariant
9967          enum.  */
9968       /* Smash this type to be a structure type.  We have to do this
9969          because the type has already been recorded.  */
9970       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9971
9972       /* Make a union to hold the variants.  */
9973       struct type *union_type = alloc_type (objfile);
9974       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9975       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9976       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9977       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9978       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9979
9980       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9981       const char *variant_name
9982         = rust_last_path_segment (TYPE_NAME (field_type));
9983       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9984       TYPE_NAME (field_type)
9985         = rust_fully_qualify (&objfile->objfile_obstack,
9986                               TYPE_NAME (type), variant_name);
9987
9988       /* Install the union in the outer struct type.  */
9989       TYPE_NFIELDS (type) = 1;
9990       TYPE_FIELDS (type)
9991         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9992       TYPE_FIELD_TYPE (type, 0) = union_type;
9993       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9994       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9995
9996       alloc_discriminant_info (union_type, -1, 0);
9997     }
9998   else
9999     {
10000       struct type *disr_type = nullptr;
10001       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10002         {
10003           disr_type = TYPE_FIELD_TYPE (type, i);
10004
10005           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10006             {
10007               /* All fields of a true enum will be structs.  */
10008               return;
10009             }
10010           else if (TYPE_NFIELDS (disr_type) == 0)
10011             {
10012               /* Could be data-less variant, so keep going.  */
10013               disr_type = nullptr;
10014             }
10015           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10016                            "RUST$ENUM$DISR") != 0)
10017             {
10018               /* Not a Rust enum.  */
10019               return;
10020             }
10021           else
10022             {
10023               /* Found one.  */
10024               break;
10025             }
10026         }
10027
10028       /* If we got here without a discriminant, then it's probably
10029          just a union.  */
10030       if (disr_type == nullptr)
10031         return;
10032
10033       /* Smash this type to be a structure type.  We have to do this
10034          because the type has already been recorded.  */
10035       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10036
10037       /* Make a union to hold the variants.  */
10038       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10039       struct type *union_type = alloc_type (objfile);
10040       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10041       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10042       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10043       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10044       TYPE_FIELDS (union_type)
10045         = (struct field *) TYPE_ZALLOC (union_type,
10046                                         (TYPE_NFIELDS (union_type)
10047                                          * sizeof (struct field)));
10048
10049       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10050               TYPE_NFIELDS (type) * sizeof (struct field));
10051
10052       /* Install the discriminant at index 0 in the union.  */
10053       TYPE_FIELD (union_type, 0) = *disr_field;
10054       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10055       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10056
10057       /* Install the union in the outer struct type.  */
10058       TYPE_FIELD_TYPE (type, 0) = union_type;
10059       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10060       TYPE_NFIELDS (type) = 1;
10061
10062       /* Set the size and offset of the union type.  */
10063       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10064
10065       /* We need a way to find the correct discriminant given a
10066          variant name.  For convenience we build a map here.  */
10067       struct type *enum_type = FIELD_TYPE (*disr_field);
10068       std::unordered_map<std::string, ULONGEST> discriminant_map;
10069       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10070         {
10071           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10072             {
10073               const char *name
10074                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10075               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10076             }
10077         }
10078
10079       int n_fields = TYPE_NFIELDS (union_type);
10080       struct discriminant_info *disc
10081         = alloc_discriminant_info (union_type, 0, -1);
10082       /* Skip the discriminant here.  */
10083       for (int i = 1; i < n_fields; ++i)
10084         {
10085           /* Find the final word in the name of this variant's type.
10086              That name can be used to look up the correct
10087              discriminant.  */
10088           const char *variant_name
10089             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10090                                                                   i)));
10091
10092           auto iter = discriminant_map.find (variant_name);
10093           if (iter != discriminant_map.end ())
10094             disc->discriminants[i] = iter->second;
10095
10096           /* Remove the discriminant field, if it exists.  */
10097           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10098           if (TYPE_NFIELDS (sub_type) > 0)
10099             {
10100               --TYPE_NFIELDS (sub_type);
10101               ++TYPE_FIELDS (sub_type);
10102             }
10103           TYPE_FIELD_NAME (union_type, i) = variant_name;
10104           TYPE_NAME (sub_type)
10105             = rust_fully_qualify (&objfile->objfile_obstack,
10106                                   TYPE_NAME (type), variant_name);
10107         }
10108     }
10109 }
10110
10111 /* Rewrite some Rust unions to be structures with variants parts.  */
10112
10113 static void
10114 rust_union_quirks (struct dwarf2_cu *cu)
10115 {
10116   gdb_assert (cu->language == language_rust);
10117   for (struct type *type : cu->rust_unions)
10118     quirk_rust_enum (type, cu->per_cu->dwarf2_per_objfile->objfile);
10119   /* We don't need this any more.  */
10120   cu->rust_unions.clear ();
10121 }
10122
10123 /* Return the symtab for PER_CU.  This works properly regardless of
10124    whether we're using the index or psymtabs.  */
10125
10126 static struct compunit_symtab *
10127 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10128 {
10129   return (per_cu->dwarf2_per_objfile->using_index
10130           ? per_cu->v.quick->compunit_symtab
10131           : per_cu->v.psymtab->compunit_symtab);
10132 }
10133
10134 /* A helper function for computing the list of all symbol tables
10135    included by PER_CU.  */
10136
10137 static void
10138 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10139                                 htab_t all_children, htab_t all_type_symtabs,
10140                                 struct dwarf2_per_cu_data *per_cu,
10141                                 struct compunit_symtab *immediate_parent)
10142 {
10143   void **slot;
10144   int ix;
10145   struct compunit_symtab *cust;
10146   struct dwarf2_per_cu_data *iter;
10147
10148   slot = htab_find_slot (all_children, per_cu, INSERT);
10149   if (*slot != NULL)
10150     {
10151       /* This inclusion and its children have been processed.  */
10152       return;
10153     }
10154
10155   *slot = per_cu;
10156   /* Only add a CU if it has a symbol table.  */
10157   cust = get_compunit_symtab (per_cu);
10158   if (cust != NULL)
10159     {
10160       /* If this is a type unit only add its symbol table if we haven't
10161          seen it yet (type unit per_cu's can share symtabs).  */
10162       if (per_cu->is_debug_types)
10163         {
10164           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10165           if (*slot == NULL)
10166             {
10167               *slot = cust;
10168               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10169               if (cust->user == NULL)
10170                 cust->user = immediate_parent;
10171             }
10172         }
10173       else
10174         {
10175           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10176           if (cust->user == NULL)
10177             cust->user = immediate_parent;
10178         }
10179     }
10180
10181   for (ix = 0;
10182        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10183        ++ix)
10184     {
10185       recursively_compute_inclusions (result, all_children,
10186                                       all_type_symtabs, iter, cust);
10187     }
10188 }
10189
10190 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10191    PER_CU.  */
10192
10193 static void
10194 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10195 {
10196   gdb_assert (! per_cu->is_debug_types);
10197
10198   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10199     {
10200       int ix, len;
10201       struct dwarf2_per_cu_data *per_cu_iter;
10202       struct compunit_symtab *compunit_symtab_iter;
10203       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10204       htab_t all_children, all_type_symtabs;
10205       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10206
10207       /* If we don't have a symtab, we can just skip this case.  */
10208       if (cust == NULL)
10209         return;
10210
10211       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10212                                         NULL, xcalloc, xfree);
10213       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10214                                             NULL, xcalloc, xfree);
10215
10216       for (ix = 0;
10217            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10218                         ix, per_cu_iter);
10219            ++ix)
10220         {
10221           recursively_compute_inclusions (&result_symtabs, all_children,
10222                                           all_type_symtabs, per_cu_iter,
10223                                           cust);
10224         }
10225
10226       /* Now we have a transitive closure of all the included symtabs.  */
10227       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10228       cust->includes
10229         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10230                      struct compunit_symtab *, len + 1);
10231       for (ix = 0;
10232            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10233                         compunit_symtab_iter);
10234            ++ix)
10235         cust->includes[ix] = compunit_symtab_iter;
10236       cust->includes[len] = NULL;
10237
10238       VEC_free (compunit_symtab_ptr, result_symtabs);
10239       htab_delete (all_children);
10240       htab_delete (all_type_symtabs);
10241     }
10242 }
10243
10244 /* Compute the 'includes' field for the symtabs of all the CUs we just
10245    read.  */
10246
10247 static void
10248 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10249 {
10250   int ix;
10251   struct dwarf2_per_cu_data *iter;
10252
10253   for (ix = 0;
10254        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10255                     ix, iter);
10256        ++ix)
10257     {
10258       if (! iter->is_debug_types)
10259         compute_compunit_symtab_includes (iter);
10260     }
10261
10262   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10263 }
10264
10265 /* Generate full symbol information for PER_CU, whose DIEs have
10266    already been loaded into memory.  */
10267
10268 static void
10269 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10270                         enum language pretend_language)
10271 {
10272   struct dwarf2_cu *cu = per_cu->cu;
10273   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10274   struct objfile *objfile = dwarf2_per_objfile->objfile;
10275   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10276   CORE_ADDR lowpc, highpc;
10277   struct compunit_symtab *cust;
10278   CORE_ADDR baseaddr;
10279   struct block *static_block;
10280   CORE_ADDR addr;
10281
10282   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10283
10284   buildsym_init ();
10285   scoped_free_pendings free_pending;
10286
10287   /* Clear the list here in case something was left over.  */
10288   cu->method_list.clear ();
10289
10290   cu->list_in_scope = &file_symbols;
10291
10292   cu->language = pretend_language;
10293   cu->language_defn = language_def (cu->language);
10294
10295   /* Do line number decoding in read_file_scope () */
10296   process_die (cu->dies, cu);
10297
10298   /* For now fudge the Go package.  */
10299   if (cu->language == language_go)
10300     fixup_go_packaging (cu);
10301
10302   /* Now that we have processed all the DIEs in the CU, all the types 
10303      should be complete, and it should now be safe to compute all of the
10304      physnames.  */
10305   compute_delayed_physnames (cu);
10306
10307   if (cu->language == language_rust)
10308     rust_union_quirks (cu);
10309
10310   /* Some compilers don't define a DW_AT_high_pc attribute for the
10311      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10312      it, by scanning the DIE's below the compilation unit.  */
10313   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10314
10315   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10316   static_block = end_symtab_get_static_block (addr, 0, 1);
10317
10318   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10319      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10320      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10321      addrmap to help ensure it has an accurate map of pc values belonging to
10322      this comp unit.  */
10323   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10324
10325   cust = end_symtab_from_static_block (static_block,
10326                                        SECT_OFF_TEXT (objfile), 0);
10327
10328   if (cust != NULL)
10329     {
10330       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10331
10332       /* Set symtab language to language from DW_AT_language.  If the
10333          compilation is from a C file generated by language preprocessors, do
10334          not set the language if it was already deduced by start_subfile.  */
10335       if (!(cu->language == language_c
10336             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10337         COMPUNIT_FILETABS (cust)->language = cu->language;
10338
10339       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10340          produce DW_AT_location with location lists but it can be possibly
10341          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10342          there were bugs in prologue debug info, fixed later in GCC-4.5
10343          by "unwind info for epilogues" patch (which is not directly related).
10344
10345          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10346          needed, it would be wrong due to missing DW_AT_producer there.
10347
10348          Still one can confuse GDB by using non-standard GCC compilation
10349          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10350          */ 
10351       if (cu->has_loclist && gcc_4_minor >= 5)
10352         cust->locations_valid = 1;
10353
10354       if (gcc_4_minor >= 5)
10355         cust->epilogue_unwind_valid = 1;
10356
10357       cust->call_site_htab = cu->call_site_htab;
10358     }
10359
10360   if (dwarf2_per_objfile->using_index)
10361     per_cu->v.quick->compunit_symtab = cust;
10362   else
10363     {
10364       struct partial_symtab *pst = per_cu->v.psymtab;
10365       pst->compunit_symtab = cust;
10366       pst->readin = 1;
10367     }
10368
10369   /* Push it for inclusion processing later.  */
10370   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10371 }
10372
10373 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10374    already been loaded into memory.  */
10375
10376 static void
10377 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10378                         enum language pretend_language)
10379 {
10380   struct dwarf2_cu *cu = per_cu->cu;
10381   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10382   struct objfile *objfile = dwarf2_per_objfile->objfile;
10383   struct compunit_symtab *cust;
10384   struct signatured_type *sig_type;
10385
10386   gdb_assert (per_cu->is_debug_types);
10387   sig_type = (struct signatured_type *) per_cu;
10388
10389   buildsym_init ();
10390   scoped_free_pendings free_pending;
10391
10392   /* Clear the list here in case something was left over.  */
10393   cu->method_list.clear ();
10394
10395   cu->list_in_scope = &file_symbols;
10396
10397   cu->language = pretend_language;
10398   cu->language_defn = language_def (cu->language);
10399
10400   /* The symbol tables are set up in read_type_unit_scope.  */
10401   process_die (cu->dies, cu);
10402
10403   /* For now fudge the Go package.  */
10404   if (cu->language == language_go)
10405     fixup_go_packaging (cu);
10406
10407   /* Now that we have processed all the DIEs in the CU, all the types 
10408      should be complete, and it should now be safe to compute all of the
10409      physnames.  */
10410   compute_delayed_physnames (cu);
10411
10412   if (cu->language == language_rust)
10413     rust_union_quirks (cu);
10414
10415   /* TUs share symbol tables.
10416      If this is the first TU to use this symtab, complete the construction
10417      of it with end_expandable_symtab.  Otherwise, complete the addition of
10418      this TU's symbols to the existing symtab.  */
10419   if (sig_type->type_unit_group->compunit_symtab == NULL)
10420     {
10421       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10422       sig_type->type_unit_group->compunit_symtab = cust;
10423
10424       if (cust != NULL)
10425         {
10426           /* Set symtab language to language from DW_AT_language.  If the
10427              compilation is from a C file generated by language preprocessors,
10428              do not set the language if it was already deduced by
10429              start_subfile.  */
10430           if (!(cu->language == language_c
10431                 && COMPUNIT_FILETABS (cust)->language != language_c))
10432             COMPUNIT_FILETABS (cust)->language = cu->language;
10433         }
10434     }
10435   else
10436     {
10437       augment_type_symtab ();
10438       cust = sig_type->type_unit_group->compunit_symtab;
10439     }
10440
10441   if (dwarf2_per_objfile->using_index)
10442     per_cu->v.quick->compunit_symtab = cust;
10443   else
10444     {
10445       struct partial_symtab *pst = per_cu->v.psymtab;
10446       pst->compunit_symtab = cust;
10447       pst->readin = 1;
10448     }
10449 }
10450
10451 /* Process an imported unit DIE.  */
10452
10453 static void
10454 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10455 {
10456   struct attribute *attr;
10457
10458   /* For now we don't handle imported units in type units.  */
10459   if (cu->per_cu->is_debug_types)
10460     {
10461       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10462                " supported in type units [in module %s]"),
10463              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10464     }
10465
10466   attr = dwarf2_attr (die, DW_AT_import, cu);
10467   if (attr != NULL)
10468     {
10469       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10470       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10471       dwarf2_per_cu_data *per_cu
10472         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10473                                             cu->per_cu->dwarf2_per_objfile);
10474
10475       /* If necessary, add it to the queue and load its DIEs.  */
10476       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10477         load_full_comp_unit (per_cu, false, cu->language);
10478
10479       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10480                      per_cu);
10481     }
10482 }
10483
10484 /* RAII object that represents a process_die scope: i.e.,
10485    starts/finishes processing a DIE.  */
10486 class process_die_scope
10487 {
10488 public:
10489   process_die_scope (die_info *die, dwarf2_cu *cu)
10490     : m_die (die), m_cu (cu)
10491   {
10492     /* We should only be processing DIEs not already in process.  */
10493     gdb_assert (!m_die->in_process);
10494     m_die->in_process = true;
10495   }
10496
10497   ~process_die_scope ()
10498   {
10499     m_die->in_process = false;
10500
10501     /* If we're done processing the DIE for the CU that owns the line
10502        header, we don't need the line header anymore.  */
10503     if (m_cu->line_header_die_owner == m_die)
10504       {
10505         delete m_cu->line_header;
10506         m_cu->line_header = NULL;
10507         m_cu->line_header_die_owner = NULL;
10508       }
10509   }
10510
10511 private:
10512   die_info *m_die;
10513   dwarf2_cu *m_cu;
10514 };
10515
10516 /* Process a die and its children.  */
10517
10518 static void
10519 process_die (struct die_info *die, struct dwarf2_cu *cu)
10520 {
10521   process_die_scope scope (die, cu);
10522
10523   switch (die->tag)
10524     {
10525     case DW_TAG_padding:
10526       break;
10527     case DW_TAG_compile_unit:
10528     case DW_TAG_partial_unit:
10529       read_file_scope (die, cu);
10530       break;
10531     case DW_TAG_type_unit:
10532       read_type_unit_scope (die, cu);
10533       break;
10534     case DW_TAG_subprogram:
10535     case DW_TAG_inlined_subroutine:
10536       read_func_scope (die, cu);
10537       break;
10538     case DW_TAG_lexical_block:
10539     case DW_TAG_try_block:
10540     case DW_TAG_catch_block:
10541       read_lexical_block_scope (die, cu);
10542       break;
10543     case DW_TAG_call_site:
10544     case DW_TAG_GNU_call_site:
10545       read_call_site_scope (die, cu);
10546       break;
10547     case DW_TAG_class_type:
10548     case DW_TAG_interface_type:
10549     case DW_TAG_structure_type:
10550     case DW_TAG_union_type:
10551       process_structure_scope (die, cu);
10552       break;
10553     case DW_TAG_enumeration_type:
10554       process_enumeration_scope (die, cu);
10555       break;
10556
10557     /* These dies have a type, but processing them does not create
10558        a symbol or recurse to process the children.  Therefore we can
10559        read them on-demand through read_type_die.  */
10560     case DW_TAG_subroutine_type:
10561     case DW_TAG_set_type:
10562     case DW_TAG_array_type:
10563     case DW_TAG_pointer_type:
10564     case DW_TAG_ptr_to_member_type:
10565     case DW_TAG_reference_type:
10566     case DW_TAG_rvalue_reference_type:
10567     case DW_TAG_string_type:
10568       break;
10569
10570     case DW_TAG_base_type:
10571     case DW_TAG_subrange_type:
10572     case DW_TAG_typedef:
10573       /* Add a typedef symbol for the type definition, if it has a
10574          DW_AT_name.  */
10575       new_symbol (die, read_type_die (die, cu), cu);
10576       break;
10577     case DW_TAG_common_block:
10578       read_common_block (die, cu);
10579       break;
10580     case DW_TAG_common_inclusion:
10581       break;
10582     case DW_TAG_namespace:
10583       cu->processing_has_namespace_info = 1;
10584       read_namespace (die, cu);
10585       break;
10586     case DW_TAG_module:
10587       cu->processing_has_namespace_info = 1;
10588       read_module (die, cu);
10589       break;
10590     case DW_TAG_imported_declaration:
10591       cu->processing_has_namespace_info = 1;
10592       if (read_namespace_alias (die, cu))
10593         break;
10594       /* The declaration is not a global namespace alias.  */
10595       /* Fall through.  */
10596     case DW_TAG_imported_module:
10597       cu->processing_has_namespace_info = 1;
10598       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10599                                  || cu->language != language_fortran))
10600         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10601                    dwarf_tag_name (die->tag));
10602       read_import_statement (die, cu);
10603       break;
10604
10605     case DW_TAG_imported_unit:
10606       process_imported_unit_die (die, cu);
10607       break;
10608
10609     case DW_TAG_variable:
10610       read_variable (die, cu);
10611       break;
10612
10613     default:
10614       new_symbol (die, NULL, cu);
10615       break;
10616     }
10617 }
10618 \f
10619 /* DWARF name computation.  */
10620
10621 /* A helper function for dwarf2_compute_name which determines whether DIE
10622    needs to have the name of the scope prepended to the name listed in the
10623    die.  */
10624
10625 static int
10626 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10627 {
10628   struct attribute *attr;
10629
10630   switch (die->tag)
10631     {
10632     case DW_TAG_namespace:
10633     case DW_TAG_typedef:
10634     case DW_TAG_class_type:
10635     case DW_TAG_interface_type:
10636     case DW_TAG_structure_type:
10637     case DW_TAG_union_type:
10638     case DW_TAG_enumeration_type:
10639     case DW_TAG_enumerator:
10640     case DW_TAG_subprogram:
10641     case DW_TAG_inlined_subroutine:
10642     case DW_TAG_member:
10643     case DW_TAG_imported_declaration:
10644       return 1;
10645
10646     case DW_TAG_variable:
10647     case DW_TAG_constant:
10648       /* We only need to prefix "globally" visible variables.  These include
10649          any variable marked with DW_AT_external or any variable that
10650          lives in a namespace.  [Variables in anonymous namespaces
10651          require prefixing, but they are not DW_AT_external.]  */
10652
10653       if (dwarf2_attr (die, DW_AT_specification, cu))
10654         {
10655           struct dwarf2_cu *spec_cu = cu;
10656
10657           return die_needs_namespace (die_specification (die, &spec_cu),
10658                                       spec_cu);
10659         }
10660
10661       attr = dwarf2_attr (die, DW_AT_external, cu);
10662       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10663           && die->parent->tag != DW_TAG_module)
10664         return 0;
10665       /* A variable in a lexical block of some kind does not need a
10666          namespace, even though in C++ such variables may be external
10667          and have a mangled name.  */
10668       if (die->parent->tag ==  DW_TAG_lexical_block
10669           || die->parent->tag ==  DW_TAG_try_block
10670           || die->parent->tag ==  DW_TAG_catch_block
10671           || die->parent->tag == DW_TAG_subprogram)
10672         return 0;
10673       return 1;
10674
10675     default:
10676       return 0;
10677     }
10678 }
10679
10680 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10681    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10682    defined for the given DIE.  */
10683
10684 static struct attribute *
10685 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10686 {
10687   struct attribute *attr;
10688
10689   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10690   if (attr == NULL)
10691     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10692
10693   return attr;
10694 }
10695
10696 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10697    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10698    defined for the given DIE.  */
10699
10700 static const char *
10701 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10702 {
10703   const char *linkage_name;
10704
10705   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10706   if (linkage_name == NULL)
10707     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10708
10709   return linkage_name;
10710 }
10711
10712 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10713    compute the physname for the object, which include a method's:
10714    - formal parameters (C++),
10715    - receiver type (Go),
10716
10717    The term "physname" is a bit confusing.
10718    For C++, for example, it is the demangled name.
10719    For Go, for example, it's the mangled name.
10720
10721    For Ada, return the DIE's linkage name rather than the fully qualified
10722    name.  PHYSNAME is ignored..
10723
10724    The result is allocated on the objfile_obstack and canonicalized.  */
10725
10726 static const char *
10727 dwarf2_compute_name (const char *name,
10728                      struct die_info *die, struct dwarf2_cu *cu,
10729                      int physname)
10730 {
10731   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10732
10733   if (name == NULL)
10734     name = dwarf2_name (die, cu);
10735
10736   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10737      but otherwise compute it by typename_concat inside GDB.
10738      FIXME: Actually this is not really true, or at least not always true.
10739      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10740      Fortran names because there is no mangling standard.  So new_symbol
10741      will set the demangled name to the result of dwarf2_full_name, and it is
10742      the demangled name that GDB uses if it exists.  */
10743   if (cu->language == language_ada
10744       || (cu->language == language_fortran && physname))
10745     {
10746       /* For Ada unit, we prefer the linkage name over the name, as
10747          the former contains the exported name, which the user expects
10748          to be able to reference.  Ideally, we want the user to be able
10749          to reference this entity using either natural or linkage name,
10750          but we haven't started looking at this enhancement yet.  */
10751       const char *linkage_name = dw2_linkage_name (die, cu);
10752
10753       if (linkage_name != NULL)
10754         return linkage_name;
10755     }
10756
10757   /* These are the only languages we know how to qualify names in.  */
10758   if (name != NULL
10759       && (cu->language == language_cplus
10760           || cu->language == language_fortran || cu->language == language_d
10761           || cu->language == language_rust))
10762     {
10763       if (die_needs_namespace (die, cu))
10764         {
10765           const char *prefix;
10766           const char *canonical_name = NULL;
10767
10768           string_file buf;
10769
10770           prefix = determine_prefix (die, cu);
10771           if (*prefix != '\0')
10772             {
10773               char *prefixed_name = typename_concat (NULL, prefix, name,
10774                                                      physname, cu);
10775
10776               buf.puts (prefixed_name);
10777               xfree (prefixed_name);
10778             }
10779           else
10780             buf.puts (name);
10781
10782           /* Template parameters may be specified in the DIE's DW_AT_name, or
10783              as children with DW_TAG_template_type_param or
10784              DW_TAG_value_type_param.  If the latter, add them to the name
10785              here.  If the name already has template parameters, then
10786              skip this step; some versions of GCC emit both, and
10787              it is more efficient to use the pre-computed name.
10788
10789              Something to keep in mind about this process: it is very
10790              unlikely, or in some cases downright impossible, to produce
10791              something that will match the mangled name of a function.
10792              If the definition of the function has the same debug info,
10793              we should be able to match up with it anyway.  But fallbacks
10794              using the minimal symbol, for instance to find a method
10795              implemented in a stripped copy of libstdc++, will not work.
10796              If we do not have debug info for the definition, we will have to
10797              match them up some other way.
10798
10799              When we do name matching there is a related problem with function
10800              templates; two instantiated function templates are allowed to
10801              differ only by their return types, which we do not add here.  */
10802
10803           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10804             {
10805               struct attribute *attr;
10806               struct die_info *child;
10807               int first = 1;
10808
10809               die->building_fullname = 1;
10810
10811               for (child = die->child; child != NULL; child = child->sibling)
10812                 {
10813                   struct type *type;
10814                   LONGEST value;
10815                   const gdb_byte *bytes;
10816                   struct dwarf2_locexpr_baton *baton;
10817                   struct value *v;
10818
10819                   if (child->tag != DW_TAG_template_type_param
10820                       && child->tag != DW_TAG_template_value_param)
10821                     continue;
10822
10823                   if (first)
10824                     {
10825                       buf.puts ("<");
10826                       first = 0;
10827                     }
10828                   else
10829                     buf.puts (", ");
10830
10831                   attr = dwarf2_attr (child, DW_AT_type, cu);
10832                   if (attr == NULL)
10833                     {
10834                       complaint (&symfile_complaints,
10835                                  _("template parameter missing DW_AT_type"));
10836                       buf.puts ("UNKNOWN_TYPE");
10837                       continue;
10838                     }
10839                   type = die_type (child, cu);
10840
10841                   if (child->tag == DW_TAG_template_type_param)
10842                     {
10843                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10844                       continue;
10845                     }
10846
10847                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10848                   if (attr == NULL)
10849                     {
10850                       complaint (&symfile_complaints,
10851                                  _("template parameter missing "
10852                                    "DW_AT_const_value"));
10853                       buf.puts ("UNKNOWN_VALUE");
10854                       continue;
10855                     }
10856
10857                   dwarf2_const_value_attr (attr, type, name,
10858                                            &cu->comp_unit_obstack, cu,
10859                                            &value, &bytes, &baton);
10860
10861                   if (TYPE_NOSIGN (type))
10862                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10863                        changed, this can use value_print instead.  */
10864                     c_printchar (value, type, &buf);
10865                   else
10866                     {
10867                       struct value_print_options opts;
10868
10869                       if (baton != NULL)
10870                         v = dwarf2_evaluate_loc_desc (type, NULL,
10871                                                       baton->data,
10872                                                       baton->size,
10873                                                       baton->per_cu);
10874                       else if (bytes != NULL)
10875                         {
10876                           v = allocate_value (type);
10877                           memcpy (value_contents_writeable (v), bytes,
10878                                   TYPE_LENGTH (type));
10879                         }
10880                       else
10881                         v = value_from_longest (type, value);
10882
10883                       /* Specify decimal so that we do not depend on
10884                          the radix.  */
10885                       get_formatted_print_options (&opts, 'd');
10886                       opts.raw = 1;
10887                       value_print (v, &buf, &opts);
10888                       release_value (v);
10889                     }
10890                 }
10891
10892               die->building_fullname = 0;
10893
10894               if (!first)
10895                 {
10896                   /* Close the argument list, with a space if necessary
10897                      (nested templates).  */
10898                   if (!buf.empty () && buf.string ().back () == '>')
10899                     buf.puts (" >");
10900                   else
10901                     buf.puts (">");
10902                 }
10903             }
10904
10905           /* For C++ methods, append formal parameter type
10906              information, if PHYSNAME.  */
10907
10908           if (physname && die->tag == DW_TAG_subprogram
10909               && cu->language == language_cplus)
10910             {
10911               struct type *type = read_type_die (die, cu);
10912
10913               c_type_print_args (type, &buf, 1, cu->language,
10914                                  &type_print_raw_options);
10915
10916               if (cu->language == language_cplus)
10917                 {
10918                   /* Assume that an artificial first parameter is
10919                      "this", but do not crash if it is not.  RealView
10920                      marks unnamed (and thus unused) parameters as
10921                      artificial; there is no way to differentiate
10922                      the two cases.  */
10923                   if (TYPE_NFIELDS (type) > 0
10924                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10925                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10926                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10927                                                                         0))))
10928                     buf.puts (" const");
10929                 }
10930             }
10931
10932           const std::string &intermediate_name = buf.string ();
10933
10934           if (cu->language == language_cplus)
10935             canonical_name
10936               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10937                                           &objfile->per_bfd->storage_obstack);
10938
10939           /* If we only computed INTERMEDIATE_NAME, or if
10940              INTERMEDIATE_NAME is already canonical, then we need to
10941              copy it to the appropriate obstack.  */
10942           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10943             name = ((const char *)
10944                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10945                                    intermediate_name.c_str (),
10946                                    intermediate_name.length ()));
10947           else
10948             name = canonical_name;
10949         }
10950     }
10951
10952   return name;
10953 }
10954
10955 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10956    If scope qualifiers are appropriate they will be added.  The result
10957    will be allocated on the storage_obstack, or NULL if the DIE does
10958    not have a name.  NAME may either be from a previous call to
10959    dwarf2_name or NULL.
10960
10961    The output string will be canonicalized (if C++).  */
10962
10963 static const char *
10964 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10965 {
10966   return dwarf2_compute_name (name, die, cu, 0);
10967 }
10968
10969 /* Construct a physname for the given DIE in CU.  NAME may either be
10970    from a previous call to dwarf2_name or NULL.  The result will be
10971    allocated on the objfile_objstack or NULL if the DIE does not have a
10972    name.
10973
10974    The output string will be canonicalized (if C++).  */
10975
10976 static const char *
10977 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10978 {
10979   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10980   const char *retval, *mangled = NULL, *canon = NULL;
10981   int need_copy = 1;
10982
10983   /* In this case dwarf2_compute_name is just a shortcut not building anything
10984      on its own.  */
10985   if (!die_needs_namespace (die, cu))
10986     return dwarf2_compute_name (name, die, cu, 1);
10987
10988   mangled = dw2_linkage_name (die, cu);
10989
10990   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10991      See https://github.com/rust-lang/rust/issues/32925.  */
10992   if (cu->language == language_rust && mangled != NULL
10993       && strchr (mangled, '{') != NULL)
10994     mangled = NULL;
10995
10996   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10997      has computed.  */
10998   gdb::unique_xmalloc_ptr<char> demangled;
10999   if (mangled != NULL)
11000     {
11001
11002       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11003         {
11004           /* Do nothing (do not demangle the symbol name).  */
11005         }
11006       else if (cu->language == language_go)
11007         {
11008           /* This is a lie, but we already lie to the caller new_symbol.
11009              new_symbol assumes we return the mangled name.
11010              This just undoes that lie until things are cleaned up.  */
11011         }
11012       else
11013         {
11014           /* Use DMGL_RET_DROP for C++ template functions to suppress
11015              their return type.  It is easier for GDB users to search
11016              for such functions as `name(params)' than `long name(params)'.
11017              In such case the minimal symbol names do not match the full
11018              symbol names but for template functions there is never a need
11019              to look up their definition from their declaration so
11020              the only disadvantage remains the minimal symbol variant
11021              `long name(params)' does not have the proper inferior type.  */
11022           demangled.reset (gdb_demangle (mangled,
11023                                          (DMGL_PARAMS | DMGL_ANSI
11024                                           | DMGL_RET_DROP)));
11025         }
11026       if (demangled)
11027         canon = demangled.get ();
11028       else
11029         {
11030           canon = mangled;
11031           need_copy = 0;
11032         }
11033     }
11034
11035   if (canon == NULL || check_physname)
11036     {
11037       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11038
11039       if (canon != NULL && strcmp (physname, canon) != 0)
11040         {
11041           /* It may not mean a bug in GDB.  The compiler could also
11042              compute DW_AT_linkage_name incorrectly.  But in such case
11043              GDB would need to be bug-to-bug compatible.  */
11044
11045           complaint (&symfile_complaints,
11046                      _("Computed physname <%s> does not match demangled <%s> "
11047                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11048                      physname, canon, mangled, sect_offset_str (die->sect_off),
11049                      objfile_name (objfile));
11050
11051           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11052              is available here - over computed PHYSNAME.  It is safer
11053              against both buggy GDB and buggy compilers.  */
11054
11055           retval = canon;
11056         }
11057       else
11058         {
11059           retval = physname;
11060           need_copy = 0;
11061         }
11062     }
11063   else
11064     retval = canon;
11065
11066   if (need_copy)
11067     retval = ((const char *)
11068               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11069                              retval, strlen (retval)));
11070
11071   return retval;
11072 }
11073
11074 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11075    a new symbol for it.
11076
11077    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11078
11079 static int
11080 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11081 {
11082   struct attribute *attr;
11083
11084   /* If the die does not have a name, this is not a namespace
11085      alias.  */
11086   attr = dwarf2_attr (die, DW_AT_name, cu);
11087   if (attr != NULL)
11088     {
11089       int num;
11090       struct die_info *d = die;
11091       struct dwarf2_cu *imported_cu = cu;
11092
11093       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11094          keep inspecting DIEs until we hit the underlying import.  */
11095 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11096       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11097         {
11098           attr = dwarf2_attr (d, DW_AT_import, cu);
11099           if (attr == NULL)
11100             break;
11101
11102           d = follow_die_ref (d, attr, &imported_cu);
11103           if (d->tag != DW_TAG_imported_declaration)
11104             break;
11105         }
11106
11107       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11108         {
11109           complaint (&symfile_complaints,
11110                      _("DIE at %s has too many recursively imported "
11111                        "declarations"), sect_offset_str (d->sect_off));
11112           return 0;
11113         }
11114
11115       if (attr != NULL)
11116         {
11117           struct type *type;
11118           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11119
11120           type = get_die_type_at_offset (sect_off, cu->per_cu);
11121           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11122             {
11123               /* This declaration is a global namespace alias.  Add
11124                  a symbol for it whose type is the aliased namespace.  */
11125               new_symbol (die, type, cu);
11126               return 1;
11127             }
11128         }
11129     }
11130
11131   return 0;
11132 }
11133
11134 /* Return the using directives repository (global or local?) to use in the
11135    current context for LANGUAGE.
11136
11137    For Ada, imported declarations can materialize renamings, which *may* be
11138    global.  However it is impossible (for now?) in DWARF to distinguish
11139    "external" imported declarations and "static" ones.  As all imported
11140    declarations seem to be static in all other languages, make them all CU-wide
11141    global only in Ada.  */
11142
11143 static struct using_direct **
11144 using_directives (enum language language)
11145 {
11146   if (language == language_ada && context_stack_depth == 0)
11147     return &global_using_directives;
11148   else
11149     return &local_using_directives;
11150 }
11151
11152 /* Read the import statement specified by the given die and record it.  */
11153
11154 static void
11155 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11156 {
11157   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11158   struct attribute *import_attr;
11159   struct die_info *imported_die, *child_die;
11160   struct dwarf2_cu *imported_cu;
11161   const char *imported_name;
11162   const char *imported_name_prefix;
11163   const char *canonical_name;
11164   const char *import_alias;
11165   const char *imported_declaration = NULL;
11166   const char *import_prefix;
11167   std::vector<const char *> excludes;
11168
11169   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11170   if (import_attr == NULL)
11171     {
11172       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11173                  dwarf_tag_name (die->tag));
11174       return;
11175     }
11176
11177   imported_cu = cu;
11178   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11179   imported_name = dwarf2_name (imported_die, imported_cu);
11180   if (imported_name == NULL)
11181     {
11182       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11183
11184         The import in the following code:
11185         namespace A
11186           {
11187             typedef int B;
11188           }
11189
11190         int main ()
11191           {
11192             using A::B;
11193             B b;
11194             return b;
11195           }
11196
11197         ...
11198          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11199             <52>   DW_AT_decl_file   : 1
11200             <53>   DW_AT_decl_line   : 6
11201             <54>   DW_AT_import      : <0x75>
11202          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11203             <59>   DW_AT_name        : B
11204             <5b>   DW_AT_decl_file   : 1
11205             <5c>   DW_AT_decl_line   : 2
11206             <5d>   DW_AT_type        : <0x6e>
11207         ...
11208          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11209             <76>   DW_AT_byte_size   : 4
11210             <77>   DW_AT_encoding    : 5        (signed)
11211
11212         imports the wrong die ( 0x75 instead of 0x58 ).
11213         This case will be ignored until the gcc bug is fixed.  */
11214       return;
11215     }
11216
11217   /* Figure out the local name after import.  */
11218   import_alias = dwarf2_name (die, cu);
11219
11220   /* Figure out where the statement is being imported to.  */
11221   import_prefix = determine_prefix (die, cu);
11222
11223   /* Figure out what the scope of the imported die is and prepend it
11224      to the name of the imported die.  */
11225   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11226
11227   if (imported_die->tag != DW_TAG_namespace
11228       && imported_die->tag != DW_TAG_module)
11229     {
11230       imported_declaration = imported_name;
11231       canonical_name = imported_name_prefix;
11232     }
11233   else if (strlen (imported_name_prefix) > 0)
11234     canonical_name = obconcat (&objfile->objfile_obstack,
11235                                imported_name_prefix,
11236                                (cu->language == language_d ? "." : "::"),
11237                                imported_name, (char *) NULL);
11238   else
11239     canonical_name = imported_name;
11240
11241   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11242     for (child_die = die->child; child_die && child_die->tag;
11243          child_die = sibling_die (child_die))
11244       {
11245         /* DWARF-4: A Fortran use statement with a “rename list” may be
11246            represented by an imported module entry with an import attribute
11247            referring to the module and owned entries corresponding to those
11248            entities that are renamed as part of being imported.  */
11249
11250         if (child_die->tag != DW_TAG_imported_declaration)
11251           {
11252             complaint (&symfile_complaints,
11253                        _("child DW_TAG_imported_declaration expected "
11254                          "- DIE at %s [in module %s]"),
11255                        sect_offset_str (child_die->sect_off),
11256                        objfile_name (objfile));
11257             continue;
11258           }
11259
11260         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11261         if (import_attr == NULL)
11262           {
11263             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11264                        dwarf_tag_name (child_die->tag));
11265             continue;
11266           }
11267
11268         imported_cu = cu;
11269         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11270                                               &imported_cu);
11271         imported_name = dwarf2_name (imported_die, imported_cu);
11272         if (imported_name == NULL)
11273           {
11274             complaint (&symfile_complaints,
11275                        _("child DW_TAG_imported_declaration has unknown "
11276                          "imported name - DIE at %s [in module %s]"),
11277                        sect_offset_str (child_die->sect_off),
11278                        objfile_name (objfile));
11279             continue;
11280           }
11281
11282         excludes.push_back (imported_name);
11283
11284         process_die (child_die, cu);
11285       }
11286
11287   add_using_directive (using_directives (cu->language),
11288                        import_prefix,
11289                        canonical_name,
11290                        import_alias,
11291                        imported_declaration,
11292                        excludes,
11293                        0,
11294                        &objfile->objfile_obstack);
11295 }
11296
11297 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11298    types, but gives them a size of zero.  Starting with version 14,
11299    ICC is compatible with GCC.  */
11300
11301 static int
11302 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11303 {
11304   if (!cu->checked_producer)
11305     check_producer (cu);
11306
11307   return cu->producer_is_icc_lt_14;
11308 }
11309
11310 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11311    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11312    this, it was first present in GCC release 4.3.0.  */
11313
11314 static int
11315 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11316 {
11317   if (!cu->checked_producer)
11318     check_producer (cu);
11319
11320   return cu->producer_is_gcc_lt_4_3;
11321 }
11322
11323 static file_and_directory
11324 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11325 {
11326   file_and_directory res;
11327
11328   /* Find the filename.  Do not use dwarf2_name here, since the filename
11329      is not a source language identifier.  */
11330   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11331   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11332
11333   if (res.comp_dir == NULL
11334       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11335       && IS_ABSOLUTE_PATH (res.name))
11336     {
11337       res.comp_dir_storage = ldirname (res.name);
11338       if (!res.comp_dir_storage.empty ())
11339         res.comp_dir = res.comp_dir_storage.c_str ();
11340     }
11341   if (res.comp_dir != NULL)
11342     {
11343       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11344          directory, get rid of it.  */
11345       const char *cp = strchr (res.comp_dir, ':');
11346
11347       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11348         res.comp_dir = cp + 1;
11349     }
11350
11351   if (res.name == NULL)
11352     res.name = "<unknown>";
11353
11354   return res;
11355 }
11356
11357 /* Handle DW_AT_stmt_list for a compilation unit.
11358    DIE is the DW_TAG_compile_unit die for CU.
11359    COMP_DIR is the compilation directory.  LOWPC is passed to
11360    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11361
11362 static void
11363 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11364                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11365 {
11366   struct dwarf2_per_objfile *dwarf2_per_objfile
11367     = cu->per_cu->dwarf2_per_objfile;
11368   struct objfile *objfile = dwarf2_per_objfile->objfile;
11369   struct attribute *attr;
11370   struct line_header line_header_local;
11371   hashval_t line_header_local_hash;
11372   void **slot;
11373   int decode_mapping;
11374
11375   gdb_assert (! cu->per_cu->is_debug_types);
11376
11377   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11378   if (attr == NULL)
11379     return;
11380
11381   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11382
11383   /* The line header hash table is only created if needed (it exists to
11384      prevent redundant reading of the line table for partial_units).
11385      If we're given a partial_unit, we'll need it.  If we're given a
11386      compile_unit, then use the line header hash table if it's already
11387      created, but don't create one just yet.  */
11388
11389   if (dwarf2_per_objfile->line_header_hash == NULL
11390       && die->tag == DW_TAG_partial_unit)
11391     {
11392       dwarf2_per_objfile->line_header_hash
11393         = htab_create_alloc_ex (127, line_header_hash_voidp,
11394                                 line_header_eq_voidp,
11395                                 free_line_header_voidp,
11396                                 &objfile->objfile_obstack,
11397                                 hashtab_obstack_allocate,
11398                                 dummy_obstack_deallocate);
11399     }
11400
11401   line_header_local.sect_off = line_offset;
11402   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11403   line_header_local_hash = line_header_hash (&line_header_local);
11404   if (dwarf2_per_objfile->line_header_hash != NULL)
11405     {
11406       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11407                                        &line_header_local,
11408                                        line_header_local_hash, NO_INSERT);
11409
11410       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11411          is not present in *SLOT (since if there is something in *SLOT then
11412          it will be for a partial_unit).  */
11413       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11414         {
11415           gdb_assert (*slot != NULL);
11416           cu->line_header = (struct line_header *) *slot;
11417           return;
11418         }
11419     }
11420
11421   /* dwarf_decode_line_header does not yet provide sufficient information.
11422      We always have to call also dwarf_decode_lines for it.  */
11423   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11424   if (lh == NULL)
11425     return;
11426
11427   cu->line_header = lh.release ();
11428   cu->line_header_die_owner = die;
11429
11430   if (dwarf2_per_objfile->line_header_hash == NULL)
11431     slot = NULL;
11432   else
11433     {
11434       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11435                                        &line_header_local,
11436                                        line_header_local_hash, INSERT);
11437       gdb_assert (slot != NULL);
11438     }
11439   if (slot != NULL && *slot == NULL)
11440     {
11441       /* This newly decoded line number information unit will be owned
11442          by line_header_hash hash table.  */
11443       *slot = cu->line_header;
11444       cu->line_header_die_owner = NULL;
11445     }
11446   else
11447     {
11448       /* We cannot free any current entry in (*slot) as that struct line_header
11449          may be already used by multiple CUs.  Create only temporary decoded
11450          line_header for this CU - it may happen at most once for each line
11451          number information unit.  And if we're not using line_header_hash
11452          then this is what we want as well.  */
11453       gdb_assert (die->tag != DW_TAG_partial_unit);
11454     }
11455   decode_mapping = (die->tag != DW_TAG_partial_unit);
11456   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11457                       decode_mapping);
11458
11459 }
11460
11461 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11462
11463 static void
11464 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11465 {
11466   struct dwarf2_per_objfile *dwarf2_per_objfile
11467     = cu->per_cu->dwarf2_per_objfile;
11468   struct objfile *objfile = dwarf2_per_objfile->objfile;
11469   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11470   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11471   CORE_ADDR highpc = ((CORE_ADDR) 0);
11472   struct attribute *attr;
11473   struct die_info *child_die;
11474   CORE_ADDR baseaddr;
11475
11476   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11477
11478   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11479
11480   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11481      from finish_block.  */
11482   if (lowpc == ((CORE_ADDR) -1))
11483     lowpc = highpc;
11484   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11485
11486   file_and_directory fnd = find_file_and_directory (die, cu);
11487
11488   prepare_one_comp_unit (cu, die, cu->language);
11489
11490   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11491      standardised yet.  As a workaround for the language detection we fall
11492      back to the DW_AT_producer string.  */
11493   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11494     cu->language = language_opencl;
11495
11496   /* Similar hack for Go.  */
11497   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11498     set_cu_language (DW_LANG_Go, cu);
11499
11500   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11501
11502   /* Decode line number information if present.  We do this before
11503      processing child DIEs, so that the line header table is available
11504      for DW_AT_decl_file.  */
11505   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11506
11507   /* Process all dies in compilation unit.  */
11508   if (die->child != NULL)
11509     {
11510       child_die = die->child;
11511       while (child_die && child_die->tag)
11512         {
11513           process_die (child_die, cu);
11514           child_die = sibling_die (child_die);
11515         }
11516     }
11517
11518   /* Decode macro information, if present.  Dwarf 2 macro information
11519      refers to information in the line number info statement program
11520      header, so we can only read it if we've read the header
11521      successfully.  */
11522   attr = dwarf2_attr (die, DW_AT_macros, cu);
11523   if (attr == NULL)
11524     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11525   if (attr && cu->line_header)
11526     {
11527       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11528         complaint (&symfile_complaints,
11529                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11530
11531       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11532     }
11533   else
11534     {
11535       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11536       if (attr && cu->line_header)
11537         {
11538           unsigned int macro_offset = DW_UNSND (attr);
11539
11540           dwarf_decode_macros (cu, macro_offset, 0);
11541         }
11542     }
11543 }
11544
11545 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11546    Create the set of symtabs used by this TU, or if this TU is sharing
11547    symtabs with another TU and the symtabs have already been created
11548    then restore those symtabs in the line header.
11549    We don't need the pc/line-number mapping for type units.  */
11550
11551 static void
11552 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11553 {
11554   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11555   struct type_unit_group *tu_group;
11556   int first_time;
11557   struct attribute *attr;
11558   unsigned int i;
11559   struct signatured_type *sig_type;
11560
11561   gdb_assert (per_cu->is_debug_types);
11562   sig_type = (struct signatured_type *) per_cu;
11563
11564   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11565
11566   /* If we're using .gdb_index (includes -readnow) then
11567      per_cu->type_unit_group may not have been set up yet.  */
11568   if (sig_type->type_unit_group == NULL)
11569     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11570   tu_group = sig_type->type_unit_group;
11571
11572   /* If we've already processed this stmt_list there's no real need to
11573      do it again, we could fake it and just recreate the part we need
11574      (file name,index -> symtab mapping).  If data shows this optimization
11575      is useful we can do it then.  */
11576   first_time = tu_group->compunit_symtab == NULL;
11577
11578   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11579      debug info.  */
11580   line_header_up lh;
11581   if (attr != NULL)
11582     {
11583       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11584       lh = dwarf_decode_line_header (line_offset, cu);
11585     }
11586   if (lh == NULL)
11587     {
11588       if (first_time)
11589         dwarf2_start_symtab (cu, "", NULL, 0);
11590       else
11591         {
11592           gdb_assert (tu_group->symtabs == NULL);
11593           restart_symtab (tu_group->compunit_symtab, "", 0);
11594         }
11595       return;
11596     }
11597
11598   cu->line_header = lh.release ();
11599   cu->line_header_die_owner = die;
11600
11601   if (first_time)
11602     {
11603       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11604
11605       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11606          still initializing it, and our caller (a few levels up)
11607          process_full_type_unit still needs to know if this is the first
11608          time.  */
11609
11610       tu_group->num_symtabs = cu->line_header->file_names.size ();
11611       tu_group->symtabs = XNEWVEC (struct symtab *,
11612                                    cu->line_header->file_names.size ());
11613
11614       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11615         {
11616           file_entry &fe = cu->line_header->file_names[i];
11617
11618           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11619
11620           if (current_subfile->symtab == NULL)
11621             {
11622               /* NOTE: start_subfile will recognize when it's been
11623                  passed a file it has already seen.  So we can't
11624                  assume there's a simple mapping from
11625                  cu->line_header->file_names to subfiles, plus
11626                  cu->line_header->file_names may contain dups.  */
11627               current_subfile->symtab
11628                 = allocate_symtab (cust, current_subfile->name);
11629             }
11630
11631           fe.symtab = current_subfile->symtab;
11632           tu_group->symtabs[i] = fe.symtab;
11633         }
11634     }
11635   else
11636     {
11637       restart_symtab (tu_group->compunit_symtab, "", 0);
11638
11639       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11640         {
11641           file_entry &fe = cu->line_header->file_names[i];
11642
11643           fe.symtab = tu_group->symtabs[i];
11644         }
11645     }
11646
11647   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11648      so they don't have a "real" (so to speak) symtab anyway.
11649      There is later code that will assign the main symtab to all symbols
11650      that don't have one.  We need to handle the case of a symbol with a
11651      missing symtab (DW_AT_decl_file) anyway.  */
11652 }
11653
11654 /* Process DW_TAG_type_unit.
11655    For TUs we want to skip the first top level sibling if it's not the
11656    actual type being defined by this TU.  In this case the first top
11657    level sibling is there to provide context only.  */
11658
11659 static void
11660 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11661 {
11662   struct die_info *child_die;
11663
11664   prepare_one_comp_unit (cu, die, language_minimal);
11665
11666   /* Initialize (or reinitialize) the machinery for building symtabs.
11667      We do this before processing child DIEs, so that the line header table
11668      is available for DW_AT_decl_file.  */
11669   setup_type_unit_groups (die, cu);
11670
11671   if (die->child != NULL)
11672     {
11673       child_die = die->child;
11674       while (child_die && child_die->tag)
11675         {
11676           process_die (child_die, cu);
11677           child_die = sibling_die (child_die);
11678         }
11679     }
11680 }
11681 \f
11682 /* DWO/DWP files.
11683
11684    http://gcc.gnu.org/wiki/DebugFission
11685    http://gcc.gnu.org/wiki/DebugFissionDWP
11686
11687    To simplify handling of both DWO files ("object" files with the DWARF info)
11688    and DWP files (a file with the DWOs packaged up into one file), we treat
11689    DWP files as having a collection of virtual DWO files.  */
11690
11691 static hashval_t
11692 hash_dwo_file (const void *item)
11693 {
11694   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11695   hashval_t hash;
11696
11697   hash = htab_hash_string (dwo_file->dwo_name);
11698   if (dwo_file->comp_dir != NULL)
11699     hash += htab_hash_string (dwo_file->comp_dir);
11700   return hash;
11701 }
11702
11703 static int
11704 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11705 {
11706   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11707   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11708
11709   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11710     return 0;
11711   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11712     return lhs->comp_dir == rhs->comp_dir;
11713   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11714 }
11715
11716 /* Allocate a hash table for DWO files.  */
11717
11718 static htab_t
11719 allocate_dwo_file_hash_table (struct objfile *objfile)
11720 {
11721   return htab_create_alloc_ex (41,
11722                                hash_dwo_file,
11723                                eq_dwo_file,
11724                                NULL,
11725                                &objfile->objfile_obstack,
11726                                hashtab_obstack_allocate,
11727                                dummy_obstack_deallocate);
11728 }
11729
11730 /* Lookup DWO file DWO_NAME.  */
11731
11732 static void **
11733 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11734                       const char *dwo_name,
11735                       const char *comp_dir)
11736 {
11737   struct dwo_file find_entry;
11738   void **slot;
11739
11740   if (dwarf2_per_objfile->dwo_files == NULL)
11741     dwarf2_per_objfile->dwo_files
11742       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11743
11744   memset (&find_entry, 0, sizeof (find_entry));
11745   find_entry.dwo_name = dwo_name;
11746   find_entry.comp_dir = comp_dir;
11747   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11748
11749   return slot;
11750 }
11751
11752 static hashval_t
11753 hash_dwo_unit (const void *item)
11754 {
11755   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11756
11757   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11758   return dwo_unit->signature;
11759 }
11760
11761 static int
11762 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11763 {
11764   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11765   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11766
11767   /* The signature is assumed to be unique within the DWO file.
11768      So while object file CU dwo_id's always have the value zero,
11769      that's OK, assuming each object file DWO file has only one CU,
11770      and that's the rule for now.  */
11771   return lhs->signature == rhs->signature;
11772 }
11773
11774 /* Allocate a hash table for DWO CUs,TUs.
11775    There is one of these tables for each of CUs,TUs for each DWO file.  */
11776
11777 static htab_t
11778 allocate_dwo_unit_table (struct objfile *objfile)
11779 {
11780   /* Start out with a pretty small number.
11781      Generally DWO files contain only one CU and maybe some TUs.  */
11782   return htab_create_alloc_ex (3,
11783                                hash_dwo_unit,
11784                                eq_dwo_unit,
11785                                NULL,
11786                                &objfile->objfile_obstack,
11787                                hashtab_obstack_allocate,
11788                                dummy_obstack_deallocate);
11789 }
11790
11791 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11792
11793 struct create_dwo_cu_data
11794 {
11795   struct dwo_file *dwo_file;
11796   struct dwo_unit dwo_unit;
11797 };
11798
11799 /* die_reader_func for create_dwo_cu.  */
11800
11801 static void
11802 create_dwo_cu_reader (const struct die_reader_specs *reader,
11803                       const gdb_byte *info_ptr,
11804                       struct die_info *comp_unit_die,
11805                       int has_children,
11806                       void *datap)
11807 {
11808   struct dwarf2_cu *cu = reader->cu;
11809   sect_offset sect_off = cu->per_cu->sect_off;
11810   struct dwarf2_section_info *section = cu->per_cu->section;
11811   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11812   struct dwo_file *dwo_file = data->dwo_file;
11813   struct dwo_unit *dwo_unit = &data->dwo_unit;
11814   struct attribute *attr;
11815
11816   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11817   if (attr == NULL)
11818     {
11819       complaint (&symfile_complaints,
11820                  _("Dwarf Error: debug entry at offset %s is missing"
11821                    " its dwo_id [in module %s]"),
11822                  sect_offset_str (sect_off), dwo_file->dwo_name);
11823       return;
11824     }
11825
11826   dwo_unit->dwo_file = dwo_file;
11827   dwo_unit->signature = DW_UNSND (attr);
11828   dwo_unit->section = section;
11829   dwo_unit->sect_off = sect_off;
11830   dwo_unit->length = cu->per_cu->length;
11831
11832   if (dwarf_read_debug)
11833     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11834                         sect_offset_str (sect_off),
11835                         hex_string (dwo_unit->signature));
11836 }
11837
11838 /* Create the dwo_units for the CUs in a DWO_FILE.
11839    Note: This function processes DWO files only, not DWP files.  */
11840
11841 static void
11842 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11843                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11844                        htab_t &cus_htab)
11845 {
11846   struct objfile *objfile = dwarf2_per_objfile->objfile;
11847   const gdb_byte *info_ptr, *end_ptr;
11848
11849   dwarf2_read_section (objfile, &section);
11850   info_ptr = section.buffer;
11851
11852   if (info_ptr == NULL)
11853     return;
11854
11855   if (dwarf_read_debug)
11856     {
11857       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11858                           get_section_name (&section),
11859                           get_section_file_name (&section));
11860     }
11861
11862   end_ptr = info_ptr + section.size;
11863   while (info_ptr < end_ptr)
11864     {
11865       struct dwarf2_per_cu_data per_cu;
11866       struct create_dwo_cu_data create_dwo_cu_data;
11867       struct dwo_unit *dwo_unit;
11868       void **slot;
11869       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11870
11871       memset (&create_dwo_cu_data.dwo_unit, 0,
11872               sizeof (create_dwo_cu_data.dwo_unit));
11873       memset (&per_cu, 0, sizeof (per_cu));
11874       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11875       per_cu.is_debug_types = 0;
11876       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11877       per_cu.section = &section;
11878       create_dwo_cu_data.dwo_file = &dwo_file;
11879
11880       init_cutu_and_read_dies_no_follow (
11881           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11882       info_ptr += per_cu.length;
11883
11884       // If the unit could not be parsed, skip it.
11885       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11886         continue;
11887
11888       if (cus_htab == NULL)
11889         cus_htab = allocate_dwo_unit_table (objfile);
11890
11891       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11892       *dwo_unit = create_dwo_cu_data.dwo_unit;
11893       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11894       gdb_assert (slot != NULL);
11895       if (*slot != NULL)
11896         {
11897           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11898           sect_offset dup_sect_off = dup_cu->sect_off;
11899
11900           complaint (&symfile_complaints,
11901                      _("debug cu entry at offset %s is duplicate to"
11902                        " the entry at offset %s, signature %s"),
11903                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11904                      hex_string (dwo_unit->signature));
11905         }
11906       *slot = (void *)dwo_unit;
11907     }
11908 }
11909
11910 /* DWP file .debug_{cu,tu}_index section format:
11911    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11912
11913    DWP Version 1:
11914
11915    Both index sections have the same format, and serve to map a 64-bit
11916    signature to a set of section numbers.  Each section begins with a header,
11917    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11918    indexes, and a pool of 32-bit section numbers.  The index sections will be
11919    aligned at 8-byte boundaries in the file.
11920
11921    The index section header consists of:
11922
11923     V, 32 bit version number
11924     -, 32 bits unused
11925     N, 32 bit number of compilation units or type units in the index
11926     M, 32 bit number of slots in the hash table
11927
11928    Numbers are recorded using the byte order of the application binary.
11929
11930    The hash table begins at offset 16 in the section, and consists of an array
11931    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11932    order of the application binary).  Unused slots in the hash table are 0.
11933    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11934
11935    The parallel table begins immediately after the hash table
11936    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11937    array of 32-bit indexes (using the byte order of the application binary),
11938    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11939    table contains a 32-bit index into the pool of section numbers.  For unused
11940    hash table slots, the corresponding entry in the parallel table will be 0.
11941
11942    The pool of section numbers begins immediately following the hash table
11943    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11944    section numbers consists of an array of 32-bit words (using the byte order
11945    of the application binary).  Each item in the array is indexed starting
11946    from 0.  The hash table entry provides the index of the first section
11947    number in the set.  Additional section numbers in the set follow, and the
11948    set is terminated by a 0 entry (section number 0 is not used in ELF).
11949
11950    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11951    section must be the first entry in the set, and the .debug_abbrev.dwo must
11952    be the second entry. Other members of the set may follow in any order.
11953
11954    ---
11955
11956    DWP Version 2:
11957
11958    DWP Version 2 combines all the .debug_info, etc. sections into one,
11959    and the entries in the index tables are now offsets into these sections.
11960    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11961    section.
11962
11963    Index Section Contents:
11964     Header
11965     Hash Table of Signatures   dwp_hash_table.hash_table
11966     Parallel Table of Indices  dwp_hash_table.unit_table
11967     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11968     Table of Section Sizes     dwp_hash_table.v2.sizes
11969
11970    The index section header consists of:
11971
11972     V, 32 bit version number
11973     L, 32 bit number of columns in the table of section offsets
11974     N, 32 bit number of compilation units or type units in the index
11975     M, 32 bit number of slots in the hash table
11976
11977    Numbers are recorded using the byte order of the application binary.
11978
11979    The hash table has the same format as version 1.
11980    The parallel table of indices has the same format as version 1,
11981    except that the entries are origin-1 indices into the table of sections
11982    offsets and the table of section sizes.
11983
11984    The table of offsets begins immediately following the parallel table
11985    (at offset 16 + 12 * M from the beginning of the section).  The table is
11986    a two-dimensional array of 32-bit words (using the byte order of the
11987    application binary), with L columns and N+1 rows, in row-major order.
11988    Each row in the array is indexed starting from 0.  The first row provides
11989    a key to the remaining rows: each column in this row provides an identifier
11990    for a debug section, and the offsets in the same column of subsequent rows
11991    refer to that section.  The section identifiers are:
11992
11993     DW_SECT_INFO         1  .debug_info.dwo
11994     DW_SECT_TYPES        2  .debug_types.dwo
11995     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11996     DW_SECT_LINE         4  .debug_line.dwo
11997     DW_SECT_LOC          5  .debug_loc.dwo
11998     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11999     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12000     DW_SECT_MACRO        8  .debug_macro.dwo
12001
12002    The offsets provided by the CU and TU index sections are the base offsets
12003    for the contributions made by each CU or TU to the corresponding section
12004    in the package file.  Each CU and TU header contains an abbrev_offset
12005    field, used to find the abbreviations table for that CU or TU within the
12006    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12007    be interpreted as relative to the base offset given in the index section.
12008    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12009    should be interpreted as relative to the base offset for .debug_line.dwo,
12010    and offsets into other debug sections obtained from DWARF attributes should
12011    also be interpreted as relative to the corresponding base offset.
12012
12013    The table of sizes begins immediately following the table of offsets.
12014    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12015    with L columns and N rows, in row-major order.  Each row in the array is
12016    indexed starting from 1 (row 0 is shared by the two tables).
12017
12018    ---
12019
12020    Hash table lookup is handled the same in version 1 and 2:
12021
12022    We assume that N and M will not exceed 2^32 - 1.
12023    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12024
12025    Given a 64-bit compilation unit signature or a type signature S, an entry
12026    in the hash table is located as follows:
12027
12028    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12029       the low-order k bits all set to 1.
12030
12031    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12032
12033    3) If the hash table entry at index H matches the signature, use that
12034       entry.  If the hash table entry at index H is unused (all zeroes),
12035       terminate the search: the signature is not present in the table.
12036
12037    4) Let H = (H + H') modulo M. Repeat at Step 3.
12038
12039    Because M > N and H' and M are relatively prime, the search is guaranteed
12040    to stop at an unused slot or find the match.  */
12041
12042 /* Create a hash table to map DWO IDs to their CU/TU entry in
12043    .debug_{info,types}.dwo in DWP_FILE.
12044    Returns NULL if there isn't one.
12045    Note: This function processes DWP files only, not DWO files.  */
12046
12047 static struct dwp_hash_table *
12048 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12049                        struct dwp_file *dwp_file, int is_debug_types)
12050 {
12051   struct objfile *objfile = dwarf2_per_objfile->objfile;
12052   bfd *dbfd = dwp_file->dbfd;
12053   const gdb_byte *index_ptr, *index_end;
12054   struct dwarf2_section_info *index;
12055   uint32_t version, nr_columns, nr_units, nr_slots;
12056   struct dwp_hash_table *htab;
12057
12058   if (is_debug_types)
12059     index = &dwp_file->sections.tu_index;
12060   else
12061     index = &dwp_file->sections.cu_index;
12062
12063   if (dwarf2_section_empty_p (index))
12064     return NULL;
12065   dwarf2_read_section (objfile, index);
12066
12067   index_ptr = index->buffer;
12068   index_end = index_ptr + index->size;
12069
12070   version = read_4_bytes (dbfd, index_ptr);
12071   index_ptr += 4;
12072   if (version == 2)
12073     nr_columns = read_4_bytes (dbfd, index_ptr);
12074   else
12075     nr_columns = 0;
12076   index_ptr += 4;
12077   nr_units = read_4_bytes (dbfd, index_ptr);
12078   index_ptr += 4;
12079   nr_slots = read_4_bytes (dbfd, index_ptr);
12080   index_ptr += 4;
12081
12082   if (version != 1 && version != 2)
12083     {
12084       error (_("Dwarf Error: unsupported DWP file version (%s)"
12085                " [in module %s]"),
12086              pulongest (version), dwp_file->name);
12087     }
12088   if (nr_slots != (nr_slots & -nr_slots))
12089     {
12090       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12091                " is not power of 2 [in module %s]"),
12092              pulongest (nr_slots), dwp_file->name);
12093     }
12094
12095   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12096   htab->version = version;
12097   htab->nr_columns = nr_columns;
12098   htab->nr_units = nr_units;
12099   htab->nr_slots = nr_slots;
12100   htab->hash_table = index_ptr;
12101   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12102
12103   /* Exit early if the table is empty.  */
12104   if (nr_slots == 0 || nr_units == 0
12105       || (version == 2 && nr_columns == 0))
12106     {
12107       /* All must be zero.  */
12108       if (nr_slots != 0 || nr_units != 0
12109           || (version == 2 && nr_columns != 0))
12110         {
12111           complaint (&symfile_complaints,
12112                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12113                        " all zero [in modules %s]"),
12114                      dwp_file->name);
12115         }
12116       return htab;
12117     }
12118
12119   if (version == 1)
12120     {
12121       htab->section_pool.v1.indices =
12122         htab->unit_table + sizeof (uint32_t) * nr_slots;
12123       /* It's harder to decide whether the section is too small in v1.
12124          V1 is deprecated anyway so we punt.  */
12125     }
12126   else
12127     {
12128       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12129       int *ids = htab->section_pool.v2.section_ids;
12130       /* Reverse map for error checking.  */
12131       int ids_seen[DW_SECT_MAX + 1];
12132       int i;
12133
12134       if (nr_columns < 2)
12135         {
12136           error (_("Dwarf Error: bad DWP hash table, too few columns"
12137                    " in section table [in module %s]"),
12138                  dwp_file->name);
12139         }
12140       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12141         {
12142           error (_("Dwarf Error: bad DWP hash table, too many columns"
12143                    " in section table [in module %s]"),
12144                  dwp_file->name);
12145         }
12146       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12147       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12148       for (i = 0; i < nr_columns; ++i)
12149         {
12150           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12151
12152           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12153             {
12154               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12155                        " in section table [in module %s]"),
12156                      id, dwp_file->name);
12157             }
12158           if (ids_seen[id] != -1)
12159             {
12160               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12161                        " id %d in section table [in module %s]"),
12162                      id, dwp_file->name);
12163             }
12164           ids_seen[id] = i;
12165           ids[i] = id;
12166         }
12167       /* Must have exactly one info or types section.  */
12168       if (((ids_seen[DW_SECT_INFO] != -1)
12169            + (ids_seen[DW_SECT_TYPES] != -1))
12170           != 1)
12171         {
12172           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12173                    " DWO info/types section [in module %s]"),
12174                  dwp_file->name);
12175         }
12176       /* Must have an abbrev section.  */
12177       if (ids_seen[DW_SECT_ABBREV] == -1)
12178         {
12179           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12180                    " section [in module %s]"),
12181                  dwp_file->name);
12182         }
12183       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12184       htab->section_pool.v2.sizes =
12185         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12186                                          * nr_units * nr_columns);
12187       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12188                                           * nr_units * nr_columns))
12189           > index_end)
12190         {
12191           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12192                    " [in module %s]"),
12193                  dwp_file->name);
12194         }
12195     }
12196
12197   return htab;
12198 }
12199
12200 /* Update SECTIONS with the data from SECTP.
12201
12202    This function is like the other "locate" section routines that are
12203    passed to bfd_map_over_sections, but in this context the sections to
12204    read comes from the DWP V1 hash table, not the full ELF section table.
12205
12206    The result is non-zero for success, or zero if an error was found.  */
12207
12208 static int
12209 locate_v1_virtual_dwo_sections (asection *sectp,
12210                                 struct virtual_v1_dwo_sections *sections)
12211 {
12212   const struct dwop_section_names *names = &dwop_section_names;
12213
12214   if (section_is_p (sectp->name, &names->abbrev_dwo))
12215     {
12216       /* There can be only one.  */
12217       if (sections->abbrev.s.section != NULL)
12218         return 0;
12219       sections->abbrev.s.section = sectp;
12220       sections->abbrev.size = bfd_get_section_size (sectp);
12221     }
12222   else if (section_is_p (sectp->name, &names->info_dwo)
12223            || section_is_p (sectp->name, &names->types_dwo))
12224     {
12225       /* There can be only one.  */
12226       if (sections->info_or_types.s.section != NULL)
12227         return 0;
12228       sections->info_or_types.s.section = sectp;
12229       sections->info_or_types.size = bfd_get_section_size (sectp);
12230     }
12231   else if (section_is_p (sectp->name, &names->line_dwo))
12232     {
12233       /* There can be only one.  */
12234       if (sections->line.s.section != NULL)
12235         return 0;
12236       sections->line.s.section = sectp;
12237       sections->line.size = bfd_get_section_size (sectp);
12238     }
12239   else if (section_is_p (sectp->name, &names->loc_dwo))
12240     {
12241       /* There can be only one.  */
12242       if (sections->loc.s.section != NULL)
12243         return 0;
12244       sections->loc.s.section = sectp;
12245       sections->loc.size = bfd_get_section_size (sectp);
12246     }
12247   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12248     {
12249       /* There can be only one.  */
12250       if (sections->macinfo.s.section != NULL)
12251         return 0;
12252       sections->macinfo.s.section = sectp;
12253       sections->macinfo.size = bfd_get_section_size (sectp);
12254     }
12255   else if (section_is_p (sectp->name, &names->macro_dwo))
12256     {
12257       /* There can be only one.  */
12258       if (sections->macro.s.section != NULL)
12259         return 0;
12260       sections->macro.s.section = sectp;
12261       sections->macro.size = bfd_get_section_size (sectp);
12262     }
12263   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12264     {
12265       /* There can be only one.  */
12266       if (sections->str_offsets.s.section != NULL)
12267         return 0;
12268       sections->str_offsets.s.section = sectp;
12269       sections->str_offsets.size = bfd_get_section_size (sectp);
12270     }
12271   else
12272     {
12273       /* No other kind of section is valid.  */
12274       return 0;
12275     }
12276
12277   return 1;
12278 }
12279
12280 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12281    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12282    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12283    This is for DWP version 1 files.  */
12284
12285 static struct dwo_unit *
12286 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12287                            struct dwp_file *dwp_file,
12288                            uint32_t unit_index,
12289                            const char *comp_dir,
12290                            ULONGEST signature, int is_debug_types)
12291 {
12292   struct objfile *objfile = dwarf2_per_objfile->objfile;
12293   const struct dwp_hash_table *dwp_htab =
12294     is_debug_types ? dwp_file->tus : dwp_file->cus;
12295   bfd *dbfd = dwp_file->dbfd;
12296   const char *kind = is_debug_types ? "TU" : "CU";
12297   struct dwo_file *dwo_file;
12298   struct dwo_unit *dwo_unit;
12299   struct virtual_v1_dwo_sections sections;
12300   void **dwo_file_slot;
12301   int i;
12302
12303   gdb_assert (dwp_file->version == 1);
12304
12305   if (dwarf_read_debug)
12306     {
12307       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12308                           kind,
12309                           pulongest (unit_index), hex_string (signature),
12310                           dwp_file->name);
12311     }
12312
12313   /* Fetch the sections of this DWO unit.
12314      Put a limit on the number of sections we look for so that bad data
12315      doesn't cause us to loop forever.  */
12316
12317 #define MAX_NR_V1_DWO_SECTIONS \
12318   (1 /* .debug_info or .debug_types */ \
12319    + 1 /* .debug_abbrev */ \
12320    + 1 /* .debug_line */ \
12321    + 1 /* .debug_loc */ \
12322    + 1 /* .debug_str_offsets */ \
12323    + 1 /* .debug_macro or .debug_macinfo */ \
12324    + 1 /* trailing zero */)
12325
12326   memset (&sections, 0, sizeof (sections));
12327
12328   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12329     {
12330       asection *sectp;
12331       uint32_t section_nr =
12332         read_4_bytes (dbfd,
12333                       dwp_htab->section_pool.v1.indices
12334                       + (unit_index + i) * sizeof (uint32_t));
12335
12336       if (section_nr == 0)
12337         break;
12338       if (section_nr >= dwp_file->num_sections)
12339         {
12340           error (_("Dwarf Error: bad DWP hash table, section number too large"
12341                    " [in module %s]"),
12342                  dwp_file->name);
12343         }
12344
12345       sectp = dwp_file->elf_sections[section_nr];
12346       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12347         {
12348           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12349                    " [in module %s]"),
12350                  dwp_file->name);
12351         }
12352     }
12353
12354   if (i < 2
12355       || dwarf2_section_empty_p (&sections.info_or_types)
12356       || dwarf2_section_empty_p (&sections.abbrev))
12357     {
12358       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12359                " [in module %s]"),
12360              dwp_file->name);
12361     }
12362   if (i == MAX_NR_V1_DWO_SECTIONS)
12363     {
12364       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12365                " [in module %s]"),
12366              dwp_file->name);
12367     }
12368
12369   /* It's easier for the rest of the code if we fake a struct dwo_file and
12370      have dwo_unit "live" in that.  At least for now.
12371
12372      The DWP file can be made up of a random collection of CUs and TUs.
12373      However, for each CU + set of TUs that came from the same original DWO
12374      file, we can combine them back into a virtual DWO file to save space
12375      (fewer struct dwo_file objects to allocate).  Remember that for really
12376      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12377
12378   std::string virtual_dwo_name =
12379     string_printf ("virtual-dwo/%d-%d-%d-%d",
12380                    get_section_id (&sections.abbrev),
12381                    get_section_id (&sections.line),
12382                    get_section_id (&sections.loc),
12383                    get_section_id (&sections.str_offsets));
12384   /* Can we use an existing virtual DWO file?  */
12385   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12386                                         virtual_dwo_name.c_str (),
12387                                         comp_dir);
12388   /* Create one if necessary.  */
12389   if (*dwo_file_slot == NULL)
12390     {
12391       if (dwarf_read_debug)
12392         {
12393           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12394                               virtual_dwo_name.c_str ());
12395         }
12396       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12397       dwo_file->dwo_name
12398         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12399                                         virtual_dwo_name.c_str (),
12400                                         virtual_dwo_name.size ());
12401       dwo_file->comp_dir = comp_dir;
12402       dwo_file->sections.abbrev = sections.abbrev;
12403       dwo_file->sections.line = sections.line;
12404       dwo_file->sections.loc = sections.loc;
12405       dwo_file->sections.macinfo = sections.macinfo;
12406       dwo_file->sections.macro = sections.macro;
12407       dwo_file->sections.str_offsets = sections.str_offsets;
12408       /* The "str" section is global to the entire DWP file.  */
12409       dwo_file->sections.str = dwp_file->sections.str;
12410       /* The info or types section is assigned below to dwo_unit,
12411          there's no need to record it in dwo_file.
12412          Also, we can't simply record type sections in dwo_file because
12413          we record a pointer into the vector in dwo_unit.  As we collect more
12414          types we'll grow the vector and eventually have to reallocate space
12415          for it, invalidating all copies of pointers into the previous
12416          contents.  */
12417       *dwo_file_slot = dwo_file;
12418     }
12419   else
12420     {
12421       if (dwarf_read_debug)
12422         {
12423           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12424                               virtual_dwo_name.c_str ());
12425         }
12426       dwo_file = (struct dwo_file *) *dwo_file_slot;
12427     }
12428
12429   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12430   dwo_unit->dwo_file = dwo_file;
12431   dwo_unit->signature = signature;
12432   dwo_unit->section =
12433     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12434   *dwo_unit->section = sections.info_or_types;
12435   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12436
12437   return dwo_unit;
12438 }
12439
12440 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12441    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12442    piece within that section used by a TU/CU, return a virtual section
12443    of just that piece.  */
12444
12445 static struct dwarf2_section_info
12446 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12447                        struct dwarf2_section_info *section,
12448                        bfd_size_type offset, bfd_size_type size)
12449 {
12450   struct dwarf2_section_info result;
12451   asection *sectp;
12452
12453   gdb_assert (section != NULL);
12454   gdb_assert (!section->is_virtual);
12455
12456   memset (&result, 0, sizeof (result));
12457   result.s.containing_section = section;
12458   result.is_virtual = 1;
12459
12460   if (size == 0)
12461     return result;
12462
12463   sectp = get_section_bfd_section (section);
12464
12465   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12466      bounds of the real section.  This is a pretty-rare event, so just
12467      flag an error (easier) instead of a warning and trying to cope.  */
12468   if (sectp == NULL
12469       || offset + size > bfd_get_section_size (sectp))
12470     {
12471       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12472                " in section %s [in module %s]"),
12473              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12474              objfile_name (dwarf2_per_objfile->objfile));
12475     }
12476
12477   result.virtual_offset = offset;
12478   result.size = size;
12479   return result;
12480 }
12481
12482 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12483    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12484    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12485    This is for DWP version 2 files.  */
12486
12487 static struct dwo_unit *
12488 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12489                            struct dwp_file *dwp_file,
12490                            uint32_t unit_index,
12491                            const char *comp_dir,
12492                            ULONGEST signature, int is_debug_types)
12493 {
12494   struct objfile *objfile = dwarf2_per_objfile->objfile;
12495   const struct dwp_hash_table *dwp_htab =
12496     is_debug_types ? dwp_file->tus : dwp_file->cus;
12497   bfd *dbfd = dwp_file->dbfd;
12498   const char *kind = is_debug_types ? "TU" : "CU";
12499   struct dwo_file *dwo_file;
12500   struct dwo_unit *dwo_unit;
12501   struct virtual_v2_dwo_sections sections;
12502   void **dwo_file_slot;
12503   int i;
12504
12505   gdb_assert (dwp_file->version == 2);
12506
12507   if (dwarf_read_debug)
12508     {
12509       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12510                           kind,
12511                           pulongest (unit_index), hex_string (signature),
12512                           dwp_file->name);
12513     }
12514
12515   /* Fetch the section offsets of this DWO unit.  */
12516
12517   memset (&sections, 0, sizeof (sections));
12518
12519   for (i = 0; i < dwp_htab->nr_columns; ++i)
12520     {
12521       uint32_t offset = read_4_bytes (dbfd,
12522                                       dwp_htab->section_pool.v2.offsets
12523                                       + (((unit_index - 1) * dwp_htab->nr_columns
12524                                           + i)
12525                                          * sizeof (uint32_t)));
12526       uint32_t size = read_4_bytes (dbfd,
12527                                     dwp_htab->section_pool.v2.sizes
12528                                     + (((unit_index - 1) * dwp_htab->nr_columns
12529                                         + i)
12530                                        * sizeof (uint32_t)));
12531
12532       switch (dwp_htab->section_pool.v2.section_ids[i])
12533         {
12534         case DW_SECT_INFO:
12535         case DW_SECT_TYPES:
12536           sections.info_or_types_offset = offset;
12537           sections.info_or_types_size = size;
12538           break;
12539         case DW_SECT_ABBREV:
12540           sections.abbrev_offset = offset;
12541           sections.abbrev_size = size;
12542           break;
12543         case DW_SECT_LINE:
12544           sections.line_offset = offset;
12545           sections.line_size = size;
12546           break;
12547         case DW_SECT_LOC:
12548           sections.loc_offset = offset;
12549           sections.loc_size = size;
12550           break;
12551         case DW_SECT_STR_OFFSETS:
12552           sections.str_offsets_offset = offset;
12553           sections.str_offsets_size = size;
12554           break;
12555         case DW_SECT_MACINFO:
12556           sections.macinfo_offset = offset;
12557           sections.macinfo_size = size;
12558           break;
12559         case DW_SECT_MACRO:
12560           sections.macro_offset = offset;
12561           sections.macro_size = size;
12562           break;
12563         }
12564     }
12565
12566   /* It's easier for the rest of the code if we fake a struct dwo_file and
12567      have dwo_unit "live" in that.  At least for now.
12568
12569      The DWP file can be made up of a random collection of CUs and TUs.
12570      However, for each CU + set of TUs that came from the same original DWO
12571      file, we can combine them back into a virtual DWO file to save space
12572      (fewer struct dwo_file objects to allocate).  Remember that for really
12573      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12574
12575   std::string virtual_dwo_name =
12576     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12577                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12578                    (long) (sections.line_size ? sections.line_offset : 0),
12579                    (long) (sections.loc_size ? sections.loc_offset : 0),
12580                    (long) (sections.str_offsets_size
12581                            ? sections.str_offsets_offset : 0));
12582   /* Can we use an existing virtual DWO file?  */
12583   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12584                                         virtual_dwo_name.c_str (),
12585                                         comp_dir);
12586   /* Create one if necessary.  */
12587   if (*dwo_file_slot == NULL)
12588     {
12589       if (dwarf_read_debug)
12590         {
12591           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12592                               virtual_dwo_name.c_str ());
12593         }
12594       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12595       dwo_file->dwo_name
12596         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12597                                         virtual_dwo_name.c_str (),
12598                                         virtual_dwo_name.size ());
12599       dwo_file->comp_dir = comp_dir;
12600       dwo_file->sections.abbrev =
12601         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12602                                sections.abbrev_offset, sections.abbrev_size);
12603       dwo_file->sections.line =
12604         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12605                                sections.line_offset, sections.line_size);
12606       dwo_file->sections.loc =
12607         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12608                                sections.loc_offset, sections.loc_size);
12609       dwo_file->sections.macinfo =
12610         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12611                                sections.macinfo_offset, sections.macinfo_size);
12612       dwo_file->sections.macro =
12613         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12614                                sections.macro_offset, sections.macro_size);
12615       dwo_file->sections.str_offsets =
12616         create_dwp_v2_section (dwarf2_per_objfile,
12617                                &dwp_file->sections.str_offsets,
12618                                sections.str_offsets_offset,
12619                                sections.str_offsets_size);
12620       /* The "str" section is global to the entire DWP file.  */
12621       dwo_file->sections.str = dwp_file->sections.str;
12622       /* The info or types section is assigned below to dwo_unit,
12623          there's no need to record it in dwo_file.
12624          Also, we can't simply record type sections in dwo_file because
12625          we record a pointer into the vector in dwo_unit.  As we collect more
12626          types we'll grow the vector and eventually have to reallocate space
12627          for it, invalidating all copies of pointers into the previous
12628          contents.  */
12629       *dwo_file_slot = dwo_file;
12630     }
12631   else
12632     {
12633       if (dwarf_read_debug)
12634         {
12635           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12636                               virtual_dwo_name.c_str ());
12637         }
12638       dwo_file = (struct dwo_file *) *dwo_file_slot;
12639     }
12640
12641   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12642   dwo_unit->dwo_file = dwo_file;
12643   dwo_unit->signature = signature;
12644   dwo_unit->section =
12645     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12646   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12647                                               is_debug_types
12648                                               ? &dwp_file->sections.types
12649                                               : &dwp_file->sections.info,
12650                                               sections.info_or_types_offset,
12651                                               sections.info_or_types_size);
12652   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12653
12654   return dwo_unit;
12655 }
12656
12657 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12658    Returns NULL if the signature isn't found.  */
12659
12660 static struct dwo_unit *
12661 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12662                         struct dwp_file *dwp_file, const char *comp_dir,
12663                         ULONGEST signature, int is_debug_types)
12664 {
12665   const struct dwp_hash_table *dwp_htab =
12666     is_debug_types ? dwp_file->tus : dwp_file->cus;
12667   bfd *dbfd = dwp_file->dbfd;
12668   uint32_t mask = dwp_htab->nr_slots - 1;
12669   uint32_t hash = signature & mask;
12670   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12671   unsigned int i;
12672   void **slot;
12673   struct dwo_unit find_dwo_cu;
12674
12675   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12676   find_dwo_cu.signature = signature;
12677   slot = htab_find_slot (is_debug_types
12678                          ? dwp_file->loaded_tus
12679                          : dwp_file->loaded_cus,
12680                          &find_dwo_cu, INSERT);
12681
12682   if (*slot != NULL)
12683     return (struct dwo_unit *) *slot;
12684
12685   /* Use a for loop so that we don't loop forever on bad debug info.  */
12686   for (i = 0; i < dwp_htab->nr_slots; ++i)
12687     {
12688       ULONGEST signature_in_table;
12689
12690       signature_in_table =
12691         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12692       if (signature_in_table == signature)
12693         {
12694           uint32_t unit_index =
12695             read_4_bytes (dbfd,
12696                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12697
12698           if (dwp_file->version == 1)
12699             {
12700               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12701                                                  dwp_file, unit_index,
12702                                                  comp_dir, signature,
12703                                                  is_debug_types);
12704             }
12705           else
12706             {
12707               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12708                                                  dwp_file, unit_index,
12709                                                  comp_dir, signature,
12710                                                  is_debug_types);
12711             }
12712           return (struct dwo_unit *) *slot;
12713         }
12714       if (signature_in_table == 0)
12715         return NULL;
12716       hash = (hash + hash2) & mask;
12717     }
12718
12719   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12720            " [in module %s]"),
12721          dwp_file->name);
12722 }
12723
12724 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12725    Open the file specified by FILE_NAME and hand it off to BFD for
12726    preliminary analysis.  Return a newly initialized bfd *, which
12727    includes a canonicalized copy of FILE_NAME.
12728    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12729    SEARCH_CWD is true if the current directory is to be searched.
12730    It will be searched before debug-file-directory.
12731    If successful, the file is added to the bfd include table of the
12732    objfile's bfd (see gdb_bfd_record_inclusion).
12733    If unable to find/open the file, return NULL.
12734    NOTE: This function is derived from symfile_bfd_open.  */
12735
12736 static gdb_bfd_ref_ptr
12737 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12738                     const char *file_name, int is_dwp, int search_cwd)
12739 {
12740   int desc;
12741   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12742      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12743      to debug_file_directory.  */
12744   const char *search_path;
12745   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12746
12747   gdb::unique_xmalloc_ptr<char> search_path_holder;
12748   if (search_cwd)
12749     {
12750       if (*debug_file_directory != '\0')
12751         {
12752           search_path_holder.reset (concat (".", dirname_separator_string,
12753                                             debug_file_directory,
12754                                             (char *) NULL));
12755           search_path = search_path_holder.get ();
12756         }
12757       else
12758         search_path = ".";
12759     }
12760   else
12761     search_path = debug_file_directory;
12762
12763   openp_flags flags = OPF_RETURN_REALPATH;
12764   if (is_dwp)
12765     flags |= OPF_SEARCH_IN_PATH;
12766
12767   gdb::unique_xmalloc_ptr<char> absolute_name;
12768   desc = openp (search_path, flags, file_name,
12769                 O_RDONLY | O_BINARY, &absolute_name);
12770   if (desc < 0)
12771     return NULL;
12772
12773   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12774                                          gnutarget, desc));
12775   if (sym_bfd == NULL)
12776     return NULL;
12777   bfd_set_cacheable (sym_bfd.get (), 1);
12778
12779   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12780     return NULL;
12781
12782   /* Success.  Record the bfd as having been included by the objfile's bfd.
12783      This is important because things like demangled_names_hash lives in the
12784      objfile's per_bfd space and may have references to things like symbol
12785      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12786   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12787
12788   return sym_bfd;
12789 }
12790
12791 /* Try to open DWO file FILE_NAME.
12792    COMP_DIR is the DW_AT_comp_dir attribute.
12793    The result is the bfd handle of the file.
12794    If there is a problem finding or opening the file, return NULL.
12795    Upon success, the canonicalized path of the file is stored in the bfd,
12796    same as symfile_bfd_open.  */
12797
12798 static gdb_bfd_ref_ptr
12799 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12800                const char *file_name, const char *comp_dir)
12801 {
12802   if (IS_ABSOLUTE_PATH (file_name))
12803     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12804                                0 /*is_dwp*/, 0 /*search_cwd*/);
12805
12806   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12807
12808   if (comp_dir != NULL)
12809     {
12810       char *path_to_try = concat (comp_dir, SLASH_STRING,
12811                                   file_name, (char *) NULL);
12812
12813       /* NOTE: If comp_dir is a relative path, this will also try the
12814          search path, which seems useful.  */
12815       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12816                                                 path_to_try,
12817                                                 0 /*is_dwp*/,
12818                                                 1 /*search_cwd*/));
12819       xfree (path_to_try);
12820       if (abfd != NULL)
12821         return abfd;
12822     }
12823
12824   /* That didn't work, try debug-file-directory, which, despite its name,
12825      is a list of paths.  */
12826
12827   if (*debug_file_directory == '\0')
12828     return NULL;
12829
12830   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12831                              0 /*is_dwp*/, 1 /*search_cwd*/);
12832 }
12833
12834 /* This function is mapped across the sections and remembers the offset and
12835    size of each of the DWO debugging sections we are interested in.  */
12836
12837 static void
12838 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12839 {
12840   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12841   const struct dwop_section_names *names = &dwop_section_names;
12842
12843   if (section_is_p (sectp->name, &names->abbrev_dwo))
12844     {
12845       dwo_sections->abbrev.s.section = sectp;
12846       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12847     }
12848   else if (section_is_p (sectp->name, &names->info_dwo))
12849     {
12850       dwo_sections->info.s.section = sectp;
12851       dwo_sections->info.size = bfd_get_section_size (sectp);
12852     }
12853   else if (section_is_p (sectp->name, &names->line_dwo))
12854     {
12855       dwo_sections->line.s.section = sectp;
12856       dwo_sections->line.size = bfd_get_section_size (sectp);
12857     }
12858   else if (section_is_p (sectp->name, &names->loc_dwo))
12859     {
12860       dwo_sections->loc.s.section = sectp;
12861       dwo_sections->loc.size = bfd_get_section_size (sectp);
12862     }
12863   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12864     {
12865       dwo_sections->macinfo.s.section = sectp;
12866       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12867     }
12868   else if (section_is_p (sectp->name, &names->macro_dwo))
12869     {
12870       dwo_sections->macro.s.section = sectp;
12871       dwo_sections->macro.size = bfd_get_section_size (sectp);
12872     }
12873   else if (section_is_p (sectp->name, &names->str_dwo))
12874     {
12875       dwo_sections->str.s.section = sectp;
12876       dwo_sections->str.size = bfd_get_section_size (sectp);
12877     }
12878   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12879     {
12880       dwo_sections->str_offsets.s.section = sectp;
12881       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12882     }
12883   else if (section_is_p (sectp->name, &names->types_dwo))
12884     {
12885       struct dwarf2_section_info type_section;
12886
12887       memset (&type_section, 0, sizeof (type_section));
12888       type_section.s.section = sectp;
12889       type_section.size = bfd_get_section_size (sectp);
12890       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12891                      &type_section);
12892     }
12893 }
12894
12895 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12896    by PER_CU.  This is for the non-DWP case.
12897    The result is NULL if DWO_NAME can't be found.  */
12898
12899 static struct dwo_file *
12900 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12901                         const char *dwo_name, const char *comp_dir)
12902 {
12903   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12904   struct objfile *objfile = dwarf2_per_objfile->objfile;
12905
12906   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12907   if (dbfd == NULL)
12908     {
12909       if (dwarf_read_debug)
12910         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12911       return NULL;
12912     }
12913
12914   /* We use a unique pointer here, despite the obstack allocation,
12915      because a dwo_file needs some cleanup if it is abandoned.  */
12916   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12917                                         struct dwo_file));
12918   dwo_file->dwo_name = dwo_name;
12919   dwo_file->comp_dir = comp_dir;
12920   dwo_file->dbfd = dbfd.release ();
12921
12922   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12923                          &dwo_file->sections);
12924
12925   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12926                          dwo_file->cus);
12927
12928   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12929                                  dwo_file->sections.types, dwo_file->tus);
12930
12931   if (dwarf_read_debug)
12932     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12933
12934   return dwo_file.release ();
12935 }
12936
12937 /* This function is mapped across the sections and remembers the offset and
12938    size of each of the DWP debugging sections common to version 1 and 2 that
12939    we are interested in.  */
12940
12941 static void
12942 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12943                                    void *dwp_file_ptr)
12944 {
12945   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12946   const struct dwop_section_names *names = &dwop_section_names;
12947   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12948
12949   /* Record the ELF section number for later lookup: this is what the
12950      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12951   gdb_assert (elf_section_nr < dwp_file->num_sections);
12952   dwp_file->elf_sections[elf_section_nr] = sectp;
12953
12954   /* Look for specific sections that we need.  */
12955   if (section_is_p (sectp->name, &names->str_dwo))
12956     {
12957       dwp_file->sections.str.s.section = sectp;
12958       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12959     }
12960   else if (section_is_p (sectp->name, &names->cu_index))
12961     {
12962       dwp_file->sections.cu_index.s.section = sectp;
12963       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12964     }
12965   else if (section_is_p (sectp->name, &names->tu_index))
12966     {
12967       dwp_file->sections.tu_index.s.section = sectp;
12968       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12969     }
12970 }
12971
12972 /* This function is mapped across the sections and remembers the offset and
12973    size of each of the DWP version 2 debugging sections that we are interested
12974    in.  This is split into a separate function because we don't know if we
12975    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12976
12977 static void
12978 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12979 {
12980   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12981   const struct dwop_section_names *names = &dwop_section_names;
12982   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12983
12984   /* Record the ELF section number for later lookup: this is what the
12985      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12986   gdb_assert (elf_section_nr < dwp_file->num_sections);
12987   dwp_file->elf_sections[elf_section_nr] = sectp;
12988
12989   /* Look for specific sections that we need.  */
12990   if (section_is_p (sectp->name, &names->abbrev_dwo))
12991     {
12992       dwp_file->sections.abbrev.s.section = sectp;
12993       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12994     }
12995   else if (section_is_p (sectp->name, &names->info_dwo))
12996     {
12997       dwp_file->sections.info.s.section = sectp;
12998       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12999     }
13000   else if (section_is_p (sectp->name, &names->line_dwo))
13001     {
13002       dwp_file->sections.line.s.section = sectp;
13003       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13004     }
13005   else if (section_is_p (sectp->name, &names->loc_dwo))
13006     {
13007       dwp_file->sections.loc.s.section = sectp;
13008       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13009     }
13010   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13011     {
13012       dwp_file->sections.macinfo.s.section = sectp;
13013       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13014     }
13015   else if (section_is_p (sectp->name, &names->macro_dwo))
13016     {
13017       dwp_file->sections.macro.s.section = sectp;
13018       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13019     }
13020   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13021     {
13022       dwp_file->sections.str_offsets.s.section = sectp;
13023       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13024     }
13025   else if (section_is_p (sectp->name, &names->types_dwo))
13026     {
13027       dwp_file->sections.types.s.section = sectp;
13028       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13029     }
13030 }
13031
13032 /* Hash function for dwp_file loaded CUs/TUs.  */
13033
13034 static hashval_t
13035 hash_dwp_loaded_cutus (const void *item)
13036 {
13037   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13038
13039   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13040   return dwo_unit->signature;
13041 }
13042
13043 /* Equality function for dwp_file loaded CUs/TUs.  */
13044
13045 static int
13046 eq_dwp_loaded_cutus (const void *a, const void *b)
13047 {
13048   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13049   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13050
13051   return dua->signature == dub->signature;
13052 }
13053
13054 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13055
13056 static htab_t
13057 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13058 {
13059   return htab_create_alloc_ex (3,
13060                                hash_dwp_loaded_cutus,
13061                                eq_dwp_loaded_cutus,
13062                                NULL,
13063                                &objfile->objfile_obstack,
13064                                hashtab_obstack_allocate,
13065                                dummy_obstack_deallocate);
13066 }
13067
13068 /* Try to open DWP file FILE_NAME.
13069    The result is the bfd handle of the file.
13070    If there is a problem finding or opening the file, return NULL.
13071    Upon success, the canonicalized path of the file is stored in the bfd,
13072    same as symfile_bfd_open.  */
13073
13074 static gdb_bfd_ref_ptr
13075 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13076                const char *file_name)
13077 {
13078   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13079                                             1 /*is_dwp*/,
13080                                             1 /*search_cwd*/));
13081   if (abfd != NULL)
13082     return abfd;
13083
13084   /* Work around upstream bug 15652.
13085      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13086      [Whether that's a "bug" is debatable, but it is getting in our way.]
13087      We have no real idea where the dwp file is, because gdb's realpath-ing
13088      of the executable's path may have discarded the needed info.
13089      [IWBN if the dwp file name was recorded in the executable, akin to
13090      .gnu_debuglink, but that doesn't exist yet.]
13091      Strip the directory from FILE_NAME and search again.  */
13092   if (*debug_file_directory != '\0')
13093     {
13094       /* Don't implicitly search the current directory here.
13095          If the user wants to search "." to handle this case,
13096          it must be added to debug-file-directory.  */
13097       return try_open_dwop_file (dwarf2_per_objfile,
13098                                  lbasename (file_name), 1 /*is_dwp*/,
13099                                  0 /*search_cwd*/);
13100     }
13101
13102   return NULL;
13103 }
13104
13105 /* Initialize the use of the DWP file for the current objfile.
13106    By convention the name of the DWP file is ${objfile}.dwp.
13107    The result is NULL if it can't be found.  */
13108
13109 static struct dwp_file *
13110 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13111 {
13112   struct objfile *objfile = dwarf2_per_objfile->objfile;
13113   struct dwp_file *dwp_file;
13114
13115   /* Try to find first .dwp for the binary file before any symbolic links
13116      resolving.  */
13117
13118   /* If the objfile is a debug file, find the name of the real binary
13119      file and get the name of dwp file from there.  */
13120   std::string dwp_name;
13121   if (objfile->separate_debug_objfile_backlink != NULL)
13122     {
13123       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13124       const char *backlink_basename = lbasename (backlink->original_name);
13125
13126       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13127     }
13128   else
13129     dwp_name = objfile->original_name;
13130
13131   dwp_name += ".dwp";
13132
13133   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13134   if (dbfd == NULL
13135       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13136     {
13137       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13138       dwp_name = objfile_name (objfile);
13139       dwp_name += ".dwp";
13140       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13141     }
13142
13143   if (dbfd == NULL)
13144     {
13145       if (dwarf_read_debug)
13146         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13147       return NULL;
13148     }
13149   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13150   dwp_file->name = bfd_get_filename (dbfd.get ());
13151   dwp_file->dbfd = dbfd.release ();
13152
13153   /* +1: section 0 is unused */
13154   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13155   dwp_file->elf_sections =
13156     OBSTACK_CALLOC (&objfile->objfile_obstack,
13157                     dwp_file->num_sections, asection *);
13158
13159   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13160                          dwp_file);
13161
13162   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13163
13164   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13165
13166   /* The DWP file version is stored in the hash table.  Oh well.  */
13167   if (dwp_file->cus && dwp_file->tus
13168       && dwp_file->cus->version != dwp_file->tus->version)
13169     {
13170       /* Technically speaking, we should try to limp along, but this is
13171          pretty bizarre.  We use pulongest here because that's the established
13172          portability solution (e.g, we cannot use %u for uint32_t).  */
13173       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13174                " TU version %s [in DWP file %s]"),
13175              pulongest (dwp_file->cus->version),
13176              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13177     }
13178
13179   if (dwp_file->cus)
13180     dwp_file->version = dwp_file->cus->version;
13181   else if (dwp_file->tus)
13182     dwp_file->version = dwp_file->tus->version;
13183   else
13184     dwp_file->version = 2;
13185
13186   if (dwp_file->version == 2)
13187     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13188                            dwp_file);
13189
13190   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13191   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13192
13193   if (dwarf_read_debug)
13194     {
13195       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13196       fprintf_unfiltered (gdb_stdlog,
13197                           "    %s CUs, %s TUs\n",
13198                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13199                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13200     }
13201
13202   return dwp_file;
13203 }
13204
13205 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13206
13207 static struct dwp_file *
13208 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13209 {
13210   if (! dwarf2_per_objfile->dwp_checked)
13211     {
13212       dwarf2_per_objfile->dwp_file
13213         = open_and_init_dwp_file (dwarf2_per_objfile);
13214       dwarf2_per_objfile->dwp_checked = 1;
13215     }
13216   return dwarf2_per_objfile->dwp_file;
13217 }
13218
13219 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13220    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13221    or in the DWP file for the objfile, referenced by THIS_UNIT.
13222    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13223    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13224
13225    This is called, for example, when wanting to read a variable with a
13226    complex location.  Therefore we don't want to do file i/o for every call.
13227    Therefore we don't want to look for a DWO file on every call.
13228    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13229    then we check if we've already seen DWO_NAME, and only THEN do we check
13230    for a DWO file.
13231
13232    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13233    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13234
13235 static struct dwo_unit *
13236 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13237                  const char *dwo_name, const char *comp_dir,
13238                  ULONGEST signature, int is_debug_types)
13239 {
13240   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13241   struct objfile *objfile = dwarf2_per_objfile->objfile;
13242   const char *kind = is_debug_types ? "TU" : "CU";
13243   void **dwo_file_slot;
13244   struct dwo_file *dwo_file;
13245   struct dwp_file *dwp_file;
13246
13247   /* First see if there's a DWP file.
13248      If we have a DWP file but didn't find the DWO inside it, don't
13249      look for the original DWO file.  It makes gdb behave differently
13250      depending on whether one is debugging in the build tree.  */
13251
13252   dwp_file = get_dwp_file (dwarf2_per_objfile);
13253   if (dwp_file != NULL)
13254     {
13255       const struct dwp_hash_table *dwp_htab =
13256         is_debug_types ? dwp_file->tus : dwp_file->cus;
13257
13258       if (dwp_htab != NULL)
13259         {
13260           struct dwo_unit *dwo_cutu =
13261             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13262                                     signature, is_debug_types);
13263
13264           if (dwo_cutu != NULL)
13265             {
13266               if (dwarf_read_debug)
13267                 {
13268                   fprintf_unfiltered (gdb_stdlog,
13269                                       "Virtual DWO %s %s found: @%s\n",
13270                                       kind, hex_string (signature),
13271                                       host_address_to_string (dwo_cutu));
13272                 }
13273               return dwo_cutu;
13274             }
13275         }
13276     }
13277   else
13278     {
13279       /* No DWP file, look for the DWO file.  */
13280
13281       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13282                                             dwo_name, comp_dir);
13283       if (*dwo_file_slot == NULL)
13284         {
13285           /* Read in the file and build a table of the CUs/TUs it contains.  */
13286           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13287         }
13288       /* NOTE: This will be NULL if unable to open the file.  */
13289       dwo_file = (struct dwo_file *) *dwo_file_slot;
13290
13291       if (dwo_file != NULL)
13292         {
13293           struct dwo_unit *dwo_cutu = NULL;
13294
13295           if (is_debug_types && dwo_file->tus)
13296             {
13297               struct dwo_unit find_dwo_cutu;
13298
13299               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13300               find_dwo_cutu.signature = signature;
13301               dwo_cutu
13302                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13303             }
13304           else if (!is_debug_types && dwo_file->cus)
13305             {
13306               struct dwo_unit find_dwo_cutu;
13307
13308               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13309               find_dwo_cutu.signature = signature;
13310               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13311                                                        &find_dwo_cutu);
13312             }
13313
13314           if (dwo_cutu != NULL)
13315             {
13316               if (dwarf_read_debug)
13317                 {
13318                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13319                                       kind, dwo_name, hex_string (signature),
13320                                       host_address_to_string (dwo_cutu));
13321                 }
13322               return dwo_cutu;
13323             }
13324         }
13325     }
13326
13327   /* We didn't find it.  This could mean a dwo_id mismatch, or
13328      someone deleted the DWO/DWP file, or the search path isn't set up
13329      correctly to find the file.  */
13330
13331   if (dwarf_read_debug)
13332     {
13333       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13334                           kind, dwo_name, hex_string (signature));
13335     }
13336
13337   /* This is a warning and not a complaint because it can be caused by
13338      pilot error (e.g., user accidentally deleting the DWO).  */
13339   {
13340     /* Print the name of the DWP file if we looked there, helps the user
13341        better diagnose the problem.  */
13342     std::string dwp_text;
13343
13344     if (dwp_file != NULL)
13345       dwp_text = string_printf (" [in DWP file %s]",
13346                                 lbasename (dwp_file->name));
13347
13348     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13349                " [in module %s]"),
13350              kind, dwo_name, hex_string (signature),
13351              dwp_text.c_str (),
13352              this_unit->is_debug_types ? "TU" : "CU",
13353              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13354   }
13355   return NULL;
13356 }
13357
13358 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13359    See lookup_dwo_cutu_unit for details.  */
13360
13361 static struct dwo_unit *
13362 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13363                       const char *dwo_name, const char *comp_dir,
13364                       ULONGEST signature)
13365 {
13366   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13367 }
13368
13369 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13370    See lookup_dwo_cutu_unit for details.  */
13371
13372 static struct dwo_unit *
13373 lookup_dwo_type_unit (struct signatured_type *this_tu,
13374                       const char *dwo_name, const char *comp_dir)
13375 {
13376   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13377 }
13378
13379 /* Traversal function for queue_and_load_all_dwo_tus.  */
13380
13381 static int
13382 queue_and_load_dwo_tu (void **slot, void *info)
13383 {
13384   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13385   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13386   ULONGEST signature = dwo_unit->signature;
13387   struct signatured_type *sig_type =
13388     lookup_dwo_signatured_type (per_cu->cu, signature);
13389
13390   if (sig_type != NULL)
13391     {
13392       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13393
13394       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13395          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13396          while processing PER_CU.  */
13397       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13398         load_full_type_unit (sig_cu);
13399       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13400     }
13401
13402   return 1;
13403 }
13404
13405 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13406    The DWO may have the only definition of the type, though it may not be
13407    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13408    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13409
13410 static void
13411 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13412 {
13413   struct dwo_unit *dwo_unit;
13414   struct dwo_file *dwo_file;
13415
13416   gdb_assert (!per_cu->is_debug_types);
13417   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13418   gdb_assert (per_cu->cu != NULL);
13419
13420   dwo_unit = per_cu->cu->dwo_unit;
13421   gdb_assert (dwo_unit != NULL);
13422
13423   dwo_file = dwo_unit->dwo_file;
13424   if (dwo_file->tus != NULL)
13425     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13426 }
13427
13428 /* Free all resources associated with DWO_FILE.
13429    Close the DWO file and munmap the sections.  */
13430
13431 static void
13432 free_dwo_file (struct dwo_file *dwo_file)
13433 {
13434   /* Note: dbfd is NULL for virtual DWO files.  */
13435   gdb_bfd_unref (dwo_file->dbfd);
13436
13437   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13438 }
13439
13440 /* Traversal function for free_dwo_files.  */
13441
13442 static int
13443 free_dwo_file_from_slot (void **slot, void *info)
13444 {
13445   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13446
13447   free_dwo_file (dwo_file);
13448
13449   return 1;
13450 }
13451
13452 /* Free all resources associated with DWO_FILES.  */
13453
13454 static void
13455 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13456 {
13457   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13458 }
13459 \f
13460 /* Read in various DIEs.  */
13461
13462 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13463    Inherit only the children of the DW_AT_abstract_origin DIE not being
13464    already referenced by DW_AT_abstract_origin from the children of the
13465    current DIE.  */
13466
13467 static void
13468 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13469 {
13470   struct die_info *child_die;
13471   sect_offset *offsetp;
13472   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13473   struct die_info *origin_die;
13474   /* Iterator of the ORIGIN_DIE children.  */
13475   struct die_info *origin_child_die;
13476   struct attribute *attr;
13477   struct dwarf2_cu *origin_cu;
13478   struct pending **origin_previous_list_in_scope;
13479
13480   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13481   if (!attr)
13482     return;
13483
13484   /* Note that following die references may follow to a die in a
13485      different cu.  */
13486
13487   origin_cu = cu;
13488   origin_die = follow_die_ref (die, attr, &origin_cu);
13489
13490   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13491      symbols in.  */
13492   origin_previous_list_in_scope = origin_cu->list_in_scope;
13493   origin_cu->list_in_scope = cu->list_in_scope;
13494
13495   if (die->tag != origin_die->tag
13496       && !(die->tag == DW_TAG_inlined_subroutine
13497            && origin_die->tag == DW_TAG_subprogram))
13498     complaint (&symfile_complaints,
13499                _("DIE %s and its abstract origin %s have different tags"),
13500                sect_offset_str (die->sect_off),
13501                sect_offset_str (origin_die->sect_off));
13502
13503   std::vector<sect_offset> offsets;
13504
13505   for (child_die = die->child;
13506        child_die && child_die->tag;
13507        child_die = sibling_die (child_die))
13508     {
13509       struct die_info *child_origin_die;
13510       struct dwarf2_cu *child_origin_cu;
13511
13512       /* We are trying to process concrete instance entries:
13513          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13514          it's not relevant to our analysis here. i.e. detecting DIEs that are
13515          present in the abstract instance but not referenced in the concrete
13516          one.  */
13517       if (child_die->tag == DW_TAG_call_site
13518           || child_die->tag == DW_TAG_GNU_call_site)
13519         continue;
13520
13521       /* For each CHILD_DIE, find the corresponding child of
13522          ORIGIN_DIE.  If there is more than one layer of
13523          DW_AT_abstract_origin, follow them all; there shouldn't be,
13524          but GCC versions at least through 4.4 generate this (GCC PR
13525          40573).  */
13526       child_origin_die = child_die;
13527       child_origin_cu = cu;
13528       while (1)
13529         {
13530           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13531                               child_origin_cu);
13532           if (attr == NULL)
13533             break;
13534           child_origin_die = follow_die_ref (child_origin_die, attr,
13535                                              &child_origin_cu);
13536         }
13537
13538       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13539          counterpart may exist.  */
13540       if (child_origin_die != child_die)
13541         {
13542           if (child_die->tag != child_origin_die->tag
13543               && !(child_die->tag == DW_TAG_inlined_subroutine
13544                    && child_origin_die->tag == DW_TAG_subprogram))
13545             complaint (&symfile_complaints,
13546                        _("Child DIE %s and its abstract origin %s have "
13547                          "different tags"),
13548                        sect_offset_str (child_die->sect_off),
13549                        sect_offset_str (child_origin_die->sect_off));
13550           if (child_origin_die->parent != origin_die)
13551             complaint (&symfile_complaints,
13552                        _("Child DIE %s and its abstract origin %s have "
13553                          "different parents"),
13554                        sect_offset_str (child_die->sect_off),
13555                        sect_offset_str (child_origin_die->sect_off));
13556           else
13557             offsets.push_back (child_origin_die->sect_off);
13558         }
13559     }
13560   std::sort (offsets.begin (), offsets.end ());
13561   sect_offset *offsets_end = offsets.data () + offsets.size ();
13562   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13563     if (offsetp[-1] == *offsetp)
13564       complaint (&symfile_complaints,
13565                  _("Multiple children of DIE %s refer "
13566                    "to DIE %s as their abstract origin"),
13567                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13568
13569   offsetp = offsets.data ();
13570   origin_child_die = origin_die->child;
13571   while (origin_child_die && origin_child_die->tag)
13572     {
13573       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13574       while (offsetp < offsets_end
13575              && *offsetp < origin_child_die->sect_off)
13576         offsetp++;
13577       if (offsetp >= offsets_end
13578           || *offsetp > origin_child_die->sect_off)
13579         {
13580           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13581              Check whether we're already processing ORIGIN_CHILD_DIE.
13582              This can happen with mutually referenced abstract_origins.
13583              PR 16581.  */
13584           if (!origin_child_die->in_process)
13585             process_die (origin_child_die, origin_cu);
13586         }
13587       origin_child_die = sibling_die (origin_child_die);
13588     }
13589   origin_cu->list_in_scope = origin_previous_list_in_scope;
13590 }
13591
13592 static void
13593 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13594 {
13595   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13596   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13597   struct context_stack *newobj;
13598   CORE_ADDR lowpc;
13599   CORE_ADDR highpc;
13600   struct die_info *child_die;
13601   struct attribute *attr, *call_line, *call_file;
13602   const char *name;
13603   CORE_ADDR baseaddr;
13604   struct block *block;
13605   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13606   std::vector<struct symbol *> template_args;
13607   struct template_symbol *templ_func = NULL;
13608
13609   if (inlined_func)
13610     {
13611       /* If we do not have call site information, we can't show the
13612          caller of this inlined function.  That's too confusing, so
13613          only use the scope for local variables.  */
13614       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13615       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13616       if (call_line == NULL || call_file == NULL)
13617         {
13618           read_lexical_block_scope (die, cu);
13619           return;
13620         }
13621     }
13622
13623   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13624
13625   name = dwarf2_name (die, cu);
13626
13627   /* Ignore functions with missing or empty names.  These are actually
13628      illegal according to the DWARF standard.  */
13629   if (name == NULL)
13630     {
13631       complaint (&symfile_complaints,
13632                  _("missing name for subprogram DIE at %s"),
13633                  sect_offset_str (die->sect_off));
13634       return;
13635     }
13636
13637   /* Ignore functions with missing or invalid low and high pc attributes.  */
13638   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13639       <= PC_BOUNDS_INVALID)
13640     {
13641       attr = dwarf2_attr (die, DW_AT_external, cu);
13642       if (!attr || !DW_UNSND (attr))
13643         complaint (&symfile_complaints,
13644                    _("cannot get low and high bounds "
13645                      "for subprogram DIE at %s"),
13646                    sect_offset_str (die->sect_off));
13647       return;
13648     }
13649
13650   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13651   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13652
13653   /* If we have any template arguments, then we must allocate a
13654      different sort of symbol.  */
13655   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13656     {
13657       if (child_die->tag == DW_TAG_template_type_param
13658           || child_die->tag == DW_TAG_template_value_param)
13659         {
13660           templ_func = allocate_template_symbol (objfile);
13661           templ_func->subclass = SYMBOL_TEMPLATE;
13662           break;
13663         }
13664     }
13665
13666   newobj = push_context (0, lowpc);
13667   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13668                              (struct symbol *) templ_func);
13669
13670   /* If there is a location expression for DW_AT_frame_base, record
13671      it.  */
13672   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13673   if (attr)
13674     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13675
13676   /* If there is a location for the static link, record it.  */
13677   newobj->static_link = NULL;
13678   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13679   if (attr)
13680     {
13681       newobj->static_link
13682         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13683       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13684     }
13685
13686   cu->list_in_scope = &local_symbols;
13687
13688   if (die->child != NULL)
13689     {
13690       child_die = die->child;
13691       while (child_die && child_die->tag)
13692         {
13693           if (child_die->tag == DW_TAG_template_type_param
13694               || child_die->tag == DW_TAG_template_value_param)
13695             {
13696               struct symbol *arg = new_symbol (child_die, NULL, cu);
13697
13698               if (arg != NULL)
13699                 template_args.push_back (arg);
13700             }
13701           else
13702             process_die (child_die, cu);
13703           child_die = sibling_die (child_die);
13704         }
13705     }
13706
13707   inherit_abstract_dies (die, cu);
13708
13709   /* If we have a DW_AT_specification, we might need to import using
13710      directives from the context of the specification DIE.  See the
13711      comment in determine_prefix.  */
13712   if (cu->language == language_cplus
13713       && dwarf2_attr (die, DW_AT_specification, cu))
13714     {
13715       struct dwarf2_cu *spec_cu = cu;
13716       struct die_info *spec_die = die_specification (die, &spec_cu);
13717
13718       while (spec_die)
13719         {
13720           child_die = spec_die->child;
13721           while (child_die && child_die->tag)
13722             {
13723               if (child_die->tag == DW_TAG_imported_module)
13724                 process_die (child_die, spec_cu);
13725               child_die = sibling_die (child_die);
13726             }
13727
13728           /* In some cases, GCC generates specification DIEs that
13729              themselves contain DW_AT_specification attributes.  */
13730           spec_die = die_specification (spec_die, &spec_cu);
13731         }
13732     }
13733
13734   newobj = pop_context ();
13735   /* Make a block for the local symbols within.  */
13736   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13737                         newobj->static_link, lowpc, highpc);
13738
13739   /* For C++, set the block's scope.  */
13740   if ((cu->language == language_cplus
13741        || cu->language == language_fortran
13742        || cu->language == language_d
13743        || cu->language == language_rust)
13744       && cu->processing_has_namespace_info)
13745     block_set_scope (block, determine_prefix (die, cu),
13746                      &objfile->objfile_obstack);
13747
13748   /* If we have address ranges, record them.  */
13749   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13750
13751   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13752
13753   /* Attach template arguments to function.  */
13754   if (!template_args.empty ())
13755     {
13756       gdb_assert (templ_func != NULL);
13757
13758       templ_func->n_template_arguments = template_args.size ();
13759       templ_func->template_arguments
13760         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13761                      templ_func->n_template_arguments);
13762       memcpy (templ_func->template_arguments,
13763               template_args.data (),
13764               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13765     }
13766
13767   /* In C++, we can have functions nested inside functions (e.g., when
13768      a function declares a class that has methods).  This means that
13769      when we finish processing a function scope, we may need to go
13770      back to building a containing block's symbol lists.  */
13771   local_symbols = newobj->locals;
13772   local_using_directives = newobj->local_using_directives;
13773
13774   /* If we've finished processing a top-level function, subsequent
13775      symbols go in the file symbol list.  */
13776   if (outermost_context_p ())
13777     cu->list_in_scope = &file_symbols;
13778 }
13779
13780 /* Process all the DIES contained within a lexical block scope.  Start
13781    a new scope, process the dies, and then close the scope.  */
13782
13783 static void
13784 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13785 {
13786   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13787   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13788   struct context_stack *newobj;
13789   CORE_ADDR lowpc, highpc;
13790   struct die_info *child_die;
13791   CORE_ADDR baseaddr;
13792
13793   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13794
13795   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13796   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13797      as multiple lexical blocks?  Handling children in a sane way would
13798      be nasty.  Might be easier to properly extend generic blocks to
13799      describe ranges.  */
13800   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13801     {
13802     case PC_BOUNDS_NOT_PRESENT:
13803       /* DW_TAG_lexical_block has no attributes, process its children as if
13804          there was no wrapping by that DW_TAG_lexical_block.
13805          GCC does no longer produces such DWARF since GCC r224161.  */
13806       for (child_die = die->child;
13807            child_die != NULL && child_die->tag;
13808            child_die = sibling_die (child_die))
13809         process_die (child_die, cu);
13810       return;
13811     case PC_BOUNDS_INVALID:
13812       return;
13813     }
13814   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13815   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13816
13817   push_context (0, lowpc);
13818   if (die->child != NULL)
13819     {
13820       child_die = die->child;
13821       while (child_die && child_die->tag)
13822         {
13823           process_die (child_die, cu);
13824           child_die = sibling_die (child_die);
13825         }
13826     }
13827   inherit_abstract_dies (die, cu);
13828   newobj = pop_context ();
13829
13830   if (local_symbols != NULL || local_using_directives != NULL)
13831     {
13832       struct block *block
13833         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13834                         newobj->start_addr, highpc);
13835
13836       /* Note that recording ranges after traversing children, as we
13837          do here, means that recording a parent's ranges entails
13838          walking across all its children's ranges as they appear in
13839          the address map, which is quadratic behavior.
13840
13841          It would be nicer to record the parent's ranges before
13842          traversing its children, simply overriding whatever you find
13843          there.  But since we don't even decide whether to create a
13844          block until after we've traversed its children, that's hard
13845          to do.  */
13846       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13847     }
13848   local_symbols = newobj->locals;
13849   local_using_directives = newobj->local_using_directives;
13850 }
13851
13852 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13853
13854 static void
13855 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13856 {
13857   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13858   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13859   CORE_ADDR pc, baseaddr;
13860   struct attribute *attr;
13861   struct call_site *call_site, call_site_local;
13862   void **slot;
13863   int nparams;
13864   struct die_info *child_die;
13865
13866   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13867
13868   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13869   if (attr == NULL)
13870     {
13871       /* This was a pre-DWARF-5 GNU extension alias
13872          for DW_AT_call_return_pc.  */
13873       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13874     }
13875   if (!attr)
13876     {
13877       complaint (&symfile_complaints,
13878                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
13879                    "DIE %s [in module %s]"),
13880                  sect_offset_str (die->sect_off), objfile_name (objfile));
13881       return;
13882     }
13883   pc = attr_value_as_address (attr) + baseaddr;
13884   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13885
13886   if (cu->call_site_htab == NULL)
13887     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13888                                                NULL, &objfile->objfile_obstack,
13889                                                hashtab_obstack_allocate, NULL);
13890   call_site_local.pc = pc;
13891   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13892   if (*slot != NULL)
13893     {
13894       complaint (&symfile_complaints,
13895                  _("Duplicate PC %s for DW_TAG_call_site "
13896                    "DIE %s [in module %s]"),
13897                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13898                  objfile_name (objfile));
13899       return;
13900     }
13901
13902   /* Count parameters at the caller.  */
13903
13904   nparams = 0;
13905   for (child_die = die->child; child_die && child_die->tag;
13906        child_die = sibling_die (child_die))
13907     {
13908       if (child_die->tag != DW_TAG_call_site_parameter
13909           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13910         {
13911           complaint (&symfile_complaints,
13912                      _("Tag %d is not DW_TAG_call_site_parameter in "
13913                        "DW_TAG_call_site child DIE %s [in module %s]"),
13914                      child_die->tag, sect_offset_str (child_die->sect_off),
13915                      objfile_name (objfile));
13916           continue;
13917         }
13918
13919       nparams++;
13920     }
13921
13922   call_site
13923     = ((struct call_site *)
13924        obstack_alloc (&objfile->objfile_obstack,
13925                       sizeof (*call_site)
13926                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13927   *slot = call_site;
13928   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13929   call_site->pc = pc;
13930
13931   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13932       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13933     {
13934       struct die_info *func_die;
13935
13936       /* Skip also over DW_TAG_inlined_subroutine.  */
13937       for (func_die = die->parent;
13938            func_die && func_die->tag != DW_TAG_subprogram
13939            && func_die->tag != DW_TAG_subroutine_type;
13940            func_die = func_die->parent);
13941
13942       /* DW_AT_call_all_calls is a superset
13943          of DW_AT_call_all_tail_calls.  */
13944       if (func_die
13945           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13946           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13947           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13948           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13949         {
13950           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13951              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13952              both the initial caller containing the real return address PC and
13953              the final callee containing the current PC of a chain of tail
13954              calls do not need to have the tail call list complete.  But any
13955              function candidate for a virtual tail call frame searched via
13956              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13957              determined unambiguously.  */
13958         }
13959       else
13960         {
13961           struct type *func_type = NULL;
13962
13963           if (func_die)
13964             func_type = get_die_type (func_die, cu);
13965           if (func_type != NULL)
13966             {
13967               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13968
13969               /* Enlist this call site to the function.  */
13970               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13971               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13972             }
13973           else
13974             complaint (&symfile_complaints,
13975                        _("Cannot find function owning DW_TAG_call_site "
13976                          "DIE %s [in module %s]"),
13977                        sect_offset_str (die->sect_off), objfile_name (objfile));
13978         }
13979     }
13980
13981   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13982   if (attr == NULL)
13983     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13984   if (attr == NULL)
13985     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13986   if (attr == NULL)
13987     {
13988       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13989       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13990     }
13991   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13992   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13993     /* Keep NULL DWARF_BLOCK.  */;
13994   else if (attr_form_is_block (attr))
13995     {
13996       struct dwarf2_locexpr_baton *dlbaton;
13997
13998       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13999       dlbaton->data = DW_BLOCK (attr)->data;
14000       dlbaton->size = DW_BLOCK (attr)->size;
14001       dlbaton->per_cu = cu->per_cu;
14002
14003       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14004     }
14005   else if (attr_form_is_ref (attr))
14006     {
14007       struct dwarf2_cu *target_cu = cu;
14008       struct die_info *target_die;
14009
14010       target_die = follow_die_ref (die, attr, &target_cu);
14011       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14012       if (die_is_declaration (target_die, target_cu))
14013         {
14014           const char *target_physname;
14015
14016           /* Prefer the mangled name; otherwise compute the demangled one.  */
14017           target_physname = dw2_linkage_name (target_die, target_cu);
14018           if (target_physname == NULL)
14019             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14020           if (target_physname == NULL)
14021             complaint (&symfile_complaints,
14022                        _("DW_AT_call_target target DIE has invalid "
14023                          "physname, for referencing DIE %s [in module %s]"),
14024                        sect_offset_str (die->sect_off), objfile_name (objfile));
14025           else
14026             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14027         }
14028       else
14029         {
14030           CORE_ADDR lowpc;
14031
14032           /* DW_AT_entry_pc should be preferred.  */
14033           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14034               <= PC_BOUNDS_INVALID)
14035             complaint (&symfile_complaints,
14036                        _("DW_AT_call_target target DIE has invalid "
14037                          "low pc, for referencing DIE %s [in module %s]"),
14038                        sect_offset_str (die->sect_off), objfile_name (objfile));
14039           else
14040             {
14041               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14042               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14043             }
14044         }
14045     }
14046   else
14047     complaint (&symfile_complaints,
14048                _("DW_TAG_call_site DW_AT_call_target is neither "
14049                  "block nor reference, for DIE %s [in module %s]"),
14050                sect_offset_str (die->sect_off), objfile_name (objfile));
14051
14052   call_site->per_cu = cu->per_cu;
14053
14054   for (child_die = die->child;
14055        child_die && child_die->tag;
14056        child_die = sibling_die (child_die))
14057     {
14058       struct call_site_parameter *parameter;
14059       struct attribute *loc, *origin;
14060
14061       if (child_die->tag != DW_TAG_call_site_parameter
14062           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14063         {
14064           /* Already printed the complaint above.  */
14065           continue;
14066         }
14067
14068       gdb_assert (call_site->parameter_count < nparams);
14069       parameter = &call_site->parameter[call_site->parameter_count];
14070
14071       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14072          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14073          register is contained in DW_AT_call_value.  */
14074
14075       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14076       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14077       if (origin == NULL)
14078         {
14079           /* This was a pre-DWARF-5 GNU extension alias
14080              for DW_AT_call_parameter.  */
14081           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14082         }
14083       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14084         {
14085           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14086
14087           sect_offset sect_off
14088             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14089           if (!offset_in_cu_p (&cu->header, sect_off))
14090             {
14091               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14092                  binding can be done only inside one CU.  Such referenced DIE
14093                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14094               complaint (&symfile_complaints,
14095                          _("DW_AT_call_parameter offset is not in CU for "
14096                            "DW_TAG_call_site child DIE %s [in module %s]"),
14097                          sect_offset_str (child_die->sect_off),
14098                          objfile_name (objfile));
14099               continue;
14100             }
14101           parameter->u.param_cu_off
14102             = (cu_offset) (sect_off - cu->header.sect_off);
14103         }
14104       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14105         {
14106           complaint (&symfile_complaints,
14107                      _("No DW_FORM_block* DW_AT_location for "
14108                        "DW_TAG_call_site child DIE %s [in module %s]"),
14109                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14110           continue;
14111         }
14112       else
14113         {
14114           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14115             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14116           if (parameter->u.dwarf_reg != -1)
14117             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14118           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14119                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14120                                              &parameter->u.fb_offset))
14121             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14122           else
14123             {
14124               complaint (&symfile_complaints,
14125                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14126                            "for DW_FORM_block* DW_AT_location is supported for "
14127                            "DW_TAG_call_site child DIE %s "
14128                            "[in module %s]"),
14129                          sect_offset_str (child_die->sect_off),
14130                          objfile_name (objfile));
14131               continue;
14132             }
14133         }
14134
14135       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14136       if (attr == NULL)
14137         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14138       if (!attr_form_is_block (attr))
14139         {
14140           complaint (&symfile_complaints,
14141                      _("No DW_FORM_block* DW_AT_call_value for "
14142                        "DW_TAG_call_site child DIE %s [in module %s]"),
14143                      sect_offset_str (child_die->sect_off),
14144                      objfile_name (objfile));
14145           continue;
14146         }
14147       parameter->value = DW_BLOCK (attr)->data;
14148       parameter->value_size = DW_BLOCK (attr)->size;
14149
14150       /* Parameters are not pre-cleared by memset above.  */
14151       parameter->data_value = NULL;
14152       parameter->data_value_size = 0;
14153       call_site->parameter_count++;
14154
14155       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14156       if (attr == NULL)
14157         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14158       if (attr)
14159         {
14160           if (!attr_form_is_block (attr))
14161             complaint (&symfile_complaints,
14162                        _("No DW_FORM_block* DW_AT_call_data_value 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           else
14167             {
14168               parameter->data_value = DW_BLOCK (attr)->data;
14169               parameter->data_value_size = DW_BLOCK (attr)->size;
14170             }
14171         }
14172     }
14173 }
14174
14175 /* Helper function for read_variable.  If DIE represents a virtual
14176    table, then return the type of the concrete object that is
14177    associated with the virtual table.  Otherwise, return NULL.  */
14178
14179 static struct type *
14180 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14181 {
14182   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14183   if (attr == NULL)
14184     return NULL;
14185
14186   /* Find the type DIE.  */
14187   struct die_info *type_die = NULL;
14188   struct dwarf2_cu *type_cu = cu;
14189
14190   if (attr_form_is_ref (attr))
14191     type_die = follow_die_ref (die, attr, &type_cu);
14192   if (type_die == NULL)
14193     return NULL;
14194
14195   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14196     return NULL;
14197   return die_containing_type (type_die, type_cu);
14198 }
14199
14200 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14201
14202 static void
14203 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14204 {
14205   struct rust_vtable_symbol *storage = NULL;
14206
14207   if (cu->language == language_rust)
14208     {
14209       struct type *containing_type = rust_containing_type (die, cu);
14210
14211       if (containing_type != NULL)
14212         {
14213           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14214
14215           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14216                                     struct rust_vtable_symbol);
14217           initialize_objfile_symbol (storage);
14218           storage->concrete_type = containing_type;
14219           storage->subclass = SYMBOL_RUST_VTABLE;
14220         }
14221     }
14222
14223   new_symbol (die, NULL, cu, storage);
14224 }
14225
14226 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14227    reading .debug_rnglists.
14228    Callback's type should be:
14229     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14230    Return true if the attributes are present and valid, otherwise,
14231    return false.  */
14232
14233 template <typename Callback>
14234 static bool
14235 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14236                          Callback &&callback)
14237 {
14238   struct dwarf2_per_objfile *dwarf2_per_objfile
14239     = cu->per_cu->dwarf2_per_objfile;
14240   struct objfile *objfile = dwarf2_per_objfile->objfile;
14241   bfd *obfd = objfile->obfd;
14242   /* Base address selection entry.  */
14243   CORE_ADDR base;
14244   int found_base;
14245   const gdb_byte *buffer;
14246   CORE_ADDR baseaddr;
14247   bool overflow = false;
14248
14249   found_base = cu->base_known;
14250   base = cu->base_address;
14251
14252   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14253   if (offset >= dwarf2_per_objfile->rnglists.size)
14254     {
14255       complaint (&symfile_complaints,
14256                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14257                  offset);
14258       return false;
14259     }
14260   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14261
14262   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14263
14264   while (1)
14265     {
14266       /* Initialize it due to a false compiler warning.  */
14267       CORE_ADDR range_beginning = 0, range_end = 0;
14268       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14269                                  + dwarf2_per_objfile->rnglists.size);
14270       unsigned int bytes_read;
14271
14272       if (buffer == buf_end)
14273         {
14274           overflow = true;
14275           break;
14276         }
14277       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14278       switch (rlet)
14279         {
14280         case DW_RLE_end_of_list:
14281           break;
14282         case DW_RLE_base_address:
14283           if (buffer + cu->header.addr_size > buf_end)
14284             {
14285               overflow = true;
14286               break;
14287             }
14288           base = read_address (obfd, buffer, cu, &bytes_read);
14289           found_base = 1;
14290           buffer += bytes_read;
14291           break;
14292         case DW_RLE_start_length:
14293           if (buffer + cu->header.addr_size > buf_end)
14294             {
14295               overflow = true;
14296               break;
14297             }
14298           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14299           buffer += bytes_read;
14300           range_end = (range_beginning
14301                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14302           buffer += bytes_read;
14303           if (buffer > buf_end)
14304             {
14305               overflow = true;
14306               break;
14307             }
14308           break;
14309         case DW_RLE_offset_pair:
14310           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14311           buffer += bytes_read;
14312           if (buffer > buf_end)
14313             {
14314               overflow = true;
14315               break;
14316             }
14317           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14318           buffer += bytes_read;
14319           if (buffer > buf_end)
14320             {
14321               overflow = true;
14322               break;
14323             }
14324           break;
14325         case DW_RLE_start_end:
14326           if (buffer + 2 * cu->header.addr_size > buf_end)
14327             {
14328               overflow = true;
14329               break;
14330             }
14331           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14332           buffer += bytes_read;
14333           range_end = read_address (obfd, buffer, cu, &bytes_read);
14334           buffer += bytes_read;
14335           break;
14336         default:
14337           complaint (&symfile_complaints,
14338                      _("Invalid .debug_rnglists data (no base address)"));
14339           return false;
14340         }
14341       if (rlet == DW_RLE_end_of_list || overflow)
14342         break;
14343       if (rlet == DW_RLE_base_address)
14344         continue;
14345
14346       if (!found_base)
14347         {
14348           /* We have no valid base address for the ranges
14349              data.  */
14350           complaint (&symfile_complaints,
14351                      _("Invalid .debug_rnglists data (no base address)"));
14352           return false;
14353         }
14354
14355       if (range_beginning > range_end)
14356         {
14357           /* Inverted range entries are invalid.  */
14358           complaint (&symfile_complaints,
14359                      _("Invalid .debug_rnglists data (inverted range)"));
14360           return false;
14361         }
14362
14363       /* Empty range entries have no effect.  */
14364       if (range_beginning == range_end)
14365         continue;
14366
14367       range_beginning += base;
14368       range_end += base;
14369
14370       /* A not-uncommon case of bad debug info.
14371          Don't pollute the addrmap with bad data.  */
14372       if (range_beginning + baseaddr == 0
14373           && !dwarf2_per_objfile->has_section_at_zero)
14374         {
14375           complaint (&symfile_complaints,
14376                      _(".debug_rnglists entry has start address of zero"
14377                        " [in module %s]"), objfile_name (objfile));
14378           continue;
14379         }
14380
14381       callback (range_beginning, range_end);
14382     }
14383
14384   if (overflow)
14385     {
14386       complaint (&symfile_complaints,
14387                  _("Offset %d is not terminated "
14388                    "for DW_AT_ranges attribute"),
14389                  offset);
14390       return false;
14391     }
14392
14393   return true;
14394 }
14395
14396 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14397    Callback's type should be:
14398     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14399    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14400
14401 template <typename Callback>
14402 static int
14403 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14404                        Callback &&callback)
14405 {
14406   struct dwarf2_per_objfile *dwarf2_per_objfile
14407       = cu->per_cu->dwarf2_per_objfile;
14408   struct objfile *objfile = dwarf2_per_objfile->objfile;
14409   struct comp_unit_head *cu_header = &cu->header;
14410   bfd *obfd = objfile->obfd;
14411   unsigned int addr_size = cu_header->addr_size;
14412   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14413   /* Base address selection entry.  */
14414   CORE_ADDR base;
14415   int found_base;
14416   unsigned int dummy;
14417   const gdb_byte *buffer;
14418   CORE_ADDR baseaddr;
14419
14420   if (cu_header->version >= 5)
14421     return dwarf2_rnglists_process (offset, cu, callback);
14422
14423   found_base = cu->base_known;
14424   base = cu->base_address;
14425
14426   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14427   if (offset >= dwarf2_per_objfile->ranges.size)
14428     {
14429       complaint (&symfile_complaints,
14430                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14431                  offset);
14432       return 0;
14433     }
14434   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14435
14436   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14437
14438   while (1)
14439     {
14440       CORE_ADDR range_beginning, range_end;
14441
14442       range_beginning = read_address (obfd, buffer, cu, &dummy);
14443       buffer += addr_size;
14444       range_end = read_address (obfd, buffer, cu, &dummy);
14445       buffer += addr_size;
14446       offset += 2 * addr_size;
14447
14448       /* An end of list marker is a pair of zero addresses.  */
14449       if (range_beginning == 0 && range_end == 0)
14450         /* Found the end of list entry.  */
14451         break;
14452
14453       /* Each base address selection entry is a pair of 2 values.
14454          The first is the largest possible address, the second is
14455          the base address.  Check for a base address here.  */
14456       if ((range_beginning & mask) == mask)
14457         {
14458           /* If we found the largest possible address, then we already
14459              have the base address in range_end.  */
14460           base = range_end;
14461           found_base = 1;
14462           continue;
14463         }
14464
14465       if (!found_base)
14466         {
14467           /* We have no valid base address for the ranges
14468              data.  */
14469           complaint (&symfile_complaints,
14470                      _("Invalid .debug_ranges data (no base address)"));
14471           return 0;
14472         }
14473
14474       if (range_beginning > range_end)
14475         {
14476           /* Inverted range entries are invalid.  */
14477           complaint (&symfile_complaints,
14478                      _("Invalid .debug_ranges data (inverted range)"));
14479           return 0;
14480         }
14481
14482       /* Empty range entries have no effect.  */
14483       if (range_beginning == range_end)
14484         continue;
14485
14486       range_beginning += base;
14487       range_end += base;
14488
14489       /* A not-uncommon case of bad debug info.
14490          Don't pollute the addrmap with bad data.  */
14491       if (range_beginning + baseaddr == 0
14492           && !dwarf2_per_objfile->has_section_at_zero)
14493         {
14494           complaint (&symfile_complaints,
14495                      _(".debug_ranges entry has start address of zero"
14496                        " [in module %s]"), objfile_name (objfile));
14497           continue;
14498         }
14499
14500       callback (range_beginning, range_end);
14501     }
14502
14503   return 1;
14504 }
14505
14506 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14507    Return 1 if the attributes are present and valid, otherwise, return 0.
14508    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14509
14510 static int
14511 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14512                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14513                     struct partial_symtab *ranges_pst)
14514 {
14515   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14516   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14517   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14518                                        SECT_OFF_TEXT (objfile));
14519   int low_set = 0;
14520   CORE_ADDR low = 0;
14521   CORE_ADDR high = 0;
14522   int retval;
14523
14524   retval = dwarf2_ranges_process (offset, cu,
14525     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14526     {
14527       if (ranges_pst != NULL)
14528         {
14529           CORE_ADDR lowpc;
14530           CORE_ADDR highpc;
14531
14532           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14533                                               range_beginning + baseaddr);
14534           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14535                                                range_end + baseaddr);
14536           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14537                              ranges_pst);
14538         }
14539
14540       /* FIXME: This is recording everything as a low-high
14541          segment of consecutive addresses.  We should have a
14542          data structure for discontiguous block ranges
14543          instead.  */
14544       if (! low_set)
14545         {
14546           low = range_beginning;
14547           high = range_end;
14548           low_set = 1;
14549         }
14550       else
14551         {
14552           if (range_beginning < low)
14553             low = range_beginning;
14554           if (range_end > high)
14555             high = range_end;
14556         }
14557     });
14558   if (!retval)
14559     return 0;
14560
14561   if (! low_set)
14562     /* If the first entry is an end-of-list marker, the range
14563        describes an empty scope, i.e. no instructions.  */
14564     return 0;
14565
14566   if (low_return)
14567     *low_return = low;
14568   if (high_return)
14569     *high_return = high;
14570   return 1;
14571 }
14572
14573 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14574    definition for the return value.  *LOWPC and *HIGHPC are set iff
14575    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14576
14577 static enum pc_bounds_kind
14578 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14579                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14580                       struct partial_symtab *pst)
14581 {
14582   struct dwarf2_per_objfile *dwarf2_per_objfile
14583     = cu->per_cu->dwarf2_per_objfile;
14584   struct attribute *attr;
14585   struct attribute *attr_high;
14586   CORE_ADDR low = 0;
14587   CORE_ADDR high = 0;
14588   enum pc_bounds_kind ret;
14589
14590   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14591   if (attr_high)
14592     {
14593       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14594       if (attr)
14595         {
14596           low = attr_value_as_address (attr);
14597           high = attr_value_as_address (attr_high);
14598           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14599             high += low;
14600         }
14601       else
14602         /* Found high w/o low attribute.  */
14603         return PC_BOUNDS_INVALID;
14604
14605       /* Found consecutive range of addresses.  */
14606       ret = PC_BOUNDS_HIGH_LOW;
14607     }
14608   else
14609     {
14610       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14611       if (attr != NULL)
14612         {
14613           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14614              We take advantage of the fact that DW_AT_ranges does not appear
14615              in DW_TAG_compile_unit of DWO files.  */
14616           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14617           unsigned int ranges_offset = (DW_UNSND (attr)
14618                                         + (need_ranges_base
14619                                            ? cu->ranges_base
14620                                            : 0));
14621
14622           /* Value of the DW_AT_ranges attribute is the offset in the
14623              .debug_ranges section.  */
14624           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14625             return PC_BOUNDS_INVALID;
14626           /* Found discontinuous range of addresses.  */
14627           ret = PC_BOUNDS_RANGES;
14628         }
14629       else
14630         return PC_BOUNDS_NOT_PRESENT;
14631     }
14632
14633   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14634   if (high <= low)
14635     return PC_BOUNDS_INVALID;
14636
14637   /* When using the GNU linker, .gnu.linkonce. sections are used to
14638      eliminate duplicate copies of functions and vtables and such.
14639      The linker will arbitrarily choose one and discard the others.
14640      The AT_*_pc values for such functions refer to local labels in
14641      these sections.  If the section from that file was discarded, the
14642      labels are not in the output, so the relocs get a value of 0.
14643      If this is a discarded function, mark the pc bounds as invalid,
14644      so that GDB will ignore it.  */
14645   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14646     return PC_BOUNDS_INVALID;
14647
14648   *lowpc = low;
14649   if (highpc)
14650     *highpc = high;
14651   return ret;
14652 }
14653
14654 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14655    its low and high PC addresses.  Do nothing if these addresses could not
14656    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14657    and HIGHPC to the high address if greater than HIGHPC.  */
14658
14659 static void
14660 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14661                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14662                                  struct dwarf2_cu *cu)
14663 {
14664   CORE_ADDR low, high;
14665   struct die_info *child = die->child;
14666
14667   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14668     {
14669       *lowpc = std::min (*lowpc, low);
14670       *highpc = std::max (*highpc, high);
14671     }
14672
14673   /* If the language does not allow nested subprograms (either inside
14674      subprograms or lexical blocks), we're done.  */
14675   if (cu->language != language_ada)
14676     return;
14677
14678   /* Check all the children of the given DIE.  If it contains nested
14679      subprograms, then check their pc bounds.  Likewise, we need to
14680      check lexical blocks as well, as they may also contain subprogram
14681      definitions.  */
14682   while (child && child->tag)
14683     {
14684       if (child->tag == DW_TAG_subprogram
14685           || child->tag == DW_TAG_lexical_block)
14686         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14687       child = sibling_die (child);
14688     }
14689 }
14690
14691 /* Get the low and high pc's represented by the scope DIE, and store
14692    them in *LOWPC and *HIGHPC.  If the correct values can't be
14693    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14694
14695 static void
14696 get_scope_pc_bounds (struct die_info *die,
14697                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14698                      struct dwarf2_cu *cu)
14699 {
14700   CORE_ADDR best_low = (CORE_ADDR) -1;
14701   CORE_ADDR best_high = (CORE_ADDR) 0;
14702   CORE_ADDR current_low, current_high;
14703
14704   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14705       >= PC_BOUNDS_RANGES)
14706     {
14707       best_low = current_low;
14708       best_high = current_high;
14709     }
14710   else
14711     {
14712       struct die_info *child = die->child;
14713
14714       while (child && child->tag)
14715         {
14716           switch (child->tag) {
14717           case DW_TAG_subprogram:
14718             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14719             break;
14720           case DW_TAG_namespace:
14721           case DW_TAG_module:
14722             /* FIXME: carlton/2004-01-16: Should we do this for
14723                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14724                that current GCC's always emit the DIEs corresponding
14725                to definitions of methods of classes as children of a
14726                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14727                the DIEs giving the declarations, which could be
14728                anywhere).  But I don't see any reason why the
14729                standards says that they have to be there.  */
14730             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14731
14732             if (current_low != ((CORE_ADDR) -1))
14733               {
14734                 best_low = std::min (best_low, current_low);
14735                 best_high = std::max (best_high, current_high);
14736               }
14737             break;
14738           default:
14739             /* Ignore.  */
14740             break;
14741           }
14742
14743           child = sibling_die (child);
14744         }
14745     }
14746
14747   *lowpc = best_low;
14748   *highpc = best_high;
14749 }
14750
14751 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14752    in DIE.  */
14753
14754 static void
14755 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14756                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14757 {
14758   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14759   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14760   struct attribute *attr;
14761   struct attribute *attr_high;
14762
14763   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14764   if (attr_high)
14765     {
14766       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14767       if (attr)
14768         {
14769           CORE_ADDR low = attr_value_as_address (attr);
14770           CORE_ADDR high = attr_value_as_address (attr_high);
14771
14772           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14773             high += low;
14774
14775           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14776           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14777           record_block_range (block, low, high - 1);
14778         }
14779     }
14780
14781   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14782   if (attr)
14783     {
14784       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14785          We take advantage of the fact that DW_AT_ranges does not appear
14786          in DW_TAG_compile_unit of DWO files.  */
14787       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14788
14789       /* The value of the DW_AT_ranges attribute is the offset of the
14790          address range list in the .debug_ranges section.  */
14791       unsigned long offset = (DW_UNSND (attr)
14792                               + (need_ranges_base ? cu->ranges_base : 0));
14793
14794       dwarf2_ranges_process (offset, cu,
14795         [&] (CORE_ADDR start, CORE_ADDR end)
14796         {
14797           start += baseaddr;
14798           end += baseaddr;
14799           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14800           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14801           record_block_range (block, start, end - 1);
14802         });
14803     }
14804 }
14805
14806 /* Check whether the producer field indicates either of GCC < 4.6, or the
14807    Intel C/C++ compiler, and cache the result in CU.  */
14808
14809 static void
14810 check_producer (struct dwarf2_cu *cu)
14811 {
14812   int major, minor;
14813
14814   if (cu->producer == NULL)
14815     {
14816       /* For unknown compilers expect their behavior is DWARF version
14817          compliant.
14818
14819          GCC started to support .debug_types sections by -gdwarf-4 since
14820          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14821          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14822          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14823          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14824     }
14825   else if (producer_is_gcc (cu->producer, &major, &minor))
14826     {
14827       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14828       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14829     }
14830   else if (producer_is_icc (cu->producer, &major, &minor))
14831     cu->producer_is_icc_lt_14 = major < 14;
14832   else
14833     {
14834       /* For other non-GCC compilers, expect their behavior is DWARF version
14835          compliant.  */
14836     }
14837
14838   cu->checked_producer = 1;
14839 }
14840
14841 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14842    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14843    during 4.6.0 experimental.  */
14844
14845 static int
14846 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14847 {
14848   if (!cu->checked_producer)
14849     check_producer (cu);
14850
14851   return cu->producer_is_gxx_lt_4_6;
14852 }
14853
14854 /* Return the default accessibility type if it is not overriden by
14855    DW_AT_accessibility.  */
14856
14857 static enum dwarf_access_attribute
14858 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14859 {
14860   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14861     {
14862       /* The default DWARF 2 accessibility for members is public, the default
14863          accessibility for inheritance is private.  */
14864
14865       if (die->tag != DW_TAG_inheritance)
14866         return DW_ACCESS_public;
14867       else
14868         return DW_ACCESS_private;
14869     }
14870   else
14871     {
14872       /* DWARF 3+ defines the default accessibility a different way.  The same
14873          rules apply now for DW_TAG_inheritance as for the members and it only
14874          depends on the container kind.  */
14875
14876       if (die->parent->tag == DW_TAG_class_type)
14877         return DW_ACCESS_private;
14878       else
14879         return DW_ACCESS_public;
14880     }
14881 }
14882
14883 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14884    offset.  If the attribute was not found return 0, otherwise return
14885    1.  If it was found but could not properly be handled, set *OFFSET
14886    to 0.  */
14887
14888 static int
14889 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14890                              LONGEST *offset)
14891 {
14892   struct attribute *attr;
14893
14894   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14895   if (attr != NULL)
14896     {
14897       *offset = 0;
14898
14899       /* Note that we do not check for a section offset first here.
14900          This is because DW_AT_data_member_location is new in DWARF 4,
14901          so if we see it, we can assume that a constant form is really
14902          a constant and not a section offset.  */
14903       if (attr_form_is_constant (attr))
14904         *offset = dwarf2_get_attr_constant_value (attr, 0);
14905       else if (attr_form_is_section_offset (attr))
14906         dwarf2_complex_location_expr_complaint ();
14907       else if (attr_form_is_block (attr))
14908         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14909       else
14910         dwarf2_complex_location_expr_complaint ();
14911
14912       return 1;
14913     }
14914
14915   return 0;
14916 }
14917
14918 /* Add an aggregate field to the field list.  */
14919
14920 static void
14921 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14922                   struct dwarf2_cu *cu)
14923 {
14924   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14925   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14926   struct nextfield *new_field;
14927   struct attribute *attr;
14928   struct field *fp;
14929   const char *fieldname = "";
14930
14931   if (die->tag == DW_TAG_inheritance)
14932     {
14933       fip->baseclasses.emplace_back ();
14934       new_field = &fip->baseclasses.back ();
14935     }
14936   else
14937     {
14938       fip->fields.emplace_back ();
14939       new_field = &fip->fields.back ();
14940     }
14941
14942   fip->nfields++;
14943
14944   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14945   if (attr)
14946     new_field->accessibility = DW_UNSND (attr);
14947   else
14948     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14949   if (new_field->accessibility != DW_ACCESS_public)
14950     fip->non_public_fields = 1;
14951
14952   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14953   if (attr)
14954     new_field->virtuality = DW_UNSND (attr);
14955   else
14956     new_field->virtuality = DW_VIRTUALITY_none;
14957
14958   fp = &new_field->field;
14959
14960   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14961     {
14962       LONGEST offset;
14963
14964       /* Data member other than a C++ static data member.  */
14965
14966       /* Get type of field.  */
14967       fp->type = die_type (die, cu);
14968
14969       SET_FIELD_BITPOS (*fp, 0);
14970
14971       /* Get bit size of field (zero if none).  */
14972       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14973       if (attr)
14974         {
14975           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14976         }
14977       else
14978         {
14979           FIELD_BITSIZE (*fp) = 0;
14980         }
14981
14982       /* Get bit offset of field.  */
14983       if (handle_data_member_location (die, cu, &offset))
14984         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14985       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14986       if (attr)
14987         {
14988           if (gdbarch_bits_big_endian (gdbarch))
14989             {
14990               /* For big endian bits, the DW_AT_bit_offset gives the
14991                  additional bit offset from the MSB of the containing
14992                  anonymous object to the MSB of the field.  We don't
14993                  have to do anything special since we don't need to
14994                  know the size of the anonymous object.  */
14995               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14996             }
14997           else
14998             {
14999               /* For little endian bits, compute the bit offset to the
15000                  MSB of the anonymous object, subtract off the number of
15001                  bits from the MSB of the field to the MSB of the
15002                  object, and then subtract off the number of bits of
15003                  the field itself.  The result is the bit offset of
15004                  the LSB of the field.  */
15005               int anonymous_size;
15006               int bit_offset = DW_UNSND (attr);
15007
15008               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15009               if (attr)
15010                 {
15011                   /* The size of the anonymous object containing
15012                      the bit field is explicit, so use the
15013                      indicated size (in bytes).  */
15014                   anonymous_size = DW_UNSND (attr);
15015                 }
15016               else
15017                 {
15018                   /* The size of the anonymous object containing
15019                      the bit field must be inferred from the type
15020                      attribute of the data member containing the
15021                      bit field.  */
15022                   anonymous_size = TYPE_LENGTH (fp->type);
15023                 }
15024               SET_FIELD_BITPOS (*fp,
15025                                 (FIELD_BITPOS (*fp)
15026                                  + anonymous_size * bits_per_byte
15027                                  - bit_offset - FIELD_BITSIZE (*fp)));
15028             }
15029         }
15030       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15031       if (attr != NULL)
15032         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15033                                 + dwarf2_get_attr_constant_value (attr, 0)));
15034
15035       /* Get name of field.  */
15036       fieldname = dwarf2_name (die, cu);
15037       if (fieldname == NULL)
15038         fieldname = "";
15039
15040       /* The name is already allocated along with this objfile, so we don't
15041          need to duplicate it for the type.  */
15042       fp->name = fieldname;
15043
15044       /* Change accessibility for artificial fields (e.g. virtual table
15045          pointer or virtual base class pointer) to private.  */
15046       if (dwarf2_attr (die, DW_AT_artificial, cu))
15047         {
15048           FIELD_ARTIFICIAL (*fp) = 1;
15049           new_field->accessibility = DW_ACCESS_private;
15050           fip->non_public_fields = 1;
15051         }
15052     }
15053   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15054     {
15055       /* C++ static member.  */
15056
15057       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15058          is a declaration, but all versions of G++ as of this writing
15059          (so through at least 3.2.1) incorrectly generate
15060          DW_TAG_variable tags.  */
15061
15062       const char *physname;
15063
15064       /* Get name of field.  */
15065       fieldname = dwarf2_name (die, cu);
15066       if (fieldname == NULL)
15067         return;
15068
15069       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15070       if (attr
15071           /* Only create a symbol if this is an external value.
15072              new_symbol checks this and puts the value in the global symbol
15073              table, which we want.  If it is not external, new_symbol
15074              will try to put the value in cu->list_in_scope which is wrong.  */
15075           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15076         {
15077           /* A static const member, not much different than an enum as far as
15078              we're concerned, except that we can support more types.  */
15079           new_symbol (die, NULL, cu);
15080         }
15081
15082       /* Get physical name.  */
15083       physname = dwarf2_physname (fieldname, die, cu);
15084
15085       /* The name is already allocated along with this objfile, so we don't
15086          need to duplicate it for the type.  */
15087       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15088       FIELD_TYPE (*fp) = die_type (die, cu);
15089       FIELD_NAME (*fp) = fieldname;
15090     }
15091   else if (die->tag == DW_TAG_inheritance)
15092     {
15093       LONGEST offset;
15094
15095       /* C++ base class field.  */
15096       if (handle_data_member_location (die, cu, &offset))
15097         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15098       FIELD_BITSIZE (*fp) = 0;
15099       FIELD_TYPE (*fp) = die_type (die, cu);
15100       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15101     }
15102   else if (die->tag == DW_TAG_variant_part)
15103     {
15104       /* process_structure_scope will treat this DIE as a union.  */
15105       process_structure_scope (die, cu);
15106
15107       /* The variant part is relative to the start of the enclosing
15108          structure.  */
15109       SET_FIELD_BITPOS (*fp, 0);
15110       fp->type = get_die_type (die, cu);
15111       fp->artificial = 1;
15112       fp->name = "<<variant>>";
15113     }
15114   else
15115     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15116 }
15117
15118 /* Can the type given by DIE define another type?  */
15119
15120 static bool
15121 type_can_define_types (const struct die_info *die)
15122 {
15123   switch (die->tag)
15124     {
15125     case DW_TAG_typedef:
15126     case DW_TAG_class_type:
15127     case DW_TAG_structure_type:
15128     case DW_TAG_union_type:
15129     case DW_TAG_enumeration_type:
15130       return true;
15131
15132     default:
15133       return false;
15134     }
15135 }
15136
15137 /* Add a type definition defined in the scope of the FIP's class.  */
15138
15139 static void
15140 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15141                       struct dwarf2_cu *cu)
15142 {
15143   struct decl_field fp;
15144   memset (&fp, 0, sizeof (fp));
15145
15146   gdb_assert (type_can_define_types (die));
15147
15148   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15149   fp.name = dwarf2_name (die, cu);
15150   fp.type = read_type_die (die, cu);
15151
15152   /* Save accessibility.  */
15153   enum dwarf_access_attribute accessibility;
15154   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15155   if (attr != NULL)
15156     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15157   else
15158     accessibility = dwarf2_default_access_attribute (die, cu);
15159   switch (accessibility)
15160     {
15161     case DW_ACCESS_public:
15162       /* The assumed value if neither private nor protected.  */
15163       break;
15164     case DW_ACCESS_private:
15165       fp.is_private = 1;
15166       break;
15167     case DW_ACCESS_protected:
15168       fp.is_protected = 1;
15169       break;
15170     default:
15171       complaint (&symfile_complaints,
15172                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15173     }
15174
15175   if (die->tag == DW_TAG_typedef)
15176     fip->typedef_field_list.push_back (fp);
15177   else
15178     fip->nested_types_list.push_back (fp);
15179 }
15180
15181 /* Create the vector of fields, and attach it to the type.  */
15182
15183 static void
15184 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15185                               struct dwarf2_cu *cu)
15186 {
15187   int nfields = fip->nfields;
15188
15189   /* Record the field count, allocate space for the array of fields,
15190      and create blank accessibility bitfields if necessary.  */
15191   TYPE_NFIELDS (type) = nfields;
15192   TYPE_FIELDS (type) = (struct field *)
15193     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15194
15195   if (fip->non_public_fields && cu->language != language_ada)
15196     {
15197       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15198
15199       TYPE_FIELD_PRIVATE_BITS (type) =
15200         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15201       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15202
15203       TYPE_FIELD_PROTECTED_BITS (type) =
15204         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15205       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15206
15207       TYPE_FIELD_IGNORE_BITS (type) =
15208         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15209       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15210     }
15211
15212   /* If the type has baseclasses, allocate and clear a bit vector for
15213      TYPE_FIELD_VIRTUAL_BITS.  */
15214   if (!fip->baseclasses.empty () && cu->language != language_ada)
15215     {
15216       int num_bytes = B_BYTES (fip->baseclasses.size ());
15217       unsigned char *pointer;
15218
15219       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15220       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15221       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15222       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15223       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15224     }
15225
15226   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15227     {
15228       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15229
15230       for (int index = 0; index < nfields; ++index)
15231         {
15232           struct nextfield &field = fip->fields[index];
15233
15234           if (field.variant.is_discriminant)
15235             di->discriminant_index = index;
15236           else if (field.variant.default_branch)
15237             di->default_index = index;
15238           else
15239             di->discriminants[index] = field.variant.discriminant_value;
15240         }
15241     }
15242
15243   /* Copy the saved-up fields into the field vector.  */
15244   for (int i = 0; i < nfields; ++i)
15245     {
15246       struct nextfield &field
15247         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15248            : fip->fields[i - fip->baseclasses.size ()]);
15249
15250       TYPE_FIELD (type, i) = field.field;
15251       switch (field.accessibility)
15252         {
15253         case DW_ACCESS_private:
15254           if (cu->language != language_ada)
15255             SET_TYPE_FIELD_PRIVATE (type, i);
15256           break;
15257
15258         case DW_ACCESS_protected:
15259           if (cu->language != language_ada)
15260             SET_TYPE_FIELD_PROTECTED (type, i);
15261           break;
15262
15263         case DW_ACCESS_public:
15264           break;
15265
15266         default:
15267           /* Unknown accessibility.  Complain and treat it as public.  */
15268           {
15269             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15270                        field.accessibility);
15271           }
15272           break;
15273         }
15274       if (i < fip->baseclasses.size ())
15275         {
15276           switch (field.virtuality)
15277             {
15278             case DW_VIRTUALITY_virtual:
15279             case DW_VIRTUALITY_pure_virtual:
15280               if (cu->language == language_ada)
15281                 error (_("unexpected virtuality in component of Ada type"));
15282               SET_TYPE_FIELD_VIRTUAL (type, i);
15283               break;
15284             }
15285         }
15286     }
15287 }
15288
15289 /* Return true if this member function is a constructor, false
15290    otherwise.  */
15291
15292 static int
15293 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15294 {
15295   const char *fieldname;
15296   const char *type_name;
15297   int len;
15298
15299   if (die->parent == NULL)
15300     return 0;
15301
15302   if (die->parent->tag != DW_TAG_structure_type
15303       && die->parent->tag != DW_TAG_union_type
15304       && die->parent->tag != DW_TAG_class_type)
15305     return 0;
15306
15307   fieldname = dwarf2_name (die, cu);
15308   type_name = dwarf2_name (die->parent, cu);
15309   if (fieldname == NULL || type_name == NULL)
15310     return 0;
15311
15312   len = strlen (fieldname);
15313   return (strncmp (fieldname, type_name, len) == 0
15314           && (type_name[len] == '\0' || type_name[len] == '<'));
15315 }
15316
15317 /* Add a member function to the proper fieldlist.  */
15318
15319 static void
15320 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15321                       struct type *type, struct dwarf2_cu *cu)
15322 {
15323   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15324   struct attribute *attr;
15325   int i;
15326   struct fnfieldlist *flp = nullptr;
15327   struct fn_field *fnp;
15328   const char *fieldname;
15329   struct type *this_type;
15330   enum dwarf_access_attribute accessibility;
15331
15332   if (cu->language == language_ada)
15333     error (_("unexpected member function in Ada type"));
15334
15335   /* Get name of member function.  */
15336   fieldname = dwarf2_name (die, cu);
15337   if (fieldname == NULL)
15338     return;
15339
15340   /* Look up member function name in fieldlist.  */
15341   for (i = 0; i < fip->fnfieldlists.size (); i++)
15342     {
15343       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15344         {
15345           flp = &fip->fnfieldlists[i];
15346           break;
15347         }
15348     }
15349
15350   /* Create a new fnfieldlist if necessary.  */
15351   if (flp == nullptr)
15352     {
15353       fip->fnfieldlists.emplace_back ();
15354       flp = &fip->fnfieldlists.back ();
15355       flp->name = fieldname;
15356       i = fip->fnfieldlists.size () - 1;
15357     }
15358
15359   /* Create a new member function field and add it to the vector of
15360      fnfieldlists.  */
15361   flp->fnfields.emplace_back ();
15362   fnp = &flp->fnfields.back ();
15363
15364   /* Delay processing of the physname until later.  */
15365   if (cu->language == language_cplus)
15366     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15367                         die, cu);
15368   else
15369     {
15370       const char *physname = dwarf2_physname (fieldname, die, cu);
15371       fnp->physname = physname ? physname : "";
15372     }
15373
15374   fnp->type = alloc_type (objfile);
15375   this_type = read_type_die (die, cu);
15376   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15377     {
15378       int nparams = TYPE_NFIELDS (this_type);
15379
15380       /* TYPE is the domain of this method, and THIS_TYPE is the type
15381            of the method itself (TYPE_CODE_METHOD).  */
15382       smash_to_method_type (fnp->type, type,
15383                             TYPE_TARGET_TYPE (this_type),
15384                             TYPE_FIELDS (this_type),
15385                             TYPE_NFIELDS (this_type),
15386                             TYPE_VARARGS (this_type));
15387
15388       /* Handle static member functions.
15389          Dwarf2 has no clean way to discern C++ static and non-static
15390          member functions.  G++ helps GDB by marking the first
15391          parameter for non-static member functions (which is the this
15392          pointer) as artificial.  We obtain this information from
15393          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15394       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15395         fnp->voffset = VOFFSET_STATIC;
15396     }
15397   else
15398     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15399                dwarf2_full_name (fieldname, die, cu));
15400
15401   /* Get fcontext from DW_AT_containing_type if present.  */
15402   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15403     fnp->fcontext = die_containing_type (die, cu);
15404
15405   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15406      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15407
15408   /* Get accessibility.  */
15409   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15410   if (attr)
15411     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15412   else
15413     accessibility = dwarf2_default_access_attribute (die, cu);
15414   switch (accessibility)
15415     {
15416     case DW_ACCESS_private:
15417       fnp->is_private = 1;
15418       break;
15419     case DW_ACCESS_protected:
15420       fnp->is_protected = 1;
15421       break;
15422     }
15423
15424   /* Check for artificial methods.  */
15425   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15426   if (attr && DW_UNSND (attr) != 0)
15427     fnp->is_artificial = 1;
15428
15429   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15430
15431   /* Get index in virtual function table if it is a virtual member
15432      function.  For older versions of GCC, this is an offset in the
15433      appropriate virtual table, as specified by DW_AT_containing_type.
15434      For everyone else, it is an expression to be evaluated relative
15435      to the object address.  */
15436
15437   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15438   if (attr)
15439     {
15440       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15441         {
15442           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15443             {
15444               /* Old-style GCC.  */
15445               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15446             }
15447           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15448                    || (DW_BLOCK (attr)->size > 1
15449                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15450                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15451             {
15452               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15453               if ((fnp->voffset % cu->header.addr_size) != 0)
15454                 dwarf2_complex_location_expr_complaint ();
15455               else
15456                 fnp->voffset /= cu->header.addr_size;
15457               fnp->voffset += 2;
15458             }
15459           else
15460             dwarf2_complex_location_expr_complaint ();
15461
15462           if (!fnp->fcontext)
15463             {
15464               /* If there is no `this' field and no DW_AT_containing_type,
15465                  we cannot actually find a base class context for the
15466                  vtable!  */
15467               if (TYPE_NFIELDS (this_type) == 0
15468                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15469                 {
15470                   complaint (&symfile_complaints,
15471                              _("cannot determine context for virtual member "
15472                                "function \"%s\" (offset %s)"),
15473                              fieldname, sect_offset_str (die->sect_off));
15474                 }
15475               else
15476                 {
15477                   fnp->fcontext
15478                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15479                 }
15480             }
15481         }
15482       else if (attr_form_is_section_offset (attr))
15483         {
15484           dwarf2_complex_location_expr_complaint ();
15485         }
15486       else
15487         {
15488           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15489                                                  fieldname);
15490         }
15491     }
15492   else
15493     {
15494       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15495       if (attr && DW_UNSND (attr))
15496         {
15497           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15498           complaint (&symfile_complaints,
15499                      _("Member function \"%s\" (offset %s) is virtual "
15500                        "but the vtable offset is not specified"),
15501                      fieldname, sect_offset_str (die->sect_off));
15502           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15503           TYPE_CPLUS_DYNAMIC (type) = 1;
15504         }
15505     }
15506 }
15507
15508 /* Create the vector of member function fields, and attach it to the type.  */
15509
15510 static void
15511 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15512                                  struct dwarf2_cu *cu)
15513 {
15514   if (cu->language == language_ada)
15515     error (_("unexpected member functions in Ada type"));
15516
15517   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15518   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15519     TYPE_ALLOC (type,
15520                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15521
15522   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15523     {
15524       struct fnfieldlist &nf = fip->fnfieldlists[i];
15525       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15526
15527       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15528       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15529       fn_flp->fn_fields = (struct fn_field *)
15530         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15531
15532       for (int k = 0; k < nf.fnfields.size (); ++k)
15533         fn_flp->fn_fields[k] = nf.fnfields[k];
15534     }
15535
15536   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15537 }
15538
15539 /* Returns non-zero if NAME is the name of a vtable member in CU's
15540    language, zero otherwise.  */
15541 static int
15542 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15543 {
15544   static const char vptr[] = "_vptr";
15545
15546   /* Look for the C++ form of the vtable.  */
15547   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15548     return 1;
15549
15550   return 0;
15551 }
15552
15553 /* GCC outputs unnamed structures that are really pointers to member
15554    functions, with the ABI-specified layout.  If TYPE describes
15555    such a structure, smash it into a member function type.
15556
15557    GCC shouldn't do this; it should just output pointer to member DIEs.
15558    This is GCC PR debug/28767.  */
15559
15560 static void
15561 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15562 {
15563   struct type *pfn_type, *self_type, *new_type;
15564
15565   /* Check for a structure with no name and two children.  */
15566   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15567     return;
15568
15569   /* Check for __pfn and __delta members.  */
15570   if (TYPE_FIELD_NAME (type, 0) == NULL
15571       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15572       || TYPE_FIELD_NAME (type, 1) == NULL
15573       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15574     return;
15575
15576   /* Find the type of the method.  */
15577   pfn_type = TYPE_FIELD_TYPE (type, 0);
15578   if (pfn_type == NULL
15579       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15580       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15581     return;
15582
15583   /* Look for the "this" argument.  */
15584   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15585   if (TYPE_NFIELDS (pfn_type) == 0
15586       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15587       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15588     return;
15589
15590   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15591   new_type = alloc_type (objfile);
15592   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15593                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15594                         TYPE_VARARGS (pfn_type));
15595   smash_to_methodptr_type (type, new_type);
15596 }
15597
15598 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15599    appropriate error checking and issuing complaints if there is a
15600    problem.  */
15601
15602 static ULONGEST
15603 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15604 {
15605   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15606
15607   if (attr == nullptr)
15608     return 0;
15609
15610   if (!attr_form_is_constant (attr))
15611     {
15612       complaint (&symfile_complaints,
15613                  _("DW_AT_alignment must have constant form"
15614                    " - DIE at %s [in module %s]"),
15615                  sect_offset_str (die->sect_off),
15616                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15617       return 0;
15618     }
15619
15620   ULONGEST align;
15621   if (attr->form == DW_FORM_sdata)
15622     {
15623       LONGEST val = DW_SND (attr);
15624       if (val < 0)
15625         {
15626           complaint (&symfile_complaints,
15627                      _("DW_AT_alignment value must not be negative"
15628                        " - DIE at %s [in module %s]"),
15629                      sect_offset_str (die->sect_off),
15630                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15631           return 0;
15632         }
15633       align = val;
15634     }
15635   else
15636     align = DW_UNSND (attr);
15637
15638   if (align == 0)
15639     {
15640       complaint (&symfile_complaints,
15641                  _("DW_AT_alignment value must not be zero"
15642                    " - DIE at %s [in module %s]"),
15643                  sect_offset_str (die->sect_off),
15644                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15645       return 0;
15646     }
15647   if ((align & (align - 1)) != 0)
15648     {
15649       complaint (&symfile_complaints,
15650                  _("DW_AT_alignment value must be a power of 2"
15651                    " - DIE at %s [in module %s]"),
15652                  sect_offset_str (die->sect_off),
15653                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15654       return 0;
15655     }
15656
15657   return align;
15658 }
15659
15660 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15661    the alignment for TYPE.  */
15662
15663 static void
15664 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15665                      struct type *type)
15666 {
15667   if (!set_type_align (type, get_alignment (cu, die)))
15668     complaint (&symfile_complaints,
15669                _("DW_AT_alignment value too large"
15670                  " - DIE at %s [in module %s]"),
15671                sect_offset_str (die->sect_off),
15672                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15673 }
15674
15675 /* Called when we find the DIE that starts a structure or union scope
15676    (definition) to create a type for the structure or union.  Fill in
15677    the type's name and general properties; the members will not be
15678    processed until process_structure_scope.  A symbol table entry for
15679    the type will also not be done until process_structure_scope (assuming
15680    the type has a name).
15681
15682    NOTE: we need to call these functions regardless of whether or not the
15683    DIE has a DW_AT_name attribute, since it might be an anonymous
15684    structure or union.  This gets the type entered into our set of
15685    user defined types.  */
15686
15687 static struct type *
15688 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15689 {
15690   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15691   struct type *type;
15692   struct attribute *attr;
15693   const char *name;
15694
15695   /* If the definition of this type lives in .debug_types, read that type.
15696      Don't follow DW_AT_specification though, that will take us back up
15697      the chain and we want to go down.  */
15698   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15699   if (attr)
15700     {
15701       type = get_DW_AT_signature_type (die, attr, cu);
15702
15703       /* The type's CU may not be the same as CU.
15704          Ensure TYPE is recorded with CU in die_type_hash.  */
15705       return set_die_type (die, type, cu);
15706     }
15707
15708   type = alloc_type (objfile);
15709   INIT_CPLUS_SPECIFIC (type);
15710
15711   name = dwarf2_name (die, cu);
15712   if (name != NULL)
15713     {
15714       if (cu->language == language_cplus
15715           || cu->language == language_d
15716           || cu->language == language_rust)
15717         {
15718           const char *full_name = dwarf2_full_name (name, die, cu);
15719
15720           /* dwarf2_full_name might have already finished building the DIE's
15721              type.  If so, there is no need to continue.  */
15722           if (get_die_type (die, cu) != NULL)
15723             return get_die_type (die, cu);
15724
15725           TYPE_TAG_NAME (type) = full_name;
15726           if (die->tag == DW_TAG_structure_type
15727               || die->tag == DW_TAG_class_type)
15728             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15729         }
15730       else
15731         {
15732           /* The name is already allocated along with this objfile, so
15733              we don't need to duplicate it for the type.  */
15734           TYPE_TAG_NAME (type) = name;
15735           if (die->tag == DW_TAG_class_type)
15736             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15737         }
15738     }
15739
15740   if (die->tag == DW_TAG_structure_type)
15741     {
15742       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15743     }
15744   else if (die->tag == DW_TAG_union_type)
15745     {
15746       TYPE_CODE (type) = TYPE_CODE_UNION;
15747     }
15748   else if (die->tag == DW_TAG_variant_part)
15749     {
15750       TYPE_CODE (type) = TYPE_CODE_UNION;
15751       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15752     }
15753   else
15754     {
15755       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15756     }
15757
15758   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15759     TYPE_DECLARED_CLASS (type) = 1;
15760
15761   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15762   if (attr)
15763     {
15764       if (attr_form_is_constant (attr))
15765         TYPE_LENGTH (type) = DW_UNSND (attr);
15766       else
15767         {
15768           /* For the moment, dynamic type sizes are not supported
15769              by GDB's struct type.  The actual size is determined
15770              on-demand when resolving the type of a given object,
15771              so set the type's length to zero for now.  Otherwise,
15772              we record an expression as the length, and that expression
15773              could lead to a very large value, which could eventually
15774              lead to us trying to allocate that much memory when creating
15775              a value of that type.  */
15776           TYPE_LENGTH (type) = 0;
15777         }
15778     }
15779   else
15780     {
15781       TYPE_LENGTH (type) = 0;
15782     }
15783
15784   maybe_set_alignment (cu, die, type);
15785
15786   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15787     {
15788       /* ICC<14 does not output the required DW_AT_declaration on
15789          incomplete types, but gives them a size of zero.  */
15790       TYPE_STUB (type) = 1;
15791     }
15792   else
15793     TYPE_STUB_SUPPORTED (type) = 1;
15794
15795   if (die_is_declaration (die, cu))
15796     TYPE_STUB (type) = 1;
15797   else if (attr == NULL && die->child == NULL
15798            && producer_is_realview (cu->producer))
15799     /* RealView does not output the required DW_AT_declaration
15800        on incomplete types.  */
15801     TYPE_STUB (type) = 1;
15802
15803   /* We need to add the type field to the die immediately so we don't
15804      infinitely recurse when dealing with pointers to the structure
15805      type within the structure itself.  */
15806   set_die_type (die, type, cu);
15807
15808   /* set_die_type should be already done.  */
15809   set_descriptive_type (type, die, cu);
15810
15811   return type;
15812 }
15813
15814 /* A helper for process_structure_scope that handles a single member
15815    DIE.  */
15816
15817 static void
15818 handle_struct_member_die (struct die_info *child_die, struct type *type,
15819                           struct field_info *fi,
15820                           std::vector<struct symbol *> *template_args,
15821                           struct dwarf2_cu *cu)
15822 {
15823   if (child_die->tag == DW_TAG_member
15824       || child_die->tag == DW_TAG_variable
15825       || child_die->tag == DW_TAG_variant_part)
15826     {
15827       /* NOTE: carlton/2002-11-05: A C++ static data member
15828          should be a DW_TAG_member that is a declaration, but
15829          all versions of G++ as of this writing (so through at
15830          least 3.2.1) incorrectly generate DW_TAG_variable
15831          tags for them instead.  */
15832       dwarf2_add_field (fi, child_die, cu);
15833     }
15834   else if (child_die->tag == DW_TAG_subprogram)
15835     {
15836       /* Rust doesn't have member functions in the C++ sense.
15837          However, it does emit ordinary functions as children
15838          of a struct DIE.  */
15839       if (cu->language == language_rust)
15840         read_func_scope (child_die, cu);
15841       else
15842         {
15843           /* C++ member function.  */
15844           dwarf2_add_member_fn (fi, child_die, type, cu);
15845         }
15846     }
15847   else if (child_die->tag == DW_TAG_inheritance)
15848     {
15849       /* C++ base class field.  */
15850       dwarf2_add_field (fi, child_die, cu);
15851     }
15852   else if (type_can_define_types (child_die))
15853     dwarf2_add_type_defn (fi, child_die, cu);
15854   else if (child_die->tag == DW_TAG_template_type_param
15855            || child_die->tag == DW_TAG_template_value_param)
15856     {
15857       struct symbol *arg = new_symbol (child_die, NULL, cu);
15858
15859       if (arg != NULL)
15860         template_args->push_back (arg);
15861     }
15862   else if (child_die->tag == DW_TAG_variant)
15863     {
15864       /* In a variant we want to get the discriminant and also add a
15865          field for our sole member child.  */
15866       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15867
15868       for (struct die_info *variant_child = child_die->child;
15869            variant_child != NULL;
15870            variant_child = sibling_die (variant_child))
15871         {
15872           if (variant_child->tag == DW_TAG_member)
15873             {
15874               handle_struct_member_die (variant_child, type, fi,
15875                                         template_args, cu);
15876               /* Only handle the one.  */
15877               break;
15878             }
15879         }
15880
15881       /* We don't handle this but we might as well report it if we see
15882          it.  */
15883       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15884           complaint (&symfile_complaints,
15885                      _("DW_AT_discr_list is not supported yet"
15886                        " - DIE at %s [in module %s]"),
15887                      sect_offset_str (child_die->sect_off),
15888                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15889
15890       /* The first field was just added, so we can stash the
15891          discriminant there.  */
15892       gdb_assert (!fi->fields.empty ());
15893       if (discr == NULL)
15894         fi->fields.back ().variant.default_branch = true;
15895       else
15896         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15897     }
15898 }
15899
15900 /* Finish creating a structure or union type, including filling in
15901    its members and creating a symbol for it.  */
15902
15903 static void
15904 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15905 {
15906   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15907   struct die_info *child_die;
15908   struct type *type;
15909
15910   type = get_die_type (die, cu);
15911   if (type == NULL)
15912     type = read_structure_type (die, cu);
15913
15914   /* When reading a DW_TAG_variant_part, we need to notice when we
15915      read the discriminant member, so we can record it later in the
15916      discriminant_info.  */
15917   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15918   sect_offset discr_offset;
15919
15920   if (is_variant_part)
15921     {
15922       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15923       if (discr == NULL)
15924         {
15925           /* Maybe it's a univariant form, an extension we support.
15926              In this case arrange not to check the offset.  */
15927           is_variant_part = false;
15928         }
15929       else if (attr_form_is_ref (discr))
15930         {
15931           struct dwarf2_cu *target_cu = cu;
15932           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15933
15934           discr_offset = target_die->sect_off;
15935         }
15936       else
15937         {
15938           complaint (&symfile_complaints,
15939                      _("DW_AT_discr does not have DIE reference form"
15940                        " - DIE at %s [in module %s]"),
15941                      sect_offset_str (die->sect_off),
15942                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15943           is_variant_part = false;
15944         }
15945     }
15946
15947   if (die->child != NULL && ! die_is_declaration (die, cu))
15948     {
15949       struct field_info fi;
15950       std::vector<struct symbol *> template_args;
15951
15952       child_die = die->child;
15953
15954       while (child_die && child_die->tag)
15955         {
15956           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15957
15958           if (is_variant_part && discr_offset == child_die->sect_off)
15959             fi.fields.back ().variant.is_discriminant = true;
15960
15961           child_die = sibling_die (child_die);
15962         }
15963
15964       /* Attach template arguments to type.  */
15965       if (!template_args.empty ())
15966         {
15967           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15968           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15969           TYPE_TEMPLATE_ARGUMENTS (type)
15970             = XOBNEWVEC (&objfile->objfile_obstack,
15971                          struct symbol *,
15972                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15973           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15974                   template_args.data (),
15975                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15976                    * sizeof (struct symbol *)));
15977         }
15978
15979       /* Attach fields and member functions to the type.  */
15980       if (fi.nfields)
15981         dwarf2_attach_fields_to_type (&fi, type, cu);
15982       if (!fi.fnfieldlists.empty ())
15983         {
15984           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15985
15986           /* Get the type which refers to the base class (possibly this
15987              class itself) which contains the vtable pointer for the current
15988              class from the DW_AT_containing_type attribute.  This use of
15989              DW_AT_containing_type is a GNU extension.  */
15990
15991           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15992             {
15993               struct type *t = die_containing_type (die, cu);
15994
15995               set_type_vptr_basetype (type, t);
15996               if (type == t)
15997                 {
15998                   int i;
15999
16000                   /* Our own class provides vtbl ptr.  */
16001                   for (i = TYPE_NFIELDS (t) - 1;
16002                        i >= TYPE_N_BASECLASSES (t);
16003                        --i)
16004                     {
16005                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16006
16007                       if (is_vtable_name (fieldname, cu))
16008                         {
16009                           set_type_vptr_fieldno (type, i);
16010                           break;
16011                         }
16012                     }
16013
16014                   /* Complain if virtual function table field not found.  */
16015                   if (i < TYPE_N_BASECLASSES (t))
16016                     complaint (&symfile_complaints,
16017                                _("virtual function table pointer "
16018                                  "not found when defining class '%s'"),
16019                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16020                                "");
16021                 }
16022               else
16023                 {
16024                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16025                 }
16026             }
16027           else if (cu->producer
16028                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16029             {
16030               /* The IBM XLC compiler does not provide direct indication
16031                  of the containing type, but the vtable pointer is
16032                  always named __vfp.  */
16033
16034               int i;
16035
16036               for (i = TYPE_NFIELDS (type) - 1;
16037                    i >= TYPE_N_BASECLASSES (type);
16038                    --i)
16039                 {
16040                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16041                     {
16042                       set_type_vptr_fieldno (type, i);
16043                       set_type_vptr_basetype (type, type);
16044                       break;
16045                     }
16046                 }
16047             }
16048         }
16049
16050       /* Copy fi.typedef_field_list linked list elements content into the
16051          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16052       if (!fi.typedef_field_list.empty ())
16053         {
16054           int count = fi.typedef_field_list.size ();
16055
16056           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16057           TYPE_TYPEDEF_FIELD_ARRAY (type)
16058             = ((struct decl_field *)
16059                TYPE_ALLOC (type,
16060                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16061           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16062
16063           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16064             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16065         }
16066
16067       /* Copy fi.nested_types_list linked list elements content into the
16068          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16069       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16070         {
16071           int count = fi.nested_types_list.size ();
16072
16073           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16074           TYPE_NESTED_TYPES_ARRAY (type)
16075             = ((struct decl_field *)
16076                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16077           TYPE_NESTED_TYPES_COUNT (type) = count;
16078
16079           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16080             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16081         }
16082     }
16083
16084   quirk_gcc_member_function_pointer (type, objfile);
16085   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16086     cu->rust_unions.push_back (type);
16087
16088   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16089      snapshots) has been known to create a die giving a declaration
16090      for a class that has, as a child, a die giving a definition for a
16091      nested class.  So we have to process our children even if the
16092      current die is a declaration.  Normally, of course, a declaration
16093      won't have any children at all.  */
16094
16095   child_die = die->child;
16096
16097   while (child_die != NULL && child_die->tag)
16098     {
16099       if (child_die->tag == DW_TAG_member
16100           || child_die->tag == DW_TAG_variable
16101           || child_die->tag == DW_TAG_inheritance
16102           || child_die->tag == DW_TAG_template_value_param
16103           || child_die->tag == DW_TAG_template_type_param)
16104         {
16105           /* Do nothing.  */
16106         }
16107       else
16108         process_die (child_die, cu);
16109
16110       child_die = sibling_die (child_die);
16111     }
16112
16113   /* Do not consider external references.  According to the DWARF standard,
16114      these DIEs are identified by the fact that they have no byte_size
16115      attribute, and a declaration attribute.  */
16116   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16117       || !die_is_declaration (die, cu))
16118     new_symbol (die, type, cu);
16119 }
16120
16121 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16122    update TYPE using some information only available in DIE's children.  */
16123
16124 static void
16125 update_enumeration_type_from_children (struct die_info *die,
16126                                        struct type *type,
16127                                        struct dwarf2_cu *cu)
16128 {
16129   struct die_info *child_die;
16130   int unsigned_enum = 1;
16131   int flag_enum = 1;
16132   ULONGEST mask = 0;
16133
16134   auto_obstack obstack;
16135
16136   for (child_die = die->child;
16137        child_die != NULL && child_die->tag;
16138        child_die = sibling_die (child_die))
16139     {
16140       struct attribute *attr;
16141       LONGEST value;
16142       const gdb_byte *bytes;
16143       struct dwarf2_locexpr_baton *baton;
16144       const char *name;
16145
16146       if (child_die->tag != DW_TAG_enumerator)
16147         continue;
16148
16149       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16150       if (attr == NULL)
16151         continue;
16152
16153       name = dwarf2_name (child_die, cu);
16154       if (name == NULL)
16155         name = "<anonymous enumerator>";
16156
16157       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16158                                &value, &bytes, &baton);
16159       if (value < 0)
16160         {
16161           unsigned_enum = 0;
16162           flag_enum = 0;
16163         }
16164       else if ((mask & value) != 0)
16165         flag_enum = 0;
16166       else
16167         mask |= value;
16168
16169       /* If we already know that the enum type is neither unsigned, nor
16170          a flag type, no need to look at the rest of the enumerates.  */
16171       if (!unsigned_enum && !flag_enum)
16172         break;
16173     }
16174
16175   if (unsigned_enum)
16176     TYPE_UNSIGNED (type) = 1;
16177   if (flag_enum)
16178     TYPE_FLAG_ENUM (type) = 1;
16179 }
16180
16181 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16182    complete the type's fields yet, or create any symbols.  */
16183
16184 static struct type *
16185 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16186 {
16187   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16188   struct type *type;
16189   struct attribute *attr;
16190   const char *name;
16191
16192   /* If the definition of this type lives in .debug_types, read that type.
16193      Don't follow DW_AT_specification though, that will take us back up
16194      the chain and we want to go down.  */
16195   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16196   if (attr)
16197     {
16198       type = get_DW_AT_signature_type (die, attr, cu);
16199
16200       /* The type's CU may not be the same as CU.
16201          Ensure TYPE is recorded with CU in die_type_hash.  */
16202       return set_die_type (die, type, cu);
16203     }
16204
16205   type = alloc_type (objfile);
16206
16207   TYPE_CODE (type) = TYPE_CODE_ENUM;
16208   name = dwarf2_full_name (NULL, die, cu);
16209   if (name != NULL)
16210     TYPE_TAG_NAME (type) = name;
16211
16212   attr = dwarf2_attr (die, DW_AT_type, cu);
16213   if (attr != NULL)
16214     {
16215       struct type *underlying_type = die_type (die, cu);
16216
16217       TYPE_TARGET_TYPE (type) = underlying_type;
16218     }
16219
16220   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16221   if (attr)
16222     {
16223       TYPE_LENGTH (type) = DW_UNSND (attr);
16224     }
16225   else
16226     {
16227       TYPE_LENGTH (type) = 0;
16228     }
16229
16230   maybe_set_alignment (cu, die, type);
16231
16232   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16233      declared as private in the package spec, and then defined only
16234      inside the package body.  Such types are known as Taft Amendment
16235      Types.  When another package uses such a type, an incomplete DIE
16236      may be generated by the compiler.  */
16237   if (die_is_declaration (die, cu))
16238     TYPE_STUB (type) = 1;
16239
16240   /* Finish the creation of this type by using the enum's children.
16241      We must call this even when the underlying type has been provided
16242      so that we can determine if we're looking at a "flag" enum.  */
16243   update_enumeration_type_from_children (die, type, cu);
16244
16245   /* If this type has an underlying type that is not a stub, then we
16246      may use its attributes.  We always use the "unsigned" attribute
16247      in this situation, because ordinarily we guess whether the type
16248      is unsigned -- but the guess can be wrong and the underlying type
16249      can tell us the reality.  However, we defer to a local size
16250      attribute if one exists, because this lets the compiler override
16251      the underlying type if needed.  */
16252   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16253     {
16254       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16255       if (TYPE_LENGTH (type) == 0)
16256         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16257       if (TYPE_RAW_ALIGN (type) == 0
16258           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16259         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16260     }
16261
16262   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16263
16264   return set_die_type (die, type, cu);
16265 }
16266
16267 /* Given a pointer to a die which begins an enumeration, process all
16268    the dies that define the members of the enumeration, and create the
16269    symbol for the enumeration type.
16270
16271    NOTE: We reverse the order of the element list.  */
16272
16273 static void
16274 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16275 {
16276   struct type *this_type;
16277
16278   this_type = get_die_type (die, cu);
16279   if (this_type == NULL)
16280     this_type = read_enumeration_type (die, cu);
16281
16282   if (die->child != NULL)
16283     {
16284       struct die_info *child_die;
16285       struct symbol *sym;
16286       struct field *fields = NULL;
16287       int num_fields = 0;
16288       const char *name;
16289
16290       child_die = die->child;
16291       while (child_die && child_die->tag)
16292         {
16293           if (child_die->tag != DW_TAG_enumerator)
16294             {
16295               process_die (child_die, cu);
16296             }
16297           else
16298             {
16299               name = dwarf2_name (child_die, cu);
16300               if (name)
16301                 {
16302                   sym = new_symbol (child_die, this_type, cu);
16303
16304                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16305                     {
16306                       fields = (struct field *)
16307                         xrealloc (fields,
16308                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16309                                   * sizeof (struct field));
16310                     }
16311
16312                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16313                   FIELD_TYPE (fields[num_fields]) = NULL;
16314                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16315                   FIELD_BITSIZE (fields[num_fields]) = 0;
16316
16317                   num_fields++;
16318                 }
16319             }
16320
16321           child_die = sibling_die (child_die);
16322         }
16323
16324       if (num_fields)
16325         {
16326           TYPE_NFIELDS (this_type) = num_fields;
16327           TYPE_FIELDS (this_type) = (struct field *)
16328             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16329           memcpy (TYPE_FIELDS (this_type), fields,
16330                   sizeof (struct field) * num_fields);
16331           xfree (fields);
16332         }
16333     }
16334
16335   /* If we are reading an enum from a .debug_types unit, and the enum
16336      is a declaration, and the enum is not the signatured type in the
16337      unit, then we do not want to add a symbol for it.  Adding a
16338      symbol would in some cases obscure the true definition of the
16339      enum, giving users an incomplete type when the definition is
16340      actually available.  Note that we do not want to do this for all
16341      enums which are just declarations, because C++0x allows forward
16342      enum declarations.  */
16343   if (cu->per_cu->is_debug_types
16344       && die_is_declaration (die, cu))
16345     {
16346       struct signatured_type *sig_type;
16347
16348       sig_type = (struct signatured_type *) cu->per_cu;
16349       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16350       if (sig_type->type_offset_in_section != die->sect_off)
16351         return;
16352     }
16353
16354   new_symbol (die, this_type, cu);
16355 }
16356
16357 /* Extract all information from a DW_TAG_array_type DIE and put it in
16358    the DIE's type field.  For now, this only handles one dimensional
16359    arrays.  */
16360
16361 static struct type *
16362 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16363 {
16364   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16365   struct die_info *child_die;
16366   struct type *type;
16367   struct type *element_type, *range_type, *index_type;
16368   struct attribute *attr;
16369   const char *name;
16370   struct dynamic_prop *byte_stride_prop = NULL;
16371   unsigned int bit_stride = 0;
16372
16373   element_type = die_type (die, cu);
16374
16375   /* The die_type call above may have already set the type for this DIE.  */
16376   type = get_die_type (die, cu);
16377   if (type)
16378     return type;
16379
16380   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16381   if (attr != NULL)
16382     {
16383       int stride_ok;
16384
16385       byte_stride_prop
16386         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16387       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16388       if (!stride_ok)
16389         {
16390           complaint (&symfile_complaints,
16391                      _("unable to read array DW_AT_byte_stride "
16392                        " - DIE at %s [in module %s]"),
16393                      sect_offset_str (die->sect_off),
16394                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16395           /* Ignore this attribute.  We will likely not be able to print
16396              arrays of this type correctly, but there is little we can do
16397              to help if we cannot read the attribute's value.  */
16398           byte_stride_prop = NULL;
16399         }
16400     }
16401
16402   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16403   if (attr != NULL)
16404     bit_stride = DW_UNSND (attr);
16405
16406   /* Irix 6.2 native cc creates array types without children for
16407      arrays with unspecified length.  */
16408   if (die->child == NULL)
16409     {
16410       index_type = objfile_type (objfile)->builtin_int;
16411       range_type = create_static_range_type (NULL, index_type, 0, -1);
16412       type = create_array_type_with_stride (NULL, element_type, range_type,
16413                                             byte_stride_prop, bit_stride);
16414       return set_die_type (die, type, cu);
16415     }
16416
16417   std::vector<struct type *> range_types;
16418   child_die = die->child;
16419   while (child_die && child_die->tag)
16420     {
16421       if (child_die->tag == DW_TAG_subrange_type)
16422         {
16423           struct type *child_type = read_type_die (child_die, cu);
16424
16425           if (child_type != NULL)
16426             {
16427               /* The range type was succesfully read.  Save it for the
16428                  array type creation.  */
16429               range_types.push_back (child_type);
16430             }
16431         }
16432       child_die = sibling_die (child_die);
16433     }
16434
16435   /* Dwarf2 dimensions are output from left to right, create the
16436      necessary array types in backwards order.  */
16437
16438   type = element_type;
16439
16440   if (read_array_order (die, cu) == DW_ORD_col_major)
16441     {
16442       int i = 0;
16443
16444       while (i < range_types.size ())
16445         type = create_array_type_with_stride (NULL, type, range_types[i++],
16446                                               byte_stride_prop, bit_stride);
16447     }
16448   else
16449     {
16450       size_t ndim = range_types.size ();
16451       while (ndim-- > 0)
16452         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16453                                               byte_stride_prop, bit_stride);
16454     }
16455
16456   /* Understand Dwarf2 support for vector types (like they occur on
16457      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16458      array type.  This is not part of the Dwarf2/3 standard yet, but a
16459      custom vendor extension.  The main difference between a regular
16460      array and the vector variant is that vectors are passed by value
16461      to functions.  */
16462   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16463   if (attr)
16464     make_vector_type (type);
16465
16466   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16467      implementation may choose to implement triple vectors using this
16468      attribute.  */
16469   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16470   if (attr)
16471     {
16472       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16473         TYPE_LENGTH (type) = DW_UNSND (attr);
16474       else
16475         complaint (&symfile_complaints,
16476                    _("DW_AT_byte_size for array type smaller "
16477                      "than the total size of elements"));
16478     }
16479
16480   name = dwarf2_name (die, cu);
16481   if (name)
16482     TYPE_NAME (type) = name;
16483
16484   maybe_set_alignment (cu, die, type);
16485
16486   /* Install the type in the die.  */
16487   set_die_type (die, type, cu);
16488
16489   /* set_die_type should be already done.  */
16490   set_descriptive_type (type, die, cu);
16491
16492   return type;
16493 }
16494
16495 static enum dwarf_array_dim_ordering
16496 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16497 {
16498   struct attribute *attr;
16499
16500   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16501
16502   if (attr)
16503     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16504
16505   /* GNU F77 is a special case, as at 08/2004 array type info is the
16506      opposite order to the dwarf2 specification, but data is still
16507      laid out as per normal fortran.
16508
16509      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16510      version checking.  */
16511
16512   if (cu->language == language_fortran
16513       && cu->producer && strstr (cu->producer, "GNU F77"))
16514     {
16515       return DW_ORD_row_major;
16516     }
16517
16518   switch (cu->language_defn->la_array_ordering)
16519     {
16520     case array_column_major:
16521       return DW_ORD_col_major;
16522     case array_row_major:
16523     default:
16524       return DW_ORD_row_major;
16525     };
16526 }
16527
16528 /* Extract all information from a DW_TAG_set_type DIE and put it in
16529    the DIE's type field.  */
16530
16531 static struct type *
16532 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16533 {
16534   struct type *domain_type, *set_type;
16535   struct attribute *attr;
16536
16537   domain_type = die_type (die, cu);
16538
16539   /* The die_type call above may have already set the type for this DIE.  */
16540   set_type = get_die_type (die, cu);
16541   if (set_type)
16542     return set_type;
16543
16544   set_type = create_set_type (NULL, domain_type);
16545
16546   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16547   if (attr)
16548     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16549
16550   maybe_set_alignment (cu, die, set_type);
16551
16552   return set_die_type (die, set_type, cu);
16553 }
16554
16555 /* A helper for read_common_block that creates a locexpr baton.
16556    SYM is the symbol which we are marking as computed.
16557    COMMON_DIE is the DIE for the common block.
16558    COMMON_LOC is the location expression attribute for the common
16559    block itself.
16560    MEMBER_LOC is the location expression attribute for the particular
16561    member of the common block that we are processing.
16562    CU is the CU from which the above come.  */
16563
16564 static void
16565 mark_common_block_symbol_computed (struct symbol *sym,
16566                                    struct die_info *common_die,
16567                                    struct attribute *common_loc,
16568                                    struct attribute *member_loc,
16569                                    struct dwarf2_cu *cu)
16570 {
16571   struct dwarf2_per_objfile *dwarf2_per_objfile
16572     = cu->per_cu->dwarf2_per_objfile;
16573   struct objfile *objfile = dwarf2_per_objfile->objfile;
16574   struct dwarf2_locexpr_baton *baton;
16575   gdb_byte *ptr;
16576   unsigned int cu_off;
16577   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16578   LONGEST offset = 0;
16579
16580   gdb_assert (common_loc && member_loc);
16581   gdb_assert (attr_form_is_block (common_loc));
16582   gdb_assert (attr_form_is_block (member_loc)
16583               || attr_form_is_constant (member_loc));
16584
16585   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16586   baton->per_cu = cu->per_cu;
16587   gdb_assert (baton->per_cu);
16588
16589   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16590
16591   if (attr_form_is_constant (member_loc))
16592     {
16593       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16594       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16595     }
16596   else
16597     baton->size += DW_BLOCK (member_loc)->size;
16598
16599   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16600   baton->data = ptr;
16601
16602   *ptr++ = DW_OP_call4;
16603   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16604   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16605   ptr += 4;
16606
16607   if (attr_form_is_constant (member_loc))
16608     {
16609       *ptr++ = DW_OP_addr;
16610       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16611       ptr += cu->header.addr_size;
16612     }
16613   else
16614     {
16615       /* We have to copy the data here, because DW_OP_call4 will only
16616          use a DW_AT_location attribute.  */
16617       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16618       ptr += DW_BLOCK (member_loc)->size;
16619     }
16620
16621   *ptr++ = DW_OP_plus;
16622   gdb_assert (ptr - baton->data == baton->size);
16623
16624   SYMBOL_LOCATION_BATON (sym) = baton;
16625   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16626 }
16627
16628 /* Create appropriate locally-scoped variables for all the
16629    DW_TAG_common_block entries.  Also create a struct common_block
16630    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16631    is used to sepate the common blocks name namespace from regular
16632    variable names.  */
16633
16634 static void
16635 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16636 {
16637   struct attribute *attr;
16638
16639   attr = dwarf2_attr (die, DW_AT_location, cu);
16640   if (attr)
16641     {
16642       /* Support the .debug_loc offsets.  */
16643       if (attr_form_is_block (attr))
16644         {
16645           /* Ok.  */
16646         }
16647       else if (attr_form_is_section_offset (attr))
16648         {
16649           dwarf2_complex_location_expr_complaint ();
16650           attr = NULL;
16651         }
16652       else
16653         {
16654           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16655                                                  "common block member");
16656           attr = NULL;
16657         }
16658     }
16659
16660   if (die->child != NULL)
16661     {
16662       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16663       struct die_info *child_die;
16664       size_t n_entries = 0, size;
16665       struct common_block *common_block;
16666       struct symbol *sym;
16667
16668       for (child_die = die->child;
16669            child_die && child_die->tag;
16670            child_die = sibling_die (child_die))
16671         ++n_entries;
16672
16673       size = (sizeof (struct common_block)
16674               + (n_entries - 1) * sizeof (struct symbol *));
16675       common_block
16676         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16677                                                  size);
16678       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16679       common_block->n_entries = 0;
16680
16681       for (child_die = die->child;
16682            child_die && child_die->tag;
16683            child_die = sibling_die (child_die))
16684         {
16685           /* Create the symbol in the DW_TAG_common_block block in the current
16686              symbol scope.  */
16687           sym = new_symbol (child_die, NULL, cu);
16688           if (sym != NULL)
16689             {
16690               struct attribute *member_loc;
16691
16692               common_block->contents[common_block->n_entries++] = sym;
16693
16694               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16695                                         cu);
16696               if (member_loc)
16697                 {
16698                   /* GDB has handled this for a long time, but it is
16699                      not specified by DWARF.  It seems to have been
16700                      emitted by gfortran at least as recently as:
16701                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16702                   complaint (&symfile_complaints,
16703                              _("Variable in common block has "
16704                                "DW_AT_data_member_location "
16705                                "- DIE at %s [in module %s]"),
16706                                sect_offset_str (child_die->sect_off),
16707                              objfile_name (objfile));
16708
16709                   if (attr_form_is_section_offset (member_loc))
16710                     dwarf2_complex_location_expr_complaint ();
16711                   else if (attr_form_is_constant (member_loc)
16712                            || attr_form_is_block (member_loc))
16713                     {
16714                       if (attr)
16715                         mark_common_block_symbol_computed (sym, die, attr,
16716                                                            member_loc, cu);
16717                     }
16718                   else
16719                     dwarf2_complex_location_expr_complaint ();
16720                 }
16721             }
16722         }
16723
16724       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16725       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16726     }
16727 }
16728
16729 /* Create a type for a C++ namespace.  */
16730
16731 static struct type *
16732 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16733 {
16734   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16735   const char *previous_prefix, *name;
16736   int is_anonymous;
16737   struct type *type;
16738
16739   /* For extensions, reuse the type of the original namespace.  */
16740   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16741     {
16742       struct die_info *ext_die;
16743       struct dwarf2_cu *ext_cu = cu;
16744
16745       ext_die = dwarf2_extension (die, &ext_cu);
16746       type = read_type_die (ext_die, ext_cu);
16747
16748       /* EXT_CU may not be the same as CU.
16749          Ensure TYPE is recorded with CU in die_type_hash.  */
16750       return set_die_type (die, type, cu);
16751     }
16752
16753   name = namespace_name (die, &is_anonymous, cu);
16754
16755   /* Now build the name of the current namespace.  */
16756
16757   previous_prefix = determine_prefix (die, cu);
16758   if (previous_prefix[0] != '\0')
16759     name = typename_concat (&objfile->objfile_obstack,
16760                             previous_prefix, name, 0, cu);
16761
16762   /* Create the type.  */
16763   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16764   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16765
16766   return set_die_type (die, type, cu);
16767 }
16768
16769 /* Read a namespace scope.  */
16770
16771 static void
16772 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16773 {
16774   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16775   int is_anonymous;
16776
16777   /* Add a symbol associated to this if we haven't seen the namespace
16778      before.  Also, add a using directive if it's an anonymous
16779      namespace.  */
16780
16781   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16782     {
16783       struct type *type;
16784
16785       type = read_type_die (die, cu);
16786       new_symbol (die, type, cu);
16787
16788       namespace_name (die, &is_anonymous, cu);
16789       if (is_anonymous)
16790         {
16791           const char *previous_prefix = determine_prefix (die, cu);
16792
16793           std::vector<const char *> excludes;
16794           add_using_directive (using_directives (cu->language),
16795                                previous_prefix, TYPE_NAME (type), NULL,
16796                                NULL, excludes, 0, &objfile->objfile_obstack);
16797         }
16798     }
16799
16800   if (die->child != NULL)
16801     {
16802       struct die_info *child_die = die->child;
16803
16804       while (child_die && child_die->tag)
16805         {
16806           process_die (child_die, cu);
16807           child_die = sibling_die (child_die);
16808         }
16809     }
16810 }
16811
16812 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16813    imported module.  Still we need that type as local Fortran "use ... only"
16814    declaration imports depend on the created type in determine_prefix.  */
16815
16816 static struct type *
16817 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16818 {
16819   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16820   const char *module_name;
16821   struct type *type;
16822
16823   module_name = dwarf2_name (die, cu);
16824   if (!module_name)
16825     complaint (&symfile_complaints,
16826                _("DW_TAG_module has no name, offset %s"),
16827                sect_offset_str (die->sect_off));
16828   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16829
16830   /* determine_prefix uses TYPE_TAG_NAME.  */
16831   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16832
16833   return set_die_type (die, type, cu);
16834 }
16835
16836 /* Read a Fortran module.  */
16837
16838 static void
16839 read_module (struct die_info *die, struct dwarf2_cu *cu)
16840 {
16841   struct die_info *child_die = die->child;
16842   struct type *type;
16843
16844   type = read_type_die (die, cu);
16845   new_symbol (die, type, cu);
16846
16847   while (child_die && child_die->tag)
16848     {
16849       process_die (child_die, cu);
16850       child_die = sibling_die (child_die);
16851     }
16852 }
16853
16854 /* Return the name of the namespace represented by DIE.  Set
16855    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16856    namespace.  */
16857
16858 static const char *
16859 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16860 {
16861   struct die_info *current_die;
16862   const char *name = NULL;
16863
16864   /* Loop through the extensions until we find a name.  */
16865
16866   for (current_die = die;
16867        current_die != NULL;
16868        current_die = dwarf2_extension (die, &cu))
16869     {
16870       /* We don't use dwarf2_name here so that we can detect the absence
16871          of a name -> anonymous namespace.  */
16872       name = dwarf2_string_attr (die, DW_AT_name, cu);
16873
16874       if (name != NULL)
16875         break;
16876     }
16877
16878   /* Is it an anonymous namespace?  */
16879
16880   *is_anonymous = (name == NULL);
16881   if (*is_anonymous)
16882     name = CP_ANONYMOUS_NAMESPACE_STR;
16883
16884   return name;
16885 }
16886
16887 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16888    the user defined type vector.  */
16889
16890 static struct type *
16891 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16892 {
16893   struct gdbarch *gdbarch
16894     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16895   struct comp_unit_head *cu_header = &cu->header;
16896   struct type *type;
16897   struct attribute *attr_byte_size;
16898   struct attribute *attr_address_class;
16899   int byte_size, addr_class;
16900   struct type *target_type;
16901
16902   target_type = die_type (die, cu);
16903
16904   /* The die_type call above may have already set the type for this DIE.  */
16905   type = get_die_type (die, cu);
16906   if (type)
16907     return type;
16908
16909   type = lookup_pointer_type (target_type);
16910
16911   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16912   if (attr_byte_size)
16913     byte_size = DW_UNSND (attr_byte_size);
16914   else
16915     byte_size = cu_header->addr_size;
16916
16917   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16918   if (attr_address_class)
16919     addr_class = DW_UNSND (attr_address_class);
16920   else
16921     addr_class = DW_ADDR_none;
16922
16923   ULONGEST alignment = get_alignment (cu, die);
16924
16925   /* If the pointer size, alignment, or address class is different
16926      than the default, create a type variant marked as such and set
16927      the length accordingly.  */
16928   if (TYPE_LENGTH (type) != byte_size
16929       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16930           && alignment != TYPE_RAW_ALIGN (type))
16931       || addr_class != DW_ADDR_none)
16932     {
16933       if (gdbarch_address_class_type_flags_p (gdbarch))
16934         {
16935           int type_flags;
16936
16937           type_flags = gdbarch_address_class_type_flags
16938                          (gdbarch, byte_size, addr_class);
16939           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16940                       == 0);
16941           type = make_type_with_address_space (type, type_flags);
16942         }
16943       else if (TYPE_LENGTH (type) != byte_size)
16944         {
16945           complaint (&symfile_complaints,
16946                      _("invalid pointer size %d"), byte_size);
16947         }
16948       else if (TYPE_RAW_ALIGN (type) != alignment)
16949         {
16950           complaint (&symfile_complaints,
16951                      _("Invalid DW_AT_alignment"
16952                        " - DIE at %s [in module %s]"),
16953                      sect_offset_str (die->sect_off),
16954                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16955         }
16956       else
16957         {
16958           /* Should we also complain about unhandled address classes?  */
16959         }
16960     }
16961
16962   TYPE_LENGTH (type) = byte_size;
16963   set_type_align (type, alignment);
16964   return set_die_type (die, type, cu);
16965 }
16966
16967 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16968    the user defined type vector.  */
16969
16970 static struct type *
16971 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16972 {
16973   struct type *type;
16974   struct type *to_type;
16975   struct type *domain;
16976
16977   to_type = die_type (die, cu);
16978   domain = die_containing_type (die, cu);
16979
16980   /* The calls above may have already set the type for this DIE.  */
16981   type = get_die_type (die, cu);
16982   if (type)
16983     return type;
16984
16985   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16986     type = lookup_methodptr_type (to_type);
16987   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16988     {
16989       struct type *new_type
16990         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16991
16992       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16993                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16994                             TYPE_VARARGS (to_type));
16995       type = lookup_methodptr_type (new_type);
16996     }
16997   else
16998     type = lookup_memberptr_type (to_type, domain);
16999
17000   return set_die_type (die, type, cu);
17001 }
17002
17003 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17004    the user defined type vector.  */
17005
17006 static struct type *
17007 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17008                           enum type_code refcode)
17009 {
17010   struct comp_unit_head *cu_header = &cu->header;
17011   struct type *type, *target_type;
17012   struct attribute *attr;
17013
17014   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17015
17016   target_type = die_type (die, cu);
17017
17018   /* The die_type call above may have already set the type for this DIE.  */
17019   type = get_die_type (die, cu);
17020   if (type)
17021     return type;
17022
17023   type = lookup_reference_type (target_type, refcode);
17024   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17025   if (attr)
17026     {
17027       TYPE_LENGTH (type) = DW_UNSND (attr);
17028     }
17029   else
17030     {
17031       TYPE_LENGTH (type) = cu_header->addr_size;
17032     }
17033   maybe_set_alignment (cu, die, type);
17034   return set_die_type (die, type, cu);
17035 }
17036
17037 /* Add the given cv-qualifiers to the element type of the array.  GCC
17038    outputs DWARF type qualifiers that apply to an array, not the
17039    element type.  But GDB relies on the array element type to carry
17040    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17041    specification.  */
17042
17043 static struct type *
17044 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17045                    struct type *base_type, int cnst, int voltl)
17046 {
17047   struct type *el_type, *inner_array;
17048
17049   base_type = copy_type (base_type);
17050   inner_array = base_type;
17051
17052   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17053     {
17054       TYPE_TARGET_TYPE (inner_array) =
17055         copy_type (TYPE_TARGET_TYPE (inner_array));
17056       inner_array = TYPE_TARGET_TYPE (inner_array);
17057     }
17058
17059   el_type = TYPE_TARGET_TYPE (inner_array);
17060   cnst |= TYPE_CONST (el_type);
17061   voltl |= TYPE_VOLATILE (el_type);
17062   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17063
17064   return set_die_type (die, base_type, cu);
17065 }
17066
17067 static struct type *
17068 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17069 {
17070   struct type *base_type, *cv_type;
17071
17072   base_type = die_type (die, cu);
17073
17074   /* The die_type call above may have already set the type for this DIE.  */
17075   cv_type = get_die_type (die, cu);
17076   if (cv_type)
17077     return cv_type;
17078
17079   /* In case the const qualifier is applied to an array type, the element type
17080      is so qualified, not the array type (section 6.7.3 of C99).  */
17081   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17082     return add_array_cv_type (die, cu, base_type, 1, 0);
17083
17084   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17085   return set_die_type (die, cv_type, cu);
17086 }
17087
17088 static struct type *
17089 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17090 {
17091   struct type *base_type, *cv_type;
17092
17093   base_type = die_type (die, cu);
17094
17095   /* The die_type call above may have already set the type for this DIE.  */
17096   cv_type = get_die_type (die, cu);
17097   if (cv_type)
17098     return cv_type;
17099
17100   /* In case the volatile qualifier is applied to an array type, the
17101      element type is so qualified, not the array type (section 6.7.3
17102      of C99).  */
17103   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17104     return add_array_cv_type (die, cu, base_type, 0, 1);
17105
17106   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17107   return set_die_type (die, cv_type, cu);
17108 }
17109
17110 /* Handle DW_TAG_restrict_type.  */
17111
17112 static struct type *
17113 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17114 {
17115   struct type *base_type, *cv_type;
17116
17117   base_type = die_type (die, cu);
17118
17119   /* The die_type call above may have already set the type for this DIE.  */
17120   cv_type = get_die_type (die, cu);
17121   if (cv_type)
17122     return cv_type;
17123
17124   cv_type = make_restrict_type (base_type);
17125   return set_die_type (die, cv_type, cu);
17126 }
17127
17128 /* Handle DW_TAG_atomic_type.  */
17129
17130 static struct type *
17131 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17132 {
17133   struct type *base_type, *cv_type;
17134
17135   base_type = die_type (die, cu);
17136
17137   /* The die_type call above may have already set the type for this DIE.  */
17138   cv_type = get_die_type (die, cu);
17139   if (cv_type)
17140     return cv_type;
17141
17142   cv_type = make_atomic_type (base_type);
17143   return set_die_type (die, cv_type, cu);
17144 }
17145
17146 /* Extract all information from a DW_TAG_string_type DIE and add to
17147    the user defined type vector.  It isn't really a user defined type,
17148    but it behaves like one, with other DIE's using an AT_user_def_type
17149    attribute to reference it.  */
17150
17151 static struct type *
17152 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17153 {
17154   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17155   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17156   struct type *type, *range_type, *index_type, *char_type;
17157   struct attribute *attr;
17158   unsigned int length;
17159
17160   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17161   if (attr)
17162     {
17163       length = DW_UNSND (attr);
17164     }
17165   else
17166     {
17167       /* Check for the DW_AT_byte_size attribute.  */
17168       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17169       if (attr)
17170         {
17171           length = DW_UNSND (attr);
17172         }
17173       else
17174         {
17175           length = 1;
17176         }
17177     }
17178
17179   index_type = objfile_type (objfile)->builtin_int;
17180   range_type = create_static_range_type (NULL, index_type, 1, length);
17181   char_type = language_string_char_type (cu->language_defn, gdbarch);
17182   type = create_string_type (NULL, char_type, range_type);
17183
17184   return set_die_type (die, type, cu);
17185 }
17186
17187 /* Assuming that DIE corresponds to a function, returns nonzero
17188    if the function is prototyped.  */
17189
17190 static int
17191 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17192 {
17193   struct attribute *attr;
17194
17195   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17196   if (attr && (DW_UNSND (attr) != 0))
17197     return 1;
17198
17199   /* The DWARF standard implies that the DW_AT_prototyped attribute
17200      is only meaninful for C, but the concept also extends to other
17201      languages that allow unprototyped functions (Eg: Objective C).
17202      For all other languages, assume that functions are always
17203      prototyped.  */
17204   if (cu->language != language_c
17205       && cu->language != language_objc
17206       && cu->language != language_opencl)
17207     return 1;
17208
17209   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17210      prototyped and unprototyped functions; default to prototyped,
17211      since that is more common in modern code (and RealView warns
17212      about unprototyped functions).  */
17213   if (producer_is_realview (cu->producer))
17214     return 1;
17215
17216   return 0;
17217 }
17218
17219 /* Handle DIES due to C code like:
17220
17221    struct foo
17222    {
17223    int (*funcp)(int a, long l);
17224    int b;
17225    };
17226
17227    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17228
17229 static struct type *
17230 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17231 {
17232   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17233   struct type *type;            /* Type that this function returns.  */
17234   struct type *ftype;           /* Function that returns above type.  */
17235   struct attribute *attr;
17236
17237   type = die_type (die, cu);
17238
17239   /* The die_type call above may have already set the type for this DIE.  */
17240   ftype = get_die_type (die, cu);
17241   if (ftype)
17242     return ftype;
17243
17244   ftype = lookup_function_type (type);
17245
17246   if (prototyped_function_p (die, cu))
17247     TYPE_PROTOTYPED (ftype) = 1;
17248
17249   /* Store the calling convention in the type if it's available in
17250      the subroutine die.  Otherwise set the calling convention to
17251      the default value DW_CC_normal.  */
17252   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17253   if (attr)
17254     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17255   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17256     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17257   else
17258     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17259
17260   /* Record whether the function returns normally to its caller or not
17261      if the DWARF producer set that information.  */
17262   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17263   if (attr && (DW_UNSND (attr) != 0))
17264     TYPE_NO_RETURN (ftype) = 1;
17265
17266   /* We need to add the subroutine type to the die immediately so
17267      we don't infinitely recurse when dealing with parameters
17268      declared as the same subroutine type.  */
17269   set_die_type (die, ftype, cu);
17270
17271   if (die->child != NULL)
17272     {
17273       struct type *void_type = objfile_type (objfile)->builtin_void;
17274       struct die_info *child_die;
17275       int nparams, iparams;
17276
17277       /* Count the number of parameters.
17278          FIXME: GDB currently ignores vararg functions, but knows about
17279          vararg member functions.  */
17280       nparams = 0;
17281       child_die = die->child;
17282       while (child_die && child_die->tag)
17283         {
17284           if (child_die->tag == DW_TAG_formal_parameter)
17285             nparams++;
17286           else if (child_die->tag == DW_TAG_unspecified_parameters)
17287             TYPE_VARARGS (ftype) = 1;
17288           child_die = sibling_die (child_die);
17289         }
17290
17291       /* Allocate storage for parameters and fill them in.  */
17292       TYPE_NFIELDS (ftype) = nparams;
17293       TYPE_FIELDS (ftype) = (struct field *)
17294         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17295
17296       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17297          even if we error out during the parameters reading below.  */
17298       for (iparams = 0; iparams < nparams; iparams++)
17299         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17300
17301       iparams = 0;
17302       child_die = die->child;
17303       while (child_die && child_die->tag)
17304         {
17305           if (child_die->tag == DW_TAG_formal_parameter)
17306             {
17307               struct type *arg_type;
17308
17309               /* DWARF version 2 has no clean way to discern C++
17310                  static and non-static member functions.  G++ helps
17311                  GDB by marking the first parameter for non-static
17312                  member functions (which is the this pointer) as
17313                  artificial.  We pass this information to
17314                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17315
17316                  DWARF version 3 added DW_AT_object_pointer, which GCC
17317                  4.5 does not yet generate.  */
17318               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17319               if (attr)
17320                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17321               else
17322                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17323               arg_type = die_type (child_die, cu);
17324
17325               /* RealView does not mark THIS as const, which the testsuite
17326                  expects.  GCC marks THIS as const in method definitions,
17327                  but not in the class specifications (GCC PR 43053).  */
17328               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17329                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17330                 {
17331                   int is_this = 0;
17332                   struct dwarf2_cu *arg_cu = cu;
17333                   const char *name = dwarf2_name (child_die, cu);
17334
17335                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17336                   if (attr)
17337                     {
17338                       /* If the compiler emits this, use it.  */
17339                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17340                         is_this = 1;
17341                     }
17342                   else if (name && strcmp (name, "this") == 0)
17343                     /* Function definitions will have the argument names.  */
17344                     is_this = 1;
17345                   else if (name == NULL && iparams == 0)
17346                     /* Declarations may not have the names, so like
17347                        elsewhere in GDB, assume an artificial first
17348                        argument is "this".  */
17349                     is_this = 1;
17350
17351                   if (is_this)
17352                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17353                                              arg_type, 0);
17354                 }
17355
17356               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17357               iparams++;
17358             }
17359           child_die = sibling_die (child_die);
17360         }
17361     }
17362
17363   return ftype;
17364 }
17365
17366 static struct type *
17367 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17368 {
17369   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17370   const char *name = NULL;
17371   struct type *this_type, *target_type;
17372
17373   name = dwarf2_full_name (NULL, die, cu);
17374   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17375   TYPE_TARGET_STUB (this_type) = 1;
17376   set_die_type (die, this_type, cu);
17377   target_type = die_type (die, cu);
17378   if (target_type != this_type)
17379     TYPE_TARGET_TYPE (this_type) = target_type;
17380   else
17381     {
17382       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17383          spec and cause infinite loops in GDB.  */
17384       complaint (&symfile_complaints,
17385                  _("Self-referential DW_TAG_typedef "
17386                    "- DIE at %s [in module %s]"),
17387                  sect_offset_str (die->sect_off), objfile_name (objfile));
17388       TYPE_TARGET_TYPE (this_type) = NULL;
17389     }
17390   return this_type;
17391 }
17392
17393 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17394    (which may be different from NAME) to the architecture back-end to allow
17395    it to guess the correct format if necessary.  */
17396
17397 static struct type *
17398 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17399                         const char *name_hint)
17400 {
17401   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17402   const struct floatformat **format;
17403   struct type *type;
17404
17405   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17406   if (format)
17407     type = init_float_type (objfile, bits, name, format);
17408   else
17409     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17410
17411   return type;
17412 }
17413
17414 /* Find a representation of a given base type and install
17415    it in the TYPE field of the die.  */
17416
17417 static struct type *
17418 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17419 {
17420   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17421   struct type *type;
17422   struct attribute *attr;
17423   int encoding = 0, bits = 0;
17424   const char *name;
17425
17426   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17427   if (attr)
17428     {
17429       encoding = DW_UNSND (attr);
17430     }
17431   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17432   if (attr)
17433     {
17434       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17435     }
17436   name = dwarf2_name (die, cu);
17437   if (!name)
17438     {
17439       complaint (&symfile_complaints,
17440                  _("DW_AT_name missing from DW_TAG_base_type"));
17441     }
17442
17443   switch (encoding)
17444     {
17445       case DW_ATE_address:
17446         /* Turn DW_ATE_address into a void * pointer.  */
17447         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17448         type = init_pointer_type (objfile, bits, name, type);
17449         break;
17450       case DW_ATE_boolean:
17451         type = init_boolean_type (objfile, bits, 1, name);
17452         break;
17453       case DW_ATE_complex_float:
17454         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17455         type = init_complex_type (objfile, name, type);
17456         break;
17457       case DW_ATE_decimal_float:
17458         type = init_decfloat_type (objfile, bits, name);
17459         break;
17460       case DW_ATE_float:
17461         type = dwarf2_init_float_type (objfile, bits, name, name);
17462         break;
17463       case DW_ATE_signed:
17464         type = init_integer_type (objfile, bits, 0, name);
17465         break;
17466       case DW_ATE_unsigned:
17467         if (cu->language == language_fortran
17468             && name
17469             && startswith (name, "character("))
17470           type = init_character_type (objfile, bits, 1, name);
17471         else
17472           type = init_integer_type (objfile, bits, 1, name);
17473         break;
17474       case DW_ATE_signed_char:
17475         if (cu->language == language_ada || cu->language == language_m2
17476             || cu->language == language_pascal
17477             || cu->language == language_fortran)
17478           type = init_character_type (objfile, bits, 0, name);
17479         else
17480           type = init_integer_type (objfile, bits, 0, name);
17481         break;
17482       case DW_ATE_unsigned_char:
17483         if (cu->language == language_ada || cu->language == language_m2
17484             || cu->language == language_pascal
17485             || cu->language == language_fortran
17486             || cu->language == language_rust)
17487           type = init_character_type (objfile, bits, 1, name);
17488         else
17489           type = init_integer_type (objfile, bits, 1, name);
17490         break;
17491       case DW_ATE_UTF:
17492         {
17493           gdbarch *arch = get_objfile_arch (objfile);
17494
17495           if (bits == 16)
17496             type = builtin_type (arch)->builtin_char16;
17497           else if (bits == 32)
17498             type = builtin_type (arch)->builtin_char32;
17499           else
17500             {
17501               complaint (&symfile_complaints,
17502                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17503                          bits);
17504               type = init_integer_type (objfile, bits, 1, name);
17505             }
17506           return set_die_type (die, type, cu);
17507         }
17508         break;
17509
17510       default:
17511         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17512                    dwarf_type_encoding_name (encoding));
17513         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17514         break;
17515     }
17516
17517   if (name && strcmp (name, "char") == 0)
17518     TYPE_NOSIGN (type) = 1;
17519
17520   maybe_set_alignment (cu, die, type);
17521
17522   return set_die_type (die, type, cu);
17523 }
17524
17525 /* Parse dwarf attribute if it's a block, reference or constant and put the
17526    resulting value of the attribute into struct bound_prop.
17527    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17528
17529 static int
17530 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17531                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17532 {
17533   struct dwarf2_property_baton *baton;
17534   struct obstack *obstack
17535     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17536
17537   if (attr == NULL || prop == NULL)
17538     return 0;
17539
17540   if (attr_form_is_block (attr))
17541     {
17542       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17543       baton->referenced_type = NULL;
17544       baton->locexpr.per_cu = cu->per_cu;
17545       baton->locexpr.size = DW_BLOCK (attr)->size;
17546       baton->locexpr.data = DW_BLOCK (attr)->data;
17547       prop->data.baton = baton;
17548       prop->kind = PROP_LOCEXPR;
17549       gdb_assert (prop->data.baton != NULL);
17550     }
17551   else if (attr_form_is_ref (attr))
17552     {
17553       struct dwarf2_cu *target_cu = cu;
17554       struct die_info *target_die;
17555       struct attribute *target_attr;
17556
17557       target_die = follow_die_ref (die, attr, &target_cu);
17558       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17559       if (target_attr == NULL)
17560         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17561                                    target_cu);
17562       if (target_attr == NULL)
17563         return 0;
17564
17565       switch (target_attr->name)
17566         {
17567           case DW_AT_location:
17568             if (attr_form_is_section_offset (target_attr))
17569               {
17570                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17571                 baton->referenced_type = die_type (target_die, target_cu);
17572                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17573                 prop->data.baton = baton;
17574                 prop->kind = PROP_LOCLIST;
17575                 gdb_assert (prop->data.baton != NULL);
17576               }
17577             else if (attr_form_is_block (target_attr))
17578               {
17579                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17580                 baton->referenced_type = die_type (target_die, target_cu);
17581                 baton->locexpr.per_cu = cu->per_cu;
17582                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17583                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17584                 prop->data.baton = baton;
17585                 prop->kind = PROP_LOCEXPR;
17586                 gdb_assert (prop->data.baton != NULL);
17587               }
17588             else
17589               {
17590                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17591                                                        "dynamic property");
17592                 return 0;
17593               }
17594             break;
17595           case DW_AT_data_member_location:
17596             {
17597               LONGEST offset;
17598
17599               if (!handle_data_member_location (target_die, target_cu,
17600                                                 &offset))
17601                 return 0;
17602
17603               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17604               baton->referenced_type = read_type_die (target_die->parent,
17605                                                       target_cu);
17606               baton->offset_info.offset = offset;
17607               baton->offset_info.type = die_type (target_die, target_cu);
17608               prop->data.baton = baton;
17609               prop->kind = PROP_ADDR_OFFSET;
17610               break;
17611             }
17612         }
17613     }
17614   else if (attr_form_is_constant (attr))
17615     {
17616       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17617       prop->kind = PROP_CONST;
17618     }
17619   else
17620     {
17621       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17622                                              dwarf2_name (die, cu));
17623       return 0;
17624     }
17625
17626   return 1;
17627 }
17628
17629 /* Read the given DW_AT_subrange DIE.  */
17630
17631 static struct type *
17632 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17633 {
17634   struct type *base_type, *orig_base_type;
17635   struct type *range_type;
17636   struct attribute *attr;
17637   struct dynamic_prop low, high;
17638   int low_default_is_valid;
17639   int high_bound_is_count = 0;
17640   const char *name;
17641   LONGEST negative_mask;
17642
17643   orig_base_type = die_type (die, cu);
17644   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17645      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17646      creating the range type, but we use the result of check_typedef
17647      when examining properties of the type.  */
17648   base_type = check_typedef (orig_base_type);
17649
17650   /* The die_type call above may have already set the type for this DIE.  */
17651   range_type = get_die_type (die, cu);
17652   if (range_type)
17653     return range_type;
17654
17655   low.kind = PROP_CONST;
17656   high.kind = PROP_CONST;
17657   high.data.const_val = 0;
17658
17659   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17660      omitting DW_AT_lower_bound.  */
17661   switch (cu->language)
17662     {
17663     case language_c:
17664     case language_cplus:
17665       low.data.const_val = 0;
17666       low_default_is_valid = 1;
17667       break;
17668     case language_fortran:
17669       low.data.const_val = 1;
17670       low_default_is_valid = 1;
17671       break;
17672     case language_d:
17673     case language_objc:
17674     case language_rust:
17675       low.data.const_val = 0;
17676       low_default_is_valid = (cu->header.version >= 4);
17677       break;
17678     case language_ada:
17679     case language_m2:
17680     case language_pascal:
17681       low.data.const_val = 1;
17682       low_default_is_valid = (cu->header.version >= 4);
17683       break;
17684     default:
17685       low.data.const_val = 0;
17686       low_default_is_valid = 0;
17687       break;
17688     }
17689
17690   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17691   if (attr)
17692     attr_to_dynamic_prop (attr, die, cu, &low);
17693   else if (!low_default_is_valid)
17694     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17695                                       "- DIE at %s [in module %s]"),
17696                sect_offset_str (die->sect_off),
17697                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17698
17699   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17700   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17701     {
17702       attr = dwarf2_attr (die, DW_AT_count, cu);
17703       if (attr_to_dynamic_prop (attr, die, cu, &high))
17704         {
17705           /* If bounds are constant do the final calculation here.  */
17706           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17707             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17708           else
17709             high_bound_is_count = 1;
17710         }
17711     }
17712
17713   /* Dwarf-2 specifications explicitly allows to create subrange types
17714      without specifying a base type.
17715      In that case, the base type must be set to the type of
17716      the lower bound, upper bound or count, in that order, if any of these
17717      three attributes references an object that has a type.
17718      If no base type is found, the Dwarf-2 specifications say that
17719      a signed integer type of size equal to the size of an address should
17720      be used.
17721      For the following C code: `extern char gdb_int [];'
17722      GCC produces an empty range DIE.
17723      FIXME: muller/2010-05-28: Possible references to object for low bound,
17724      high bound or count are not yet handled by this code.  */
17725   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17726     {
17727       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17728       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17729       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17730       struct type *int_type = objfile_type (objfile)->builtin_int;
17731
17732       /* Test "int", "long int", and "long long int" objfile types,
17733          and select the first one having a size above or equal to the
17734          architecture address size.  */
17735       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17736         base_type = int_type;
17737       else
17738         {
17739           int_type = objfile_type (objfile)->builtin_long;
17740           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17741             base_type = int_type;
17742           else
17743             {
17744               int_type = objfile_type (objfile)->builtin_long_long;
17745               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17746                 base_type = int_type;
17747             }
17748         }
17749     }
17750
17751   /* Normally, the DWARF producers are expected to use a signed
17752      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17753      But this is unfortunately not always the case, as witnessed
17754      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17755      is used instead.  To work around that ambiguity, we treat
17756      the bounds as signed, and thus sign-extend their values, when
17757      the base type is signed.  */
17758   negative_mask =
17759     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17760   if (low.kind == PROP_CONST
17761       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17762     low.data.const_val |= negative_mask;
17763   if (high.kind == PROP_CONST
17764       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17765     high.data.const_val |= negative_mask;
17766
17767   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17768
17769   if (high_bound_is_count)
17770     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17771
17772   /* Ada expects an empty array on no boundary attributes.  */
17773   if (attr == NULL && cu->language != language_ada)
17774     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17775
17776   name = dwarf2_name (die, cu);
17777   if (name)
17778     TYPE_NAME (range_type) = name;
17779
17780   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17781   if (attr)
17782     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17783
17784   maybe_set_alignment (cu, die, range_type);
17785
17786   set_die_type (die, range_type, cu);
17787
17788   /* set_die_type should be already done.  */
17789   set_descriptive_type (range_type, die, cu);
17790
17791   return range_type;
17792 }
17793
17794 static struct type *
17795 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17796 {
17797   struct type *type;
17798
17799   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17800                     NULL);
17801   TYPE_NAME (type) = dwarf2_name (die, cu);
17802
17803   /* In Ada, an unspecified type is typically used when the description
17804      of the type is defered to a different unit.  When encountering
17805      such a type, we treat it as a stub, and try to resolve it later on,
17806      when needed.  */
17807   if (cu->language == language_ada)
17808     TYPE_STUB (type) = 1;
17809
17810   return set_die_type (die, type, cu);
17811 }
17812
17813 /* Read a single die and all its descendents.  Set the die's sibling
17814    field to NULL; set other fields in the die correctly, and set all
17815    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17816    location of the info_ptr after reading all of those dies.  PARENT
17817    is the parent of the die in question.  */
17818
17819 static struct die_info *
17820 read_die_and_children (const struct die_reader_specs *reader,
17821                        const gdb_byte *info_ptr,
17822                        const gdb_byte **new_info_ptr,
17823                        struct die_info *parent)
17824 {
17825   struct die_info *die;
17826   const gdb_byte *cur_ptr;
17827   int has_children;
17828
17829   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17830   if (die == NULL)
17831     {
17832       *new_info_ptr = cur_ptr;
17833       return NULL;
17834     }
17835   store_in_ref_table (die, reader->cu);
17836
17837   if (has_children)
17838     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17839   else
17840     {
17841       die->child = NULL;
17842       *new_info_ptr = cur_ptr;
17843     }
17844
17845   die->sibling = NULL;
17846   die->parent = parent;
17847   return die;
17848 }
17849
17850 /* Read a die, all of its descendents, and all of its siblings; set
17851    all of the fields of all of the dies correctly.  Arguments are as
17852    in read_die_and_children.  */
17853
17854 static struct die_info *
17855 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17856                          const gdb_byte *info_ptr,
17857                          const gdb_byte **new_info_ptr,
17858                          struct die_info *parent)
17859 {
17860   struct die_info *first_die, *last_sibling;
17861   const gdb_byte *cur_ptr;
17862
17863   cur_ptr = info_ptr;
17864   first_die = last_sibling = NULL;
17865
17866   while (1)
17867     {
17868       struct die_info *die
17869         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17870
17871       if (die == NULL)
17872         {
17873           *new_info_ptr = cur_ptr;
17874           return first_die;
17875         }
17876
17877       if (!first_die)
17878         first_die = die;
17879       else
17880         last_sibling->sibling = die;
17881
17882       last_sibling = die;
17883     }
17884 }
17885
17886 /* Read a die, all of its descendents, and all of its siblings; set
17887    all of the fields of all of the dies correctly.  Arguments are as
17888    in read_die_and_children.
17889    This the main entry point for reading a DIE and all its children.  */
17890
17891 static struct die_info *
17892 read_die_and_siblings (const struct die_reader_specs *reader,
17893                        const gdb_byte *info_ptr,
17894                        const gdb_byte **new_info_ptr,
17895                        struct die_info *parent)
17896 {
17897   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17898                                                   new_info_ptr, parent);
17899
17900   if (dwarf_die_debug)
17901     {
17902       fprintf_unfiltered (gdb_stdlog,
17903                           "Read die from %s@0x%x of %s:\n",
17904                           get_section_name (reader->die_section),
17905                           (unsigned) (info_ptr - reader->die_section->buffer),
17906                           bfd_get_filename (reader->abfd));
17907       dump_die (die, dwarf_die_debug);
17908     }
17909
17910   return die;
17911 }
17912
17913 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17914    attributes.
17915    The caller is responsible for filling in the extra attributes
17916    and updating (*DIEP)->num_attrs.
17917    Set DIEP to point to a newly allocated die with its information,
17918    except for its child, sibling, and parent fields.
17919    Set HAS_CHILDREN to tell whether the die has children or not.  */
17920
17921 static const gdb_byte *
17922 read_full_die_1 (const struct die_reader_specs *reader,
17923                  struct die_info **diep, const gdb_byte *info_ptr,
17924                  int *has_children, int num_extra_attrs)
17925 {
17926   unsigned int abbrev_number, bytes_read, i;
17927   struct abbrev_info *abbrev;
17928   struct die_info *die;
17929   struct dwarf2_cu *cu = reader->cu;
17930   bfd *abfd = reader->abfd;
17931
17932   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17933   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17934   info_ptr += bytes_read;
17935   if (!abbrev_number)
17936     {
17937       *diep = NULL;
17938       *has_children = 0;
17939       return info_ptr;
17940     }
17941
17942   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17943   if (!abbrev)
17944     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17945            abbrev_number,
17946            bfd_get_filename (abfd));
17947
17948   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17949   die->sect_off = sect_off;
17950   die->tag = abbrev->tag;
17951   die->abbrev = abbrev_number;
17952
17953   /* Make the result usable.
17954      The caller needs to update num_attrs after adding the extra
17955      attributes.  */
17956   die->num_attrs = abbrev->num_attrs;
17957
17958   for (i = 0; i < abbrev->num_attrs; ++i)
17959     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17960                                info_ptr);
17961
17962   *diep = die;
17963   *has_children = abbrev->has_children;
17964   return info_ptr;
17965 }
17966
17967 /* Read a die and all its attributes.
17968    Set DIEP to point to a newly allocated die with its information,
17969    except for its child, sibling, and parent fields.
17970    Set HAS_CHILDREN to tell whether the die has children or not.  */
17971
17972 static const gdb_byte *
17973 read_full_die (const struct die_reader_specs *reader,
17974                struct die_info **diep, const gdb_byte *info_ptr,
17975                int *has_children)
17976 {
17977   const gdb_byte *result;
17978
17979   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17980
17981   if (dwarf_die_debug)
17982     {
17983       fprintf_unfiltered (gdb_stdlog,
17984                           "Read die from %s@0x%x of %s:\n",
17985                           get_section_name (reader->die_section),
17986                           (unsigned) (info_ptr - reader->die_section->buffer),
17987                           bfd_get_filename (reader->abfd));
17988       dump_die (*diep, dwarf_die_debug);
17989     }
17990
17991   return result;
17992 }
17993 \f
17994 /* Abbreviation tables.
17995
17996    In DWARF version 2, the description of the debugging information is
17997    stored in a separate .debug_abbrev section.  Before we read any
17998    dies from a section we read in all abbreviations and install them
17999    in a hash table.  */
18000
18001 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18002
18003 struct abbrev_info *
18004 abbrev_table::alloc_abbrev ()
18005 {
18006   struct abbrev_info *abbrev;
18007
18008   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18009   memset (abbrev, 0, sizeof (struct abbrev_info));
18010
18011   return abbrev;
18012 }
18013
18014 /* Add an abbreviation to the table.  */
18015
18016 void
18017 abbrev_table::add_abbrev (unsigned int abbrev_number,
18018                           struct abbrev_info *abbrev)
18019 {
18020   unsigned int hash_number;
18021
18022   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18023   abbrev->next = m_abbrevs[hash_number];
18024   m_abbrevs[hash_number] = abbrev;
18025 }
18026
18027 /* Look up an abbrev in the table.
18028    Returns NULL if the abbrev is not found.  */
18029
18030 struct abbrev_info *
18031 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18032 {
18033   unsigned int hash_number;
18034   struct abbrev_info *abbrev;
18035
18036   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18037   abbrev = m_abbrevs[hash_number];
18038
18039   while (abbrev)
18040     {
18041       if (abbrev->number == abbrev_number)
18042         return abbrev;
18043       abbrev = abbrev->next;
18044     }
18045   return NULL;
18046 }
18047
18048 /* Read in an abbrev table.  */
18049
18050 static abbrev_table_up
18051 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18052                          struct dwarf2_section_info *section,
18053                          sect_offset sect_off)
18054 {
18055   struct objfile *objfile = dwarf2_per_objfile->objfile;
18056   bfd *abfd = get_section_bfd_owner (section);
18057   const gdb_byte *abbrev_ptr;
18058   struct abbrev_info *cur_abbrev;
18059   unsigned int abbrev_number, bytes_read, abbrev_name;
18060   unsigned int abbrev_form;
18061   struct attr_abbrev *cur_attrs;
18062   unsigned int allocated_attrs;
18063
18064   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18065
18066   dwarf2_read_section (objfile, section);
18067   abbrev_ptr = section->buffer + to_underlying (sect_off);
18068   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18069   abbrev_ptr += bytes_read;
18070
18071   allocated_attrs = ATTR_ALLOC_CHUNK;
18072   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18073
18074   /* Loop until we reach an abbrev number of 0.  */
18075   while (abbrev_number)
18076     {
18077       cur_abbrev = abbrev_table->alloc_abbrev ();
18078
18079       /* read in abbrev header */
18080       cur_abbrev->number = abbrev_number;
18081       cur_abbrev->tag
18082         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18083       abbrev_ptr += bytes_read;
18084       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18085       abbrev_ptr += 1;
18086
18087       /* now read in declarations */
18088       for (;;)
18089         {
18090           LONGEST implicit_const;
18091
18092           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18093           abbrev_ptr += bytes_read;
18094           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18095           abbrev_ptr += bytes_read;
18096           if (abbrev_form == DW_FORM_implicit_const)
18097             {
18098               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18099                                                    &bytes_read);
18100               abbrev_ptr += bytes_read;
18101             }
18102           else
18103             {
18104               /* Initialize it due to a false compiler warning.  */
18105               implicit_const = -1;
18106             }
18107
18108           if (abbrev_name == 0)
18109             break;
18110
18111           if (cur_abbrev->num_attrs == allocated_attrs)
18112             {
18113               allocated_attrs += ATTR_ALLOC_CHUNK;
18114               cur_attrs
18115                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18116             }
18117
18118           cur_attrs[cur_abbrev->num_attrs].name
18119             = (enum dwarf_attribute) abbrev_name;
18120           cur_attrs[cur_abbrev->num_attrs].form
18121             = (enum dwarf_form) abbrev_form;
18122           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18123           ++cur_abbrev->num_attrs;
18124         }
18125
18126       cur_abbrev->attrs =
18127         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18128                    cur_abbrev->num_attrs);
18129       memcpy (cur_abbrev->attrs, cur_attrs,
18130               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18131
18132       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18133
18134       /* Get next abbreviation.
18135          Under Irix6 the abbreviations for a compilation unit are not
18136          always properly terminated with an abbrev number of 0.
18137          Exit loop if we encounter an abbreviation which we have
18138          already read (which means we are about to read the abbreviations
18139          for the next compile unit) or if the end of the abbreviation
18140          table is reached.  */
18141       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18142         break;
18143       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18144       abbrev_ptr += bytes_read;
18145       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18146         break;
18147     }
18148
18149   xfree (cur_attrs);
18150   return abbrev_table;
18151 }
18152
18153 /* Returns nonzero if TAG represents a type that we might generate a partial
18154    symbol for.  */
18155
18156 static int
18157 is_type_tag_for_partial (int tag)
18158 {
18159   switch (tag)
18160     {
18161 #if 0
18162     /* Some types that would be reasonable to generate partial symbols for,
18163        that we don't at present.  */
18164     case DW_TAG_array_type:
18165     case DW_TAG_file_type:
18166     case DW_TAG_ptr_to_member_type:
18167     case DW_TAG_set_type:
18168     case DW_TAG_string_type:
18169     case DW_TAG_subroutine_type:
18170 #endif
18171     case DW_TAG_base_type:
18172     case DW_TAG_class_type:
18173     case DW_TAG_interface_type:
18174     case DW_TAG_enumeration_type:
18175     case DW_TAG_structure_type:
18176     case DW_TAG_subrange_type:
18177     case DW_TAG_typedef:
18178     case DW_TAG_union_type:
18179       return 1;
18180     default:
18181       return 0;
18182     }
18183 }
18184
18185 /* Load all DIEs that are interesting for partial symbols into memory.  */
18186
18187 static struct partial_die_info *
18188 load_partial_dies (const struct die_reader_specs *reader,
18189                    const gdb_byte *info_ptr, int building_psymtab)
18190 {
18191   struct dwarf2_cu *cu = reader->cu;
18192   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18193   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18194   unsigned int bytes_read;
18195   unsigned int load_all = 0;
18196   int nesting_level = 1;
18197
18198   parent_die = NULL;
18199   last_die = NULL;
18200
18201   gdb_assert (cu->per_cu != NULL);
18202   if (cu->per_cu->load_all_dies)
18203     load_all = 1;
18204
18205   cu->partial_dies
18206     = htab_create_alloc_ex (cu->header.length / 12,
18207                             partial_die_hash,
18208                             partial_die_eq,
18209                             NULL,
18210                             &cu->comp_unit_obstack,
18211                             hashtab_obstack_allocate,
18212                             dummy_obstack_deallocate);
18213
18214   while (1)
18215     {
18216       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18217
18218       /* A NULL abbrev means the end of a series of children.  */
18219       if (abbrev == NULL)
18220         {
18221           if (--nesting_level == 0)
18222             return first_die;
18223
18224           info_ptr += bytes_read;
18225           last_die = parent_die;
18226           parent_die = parent_die->die_parent;
18227           continue;
18228         }
18229
18230       /* Check for template arguments.  We never save these; if
18231          they're seen, we just mark the parent, and go on our way.  */
18232       if (parent_die != NULL
18233           && cu->language == language_cplus
18234           && (abbrev->tag == DW_TAG_template_type_param
18235               || abbrev->tag == DW_TAG_template_value_param))
18236         {
18237           parent_die->has_template_arguments = 1;
18238
18239           if (!load_all)
18240             {
18241               /* We don't need a partial DIE for the template argument.  */
18242               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18243               continue;
18244             }
18245         }
18246
18247       /* We only recurse into c++ subprograms looking for template arguments.
18248          Skip their other children.  */
18249       if (!load_all
18250           && cu->language == language_cplus
18251           && parent_die != NULL
18252           && parent_die->tag == DW_TAG_subprogram)
18253         {
18254           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18255           continue;
18256         }
18257
18258       /* Check whether this DIE is interesting enough to save.  Normally
18259          we would not be interested in members here, but there may be
18260          later variables referencing them via DW_AT_specification (for
18261          static members).  */
18262       if (!load_all
18263           && !is_type_tag_for_partial (abbrev->tag)
18264           && abbrev->tag != DW_TAG_constant
18265           && abbrev->tag != DW_TAG_enumerator
18266           && abbrev->tag != DW_TAG_subprogram
18267           && abbrev->tag != DW_TAG_inlined_subroutine
18268           && abbrev->tag != DW_TAG_lexical_block
18269           && abbrev->tag != DW_TAG_variable
18270           && abbrev->tag != DW_TAG_namespace
18271           && abbrev->tag != DW_TAG_module
18272           && abbrev->tag != DW_TAG_member
18273           && abbrev->tag != DW_TAG_imported_unit
18274           && abbrev->tag != DW_TAG_imported_declaration)
18275         {
18276           /* Otherwise we skip to the next sibling, if any.  */
18277           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18278           continue;
18279         }
18280
18281       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18282                                    abbrev);
18283
18284       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18285
18286       /* This two-pass algorithm for processing partial symbols has a
18287          high cost in cache pressure.  Thus, handle some simple cases
18288          here which cover the majority of C partial symbols.  DIEs
18289          which neither have specification tags in them, nor could have
18290          specification tags elsewhere pointing at them, can simply be
18291          processed and discarded.
18292
18293          This segment is also optional; scan_partial_symbols and
18294          add_partial_symbol will handle these DIEs if we chain
18295          them in normally.  When compilers which do not emit large
18296          quantities of duplicate debug information are more common,
18297          this code can probably be removed.  */
18298
18299       /* Any complete simple types at the top level (pretty much all
18300          of them, for a language without namespaces), can be processed
18301          directly.  */
18302       if (parent_die == NULL
18303           && pdi.has_specification == 0
18304           && pdi.is_declaration == 0
18305           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18306               || pdi.tag == DW_TAG_base_type
18307               || pdi.tag == DW_TAG_subrange_type))
18308         {
18309           if (building_psymtab && pdi.name != NULL)
18310             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18311                                  VAR_DOMAIN, LOC_TYPEDEF,
18312                                  &objfile->static_psymbols,
18313                                  0, cu->language, objfile);
18314           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18315           continue;
18316         }
18317
18318       /* The exception for DW_TAG_typedef with has_children above is
18319          a workaround of GCC PR debug/47510.  In the case of this complaint
18320          type_name_no_tag_or_error will error on such types later.
18321
18322          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18323          it could not find the child DIEs referenced later, this is checked
18324          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18325
18326       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18327         complaint (&symfile_complaints,
18328                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18329                      "- DIE at %s [in module %s]"),
18330                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18331
18332       /* If we're at the second level, and we're an enumerator, and
18333          our parent has no specification (meaning possibly lives in a
18334          namespace elsewhere), then we can add the partial symbol now
18335          instead of queueing it.  */
18336       if (pdi.tag == DW_TAG_enumerator
18337           && parent_die != NULL
18338           && parent_die->die_parent == NULL
18339           && parent_die->tag == DW_TAG_enumeration_type
18340           && parent_die->has_specification == 0)
18341         {
18342           if (pdi.name == NULL)
18343             complaint (&symfile_complaints,
18344                        _("malformed enumerator DIE ignored"));
18345           else if (building_psymtab)
18346             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18347                                  VAR_DOMAIN, LOC_CONST,
18348                                  cu->language == language_cplus
18349                                  ? &objfile->global_psymbols
18350                                  : &objfile->static_psymbols,
18351                                  0, cu->language, objfile);
18352
18353           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18354           continue;
18355         }
18356
18357       struct partial_die_info *part_die
18358         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18359
18360       /* We'll save this DIE so link it in.  */
18361       part_die->die_parent = parent_die;
18362       part_die->die_sibling = NULL;
18363       part_die->die_child = NULL;
18364
18365       if (last_die && last_die == parent_die)
18366         last_die->die_child = part_die;
18367       else if (last_die)
18368         last_die->die_sibling = part_die;
18369
18370       last_die = part_die;
18371
18372       if (first_die == NULL)
18373         first_die = part_die;
18374
18375       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18376          find interesting need to be in the hash table, because we
18377          also have the parent/sibling/child chains; only those that we
18378          might refer to by offset later during partial symbol reading.
18379
18380          For now this means things that might have be the target of a
18381          DW_AT_specification, DW_AT_abstract_origin, or
18382          DW_AT_extension.  DW_AT_extension will refer only to
18383          namespaces; DW_AT_abstract_origin refers to functions (and
18384          many things under the function DIE, but we do not recurse
18385          into function DIEs during partial symbol reading) and
18386          possibly variables as well; DW_AT_specification refers to
18387          declarations.  Declarations ought to have the DW_AT_declaration
18388          flag.  It happens that GCC forgets to put it in sometimes, but
18389          only for functions, not for types.
18390
18391          Adding more things than necessary to the hash table is harmless
18392          except for the performance cost.  Adding too few will result in
18393          wasted time in find_partial_die, when we reread the compilation
18394          unit with load_all_dies set.  */
18395
18396       if (load_all
18397           || abbrev->tag == DW_TAG_constant
18398           || abbrev->tag == DW_TAG_subprogram
18399           || abbrev->tag == DW_TAG_variable
18400           || abbrev->tag == DW_TAG_namespace
18401           || part_die->is_declaration)
18402         {
18403           void **slot;
18404
18405           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18406                                            to_underlying (part_die->sect_off),
18407                                            INSERT);
18408           *slot = part_die;
18409         }
18410
18411       /* For some DIEs we want to follow their children (if any).  For C
18412          we have no reason to follow the children of structures; for other
18413          languages we have to, so that we can get at method physnames
18414          to infer fully qualified class names, for DW_AT_specification,
18415          and for C++ template arguments.  For C++, we also look one level
18416          inside functions to find template arguments (if the name of the
18417          function does not already contain the template arguments).
18418
18419          For Ada, we need to scan the children of subprograms and lexical
18420          blocks as well because Ada allows the definition of nested
18421          entities that could be interesting for the debugger, such as
18422          nested subprograms for instance.  */
18423       if (last_die->has_children
18424           && (load_all
18425               || last_die->tag == DW_TAG_namespace
18426               || last_die->tag == DW_TAG_module
18427               || last_die->tag == DW_TAG_enumeration_type
18428               || (cu->language == language_cplus
18429                   && last_die->tag == DW_TAG_subprogram
18430                   && (last_die->name == NULL
18431                       || strchr (last_die->name, '<') == NULL))
18432               || (cu->language != language_c
18433                   && (last_die->tag == DW_TAG_class_type
18434                       || last_die->tag == DW_TAG_interface_type
18435                       || last_die->tag == DW_TAG_structure_type
18436                       || last_die->tag == DW_TAG_union_type))
18437               || (cu->language == language_ada
18438                   && (last_die->tag == DW_TAG_subprogram
18439                       || last_die->tag == DW_TAG_lexical_block))))
18440         {
18441           nesting_level++;
18442           parent_die = last_die;
18443           continue;
18444         }
18445
18446       /* Otherwise we skip to the next sibling, if any.  */
18447       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18448
18449       /* Back to the top, do it again.  */
18450     }
18451 }
18452
18453 partial_die_info::partial_die_info (sect_offset sect_off_,
18454                                     struct abbrev_info *abbrev)
18455   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18456 {
18457 }
18458
18459 /* Read a minimal amount of information into the minimal die structure.
18460    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18461
18462 const gdb_byte *
18463 partial_die_info::read (const struct die_reader_specs *reader,
18464                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18465 {
18466   struct dwarf2_cu *cu = reader->cu;
18467   struct dwarf2_per_objfile *dwarf2_per_objfile
18468     = cu->per_cu->dwarf2_per_objfile;
18469   unsigned int i;
18470   int has_low_pc_attr = 0;
18471   int has_high_pc_attr = 0;
18472   int high_pc_relative = 0;
18473
18474   for (i = 0; i < abbrev.num_attrs; ++i)
18475     {
18476       struct attribute attr;
18477
18478       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18479
18480       /* Store the data if it is of an attribute we want to keep in a
18481          partial symbol table.  */
18482       switch (attr.name)
18483         {
18484         case DW_AT_name:
18485           switch (tag)
18486             {
18487             case DW_TAG_compile_unit:
18488             case DW_TAG_partial_unit:
18489             case DW_TAG_type_unit:
18490               /* Compilation units have a DW_AT_name that is a filename, not
18491                  a source language identifier.  */
18492             case DW_TAG_enumeration_type:
18493             case DW_TAG_enumerator:
18494               /* These tags always have simple identifiers already; no need
18495                  to canonicalize them.  */
18496               name = DW_STRING (&attr);
18497               break;
18498             default:
18499               {
18500                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18501
18502                 name
18503                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18504                                               &objfile->per_bfd->storage_obstack);
18505               }
18506               break;
18507             }
18508           break;
18509         case DW_AT_linkage_name:
18510         case DW_AT_MIPS_linkage_name:
18511           /* Note that both forms of linkage name might appear.  We
18512              assume they will be the same, and we only store the last
18513              one we see.  */
18514           if (cu->language == language_ada)
18515             name = DW_STRING (&attr);
18516           linkage_name = DW_STRING (&attr);
18517           break;
18518         case DW_AT_low_pc:
18519           has_low_pc_attr = 1;
18520           lowpc = attr_value_as_address (&attr);
18521           break;
18522         case DW_AT_high_pc:
18523           has_high_pc_attr = 1;
18524           highpc = attr_value_as_address (&attr);
18525           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18526                 high_pc_relative = 1;
18527           break;
18528         case DW_AT_location:
18529           /* Support the .debug_loc offsets.  */
18530           if (attr_form_is_block (&attr))
18531             {
18532                d.locdesc = DW_BLOCK (&attr);
18533             }
18534           else if (attr_form_is_section_offset (&attr))
18535             {
18536               dwarf2_complex_location_expr_complaint ();
18537             }
18538           else
18539             {
18540               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18541                                                      "partial symbol information");
18542             }
18543           break;
18544         case DW_AT_external:
18545           is_external = DW_UNSND (&attr);
18546           break;
18547         case DW_AT_declaration:
18548           is_declaration = DW_UNSND (&attr);
18549           break;
18550         case DW_AT_type:
18551           has_type = 1;
18552           break;
18553         case DW_AT_abstract_origin:
18554         case DW_AT_specification:
18555         case DW_AT_extension:
18556           has_specification = 1;
18557           spec_offset = dwarf2_get_ref_die_offset (&attr);
18558           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18559                                    || cu->per_cu->is_dwz);
18560           break;
18561         case DW_AT_sibling:
18562           /* Ignore absolute siblings, they might point outside of
18563              the current compile unit.  */
18564           if (attr.form == DW_FORM_ref_addr)
18565             complaint (&symfile_complaints,
18566                        _("ignoring absolute DW_AT_sibling"));
18567           else
18568             {
18569               const gdb_byte *buffer = reader->buffer;
18570               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18571               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18572
18573               if (sibling_ptr < info_ptr)
18574                 complaint (&symfile_complaints,
18575                            _("DW_AT_sibling points backwards"));
18576               else if (sibling_ptr > reader->buffer_end)
18577                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18578               else
18579                 sibling = sibling_ptr;
18580             }
18581           break;
18582         case DW_AT_byte_size:
18583           has_byte_size = 1;
18584           break;
18585         case DW_AT_const_value:
18586           has_const_value = 1;
18587           break;
18588         case DW_AT_calling_convention:
18589           /* DWARF doesn't provide a way to identify a program's source-level
18590              entry point.  DW_AT_calling_convention attributes are only meant
18591              to describe functions' calling conventions.
18592
18593              However, because it's a necessary piece of information in
18594              Fortran, and before DWARF 4 DW_CC_program was the only
18595              piece of debugging information whose definition refers to
18596              a 'main program' at all, several compilers marked Fortran
18597              main programs with DW_CC_program --- even when those
18598              functions use the standard calling conventions.
18599
18600              Although DWARF now specifies a way to provide this
18601              information, we support this practice for backward
18602              compatibility.  */
18603           if (DW_UNSND (&attr) == DW_CC_program
18604               && cu->language == language_fortran)
18605             main_subprogram = 1;
18606           break;
18607         case DW_AT_inline:
18608           if (DW_UNSND (&attr) == DW_INL_inlined
18609               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18610             may_be_inlined = 1;
18611           break;
18612
18613         case DW_AT_import:
18614           if (tag == DW_TAG_imported_unit)
18615             {
18616               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18617               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18618                                   || cu->per_cu->is_dwz);
18619             }
18620           break;
18621
18622         case DW_AT_main_subprogram:
18623           main_subprogram = DW_UNSND (&attr);
18624           break;
18625
18626         default:
18627           break;
18628         }
18629     }
18630
18631   if (high_pc_relative)
18632     highpc += lowpc;
18633
18634   if (has_low_pc_attr && has_high_pc_attr)
18635     {
18636       /* When using the GNU linker, .gnu.linkonce. sections are used to
18637          eliminate duplicate copies of functions and vtables and such.
18638          The linker will arbitrarily choose one and discard the others.
18639          The AT_*_pc values for such functions refer to local labels in
18640          these sections.  If the section from that file was discarded, the
18641          labels are not in the output, so the relocs get a value of 0.
18642          If this is a discarded function, mark the pc bounds as invalid,
18643          so that GDB will ignore it.  */
18644       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18645         {
18646           struct objfile *objfile = dwarf2_per_objfile->objfile;
18647           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18648
18649           complaint (&symfile_complaints,
18650                      _("DW_AT_low_pc %s is zero "
18651                        "for DIE at %s [in module %s]"),
18652                      paddress (gdbarch, lowpc),
18653                      sect_offset_str (sect_off),
18654                      objfile_name (objfile));
18655         }
18656       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18657       else if (lowpc >= highpc)
18658         {
18659           struct objfile *objfile = dwarf2_per_objfile->objfile;
18660           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18661
18662           complaint (&symfile_complaints,
18663                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18664                        "for DIE at %s [in module %s]"),
18665                      paddress (gdbarch, lowpc),
18666                      paddress (gdbarch, highpc),
18667                      sect_offset_str (sect_off),
18668                      objfile_name (objfile));
18669         }
18670       else
18671         has_pc_info = 1;
18672     }
18673
18674   return info_ptr;
18675 }
18676
18677 /* Find a cached partial DIE at OFFSET in CU.  */
18678
18679 struct partial_die_info *
18680 dwarf2_cu::find_partial_die (sect_offset sect_off)
18681 {
18682   struct partial_die_info *lookup_die = NULL;
18683   struct partial_die_info part_die (sect_off);
18684
18685   lookup_die = ((struct partial_die_info *)
18686                 htab_find_with_hash (partial_dies, &part_die,
18687                                      to_underlying (sect_off)));
18688
18689   return lookup_die;
18690 }
18691
18692 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18693    except in the case of .debug_types DIEs which do not reference
18694    outside their CU (they do however referencing other types via
18695    DW_FORM_ref_sig8).  */
18696
18697 static struct partial_die_info *
18698 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18699 {
18700   struct dwarf2_per_objfile *dwarf2_per_objfile
18701     = cu->per_cu->dwarf2_per_objfile;
18702   struct objfile *objfile = dwarf2_per_objfile->objfile;
18703   struct dwarf2_per_cu_data *per_cu = NULL;
18704   struct partial_die_info *pd = NULL;
18705
18706   if (offset_in_dwz == cu->per_cu->is_dwz
18707       && offset_in_cu_p (&cu->header, sect_off))
18708     {
18709       pd = cu->find_partial_die (sect_off);
18710       if (pd != NULL)
18711         return pd;
18712       /* We missed recording what we needed.
18713          Load all dies and try again.  */
18714       per_cu = cu->per_cu;
18715     }
18716   else
18717     {
18718       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18719       if (cu->per_cu->is_debug_types)
18720         {
18721           error (_("Dwarf Error: Type Unit at offset %s contains"
18722                    " external reference to offset %s [in module %s].\n"),
18723                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18724                  bfd_get_filename (objfile->obfd));
18725         }
18726       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18727                                                  dwarf2_per_objfile);
18728
18729       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18730         load_partial_comp_unit (per_cu);
18731
18732       per_cu->cu->last_used = 0;
18733       pd = per_cu->cu->find_partial_die (sect_off);
18734     }
18735
18736   /* If we didn't find it, and not all dies have been loaded,
18737      load them all and try again.  */
18738
18739   if (pd == NULL && per_cu->load_all_dies == 0)
18740     {
18741       per_cu->load_all_dies = 1;
18742
18743       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18744          THIS_CU->cu may already be in use.  So we can't just free it and
18745          replace its DIEs with the ones we read in.  Instead, we leave those
18746          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18747          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18748          set.  */
18749       load_partial_comp_unit (per_cu);
18750
18751       pd = per_cu->cu->find_partial_die (sect_off);
18752     }
18753
18754   if (pd == NULL)
18755     internal_error (__FILE__, __LINE__,
18756                     _("could not find partial DIE %s "
18757                       "in cache [from module %s]\n"),
18758                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18759   return pd;
18760 }
18761
18762 /* See if we can figure out if the class lives in a namespace.  We do
18763    this by looking for a member function; its demangled name will
18764    contain namespace info, if there is any.  */
18765
18766 static void
18767 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18768                                   struct dwarf2_cu *cu)
18769 {
18770   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18771      what template types look like, because the demangler
18772      frequently doesn't give the same name as the debug info.  We
18773      could fix this by only using the demangled name to get the
18774      prefix (but see comment in read_structure_type).  */
18775
18776   struct partial_die_info *real_pdi;
18777   struct partial_die_info *child_pdi;
18778
18779   /* If this DIE (this DIE's specification, if any) has a parent, then
18780      we should not do this.  We'll prepend the parent's fully qualified
18781      name when we create the partial symbol.  */
18782
18783   real_pdi = struct_pdi;
18784   while (real_pdi->has_specification)
18785     real_pdi = find_partial_die (real_pdi->spec_offset,
18786                                  real_pdi->spec_is_dwz, cu);
18787
18788   if (real_pdi->die_parent != NULL)
18789     return;
18790
18791   for (child_pdi = struct_pdi->die_child;
18792        child_pdi != NULL;
18793        child_pdi = child_pdi->die_sibling)
18794     {
18795       if (child_pdi->tag == DW_TAG_subprogram
18796           && child_pdi->linkage_name != NULL)
18797         {
18798           char *actual_class_name
18799             = language_class_name_from_physname (cu->language_defn,
18800                                                  child_pdi->linkage_name);
18801           if (actual_class_name != NULL)
18802             {
18803               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18804               struct_pdi->name
18805                 = ((const char *)
18806                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18807                                   actual_class_name,
18808                                   strlen (actual_class_name)));
18809               xfree (actual_class_name);
18810             }
18811           break;
18812         }
18813     }
18814 }
18815
18816 void
18817 partial_die_info::fixup (struct dwarf2_cu *cu)
18818 {
18819   /* Once we've fixed up a die, there's no point in doing so again.
18820      This also avoids a memory leak if we were to call
18821      guess_partial_die_structure_name multiple times.  */
18822   if (fixup_called)
18823     return;
18824
18825   /* If we found a reference attribute and the DIE has no name, try
18826      to find a name in the referred to DIE.  */
18827
18828   if (name == NULL && has_specification)
18829     {
18830       struct partial_die_info *spec_die;
18831
18832       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18833
18834       spec_die->fixup (cu);
18835
18836       if (spec_die->name)
18837         {
18838           name = spec_die->name;
18839
18840           /* Copy DW_AT_external attribute if it is set.  */
18841           if (spec_die->is_external)
18842             is_external = spec_die->is_external;
18843         }
18844     }
18845
18846   /* Set default names for some unnamed DIEs.  */
18847
18848   if (name == NULL && tag == DW_TAG_namespace)
18849     name = CP_ANONYMOUS_NAMESPACE_STR;
18850
18851   /* If there is no parent die to provide a namespace, and there are
18852      children, see if we can determine the namespace from their linkage
18853      name.  */
18854   if (cu->language == language_cplus
18855       && !VEC_empty (dwarf2_section_info_def,
18856                      cu->per_cu->dwarf2_per_objfile->types)
18857       && die_parent == NULL
18858       && has_children
18859       && (tag == DW_TAG_class_type
18860           || tag == DW_TAG_structure_type
18861           || tag == DW_TAG_union_type))
18862     guess_partial_die_structure_name (this, cu);
18863
18864   /* GCC might emit a nameless struct or union that has a linkage
18865      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18866   if (name == NULL
18867       && (tag == DW_TAG_class_type
18868           || tag == DW_TAG_interface_type
18869           || tag == DW_TAG_structure_type
18870           || tag == DW_TAG_union_type)
18871       && linkage_name != NULL)
18872     {
18873       char *demangled;
18874
18875       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18876       if (demangled)
18877         {
18878           const char *base;
18879
18880           /* Strip any leading namespaces/classes, keep only the base name.
18881              DW_AT_name for named DIEs does not contain the prefixes.  */
18882           base = strrchr (demangled, ':');
18883           if (base && base > demangled && base[-1] == ':')
18884             base++;
18885           else
18886             base = demangled;
18887
18888           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18889           name
18890             = ((const char *)
18891                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18892                               base, strlen (base)));
18893           xfree (demangled);
18894         }
18895     }
18896
18897   fixup_called = 1;
18898 }
18899
18900 /* Read an attribute value described by an attribute form.  */
18901
18902 static const gdb_byte *
18903 read_attribute_value (const struct die_reader_specs *reader,
18904                       struct attribute *attr, unsigned form,
18905                       LONGEST implicit_const, const gdb_byte *info_ptr)
18906 {
18907   struct dwarf2_cu *cu = reader->cu;
18908   struct dwarf2_per_objfile *dwarf2_per_objfile
18909     = cu->per_cu->dwarf2_per_objfile;
18910   struct objfile *objfile = dwarf2_per_objfile->objfile;
18911   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18912   bfd *abfd = reader->abfd;
18913   struct comp_unit_head *cu_header = &cu->header;
18914   unsigned int bytes_read;
18915   struct dwarf_block *blk;
18916
18917   attr->form = (enum dwarf_form) form;
18918   switch (form)
18919     {
18920     case DW_FORM_ref_addr:
18921       if (cu->header.version == 2)
18922         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18923       else
18924         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18925                                        &cu->header, &bytes_read);
18926       info_ptr += bytes_read;
18927       break;
18928     case DW_FORM_GNU_ref_alt:
18929       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18930       info_ptr += bytes_read;
18931       break;
18932     case DW_FORM_addr:
18933       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18934       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18935       info_ptr += bytes_read;
18936       break;
18937     case DW_FORM_block2:
18938       blk = dwarf_alloc_block (cu);
18939       blk->size = read_2_bytes (abfd, info_ptr);
18940       info_ptr += 2;
18941       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18942       info_ptr += blk->size;
18943       DW_BLOCK (attr) = blk;
18944       break;
18945     case DW_FORM_block4:
18946       blk = dwarf_alloc_block (cu);
18947       blk->size = read_4_bytes (abfd, info_ptr);
18948       info_ptr += 4;
18949       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18950       info_ptr += blk->size;
18951       DW_BLOCK (attr) = blk;
18952       break;
18953     case DW_FORM_data2:
18954       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18955       info_ptr += 2;
18956       break;
18957     case DW_FORM_data4:
18958       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18959       info_ptr += 4;
18960       break;
18961     case DW_FORM_data8:
18962       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18963       info_ptr += 8;
18964       break;
18965     case DW_FORM_data16:
18966       blk = dwarf_alloc_block (cu);
18967       blk->size = 16;
18968       blk->data = read_n_bytes (abfd, info_ptr, 16);
18969       info_ptr += 16;
18970       DW_BLOCK (attr) = blk;
18971       break;
18972     case DW_FORM_sec_offset:
18973       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18974       info_ptr += bytes_read;
18975       break;
18976     case DW_FORM_string:
18977       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18978       DW_STRING_IS_CANONICAL (attr) = 0;
18979       info_ptr += bytes_read;
18980       break;
18981     case DW_FORM_strp:
18982       if (!cu->per_cu->is_dwz)
18983         {
18984           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18985                                                    abfd, info_ptr, cu_header,
18986                                                    &bytes_read);
18987           DW_STRING_IS_CANONICAL (attr) = 0;
18988           info_ptr += bytes_read;
18989           break;
18990         }
18991       /* FALLTHROUGH */
18992     case DW_FORM_line_strp:
18993       if (!cu->per_cu->is_dwz)
18994         {
18995           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18996                                                         abfd, info_ptr,
18997                                                         cu_header, &bytes_read);
18998           DW_STRING_IS_CANONICAL (attr) = 0;
18999           info_ptr += bytes_read;
19000           break;
19001         }
19002       /* FALLTHROUGH */
19003     case DW_FORM_GNU_strp_alt:
19004       {
19005         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19006         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19007                                           &bytes_read);
19008
19009         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19010                                                           dwz, str_offset);
19011         DW_STRING_IS_CANONICAL (attr) = 0;
19012         info_ptr += bytes_read;
19013       }
19014       break;
19015     case DW_FORM_exprloc:
19016     case DW_FORM_block:
19017       blk = dwarf_alloc_block (cu);
19018       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19019       info_ptr += bytes_read;
19020       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19021       info_ptr += blk->size;
19022       DW_BLOCK (attr) = blk;
19023       break;
19024     case DW_FORM_block1:
19025       blk = dwarf_alloc_block (cu);
19026       blk->size = read_1_byte (abfd, info_ptr);
19027       info_ptr += 1;
19028       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19029       info_ptr += blk->size;
19030       DW_BLOCK (attr) = blk;
19031       break;
19032     case DW_FORM_data1:
19033       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19034       info_ptr += 1;
19035       break;
19036     case DW_FORM_flag:
19037       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19038       info_ptr += 1;
19039       break;
19040     case DW_FORM_flag_present:
19041       DW_UNSND (attr) = 1;
19042       break;
19043     case DW_FORM_sdata:
19044       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19045       info_ptr += bytes_read;
19046       break;
19047     case DW_FORM_udata:
19048       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19049       info_ptr += bytes_read;
19050       break;
19051     case DW_FORM_ref1:
19052       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19053                          + read_1_byte (abfd, info_ptr));
19054       info_ptr += 1;
19055       break;
19056     case DW_FORM_ref2:
19057       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19058                          + read_2_bytes (abfd, info_ptr));
19059       info_ptr += 2;
19060       break;
19061     case DW_FORM_ref4:
19062       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19063                          + read_4_bytes (abfd, info_ptr));
19064       info_ptr += 4;
19065       break;
19066     case DW_FORM_ref8:
19067       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19068                          + read_8_bytes (abfd, info_ptr));
19069       info_ptr += 8;
19070       break;
19071     case DW_FORM_ref_sig8:
19072       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19073       info_ptr += 8;
19074       break;
19075     case DW_FORM_ref_udata:
19076       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19077                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19078       info_ptr += bytes_read;
19079       break;
19080     case DW_FORM_indirect:
19081       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19082       info_ptr += bytes_read;
19083       if (form == DW_FORM_implicit_const)
19084         {
19085           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19086           info_ptr += bytes_read;
19087         }
19088       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19089                                        info_ptr);
19090       break;
19091     case DW_FORM_implicit_const:
19092       DW_SND (attr) = implicit_const;
19093       break;
19094     case DW_FORM_GNU_addr_index:
19095       if (reader->dwo_file == NULL)
19096         {
19097           /* For now flag a hard error.
19098              Later we can turn this into a complaint.  */
19099           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19100                  dwarf_form_name (form),
19101                  bfd_get_filename (abfd));
19102         }
19103       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19104       info_ptr += bytes_read;
19105       break;
19106     case DW_FORM_GNU_str_index:
19107       if (reader->dwo_file == NULL)
19108         {
19109           /* For now flag a hard error.
19110              Later we can turn this into a complaint if warranted.  */
19111           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19112                  dwarf_form_name (form),
19113                  bfd_get_filename (abfd));
19114         }
19115       {
19116         ULONGEST str_index =
19117           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19118
19119         DW_STRING (attr) = read_str_index (reader, str_index);
19120         DW_STRING_IS_CANONICAL (attr) = 0;
19121         info_ptr += bytes_read;
19122       }
19123       break;
19124     default:
19125       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19126              dwarf_form_name (form),
19127              bfd_get_filename (abfd));
19128     }
19129
19130   /* Super hack.  */
19131   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19132     attr->form = DW_FORM_GNU_ref_alt;
19133
19134   /* We have seen instances where the compiler tried to emit a byte
19135      size attribute of -1 which ended up being encoded as an unsigned
19136      0xffffffff.  Although 0xffffffff is technically a valid size value,
19137      an object of this size seems pretty unlikely so we can relatively
19138      safely treat these cases as if the size attribute was invalid and
19139      treat them as zero by default.  */
19140   if (attr->name == DW_AT_byte_size
19141       && form == DW_FORM_data4
19142       && DW_UNSND (attr) >= 0xffffffff)
19143     {
19144       complaint
19145         (&symfile_complaints,
19146          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19147          hex_string (DW_UNSND (attr)));
19148       DW_UNSND (attr) = 0;
19149     }
19150
19151   return info_ptr;
19152 }
19153
19154 /* Read an attribute described by an abbreviated attribute.  */
19155
19156 static const gdb_byte *
19157 read_attribute (const struct die_reader_specs *reader,
19158                 struct attribute *attr, struct attr_abbrev *abbrev,
19159                 const gdb_byte *info_ptr)
19160 {
19161   attr->name = abbrev->name;
19162   return read_attribute_value (reader, attr, abbrev->form,
19163                                abbrev->implicit_const, info_ptr);
19164 }
19165
19166 /* Read dwarf information from a buffer.  */
19167
19168 static unsigned int
19169 read_1_byte (bfd *abfd, const gdb_byte *buf)
19170 {
19171   return bfd_get_8 (abfd, buf);
19172 }
19173
19174 static int
19175 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19176 {
19177   return bfd_get_signed_8 (abfd, buf);
19178 }
19179
19180 static unsigned int
19181 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19182 {
19183   return bfd_get_16 (abfd, buf);
19184 }
19185
19186 static int
19187 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19188 {
19189   return bfd_get_signed_16 (abfd, buf);
19190 }
19191
19192 static unsigned int
19193 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19194 {
19195   return bfd_get_32 (abfd, buf);
19196 }
19197
19198 static int
19199 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19200 {
19201   return bfd_get_signed_32 (abfd, buf);
19202 }
19203
19204 static ULONGEST
19205 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19206 {
19207   return bfd_get_64 (abfd, buf);
19208 }
19209
19210 static CORE_ADDR
19211 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19212               unsigned int *bytes_read)
19213 {
19214   struct comp_unit_head *cu_header = &cu->header;
19215   CORE_ADDR retval = 0;
19216
19217   if (cu_header->signed_addr_p)
19218     {
19219       switch (cu_header->addr_size)
19220         {
19221         case 2:
19222           retval = bfd_get_signed_16 (abfd, buf);
19223           break;
19224         case 4:
19225           retval = bfd_get_signed_32 (abfd, buf);
19226           break;
19227         case 8:
19228           retval = bfd_get_signed_64 (abfd, buf);
19229           break;
19230         default:
19231           internal_error (__FILE__, __LINE__,
19232                           _("read_address: bad switch, signed [in module %s]"),
19233                           bfd_get_filename (abfd));
19234         }
19235     }
19236   else
19237     {
19238       switch (cu_header->addr_size)
19239         {
19240         case 2:
19241           retval = bfd_get_16 (abfd, buf);
19242           break;
19243         case 4:
19244           retval = bfd_get_32 (abfd, buf);
19245           break;
19246         case 8:
19247           retval = bfd_get_64 (abfd, buf);
19248           break;
19249         default:
19250           internal_error (__FILE__, __LINE__,
19251                           _("read_address: bad switch, "
19252                             "unsigned [in module %s]"),
19253                           bfd_get_filename (abfd));
19254         }
19255     }
19256
19257   *bytes_read = cu_header->addr_size;
19258   return retval;
19259 }
19260
19261 /* Read the initial length from a section.  The (draft) DWARF 3
19262    specification allows the initial length to take up either 4 bytes
19263    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19264    bytes describe the length and all offsets will be 8 bytes in length
19265    instead of 4.
19266
19267    An older, non-standard 64-bit format is also handled by this
19268    function.  The older format in question stores the initial length
19269    as an 8-byte quantity without an escape value.  Lengths greater
19270    than 2^32 aren't very common which means that the initial 4 bytes
19271    is almost always zero.  Since a length value of zero doesn't make
19272    sense for the 32-bit format, this initial zero can be considered to
19273    be an escape value which indicates the presence of the older 64-bit
19274    format.  As written, the code can't detect (old format) lengths
19275    greater than 4GB.  If it becomes necessary to handle lengths
19276    somewhat larger than 4GB, we could allow other small values (such
19277    as the non-sensical values of 1, 2, and 3) to also be used as
19278    escape values indicating the presence of the old format.
19279
19280    The value returned via bytes_read should be used to increment the
19281    relevant pointer after calling read_initial_length().
19282
19283    [ Note:  read_initial_length() and read_offset() are based on the
19284      document entitled "DWARF Debugging Information Format", revision
19285      3, draft 8, dated November 19, 2001.  This document was obtained
19286      from:
19287
19288         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19289
19290      This document is only a draft and is subject to change.  (So beware.)
19291
19292      Details regarding the older, non-standard 64-bit format were
19293      determined empirically by examining 64-bit ELF files produced by
19294      the SGI toolchain on an IRIX 6.5 machine.
19295
19296      - Kevin, July 16, 2002
19297    ] */
19298
19299 static LONGEST
19300 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19301 {
19302   LONGEST length = bfd_get_32 (abfd, buf);
19303
19304   if (length == 0xffffffff)
19305     {
19306       length = bfd_get_64 (abfd, buf + 4);
19307       *bytes_read = 12;
19308     }
19309   else if (length == 0)
19310     {
19311       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19312       length = bfd_get_64 (abfd, buf);
19313       *bytes_read = 8;
19314     }
19315   else
19316     {
19317       *bytes_read = 4;
19318     }
19319
19320   return length;
19321 }
19322
19323 /* Cover function for read_initial_length.
19324    Returns the length of the object at BUF, and stores the size of the
19325    initial length in *BYTES_READ and stores the size that offsets will be in
19326    *OFFSET_SIZE.
19327    If the initial length size is not equivalent to that specified in
19328    CU_HEADER then issue a complaint.
19329    This is useful when reading non-comp-unit headers.  */
19330
19331 static LONGEST
19332 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19333                                         const struct comp_unit_head *cu_header,
19334                                         unsigned int *bytes_read,
19335                                         unsigned int *offset_size)
19336 {
19337   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19338
19339   gdb_assert (cu_header->initial_length_size == 4
19340               || cu_header->initial_length_size == 8
19341               || cu_header->initial_length_size == 12);
19342
19343   if (cu_header->initial_length_size != *bytes_read)
19344     complaint (&symfile_complaints,
19345                _("intermixed 32-bit and 64-bit DWARF sections"));
19346
19347   *offset_size = (*bytes_read == 4) ? 4 : 8;
19348   return length;
19349 }
19350
19351 /* Read an offset from the data stream.  The size of the offset is
19352    given by cu_header->offset_size.  */
19353
19354 static LONGEST
19355 read_offset (bfd *abfd, const gdb_byte *buf,
19356              const struct comp_unit_head *cu_header,
19357              unsigned int *bytes_read)
19358 {
19359   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19360
19361   *bytes_read = cu_header->offset_size;
19362   return offset;
19363 }
19364
19365 /* Read an offset from the data stream.  */
19366
19367 static LONGEST
19368 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19369 {
19370   LONGEST retval = 0;
19371
19372   switch (offset_size)
19373     {
19374     case 4:
19375       retval = bfd_get_32 (abfd, buf);
19376       break;
19377     case 8:
19378       retval = bfd_get_64 (abfd, buf);
19379       break;
19380     default:
19381       internal_error (__FILE__, __LINE__,
19382                       _("read_offset_1: bad switch [in module %s]"),
19383                       bfd_get_filename (abfd));
19384     }
19385
19386   return retval;
19387 }
19388
19389 static const gdb_byte *
19390 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19391 {
19392   /* If the size of a host char is 8 bits, we can return a pointer
19393      to the buffer, otherwise we have to copy the data to a buffer
19394      allocated on the temporary obstack.  */
19395   gdb_assert (HOST_CHAR_BIT == 8);
19396   return buf;
19397 }
19398
19399 static const char *
19400 read_direct_string (bfd *abfd, const gdb_byte *buf,
19401                     unsigned int *bytes_read_ptr)
19402 {
19403   /* If the size of a host char is 8 bits, we can return a pointer
19404      to the string, otherwise we have to copy the string to a buffer
19405      allocated on the temporary obstack.  */
19406   gdb_assert (HOST_CHAR_BIT == 8);
19407   if (*buf == '\0')
19408     {
19409       *bytes_read_ptr = 1;
19410       return NULL;
19411     }
19412   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19413   return (const char *) buf;
19414 }
19415
19416 /* Return pointer to string at section SECT offset STR_OFFSET with error
19417    reporting strings FORM_NAME and SECT_NAME.  */
19418
19419 static const char *
19420 read_indirect_string_at_offset_from (struct objfile *objfile,
19421                                      bfd *abfd, LONGEST str_offset,
19422                                      struct dwarf2_section_info *sect,
19423                                      const char *form_name,
19424                                      const char *sect_name)
19425 {
19426   dwarf2_read_section (objfile, sect);
19427   if (sect->buffer == NULL)
19428     error (_("%s used without %s section [in module %s]"),
19429            form_name, sect_name, bfd_get_filename (abfd));
19430   if (str_offset >= sect->size)
19431     error (_("%s pointing outside of %s section [in module %s]"),
19432            form_name, sect_name, bfd_get_filename (abfd));
19433   gdb_assert (HOST_CHAR_BIT == 8);
19434   if (sect->buffer[str_offset] == '\0')
19435     return NULL;
19436   return (const char *) (sect->buffer + str_offset);
19437 }
19438
19439 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19440
19441 static const char *
19442 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19443                                 bfd *abfd, LONGEST str_offset)
19444 {
19445   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19446                                               abfd, str_offset,
19447                                               &dwarf2_per_objfile->str,
19448                                               "DW_FORM_strp", ".debug_str");
19449 }
19450
19451 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19452
19453 static const char *
19454 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19455                                      bfd *abfd, LONGEST str_offset)
19456 {
19457   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19458                                               abfd, str_offset,
19459                                               &dwarf2_per_objfile->line_str,
19460                                               "DW_FORM_line_strp",
19461                                               ".debug_line_str");
19462 }
19463
19464 /* Read a string at offset STR_OFFSET in the .debug_str section from
19465    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19466    the string consists of a single NUL byte, return NULL; otherwise
19467    return a pointer to the string.  */
19468
19469 static const char *
19470 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19471                                LONGEST str_offset)
19472 {
19473   dwarf2_read_section (objfile, &dwz->str);
19474
19475   if (dwz->str.buffer == NULL)
19476     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19477              "section [in module %s]"),
19478            bfd_get_filename (dwz->dwz_bfd));
19479   if (str_offset >= dwz->str.size)
19480     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19481              ".debug_str section [in module %s]"),
19482            bfd_get_filename (dwz->dwz_bfd));
19483   gdb_assert (HOST_CHAR_BIT == 8);
19484   if (dwz->str.buffer[str_offset] == '\0')
19485     return NULL;
19486   return (const char *) (dwz->str.buffer + str_offset);
19487 }
19488
19489 /* Return pointer to string at .debug_str offset as read from BUF.
19490    BUF is assumed to be in a compilation unit described by CU_HEADER.
19491    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19492
19493 static const char *
19494 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19495                       const gdb_byte *buf,
19496                       const struct comp_unit_head *cu_header,
19497                       unsigned int *bytes_read_ptr)
19498 {
19499   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19500
19501   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19502 }
19503
19504 /* Return pointer to string at .debug_line_str offset as read from BUF.
19505    BUF is assumed to be in a compilation unit described by CU_HEADER.
19506    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19507
19508 static const char *
19509 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19510                            bfd *abfd, const gdb_byte *buf,
19511                            const struct comp_unit_head *cu_header,
19512                            unsigned int *bytes_read_ptr)
19513 {
19514   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19515
19516   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19517                                               str_offset);
19518 }
19519
19520 ULONGEST
19521 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19522                           unsigned int *bytes_read_ptr)
19523 {
19524   ULONGEST result;
19525   unsigned int num_read;
19526   int shift;
19527   unsigned char byte;
19528
19529   result = 0;
19530   shift = 0;
19531   num_read = 0;
19532   while (1)
19533     {
19534       byte = bfd_get_8 (abfd, buf);
19535       buf++;
19536       num_read++;
19537       result |= ((ULONGEST) (byte & 127) << shift);
19538       if ((byte & 128) == 0)
19539         {
19540           break;
19541         }
19542       shift += 7;
19543     }
19544   *bytes_read_ptr = num_read;
19545   return result;
19546 }
19547
19548 static LONGEST
19549 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19550                     unsigned int *bytes_read_ptr)
19551 {
19552   LONGEST result;
19553   int shift, num_read;
19554   unsigned char byte;
19555
19556   result = 0;
19557   shift = 0;
19558   num_read = 0;
19559   while (1)
19560     {
19561       byte = bfd_get_8 (abfd, buf);
19562       buf++;
19563       num_read++;
19564       result |= ((LONGEST) (byte & 127) << shift);
19565       shift += 7;
19566       if ((byte & 128) == 0)
19567         {
19568           break;
19569         }
19570     }
19571   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19572     result |= -(((LONGEST) 1) << shift);
19573   *bytes_read_ptr = num_read;
19574   return result;
19575 }
19576
19577 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19578    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19579    ADDR_SIZE is the size of addresses from the CU header.  */
19580
19581 static CORE_ADDR
19582 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19583                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19584 {
19585   struct objfile *objfile = dwarf2_per_objfile->objfile;
19586   bfd *abfd = objfile->obfd;
19587   const gdb_byte *info_ptr;
19588
19589   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19590   if (dwarf2_per_objfile->addr.buffer == NULL)
19591     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19592            objfile_name (objfile));
19593   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19594     error (_("DW_FORM_addr_index pointing outside of "
19595              ".debug_addr section [in module %s]"),
19596            objfile_name (objfile));
19597   info_ptr = (dwarf2_per_objfile->addr.buffer
19598               + addr_base + addr_index * addr_size);
19599   if (addr_size == 4)
19600     return bfd_get_32 (abfd, info_ptr);
19601   else
19602     return bfd_get_64 (abfd, info_ptr);
19603 }
19604
19605 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19606
19607 static CORE_ADDR
19608 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19609 {
19610   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19611                             cu->addr_base, cu->header.addr_size);
19612 }
19613
19614 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19615
19616 static CORE_ADDR
19617 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19618                              unsigned int *bytes_read)
19619 {
19620   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19621   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19622
19623   return read_addr_index (cu, addr_index);
19624 }
19625
19626 /* Data structure to pass results from dwarf2_read_addr_index_reader
19627    back to dwarf2_read_addr_index.  */
19628
19629 struct dwarf2_read_addr_index_data
19630 {
19631   ULONGEST addr_base;
19632   int addr_size;
19633 };
19634
19635 /* die_reader_func for dwarf2_read_addr_index.  */
19636
19637 static void
19638 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19639                                const gdb_byte *info_ptr,
19640                                struct die_info *comp_unit_die,
19641                                int has_children,
19642                                void *data)
19643 {
19644   struct dwarf2_cu *cu = reader->cu;
19645   struct dwarf2_read_addr_index_data *aidata =
19646     (struct dwarf2_read_addr_index_data *) data;
19647
19648   aidata->addr_base = cu->addr_base;
19649   aidata->addr_size = cu->header.addr_size;
19650 }
19651
19652 /* Given an index in .debug_addr, fetch the value.
19653    NOTE: This can be called during dwarf expression evaluation,
19654    long after the debug information has been read, and thus per_cu->cu
19655    may no longer exist.  */
19656
19657 CORE_ADDR
19658 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19659                         unsigned int addr_index)
19660 {
19661   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19662   struct dwarf2_cu *cu = per_cu->cu;
19663   ULONGEST addr_base;
19664   int addr_size;
19665
19666   /* We need addr_base and addr_size.
19667      If we don't have PER_CU->cu, we have to get it.
19668      Nasty, but the alternative is storing the needed info in PER_CU,
19669      which at this point doesn't seem justified: it's not clear how frequently
19670      it would get used and it would increase the size of every PER_CU.
19671      Entry points like dwarf2_per_cu_addr_size do a similar thing
19672      so we're not in uncharted territory here.
19673      Alas we need to be a bit more complicated as addr_base is contained
19674      in the DIE.
19675
19676      We don't need to read the entire CU(/TU).
19677      We just need the header and top level die.
19678
19679      IWBN to use the aging mechanism to let us lazily later discard the CU.
19680      For now we skip this optimization.  */
19681
19682   if (cu != NULL)
19683     {
19684       addr_base = cu->addr_base;
19685       addr_size = cu->header.addr_size;
19686     }
19687   else
19688     {
19689       struct dwarf2_read_addr_index_data aidata;
19690
19691       /* Note: We can't use init_cutu_and_read_dies_simple here,
19692          we need addr_base.  */
19693       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19694                                dwarf2_read_addr_index_reader, &aidata);
19695       addr_base = aidata.addr_base;
19696       addr_size = aidata.addr_size;
19697     }
19698
19699   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19700                             addr_size);
19701 }
19702
19703 /* Given a DW_FORM_GNU_str_index, fetch the string.
19704    This is only used by the Fission support.  */
19705
19706 static const char *
19707 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19708 {
19709   struct dwarf2_cu *cu = reader->cu;
19710   struct dwarf2_per_objfile *dwarf2_per_objfile
19711     = cu->per_cu->dwarf2_per_objfile;
19712   struct objfile *objfile = dwarf2_per_objfile->objfile;
19713   const char *objf_name = objfile_name (objfile);
19714   bfd *abfd = objfile->obfd;
19715   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19716   struct dwarf2_section_info *str_offsets_section =
19717     &reader->dwo_file->sections.str_offsets;
19718   const gdb_byte *info_ptr;
19719   ULONGEST str_offset;
19720   static const char form_name[] = "DW_FORM_GNU_str_index";
19721
19722   dwarf2_read_section (objfile, str_section);
19723   dwarf2_read_section (objfile, str_offsets_section);
19724   if (str_section->buffer == NULL)
19725     error (_("%s used without .debug_str.dwo section"
19726              " in CU at offset %s [in module %s]"),
19727            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19728   if (str_offsets_section->buffer == NULL)
19729     error (_("%s used without .debug_str_offsets.dwo section"
19730              " in CU at offset %s [in module %s]"),
19731            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19732   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19733     error (_("%s pointing outside of .debug_str_offsets.dwo"
19734              " section in CU at offset %s [in module %s]"),
19735            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19736   info_ptr = (str_offsets_section->buffer
19737               + str_index * cu->header.offset_size);
19738   if (cu->header.offset_size == 4)
19739     str_offset = bfd_get_32 (abfd, info_ptr);
19740   else
19741     str_offset = bfd_get_64 (abfd, info_ptr);
19742   if (str_offset >= str_section->size)
19743     error (_("Offset from %s pointing outside of"
19744              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19745            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19746   return (const char *) (str_section->buffer + str_offset);
19747 }
19748
19749 /* Return the length of an LEB128 number in BUF.  */
19750
19751 static int
19752 leb128_size (const gdb_byte *buf)
19753 {
19754   const gdb_byte *begin = buf;
19755   gdb_byte byte;
19756
19757   while (1)
19758     {
19759       byte = *buf++;
19760       if ((byte & 128) == 0)
19761         return buf - begin;
19762     }
19763 }
19764
19765 static void
19766 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19767 {
19768   switch (lang)
19769     {
19770     case DW_LANG_C89:
19771     case DW_LANG_C99:
19772     case DW_LANG_C11:
19773     case DW_LANG_C:
19774     case DW_LANG_UPC:
19775       cu->language = language_c;
19776       break;
19777     case DW_LANG_Java:
19778     case DW_LANG_C_plus_plus:
19779     case DW_LANG_C_plus_plus_11:
19780     case DW_LANG_C_plus_plus_14:
19781       cu->language = language_cplus;
19782       break;
19783     case DW_LANG_D:
19784       cu->language = language_d;
19785       break;
19786     case DW_LANG_Fortran77:
19787     case DW_LANG_Fortran90:
19788     case DW_LANG_Fortran95:
19789     case DW_LANG_Fortran03:
19790     case DW_LANG_Fortran08:
19791       cu->language = language_fortran;
19792       break;
19793     case DW_LANG_Go:
19794       cu->language = language_go;
19795       break;
19796     case DW_LANG_Mips_Assembler:
19797       cu->language = language_asm;
19798       break;
19799     case DW_LANG_Ada83:
19800     case DW_LANG_Ada95:
19801       cu->language = language_ada;
19802       break;
19803     case DW_LANG_Modula2:
19804       cu->language = language_m2;
19805       break;
19806     case DW_LANG_Pascal83:
19807       cu->language = language_pascal;
19808       break;
19809     case DW_LANG_ObjC:
19810       cu->language = language_objc;
19811       break;
19812     case DW_LANG_Rust:
19813     case DW_LANG_Rust_old:
19814       cu->language = language_rust;
19815       break;
19816     case DW_LANG_Cobol74:
19817     case DW_LANG_Cobol85:
19818     default:
19819       cu->language = language_minimal;
19820       break;
19821     }
19822   cu->language_defn = language_def (cu->language);
19823 }
19824
19825 /* Return the named attribute or NULL if not there.  */
19826
19827 static struct attribute *
19828 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19829 {
19830   for (;;)
19831     {
19832       unsigned int i;
19833       struct attribute *spec = NULL;
19834
19835       for (i = 0; i < die->num_attrs; ++i)
19836         {
19837           if (die->attrs[i].name == name)
19838             return &die->attrs[i];
19839           if (die->attrs[i].name == DW_AT_specification
19840               || die->attrs[i].name == DW_AT_abstract_origin)
19841             spec = &die->attrs[i];
19842         }
19843
19844       if (!spec)
19845         break;
19846
19847       die = follow_die_ref (die, spec, &cu);
19848     }
19849
19850   return NULL;
19851 }
19852
19853 /* Return the named attribute or NULL if not there,
19854    but do not follow DW_AT_specification, etc.
19855    This is for use in contexts where we're reading .debug_types dies.
19856    Following DW_AT_specification, DW_AT_abstract_origin will take us
19857    back up the chain, and we want to go down.  */
19858
19859 static struct attribute *
19860 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19861 {
19862   unsigned int i;
19863
19864   for (i = 0; i < die->num_attrs; ++i)
19865     if (die->attrs[i].name == name)
19866       return &die->attrs[i];
19867
19868   return NULL;
19869 }
19870
19871 /* Return the string associated with a string-typed attribute, or NULL if it
19872    is either not found or is of an incorrect type.  */
19873
19874 static const char *
19875 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19876 {
19877   struct attribute *attr;
19878   const char *str = NULL;
19879
19880   attr = dwarf2_attr (die, name, cu);
19881
19882   if (attr != NULL)
19883     {
19884       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19885           || attr->form == DW_FORM_string
19886           || attr->form == DW_FORM_GNU_str_index
19887           || attr->form == DW_FORM_GNU_strp_alt)
19888         str = DW_STRING (attr);
19889       else
19890         complaint (&symfile_complaints,
19891                    _("string type expected for attribute %s for "
19892                      "DIE at %s in module %s"),
19893                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19894                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19895     }
19896
19897   return str;
19898 }
19899
19900 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19901    and holds a non-zero value.  This function should only be used for
19902    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19903
19904 static int
19905 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19906 {
19907   struct attribute *attr = dwarf2_attr (die, name, cu);
19908
19909   return (attr && DW_UNSND (attr));
19910 }
19911
19912 static int
19913 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19914 {
19915   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19916      which value is non-zero.  However, we have to be careful with
19917      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19918      (via dwarf2_flag_true_p) follows this attribute.  So we may
19919      end up accidently finding a declaration attribute that belongs
19920      to a different DIE referenced by the specification attribute,
19921      even though the given DIE does not have a declaration attribute.  */
19922   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19923           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19924 }
19925
19926 /* Return the die giving the specification for DIE, if there is
19927    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19928    containing the return value on output.  If there is no
19929    specification, but there is an abstract origin, that is
19930    returned.  */
19931
19932 static struct die_info *
19933 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19934 {
19935   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19936                                              *spec_cu);
19937
19938   if (spec_attr == NULL)
19939     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19940
19941   if (spec_attr == NULL)
19942     return NULL;
19943   else
19944     return follow_die_ref (die, spec_attr, spec_cu);
19945 }
19946
19947 /* Stub for free_line_header to match void * callback types.  */
19948
19949 static void
19950 free_line_header_voidp (void *arg)
19951 {
19952   struct line_header *lh = (struct line_header *) arg;
19953
19954   delete lh;
19955 }
19956
19957 void
19958 line_header::add_include_dir (const char *include_dir)
19959 {
19960   if (dwarf_line_debug >= 2)
19961     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19962                         include_dirs.size () + 1, include_dir);
19963
19964   include_dirs.push_back (include_dir);
19965 }
19966
19967 void
19968 line_header::add_file_name (const char *name,
19969                             dir_index d_index,
19970                             unsigned int mod_time,
19971                             unsigned int length)
19972 {
19973   if (dwarf_line_debug >= 2)
19974     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19975                         (unsigned) file_names.size () + 1, name);
19976
19977   file_names.emplace_back (name, d_index, mod_time, length);
19978 }
19979
19980 /* A convenience function to find the proper .debug_line section for a CU.  */
19981
19982 static struct dwarf2_section_info *
19983 get_debug_line_section (struct dwarf2_cu *cu)
19984 {
19985   struct dwarf2_section_info *section;
19986   struct dwarf2_per_objfile *dwarf2_per_objfile
19987     = cu->per_cu->dwarf2_per_objfile;
19988
19989   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19990      DWO file.  */
19991   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19992     section = &cu->dwo_unit->dwo_file->sections.line;
19993   else if (cu->per_cu->is_dwz)
19994     {
19995       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19996
19997       section = &dwz->line;
19998     }
19999   else
20000     section = &dwarf2_per_objfile->line;
20001
20002   return section;
20003 }
20004
20005 /* Read directory or file name entry format, starting with byte of
20006    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20007    entries count and the entries themselves in the described entry
20008    format.  */
20009
20010 static void
20011 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20012                         bfd *abfd, const gdb_byte **bufp,
20013                         struct line_header *lh,
20014                         const struct comp_unit_head *cu_header,
20015                         void (*callback) (struct line_header *lh,
20016                                           const char *name,
20017                                           dir_index d_index,
20018                                           unsigned int mod_time,
20019                                           unsigned int length))
20020 {
20021   gdb_byte format_count, formati;
20022   ULONGEST data_count, datai;
20023   const gdb_byte *buf = *bufp;
20024   const gdb_byte *format_header_data;
20025   unsigned int bytes_read;
20026
20027   format_count = read_1_byte (abfd, buf);
20028   buf += 1;
20029   format_header_data = buf;
20030   for (formati = 0; formati < format_count; formati++)
20031     {
20032       read_unsigned_leb128 (abfd, buf, &bytes_read);
20033       buf += bytes_read;
20034       read_unsigned_leb128 (abfd, buf, &bytes_read);
20035       buf += bytes_read;
20036     }
20037
20038   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20039   buf += bytes_read;
20040   for (datai = 0; datai < data_count; datai++)
20041     {
20042       const gdb_byte *format = format_header_data;
20043       struct file_entry fe;
20044
20045       for (formati = 0; formati < format_count; formati++)
20046         {
20047           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20048           format += bytes_read;
20049
20050           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20051           format += bytes_read;
20052
20053           gdb::optional<const char *> string;
20054           gdb::optional<unsigned int> uint;
20055
20056           switch (form)
20057             {
20058             case DW_FORM_string:
20059               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20060               buf += bytes_read;
20061               break;
20062
20063             case DW_FORM_line_strp:
20064               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20065                                                          abfd, buf,
20066                                                          cu_header,
20067                                                          &bytes_read));
20068               buf += bytes_read;
20069               break;
20070
20071             case DW_FORM_data1:
20072               uint.emplace (read_1_byte (abfd, buf));
20073               buf += 1;
20074               break;
20075
20076             case DW_FORM_data2:
20077               uint.emplace (read_2_bytes (abfd, buf));
20078               buf += 2;
20079               break;
20080
20081             case DW_FORM_data4:
20082               uint.emplace (read_4_bytes (abfd, buf));
20083               buf += 4;
20084               break;
20085
20086             case DW_FORM_data8:
20087               uint.emplace (read_8_bytes (abfd, buf));
20088               buf += 8;
20089               break;
20090
20091             case DW_FORM_udata:
20092               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20093               buf += bytes_read;
20094               break;
20095
20096             case DW_FORM_block:
20097               /* It is valid only for DW_LNCT_timestamp which is ignored by
20098                  current GDB.  */
20099               break;
20100             }
20101
20102           switch (content_type)
20103             {
20104             case DW_LNCT_path:
20105               if (string.has_value ())
20106                 fe.name = *string;
20107               break;
20108             case DW_LNCT_directory_index:
20109               if (uint.has_value ())
20110                 fe.d_index = (dir_index) *uint;
20111               break;
20112             case DW_LNCT_timestamp:
20113               if (uint.has_value ())
20114                 fe.mod_time = *uint;
20115               break;
20116             case DW_LNCT_size:
20117               if (uint.has_value ())
20118                 fe.length = *uint;
20119               break;
20120             case DW_LNCT_MD5:
20121               break;
20122             default:
20123               complaint (&symfile_complaints,
20124                          _("Unknown format content type %s"),
20125                          pulongest (content_type));
20126             }
20127         }
20128
20129       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20130     }
20131
20132   *bufp = buf;
20133 }
20134
20135 /* Read the statement program header starting at OFFSET in
20136    .debug_line, or .debug_line.dwo.  Return a pointer
20137    to a struct line_header, allocated using xmalloc.
20138    Returns NULL if there is a problem reading the header, e.g., if it
20139    has a version we don't understand.
20140
20141    NOTE: the strings in the include directory and file name tables of
20142    the returned object point into the dwarf line section buffer,
20143    and must not be freed.  */
20144
20145 static line_header_up
20146 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20147 {
20148   const gdb_byte *line_ptr;
20149   unsigned int bytes_read, offset_size;
20150   int i;
20151   const char *cur_dir, *cur_file;
20152   struct dwarf2_section_info *section;
20153   bfd *abfd;
20154   struct dwarf2_per_objfile *dwarf2_per_objfile
20155     = cu->per_cu->dwarf2_per_objfile;
20156
20157   section = get_debug_line_section (cu);
20158   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20159   if (section->buffer == NULL)
20160     {
20161       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20162         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20163       else
20164         complaint (&symfile_complaints, _("missing .debug_line section"));
20165       return 0;
20166     }
20167
20168   /* We can't do this until we know the section is non-empty.
20169      Only then do we know we have such a section.  */
20170   abfd = get_section_bfd_owner (section);
20171
20172   /* Make sure that at least there's room for the total_length field.
20173      That could be 12 bytes long, but we're just going to fudge that.  */
20174   if (to_underlying (sect_off) + 4 >= section->size)
20175     {
20176       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20177       return 0;
20178     }
20179
20180   line_header_up lh (new line_header ());
20181
20182   lh->sect_off = sect_off;
20183   lh->offset_in_dwz = cu->per_cu->is_dwz;
20184
20185   line_ptr = section->buffer + to_underlying (sect_off);
20186
20187   /* Read in the header.  */
20188   lh->total_length =
20189     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20190                                             &bytes_read, &offset_size);
20191   line_ptr += bytes_read;
20192   if (line_ptr + lh->total_length > (section->buffer + section->size))
20193     {
20194       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20195       return 0;
20196     }
20197   lh->statement_program_end = line_ptr + lh->total_length;
20198   lh->version = read_2_bytes (abfd, line_ptr);
20199   line_ptr += 2;
20200   if (lh->version > 5)
20201     {
20202       /* This is a version we don't understand.  The format could have
20203          changed in ways we don't handle properly so just punt.  */
20204       complaint (&symfile_complaints,
20205                  _("unsupported version in .debug_line section"));
20206       return NULL;
20207     }
20208   if (lh->version >= 5)
20209     {
20210       gdb_byte segment_selector_size;
20211
20212       /* Skip address size.  */
20213       read_1_byte (abfd, line_ptr);
20214       line_ptr += 1;
20215
20216       segment_selector_size = read_1_byte (abfd, line_ptr);
20217       line_ptr += 1;
20218       if (segment_selector_size != 0)
20219         {
20220           complaint (&symfile_complaints,
20221                      _("unsupported segment selector size %u "
20222                        "in .debug_line section"),
20223                      segment_selector_size);
20224           return NULL;
20225         }
20226     }
20227   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20228   line_ptr += offset_size;
20229   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20230   line_ptr += 1;
20231   if (lh->version >= 4)
20232     {
20233       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20234       line_ptr += 1;
20235     }
20236   else
20237     lh->maximum_ops_per_instruction = 1;
20238
20239   if (lh->maximum_ops_per_instruction == 0)
20240     {
20241       lh->maximum_ops_per_instruction = 1;
20242       complaint (&symfile_complaints,
20243                  _("invalid maximum_ops_per_instruction "
20244                    "in `.debug_line' section"));
20245     }
20246
20247   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20248   line_ptr += 1;
20249   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20250   line_ptr += 1;
20251   lh->line_range = read_1_byte (abfd, line_ptr);
20252   line_ptr += 1;
20253   lh->opcode_base = read_1_byte (abfd, line_ptr);
20254   line_ptr += 1;
20255   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20256
20257   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20258   for (i = 1; i < lh->opcode_base; ++i)
20259     {
20260       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20261       line_ptr += 1;
20262     }
20263
20264   if (lh->version >= 5)
20265     {
20266       /* Read directory table.  */
20267       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20268                               &cu->header,
20269                               [] (struct line_header *lh, const char *name,
20270                                   dir_index d_index, unsigned int mod_time,
20271                                   unsigned int length)
20272         {
20273           lh->add_include_dir (name);
20274         });
20275
20276       /* Read file name table.  */
20277       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20278                               &cu->header,
20279                               [] (struct line_header *lh, const char *name,
20280                                   dir_index d_index, unsigned int mod_time,
20281                                   unsigned int length)
20282         {
20283           lh->add_file_name (name, d_index, mod_time, length);
20284         });
20285     }
20286   else
20287     {
20288       /* Read directory table.  */
20289       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20290         {
20291           line_ptr += bytes_read;
20292           lh->add_include_dir (cur_dir);
20293         }
20294       line_ptr += bytes_read;
20295
20296       /* Read file name table.  */
20297       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20298         {
20299           unsigned int mod_time, length;
20300           dir_index d_index;
20301
20302           line_ptr += bytes_read;
20303           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20304           line_ptr += bytes_read;
20305           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20306           line_ptr += bytes_read;
20307           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20308           line_ptr += bytes_read;
20309
20310           lh->add_file_name (cur_file, d_index, mod_time, length);
20311         }
20312       line_ptr += bytes_read;
20313     }
20314   lh->statement_program_start = line_ptr;
20315
20316   if (line_ptr > (section->buffer + section->size))
20317     complaint (&symfile_complaints,
20318                _("line number info header doesn't "
20319                  "fit in `.debug_line' section"));
20320
20321   return lh;
20322 }
20323
20324 /* Subroutine of dwarf_decode_lines to simplify it.
20325    Return the file name of the psymtab for included file FILE_INDEX
20326    in line header LH of PST.
20327    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20328    If space for the result is malloc'd, *NAME_HOLDER will be set.
20329    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20330
20331 static const char *
20332 psymtab_include_file_name (const struct line_header *lh, int file_index,
20333                            const struct partial_symtab *pst,
20334                            const char *comp_dir,
20335                            gdb::unique_xmalloc_ptr<char> *name_holder)
20336 {
20337   const file_entry &fe = lh->file_names[file_index];
20338   const char *include_name = fe.name;
20339   const char *include_name_to_compare = include_name;
20340   const char *pst_filename;
20341   int file_is_pst;
20342
20343   const char *dir_name = fe.include_dir (lh);
20344
20345   gdb::unique_xmalloc_ptr<char> hold_compare;
20346   if (!IS_ABSOLUTE_PATH (include_name)
20347       && (dir_name != NULL || comp_dir != NULL))
20348     {
20349       /* Avoid creating a duplicate psymtab for PST.
20350          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20351          Before we do the comparison, however, we need to account
20352          for DIR_NAME and COMP_DIR.
20353          First prepend dir_name (if non-NULL).  If we still don't
20354          have an absolute path prepend comp_dir (if non-NULL).
20355          However, the directory we record in the include-file's
20356          psymtab does not contain COMP_DIR (to match the
20357          corresponding symtab(s)).
20358
20359          Example:
20360
20361          bash$ cd /tmp
20362          bash$ gcc -g ./hello.c
20363          include_name = "hello.c"
20364          dir_name = "."
20365          DW_AT_comp_dir = comp_dir = "/tmp"
20366          DW_AT_name = "./hello.c"
20367
20368       */
20369
20370       if (dir_name != NULL)
20371         {
20372           name_holder->reset (concat (dir_name, SLASH_STRING,
20373                                       include_name, (char *) NULL));
20374           include_name = name_holder->get ();
20375           include_name_to_compare = include_name;
20376         }
20377       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20378         {
20379           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20380                                       include_name, (char *) NULL));
20381           include_name_to_compare = hold_compare.get ();
20382         }
20383     }
20384
20385   pst_filename = pst->filename;
20386   gdb::unique_xmalloc_ptr<char> copied_name;
20387   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20388     {
20389       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20390                                  pst_filename, (char *) NULL));
20391       pst_filename = copied_name.get ();
20392     }
20393
20394   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20395
20396   if (file_is_pst)
20397     return NULL;
20398   return include_name;
20399 }
20400
20401 /* State machine to track the state of the line number program.  */
20402
20403 class lnp_state_machine
20404 {
20405 public:
20406   /* Initialize a machine state for the start of a line number
20407      program.  */
20408   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20409
20410   file_entry *current_file ()
20411   {
20412     /* lh->file_names is 0-based, but the file name numbers in the
20413        statement program are 1-based.  */
20414     return m_line_header->file_name_at (m_file);
20415   }
20416
20417   /* Record the line in the state machine.  END_SEQUENCE is true if
20418      we're processing the end of a sequence.  */
20419   void record_line (bool end_sequence);
20420
20421   /* Check address and if invalid nop-out the rest of the lines in this
20422      sequence.  */
20423   void check_line_address (struct dwarf2_cu *cu,
20424                            const gdb_byte *line_ptr,
20425                            CORE_ADDR lowpc, CORE_ADDR address);
20426
20427   void handle_set_discriminator (unsigned int discriminator)
20428   {
20429     m_discriminator = discriminator;
20430     m_line_has_non_zero_discriminator |= discriminator != 0;
20431   }
20432
20433   /* Handle DW_LNE_set_address.  */
20434   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20435   {
20436     m_op_index = 0;
20437     address += baseaddr;
20438     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20439   }
20440
20441   /* Handle DW_LNS_advance_pc.  */
20442   void handle_advance_pc (CORE_ADDR adjust);
20443
20444   /* Handle a special opcode.  */
20445   void handle_special_opcode (unsigned char op_code);
20446
20447   /* Handle DW_LNS_advance_line.  */
20448   void handle_advance_line (int line_delta)
20449   {
20450     advance_line (line_delta);
20451   }
20452
20453   /* Handle DW_LNS_set_file.  */
20454   void handle_set_file (file_name_index file);
20455
20456   /* Handle DW_LNS_negate_stmt.  */
20457   void handle_negate_stmt ()
20458   {
20459     m_is_stmt = !m_is_stmt;
20460   }
20461
20462   /* Handle DW_LNS_const_add_pc.  */
20463   void handle_const_add_pc ();
20464
20465   /* Handle DW_LNS_fixed_advance_pc.  */
20466   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20467   {
20468     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20469     m_op_index = 0;
20470   }
20471
20472   /* Handle DW_LNS_copy.  */
20473   void handle_copy ()
20474   {
20475     record_line (false);
20476     m_discriminator = 0;
20477   }
20478
20479   /* Handle DW_LNE_end_sequence.  */
20480   void handle_end_sequence ()
20481   {
20482     m_record_line_callback = ::record_line;
20483   }
20484
20485 private:
20486   /* Advance the line by LINE_DELTA.  */
20487   void advance_line (int line_delta)
20488   {
20489     m_line += line_delta;
20490
20491     if (line_delta != 0)
20492       m_line_has_non_zero_discriminator = m_discriminator != 0;
20493   }
20494
20495   gdbarch *m_gdbarch;
20496
20497   /* True if we're recording lines.
20498      Otherwise we're building partial symtabs and are just interested in
20499      finding include files mentioned by the line number program.  */
20500   bool m_record_lines_p;
20501
20502   /* The line number header.  */
20503   line_header *m_line_header;
20504
20505   /* These are part of the standard DWARF line number state machine,
20506      and initialized according to the DWARF spec.  */
20507
20508   unsigned char m_op_index = 0;
20509   /* The line table index (1-based) of the current file.  */
20510   file_name_index m_file = (file_name_index) 1;
20511   unsigned int m_line = 1;
20512
20513   /* These are initialized in the constructor.  */
20514
20515   CORE_ADDR m_address;
20516   bool m_is_stmt;
20517   unsigned int m_discriminator;
20518
20519   /* Additional bits of state we need to track.  */
20520
20521   /* The last file that we called dwarf2_start_subfile for.
20522      This is only used for TLLs.  */
20523   unsigned int m_last_file = 0;
20524   /* The last file a line number was recorded for.  */
20525   struct subfile *m_last_subfile = NULL;
20526
20527   /* The function to call to record a line.  */
20528   record_line_ftype *m_record_line_callback = NULL;
20529
20530   /* The last line number that was recorded, used to coalesce
20531      consecutive entries for the same line.  This can happen, for
20532      example, when discriminators are present.  PR 17276.  */
20533   unsigned int m_last_line = 0;
20534   bool m_line_has_non_zero_discriminator = false;
20535 };
20536
20537 void
20538 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20539 {
20540   CORE_ADDR addr_adj = (((m_op_index + adjust)
20541                          / m_line_header->maximum_ops_per_instruction)
20542                         * m_line_header->minimum_instruction_length);
20543   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20544   m_op_index = ((m_op_index + adjust)
20545                 % m_line_header->maximum_ops_per_instruction);
20546 }
20547
20548 void
20549 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20550 {
20551   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20552   CORE_ADDR addr_adj = (((m_op_index
20553                           + (adj_opcode / m_line_header->line_range))
20554                          / m_line_header->maximum_ops_per_instruction)
20555                         * m_line_header->minimum_instruction_length);
20556   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20557   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20558                 % m_line_header->maximum_ops_per_instruction);
20559
20560   int line_delta = (m_line_header->line_base
20561                     + (adj_opcode % m_line_header->line_range));
20562   advance_line (line_delta);
20563   record_line (false);
20564   m_discriminator = 0;
20565 }
20566
20567 void
20568 lnp_state_machine::handle_set_file (file_name_index file)
20569 {
20570   m_file = file;
20571
20572   const file_entry *fe = current_file ();
20573   if (fe == NULL)
20574     dwarf2_debug_line_missing_file_complaint ();
20575   else if (m_record_lines_p)
20576     {
20577       const char *dir = fe->include_dir (m_line_header);
20578
20579       m_last_subfile = current_subfile;
20580       m_line_has_non_zero_discriminator = m_discriminator != 0;
20581       dwarf2_start_subfile (fe->name, dir);
20582     }
20583 }
20584
20585 void
20586 lnp_state_machine::handle_const_add_pc ()
20587 {
20588   CORE_ADDR adjust
20589     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20590
20591   CORE_ADDR addr_adj
20592     = (((m_op_index + adjust)
20593         / m_line_header->maximum_ops_per_instruction)
20594        * m_line_header->minimum_instruction_length);
20595
20596   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20597   m_op_index = ((m_op_index + adjust)
20598                 % m_line_header->maximum_ops_per_instruction);
20599 }
20600
20601 /* Ignore this record_line request.  */
20602
20603 static void
20604 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20605 {
20606   return;
20607 }
20608
20609 /* Return non-zero if we should add LINE to the line number table.
20610    LINE is the line to add, LAST_LINE is the last line that was added,
20611    LAST_SUBFILE is the subfile for LAST_LINE.
20612    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20613    had a non-zero discriminator.
20614
20615    We have to be careful in the presence of discriminators.
20616    E.g., for this line:
20617
20618      for (i = 0; i < 100000; i++);
20619
20620    clang can emit four line number entries for that one line,
20621    each with a different discriminator.
20622    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20623
20624    However, we want gdb to coalesce all four entries into one.
20625    Otherwise the user could stepi into the middle of the line and
20626    gdb would get confused about whether the pc really was in the
20627    middle of the line.
20628
20629    Things are further complicated by the fact that two consecutive
20630    line number entries for the same line is a heuristic used by gcc
20631    to denote the end of the prologue.  So we can't just discard duplicate
20632    entries, we have to be selective about it.  The heuristic we use is
20633    that we only collapse consecutive entries for the same line if at least
20634    one of those entries has a non-zero discriminator.  PR 17276.
20635
20636    Note: Addresses in the line number state machine can never go backwards
20637    within one sequence, thus this coalescing is ok.  */
20638
20639 static int
20640 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20641                      int line_has_non_zero_discriminator,
20642                      struct subfile *last_subfile)
20643 {
20644   if (current_subfile != last_subfile)
20645     return 1;
20646   if (line != last_line)
20647     return 1;
20648   /* Same line for the same file that we've seen already.
20649      As a last check, for pr 17276, only record the line if the line
20650      has never had a non-zero discriminator.  */
20651   if (!line_has_non_zero_discriminator)
20652     return 1;
20653   return 0;
20654 }
20655
20656 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20657    in the line table of subfile SUBFILE.  */
20658
20659 static void
20660 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20661                      unsigned int line, CORE_ADDR address,
20662                      record_line_ftype p_record_line)
20663 {
20664   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20665
20666   if (dwarf_line_debug)
20667     {
20668       fprintf_unfiltered (gdb_stdlog,
20669                           "Recording line %u, file %s, address %s\n",
20670                           line, lbasename (subfile->name),
20671                           paddress (gdbarch, address));
20672     }
20673
20674   (*p_record_line) (subfile, line, addr);
20675 }
20676
20677 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20678    Mark the end of a set of line number records.
20679    The arguments are the same as for dwarf_record_line_1.
20680    If SUBFILE is NULL the request is ignored.  */
20681
20682 static void
20683 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20684                    CORE_ADDR address, record_line_ftype p_record_line)
20685 {
20686   if (subfile == NULL)
20687     return;
20688
20689   if (dwarf_line_debug)
20690     {
20691       fprintf_unfiltered (gdb_stdlog,
20692                           "Finishing current line, file %s, address %s\n",
20693                           lbasename (subfile->name),
20694                           paddress (gdbarch, address));
20695     }
20696
20697   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20698 }
20699
20700 void
20701 lnp_state_machine::record_line (bool end_sequence)
20702 {
20703   if (dwarf_line_debug)
20704     {
20705       fprintf_unfiltered (gdb_stdlog,
20706                           "Processing actual line %u: file %u,"
20707                           " address %s, is_stmt %u, discrim %u\n",
20708                           m_line, to_underlying (m_file),
20709                           paddress (m_gdbarch, m_address),
20710                           m_is_stmt, m_discriminator);
20711     }
20712
20713   file_entry *fe = current_file ();
20714
20715   if (fe == NULL)
20716     dwarf2_debug_line_missing_file_complaint ();
20717   /* For now we ignore lines not starting on an instruction boundary.
20718      But not when processing end_sequence for compatibility with the
20719      previous version of the code.  */
20720   else if (m_op_index == 0 || end_sequence)
20721     {
20722       fe->included_p = 1;
20723       if (m_record_lines_p && m_is_stmt)
20724         {
20725           if (m_last_subfile != current_subfile || end_sequence)
20726             {
20727               dwarf_finish_line (m_gdbarch, m_last_subfile,
20728                                  m_address, m_record_line_callback);
20729             }
20730
20731           if (!end_sequence)
20732             {
20733               if (dwarf_record_line_p (m_line, m_last_line,
20734                                        m_line_has_non_zero_discriminator,
20735                                        m_last_subfile))
20736                 {
20737                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20738                                        m_line, m_address,
20739                                        m_record_line_callback);
20740                 }
20741               m_last_subfile = current_subfile;
20742               m_last_line = m_line;
20743             }
20744         }
20745     }
20746 }
20747
20748 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20749                                       bool record_lines_p)
20750 {
20751   m_gdbarch = arch;
20752   m_record_lines_p = record_lines_p;
20753   m_line_header = lh;
20754
20755   m_record_line_callback = ::record_line;
20756
20757   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20758      was a line entry for it so that the backend has a chance to adjust it
20759      and also record it in case it needs it.  This is currently used by MIPS
20760      code, cf. `mips_adjust_dwarf2_line'.  */
20761   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20762   m_is_stmt = lh->default_is_stmt;
20763   m_discriminator = 0;
20764 }
20765
20766 void
20767 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20768                                        const gdb_byte *line_ptr,
20769                                        CORE_ADDR lowpc, CORE_ADDR address)
20770 {
20771   /* If address < lowpc then it's not a usable value, it's outside the
20772      pc range of the CU.  However, we restrict the test to only address
20773      values of zero to preserve GDB's previous behaviour which is to
20774      handle the specific case of a function being GC'd by the linker.  */
20775
20776   if (address == 0 && address < lowpc)
20777     {
20778       /* This line table is for a function which has been
20779          GCd by the linker.  Ignore it.  PR gdb/12528 */
20780
20781       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20782       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20783
20784       complaint (&symfile_complaints,
20785                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20786                  line_offset, objfile_name (objfile));
20787       m_record_line_callback = noop_record_line;
20788       /* Note: record_line_callback is left as noop_record_line until
20789          we see DW_LNE_end_sequence.  */
20790     }
20791 }
20792
20793 /* Subroutine of dwarf_decode_lines to simplify it.
20794    Process the line number information in LH.
20795    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20796    program in order to set included_p for every referenced header.  */
20797
20798 static void
20799 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20800                       const int decode_for_pst_p, CORE_ADDR lowpc)
20801 {
20802   const gdb_byte *line_ptr, *extended_end;
20803   const gdb_byte *line_end;
20804   unsigned int bytes_read, extended_len;
20805   unsigned char op_code, extended_op;
20806   CORE_ADDR baseaddr;
20807   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20808   bfd *abfd = objfile->obfd;
20809   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20810   /* True if we're recording line info (as opposed to building partial
20811      symtabs and just interested in finding include files mentioned by
20812      the line number program).  */
20813   bool record_lines_p = !decode_for_pst_p;
20814
20815   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20816
20817   line_ptr = lh->statement_program_start;
20818   line_end = lh->statement_program_end;
20819
20820   /* Read the statement sequences until there's nothing left.  */
20821   while (line_ptr < line_end)
20822     {
20823       /* The DWARF line number program state machine.  Reset the state
20824          machine at the start of each sequence.  */
20825       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20826       bool end_sequence = false;
20827
20828       if (record_lines_p)
20829         {
20830           /* Start a subfile for the current file of the state
20831              machine.  */
20832           const file_entry *fe = state_machine.current_file ();
20833
20834           if (fe != NULL)
20835             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20836         }
20837
20838       /* Decode the table.  */
20839       while (line_ptr < line_end && !end_sequence)
20840         {
20841           op_code = read_1_byte (abfd, line_ptr);
20842           line_ptr += 1;
20843
20844           if (op_code >= lh->opcode_base)
20845             {
20846               /* Special opcode.  */
20847               state_machine.handle_special_opcode (op_code);
20848             }
20849           else switch (op_code)
20850             {
20851             case DW_LNS_extended_op:
20852               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20853                                                    &bytes_read);
20854               line_ptr += bytes_read;
20855               extended_end = line_ptr + extended_len;
20856               extended_op = read_1_byte (abfd, line_ptr);
20857               line_ptr += 1;
20858               switch (extended_op)
20859                 {
20860                 case DW_LNE_end_sequence:
20861                   state_machine.handle_end_sequence ();
20862                   end_sequence = true;
20863                   break;
20864                 case DW_LNE_set_address:
20865                   {
20866                     CORE_ADDR address
20867                       = read_address (abfd, line_ptr, cu, &bytes_read);
20868                     line_ptr += bytes_read;
20869
20870                     state_machine.check_line_address (cu, line_ptr,
20871                                                       lowpc, address);
20872                     state_machine.handle_set_address (baseaddr, address);
20873                   }
20874                   break;
20875                 case DW_LNE_define_file:
20876                   {
20877                     const char *cur_file;
20878                     unsigned int mod_time, length;
20879                     dir_index dindex;
20880
20881                     cur_file = read_direct_string (abfd, line_ptr,
20882                                                    &bytes_read);
20883                     line_ptr += bytes_read;
20884                     dindex = (dir_index)
20885                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20886                     line_ptr += bytes_read;
20887                     mod_time =
20888                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20889                     line_ptr += bytes_read;
20890                     length =
20891                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20892                     line_ptr += bytes_read;
20893                     lh->add_file_name (cur_file, dindex, mod_time, length);
20894                   }
20895                   break;
20896                 case DW_LNE_set_discriminator:
20897                   {
20898                     /* The discriminator is not interesting to the
20899                        debugger; just ignore it.  We still need to
20900                        check its value though:
20901                        if there are consecutive entries for the same
20902                        (non-prologue) line we want to coalesce them.
20903                        PR 17276.  */
20904                     unsigned int discr
20905                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20906                     line_ptr += bytes_read;
20907
20908                     state_machine.handle_set_discriminator (discr);
20909                   }
20910                   break;
20911                 default:
20912                   complaint (&symfile_complaints,
20913                              _("mangled .debug_line section"));
20914                   return;
20915                 }
20916               /* Make sure that we parsed the extended op correctly.  If e.g.
20917                  we expected a different address size than the producer used,
20918                  we may have read the wrong number of bytes.  */
20919               if (line_ptr != extended_end)
20920                 {
20921                   complaint (&symfile_complaints,
20922                              _("mangled .debug_line section"));
20923                   return;
20924                 }
20925               break;
20926             case DW_LNS_copy:
20927               state_machine.handle_copy ();
20928               break;
20929             case DW_LNS_advance_pc:
20930               {
20931                 CORE_ADDR adjust
20932                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20933                 line_ptr += bytes_read;
20934
20935                 state_machine.handle_advance_pc (adjust);
20936               }
20937               break;
20938             case DW_LNS_advance_line:
20939               {
20940                 int line_delta
20941                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20942                 line_ptr += bytes_read;
20943
20944                 state_machine.handle_advance_line (line_delta);
20945               }
20946               break;
20947             case DW_LNS_set_file:
20948               {
20949                 file_name_index file
20950                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20951                                                             &bytes_read);
20952                 line_ptr += bytes_read;
20953
20954                 state_machine.handle_set_file (file);
20955               }
20956               break;
20957             case DW_LNS_set_column:
20958               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20959               line_ptr += bytes_read;
20960               break;
20961             case DW_LNS_negate_stmt:
20962               state_machine.handle_negate_stmt ();
20963               break;
20964             case DW_LNS_set_basic_block:
20965               break;
20966             /* Add to the address register of the state machine the
20967                address increment value corresponding to special opcode
20968                255.  I.e., this value is scaled by the minimum
20969                instruction length since special opcode 255 would have
20970                scaled the increment.  */
20971             case DW_LNS_const_add_pc:
20972               state_machine.handle_const_add_pc ();
20973               break;
20974             case DW_LNS_fixed_advance_pc:
20975               {
20976                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20977                 line_ptr += 2;
20978
20979                 state_machine.handle_fixed_advance_pc (addr_adj);
20980               }
20981               break;
20982             default:
20983               {
20984                 /* Unknown standard opcode, ignore it.  */
20985                 int i;
20986
20987                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20988                   {
20989                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20990                     line_ptr += bytes_read;
20991                   }
20992               }
20993             }
20994         }
20995
20996       if (!end_sequence)
20997         dwarf2_debug_line_missing_end_sequence_complaint ();
20998
20999       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21000          in which case we still finish recording the last line).  */
21001       state_machine.record_line (true);
21002     }
21003 }
21004
21005 /* Decode the Line Number Program (LNP) for the given line_header
21006    structure and CU.  The actual information extracted and the type
21007    of structures created from the LNP depends on the value of PST.
21008
21009    1. If PST is NULL, then this procedure uses the data from the program
21010       to create all necessary symbol tables, and their linetables.
21011
21012    2. If PST is not NULL, this procedure reads the program to determine
21013       the list of files included by the unit represented by PST, and
21014       builds all the associated partial symbol tables.
21015
21016    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21017    It is used for relative paths in the line table.
21018    NOTE: When processing partial symtabs (pst != NULL),
21019    comp_dir == pst->dirname.
21020
21021    NOTE: It is important that psymtabs have the same file name (via strcmp)
21022    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21023    symtab we don't use it in the name of the psymtabs we create.
21024    E.g. expand_line_sal requires this when finding psymtabs to expand.
21025    A good testcase for this is mb-inline.exp.
21026
21027    LOWPC is the lowest address in CU (or 0 if not known).
21028
21029    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21030    for its PC<->lines mapping information.  Otherwise only the filename
21031    table is read in.  */
21032
21033 static void
21034 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21035                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21036                     CORE_ADDR lowpc, int decode_mapping)
21037 {
21038   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21039   const int decode_for_pst_p = (pst != NULL);
21040
21041   if (decode_mapping)
21042     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21043
21044   if (decode_for_pst_p)
21045     {
21046       int file_index;
21047
21048       /* Now that we're done scanning the Line Header Program, we can
21049          create the psymtab of each included file.  */
21050       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21051         if (lh->file_names[file_index].included_p == 1)
21052           {
21053             gdb::unique_xmalloc_ptr<char> name_holder;
21054             const char *include_name =
21055               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21056                                          &name_holder);
21057             if (include_name != NULL)
21058               dwarf2_create_include_psymtab (include_name, pst, objfile);
21059           }
21060     }
21061   else
21062     {
21063       /* Make sure a symtab is created for every file, even files
21064          which contain only variables (i.e. no code with associated
21065          line numbers).  */
21066       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21067       int i;
21068
21069       for (i = 0; i < lh->file_names.size (); i++)
21070         {
21071           file_entry &fe = lh->file_names[i];
21072
21073           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21074
21075           if (current_subfile->symtab == NULL)
21076             {
21077               current_subfile->symtab
21078                 = allocate_symtab (cust, current_subfile->name);
21079             }
21080           fe.symtab = current_subfile->symtab;
21081         }
21082     }
21083 }
21084
21085 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21086    DIRNAME the name of the source directory which contains FILENAME
21087    or NULL if not known.
21088    This routine tries to keep line numbers from identical absolute and
21089    relative file names in a common subfile.
21090
21091    Using the `list' example from the GDB testsuite, which resides in
21092    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21093    of /srcdir/list0.c yields the following debugging information for list0.c:
21094
21095    DW_AT_name:          /srcdir/list0.c
21096    DW_AT_comp_dir:      /compdir
21097    files.files[0].name: list0.h
21098    files.files[0].dir:  /srcdir
21099    files.files[1].name: list0.c
21100    files.files[1].dir:  /srcdir
21101
21102    The line number information for list0.c has to end up in a single
21103    subfile, so that `break /srcdir/list0.c:1' works as expected.
21104    start_subfile will ensure that this happens provided that we pass the
21105    concatenation of files.files[1].dir and files.files[1].name as the
21106    subfile's name.  */
21107
21108 static void
21109 dwarf2_start_subfile (const char *filename, const char *dirname)
21110 {
21111   char *copy = NULL;
21112
21113   /* In order not to lose the line information directory,
21114      we concatenate it to the filename when it makes sense.
21115      Note that the Dwarf3 standard says (speaking of filenames in line
21116      information): ``The directory index is ignored for file names
21117      that represent full path names''.  Thus ignoring dirname in the
21118      `else' branch below isn't an issue.  */
21119
21120   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21121     {
21122       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21123       filename = copy;
21124     }
21125
21126   start_subfile (filename);
21127
21128   if (copy != NULL)
21129     xfree (copy);
21130 }
21131
21132 /* Start a symtab for DWARF.
21133    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21134
21135 static struct compunit_symtab *
21136 dwarf2_start_symtab (struct dwarf2_cu *cu,
21137                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21138 {
21139   struct compunit_symtab *cust
21140     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21141                     low_pc, cu->language);
21142
21143   record_debugformat ("DWARF 2");
21144   record_producer (cu->producer);
21145
21146   /* We assume that we're processing GCC output.  */
21147   processing_gcc_compilation = 2;
21148
21149   cu->processing_has_namespace_info = 0;
21150
21151   return cust;
21152 }
21153
21154 static void
21155 var_decode_location (struct attribute *attr, struct symbol *sym,
21156                      struct dwarf2_cu *cu)
21157 {
21158   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21159   struct comp_unit_head *cu_header = &cu->header;
21160
21161   /* NOTE drow/2003-01-30: There used to be a comment and some special
21162      code here to turn a symbol with DW_AT_external and a
21163      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21164      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21165      with some versions of binutils) where shared libraries could have
21166      relocations against symbols in their debug information - the
21167      minimal symbol would have the right address, but the debug info
21168      would not.  It's no longer necessary, because we will explicitly
21169      apply relocations when we read in the debug information now.  */
21170
21171   /* A DW_AT_location attribute with no contents indicates that a
21172      variable has been optimized away.  */
21173   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21174     {
21175       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21176       return;
21177     }
21178
21179   /* Handle one degenerate form of location expression specially, to
21180      preserve GDB's previous behavior when section offsets are
21181      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21182      then mark this symbol as LOC_STATIC.  */
21183
21184   if (attr_form_is_block (attr)
21185       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21186            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21187           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21188               && (DW_BLOCK (attr)->size
21189                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21190     {
21191       unsigned int dummy;
21192
21193       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21194         SYMBOL_VALUE_ADDRESS (sym) =
21195           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21196       else
21197         SYMBOL_VALUE_ADDRESS (sym) =
21198           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21199       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21200       fixup_symbol_section (sym, objfile);
21201       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21202                                               SYMBOL_SECTION (sym));
21203       return;
21204     }
21205
21206   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21207      expression evaluator, and use LOC_COMPUTED only when necessary
21208      (i.e. when the value of a register or memory location is
21209      referenced, or a thread-local block, etc.).  Then again, it might
21210      not be worthwhile.  I'm assuming that it isn't unless performance
21211      or memory numbers show me otherwise.  */
21212
21213   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21214
21215   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21216     cu->has_loclist = 1;
21217 }
21218
21219 /* Given a pointer to a DWARF information entry, figure out if we need
21220    to make a symbol table entry for it, and if so, create a new entry
21221    and return a pointer to it.
21222    If TYPE is NULL, determine symbol type from the die, otherwise
21223    used the passed type.
21224    If SPACE is not NULL, use it to hold the new symbol.  If it is
21225    NULL, allocate a new symbol on the objfile's obstack.  */
21226
21227 static struct symbol *
21228 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21229             struct symbol *space)
21230 {
21231   struct dwarf2_per_objfile *dwarf2_per_objfile
21232     = cu->per_cu->dwarf2_per_objfile;
21233   struct objfile *objfile = dwarf2_per_objfile->objfile;
21234   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21235   struct symbol *sym = NULL;
21236   const char *name;
21237   struct attribute *attr = NULL;
21238   struct attribute *attr2 = NULL;
21239   CORE_ADDR baseaddr;
21240   struct pending **list_to_add = NULL;
21241
21242   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21243
21244   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21245
21246   name = dwarf2_name (die, cu);
21247   if (name)
21248     {
21249       const char *linkagename;
21250       int suppress_add = 0;
21251
21252       if (space)
21253         sym = space;
21254       else
21255         sym = allocate_symbol (objfile);
21256       OBJSTAT (objfile, n_syms++);
21257
21258       /* Cache this symbol's name and the name's demangled form (if any).  */
21259       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21260       linkagename = dwarf2_physname (name, die, cu);
21261       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21262
21263       /* Fortran does not have mangling standard and the mangling does differ
21264          between gfortran, iFort etc.  */
21265       if (cu->language == language_fortran
21266           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21267         symbol_set_demangled_name (&(sym->ginfo),
21268                                    dwarf2_full_name (name, die, cu),
21269                                    NULL);
21270
21271       /* Default assumptions.
21272          Use the passed type or decode it from the die.  */
21273       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21274       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21275       if (type != NULL)
21276         SYMBOL_TYPE (sym) = type;
21277       else
21278         SYMBOL_TYPE (sym) = die_type (die, cu);
21279       attr = dwarf2_attr (die,
21280                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21281                           cu);
21282       if (attr)
21283         {
21284           SYMBOL_LINE (sym) = DW_UNSND (attr);
21285         }
21286
21287       attr = dwarf2_attr (die,
21288                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21289                           cu);
21290       if (attr)
21291         {
21292           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21293           struct file_entry *fe;
21294
21295           if (cu->line_header != NULL)
21296             fe = cu->line_header->file_name_at (file_index);
21297           else
21298             fe = NULL;
21299
21300           if (fe == NULL)
21301             complaint (&symfile_complaints,
21302                        _("file index out of range"));
21303           else
21304             symbol_set_symtab (sym, fe->symtab);
21305         }
21306
21307       switch (die->tag)
21308         {
21309         case DW_TAG_label:
21310           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21311           if (attr)
21312             {
21313               CORE_ADDR addr;
21314
21315               addr = attr_value_as_address (attr);
21316               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21317               SYMBOL_VALUE_ADDRESS (sym) = addr;
21318             }
21319           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21320           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21321           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21322           add_symbol_to_list (sym, cu->list_in_scope);
21323           break;
21324         case DW_TAG_subprogram:
21325           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21326              finish_block.  */
21327           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21328           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21329           if ((attr2 && (DW_UNSND (attr2) != 0))
21330               || cu->language == language_ada)
21331             {
21332               /* Subprograms marked external are stored as a global symbol.
21333                  Ada subprograms, whether marked external or not, are always
21334                  stored as a global symbol, because we want to be able to
21335                  access them globally.  For instance, we want to be able
21336                  to break on a nested subprogram without having to
21337                  specify the context.  */
21338               list_to_add = &global_symbols;
21339             }
21340           else
21341             {
21342               list_to_add = cu->list_in_scope;
21343             }
21344           break;
21345         case DW_TAG_inlined_subroutine:
21346           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21347              finish_block.  */
21348           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21349           SYMBOL_INLINED (sym) = 1;
21350           list_to_add = cu->list_in_scope;
21351           break;
21352         case DW_TAG_template_value_param:
21353           suppress_add = 1;
21354           /* Fall through.  */
21355         case DW_TAG_constant:
21356         case DW_TAG_variable:
21357         case DW_TAG_member:
21358           /* Compilation with minimal debug info may result in
21359              variables with missing type entries.  Change the
21360              misleading `void' type to something sensible.  */
21361           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21362             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21363
21364           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21365           /* In the case of DW_TAG_member, we should only be called for
21366              static const members.  */
21367           if (die->tag == DW_TAG_member)
21368             {
21369               /* dwarf2_add_field uses die_is_declaration,
21370                  so we do the same.  */
21371               gdb_assert (die_is_declaration (die, cu));
21372               gdb_assert (attr);
21373             }
21374           if (attr)
21375             {
21376               dwarf2_const_value (attr, sym, cu);
21377               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21378               if (!suppress_add)
21379                 {
21380                   if (attr2 && (DW_UNSND (attr2) != 0))
21381                     list_to_add = &global_symbols;
21382                   else
21383                     list_to_add = cu->list_in_scope;
21384                 }
21385               break;
21386             }
21387           attr = dwarf2_attr (die, DW_AT_location, cu);
21388           if (attr)
21389             {
21390               var_decode_location (attr, sym, cu);
21391               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21392
21393               /* Fortran explicitly imports any global symbols to the local
21394                  scope by DW_TAG_common_block.  */
21395               if (cu->language == language_fortran && die->parent
21396                   && die->parent->tag == DW_TAG_common_block)
21397                 attr2 = NULL;
21398
21399               if (SYMBOL_CLASS (sym) == LOC_STATIC
21400                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21401                   && !dwarf2_per_objfile->has_section_at_zero)
21402                 {
21403                   /* When a static variable is eliminated by the linker,
21404                      the corresponding debug information is not stripped
21405                      out, but the variable address is set to null;
21406                      do not add such variables into symbol table.  */
21407                 }
21408               else if (attr2 && (DW_UNSND (attr2) != 0))
21409                 {
21410                   /* Workaround gfortran PR debug/40040 - it uses
21411                      DW_AT_location for variables in -fPIC libraries which may
21412                      get overriden by other libraries/executable and get
21413                      a different address.  Resolve it by the minimal symbol
21414                      which may come from inferior's executable using copy
21415                      relocation.  Make this workaround only for gfortran as for
21416                      other compilers GDB cannot guess the minimal symbol
21417                      Fortran mangling kind.  */
21418                   if (cu->language == language_fortran && die->parent
21419                       && die->parent->tag == DW_TAG_module
21420                       && cu->producer
21421                       && startswith (cu->producer, "GNU Fortran"))
21422                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21423
21424                   /* A variable with DW_AT_external is never static,
21425                      but it may be block-scoped.  */
21426                   list_to_add = (cu->list_in_scope == &file_symbols
21427                                  ? &global_symbols : cu->list_in_scope);
21428                 }
21429               else
21430                 list_to_add = cu->list_in_scope;
21431             }
21432           else
21433             {
21434               /* We do not know the address of this symbol.
21435                  If it is an external symbol and we have type information
21436                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21437                  The address of the variable will then be determined from
21438                  the minimal symbol table whenever the variable is
21439                  referenced.  */
21440               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21441
21442               /* Fortran explicitly imports any global symbols to the local
21443                  scope by DW_TAG_common_block.  */
21444               if (cu->language == language_fortran && die->parent
21445                   && die->parent->tag == DW_TAG_common_block)
21446                 {
21447                   /* SYMBOL_CLASS doesn't matter here because
21448                      read_common_block is going to reset it.  */
21449                   if (!suppress_add)
21450                     list_to_add = cu->list_in_scope;
21451                 }
21452               else if (attr2 && (DW_UNSND (attr2) != 0)
21453                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21454                 {
21455                   /* A variable with DW_AT_external is never static, but it
21456                      may be block-scoped.  */
21457                   list_to_add = (cu->list_in_scope == &file_symbols
21458                                  ? &global_symbols : cu->list_in_scope);
21459
21460                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21461                 }
21462               else if (!die_is_declaration (die, cu))
21463                 {
21464                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21465                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21466                   if (!suppress_add)
21467                     list_to_add = cu->list_in_scope;
21468                 }
21469             }
21470           break;
21471         case DW_TAG_formal_parameter:
21472           /* If we are inside a function, mark this as an argument.  If
21473              not, we might be looking at an argument to an inlined function
21474              when we do not have enough information to show inlined frames;
21475              pretend it's a local variable in that case so that the user can
21476              still see it.  */
21477           if (context_stack_depth > 0
21478               && context_stack[context_stack_depth - 1].name != NULL)
21479             SYMBOL_IS_ARGUMENT (sym) = 1;
21480           attr = dwarf2_attr (die, DW_AT_location, cu);
21481           if (attr)
21482             {
21483               var_decode_location (attr, sym, cu);
21484             }
21485           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21486           if (attr)
21487             {
21488               dwarf2_const_value (attr, sym, cu);
21489             }
21490
21491           list_to_add = cu->list_in_scope;
21492           break;
21493         case DW_TAG_unspecified_parameters:
21494           /* From varargs functions; gdb doesn't seem to have any
21495              interest in this information, so just ignore it for now.
21496              (FIXME?) */
21497           break;
21498         case DW_TAG_template_type_param:
21499           suppress_add = 1;
21500           /* Fall through.  */
21501         case DW_TAG_class_type:
21502         case DW_TAG_interface_type:
21503         case DW_TAG_structure_type:
21504         case DW_TAG_union_type:
21505         case DW_TAG_set_type:
21506         case DW_TAG_enumeration_type:
21507           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21508           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21509
21510           {
21511             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21512                really ever be static objects: otherwise, if you try
21513                to, say, break of a class's method and you're in a file
21514                which doesn't mention that class, it won't work unless
21515                the check for all static symbols in lookup_symbol_aux
21516                saves you.  See the OtherFileClass tests in
21517                gdb.c++/namespace.exp.  */
21518
21519             if (!suppress_add)
21520               {
21521                 list_to_add = (cu->list_in_scope == &file_symbols
21522                                && cu->language == language_cplus
21523                                ? &global_symbols : cu->list_in_scope);
21524
21525                 /* The semantics of C++ state that "struct foo {
21526                    ... }" also defines a typedef for "foo".  */
21527                 if (cu->language == language_cplus
21528                     || cu->language == language_ada
21529                     || cu->language == language_d
21530                     || cu->language == language_rust)
21531                   {
21532                     /* The symbol's name is already allocated along
21533                        with this objfile, so we don't need to
21534                        duplicate it for the type.  */
21535                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21536                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21537                   }
21538               }
21539           }
21540           break;
21541         case DW_TAG_typedef:
21542           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21543           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21544           list_to_add = cu->list_in_scope;
21545           break;
21546         case DW_TAG_base_type:
21547         case DW_TAG_subrange_type:
21548           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21549           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21550           list_to_add = cu->list_in_scope;
21551           break;
21552         case DW_TAG_enumerator:
21553           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21554           if (attr)
21555             {
21556               dwarf2_const_value (attr, sym, cu);
21557             }
21558           {
21559             /* NOTE: carlton/2003-11-10: See comment above in the
21560                DW_TAG_class_type, etc. block.  */
21561
21562             list_to_add = (cu->list_in_scope == &file_symbols
21563                            && cu->language == language_cplus
21564                            ? &global_symbols : cu->list_in_scope);
21565           }
21566           break;
21567         case DW_TAG_imported_declaration:
21568         case DW_TAG_namespace:
21569           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21570           list_to_add = &global_symbols;
21571           break;
21572         case DW_TAG_module:
21573           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21574           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21575           list_to_add = &global_symbols;
21576           break;
21577         case DW_TAG_common_block:
21578           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21579           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21580           add_symbol_to_list (sym, cu->list_in_scope);
21581           break;
21582         default:
21583           /* Not a tag we recognize.  Hopefully we aren't processing
21584              trash data, but since we must specifically ignore things
21585              we don't recognize, there is nothing else we should do at
21586              this point.  */
21587           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21588                      dwarf_tag_name (die->tag));
21589           break;
21590         }
21591
21592       if (suppress_add)
21593         {
21594           sym->hash_next = objfile->template_symbols;
21595           objfile->template_symbols = sym;
21596           list_to_add = NULL;
21597         }
21598
21599       if (list_to_add != NULL)
21600         add_symbol_to_list (sym, list_to_add);
21601
21602       /* For the benefit of old versions of GCC, check for anonymous
21603          namespaces based on the demangled name.  */
21604       if (!cu->processing_has_namespace_info
21605           && cu->language == language_cplus)
21606         cp_scan_for_anonymous_namespaces (sym, objfile);
21607     }
21608   return (sym);
21609 }
21610
21611 /* Given an attr with a DW_FORM_dataN value in host byte order,
21612    zero-extend it as appropriate for the symbol's type.  The DWARF
21613    standard (v4) is not entirely clear about the meaning of using
21614    DW_FORM_dataN for a constant with a signed type, where the type is
21615    wider than the data.  The conclusion of a discussion on the DWARF
21616    list was that this is unspecified.  We choose to always zero-extend
21617    because that is the interpretation long in use by GCC.  */
21618
21619 static gdb_byte *
21620 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21621                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21622 {
21623   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21624   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21625                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21626   LONGEST l = DW_UNSND (attr);
21627
21628   if (bits < sizeof (*value) * 8)
21629     {
21630       l &= ((LONGEST) 1 << bits) - 1;
21631       *value = l;
21632     }
21633   else if (bits == sizeof (*value) * 8)
21634     *value = l;
21635   else
21636     {
21637       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21638       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21639       return bytes;
21640     }
21641
21642   return NULL;
21643 }
21644
21645 /* Read a constant value from an attribute.  Either set *VALUE, or if
21646    the value does not fit in *VALUE, set *BYTES - either already
21647    allocated on the objfile obstack, or newly allocated on OBSTACK,
21648    or, set *BATON, if we translated the constant to a location
21649    expression.  */
21650
21651 static void
21652 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21653                          const char *name, struct obstack *obstack,
21654                          struct dwarf2_cu *cu,
21655                          LONGEST *value, const gdb_byte **bytes,
21656                          struct dwarf2_locexpr_baton **baton)
21657 {
21658   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21659   struct comp_unit_head *cu_header = &cu->header;
21660   struct dwarf_block *blk;
21661   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21662                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21663
21664   *value = 0;
21665   *bytes = NULL;
21666   *baton = NULL;
21667
21668   switch (attr->form)
21669     {
21670     case DW_FORM_addr:
21671     case DW_FORM_GNU_addr_index:
21672       {
21673         gdb_byte *data;
21674
21675         if (TYPE_LENGTH (type) != cu_header->addr_size)
21676           dwarf2_const_value_length_mismatch_complaint (name,
21677                                                         cu_header->addr_size,
21678                                                         TYPE_LENGTH (type));
21679         /* Symbols of this form are reasonably rare, so we just
21680            piggyback on the existing location code rather than writing
21681            a new implementation of symbol_computed_ops.  */
21682         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21683         (*baton)->per_cu = cu->per_cu;
21684         gdb_assert ((*baton)->per_cu);
21685
21686         (*baton)->size = 2 + cu_header->addr_size;
21687         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21688         (*baton)->data = data;
21689
21690         data[0] = DW_OP_addr;
21691         store_unsigned_integer (&data[1], cu_header->addr_size,
21692                                 byte_order, DW_ADDR (attr));
21693         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21694       }
21695       break;
21696     case DW_FORM_string:
21697     case DW_FORM_strp:
21698     case DW_FORM_GNU_str_index:
21699     case DW_FORM_GNU_strp_alt:
21700       /* DW_STRING is already allocated on the objfile obstack, point
21701          directly to it.  */
21702       *bytes = (const gdb_byte *) DW_STRING (attr);
21703       break;
21704     case DW_FORM_block1:
21705     case DW_FORM_block2:
21706     case DW_FORM_block4:
21707     case DW_FORM_block:
21708     case DW_FORM_exprloc:
21709     case DW_FORM_data16:
21710       blk = DW_BLOCK (attr);
21711       if (TYPE_LENGTH (type) != blk->size)
21712         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21713                                                       TYPE_LENGTH (type));
21714       *bytes = blk->data;
21715       break;
21716
21717       /* The DW_AT_const_value attributes are supposed to carry the
21718          symbol's value "represented as it would be on the target
21719          architecture."  By the time we get here, it's already been
21720          converted to host endianness, so we just need to sign- or
21721          zero-extend it as appropriate.  */
21722     case DW_FORM_data1:
21723       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21724       break;
21725     case DW_FORM_data2:
21726       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21727       break;
21728     case DW_FORM_data4:
21729       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21730       break;
21731     case DW_FORM_data8:
21732       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21733       break;
21734
21735     case DW_FORM_sdata:
21736     case DW_FORM_implicit_const:
21737       *value = DW_SND (attr);
21738       break;
21739
21740     case DW_FORM_udata:
21741       *value = DW_UNSND (attr);
21742       break;
21743
21744     default:
21745       complaint (&symfile_complaints,
21746                  _("unsupported const value attribute form: '%s'"),
21747                  dwarf_form_name (attr->form));
21748       *value = 0;
21749       break;
21750     }
21751 }
21752
21753
21754 /* Copy constant value from an attribute to a symbol.  */
21755
21756 static void
21757 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21758                     struct dwarf2_cu *cu)
21759 {
21760   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21761   LONGEST value;
21762   const gdb_byte *bytes;
21763   struct dwarf2_locexpr_baton *baton;
21764
21765   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21766                            SYMBOL_PRINT_NAME (sym),
21767                            &objfile->objfile_obstack, cu,
21768                            &value, &bytes, &baton);
21769
21770   if (baton != NULL)
21771     {
21772       SYMBOL_LOCATION_BATON (sym) = baton;
21773       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21774     }
21775   else if (bytes != NULL)
21776      {
21777       SYMBOL_VALUE_BYTES (sym) = bytes;
21778       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21779     }
21780   else
21781     {
21782       SYMBOL_VALUE (sym) = value;
21783       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21784     }
21785 }
21786
21787 /* Return the type of the die in question using its DW_AT_type attribute.  */
21788
21789 static struct type *
21790 die_type (struct die_info *die, struct dwarf2_cu *cu)
21791 {
21792   struct attribute *type_attr;
21793
21794   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21795   if (!type_attr)
21796     {
21797       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21798       /* A missing DW_AT_type represents a void type.  */
21799       return objfile_type (objfile)->builtin_void;
21800     }
21801
21802   return lookup_die_type (die, type_attr, cu);
21803 }
21804
21805 /* True iff CU's producer generates GNAT Ada auxiliary information
21806    that allows to find parallel types through that information instead
21807    of having to do expensive parallel lookups by type name.  */
21808
21809 static int
21810 need_gnat_info (struct dwarf2_cu *cu)
21811 {
21812   /* Assume that the Ada compiler was GNAT, which always produces
21813      the auxiliary information.  */
21814   return (cu->language == language_ada);
21815 }
21816
21817 /* Return the auxiliary type of the die in question using its
21818    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21819    attribute is not present.  */
21820
21821 static struct type *
21822 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21823 {
21824   struct attribute *type_attr;
21825
21826   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21827   if (!type_attr)
21828     return NULL;
21829
21830   return lookup_die_type (die, type_attr, cu);
21831 }
21832
21833 /* If DIE has a descriptive_type attribute, then set the TYPE's
21834    descriptive type accordingly.  */
21835
21836 static void
21837 set_descriptive_type (struct type *type, struct die_info *die,
21838                       struct dwarf2_cu *cu)
21839 {
21840   struct type *descriptive_type = die_descriptive_type (die, cu);
21841
21842   if (descriptive_type)
21843     {
21844       ALLOCATE_GNAT_AUX_TYPE (type);
21845       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21846     }
21847 }
21848
21849 /* Return the containing type of the die in question using its
21850    DW_AT_containing_type attribute.  */
21851
21852 static struct type *
21853 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21854 {
21855   struct attribute *type_attr;
21856   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21857
21858   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21859   if (!type_attr)
21860     error (_("Dwarf Error: Problem turning containing type into gdb type "
21861              "[in module %s]"), objfile_name (objfile));
21862
21863   return lookup_die_type (die, type_attr, cu);
21864 }
21865
21866 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21867
21868 static struct type *
21869 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21870 {
21871   struct dwarf2_per_objfile *dwarf2_per_objfile
21872     = cu->per_cu->dwarf2_per_objfile;
21873   struct objfile *objfile = dwarf2_per_objfile->objfile;
21874   char *message, *saved;
21875
21876   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21877                         objfile_name (objfile),
21878                         sect_offset_str (cu->header.sect_off),
21879                         sect_offset_str (die->sect_off));
21880   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21881                                   message, strlen (message));
21882   xfree (message);
21883
21884   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21885 }
21886
21887 /* Look up the type of DIE in CU using its type attribute ATTR.
21888    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21889    DW_AT_containing_type.
21890    If there is no type substitute an error marker.  */
21891
21892 static struct type *
21893 lookup_die_type (struct die_info *die, const struct attribute *attr,
21894                  struct dwarf2_cu *cu)
21895 {
21896   struct dwarf2_per_objfile *dwarf2_per_objfile
21897     = cu->per_cu->dwarf2_per_objfile;
21898   struct objfile *objfile = dwarf2_per_objfile->objfile;
21899   struct type *this_type;
21900
21901   gdb_assert (attr->name == DW_AT_type
21902               || attr->name == DW_AT_GNAT_descriptive_type
21903               || attr->name == DW_AT_containing_type);
21904
21905   /* First see if we have it cached.  */
21906
21907   if (attr->form == DW_FORM_GNU_ref_alt)
21908     {
21909       struct dwarf2_per_cu_data *per_cu;
21910       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21911
21912       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21913                                                  dwarf2_per_objfile);
21914       this_type = get_die_type_at_offset (sect_off, per_cu);
21915     }
21916   else if (attr_form_is_ref (attr))
21917     {
21918       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21919
21920       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21921     }
21922   else if (attr->form == DW_FORM_ref_sig8)
21923     {
21924       ULONGEST signature = DW_SIGNATURE (attr);
21925
21926       return get_signatured_type (die, signature, cu);
21927     }
21928   else
21929     {
21930       complaint (&symfile_complaints,
21931                  _("Dwarf Error: Bad type attribute %s in DIE"
21932                    " at %s [in module %s]"),
21933                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21934                  objfile_name (objfile));
21935       return build_error_marker_type (cu, die);
21936     }
21937
21938   /* If not cached we need to read it in.  */
21939
21940   if (this_type == NULL)
21941     {
21942       struct die_info *type_die = NULL;
21943       struct dwarf2_cu *type_cu = cu;
21944
21945       if (attr_form_is_ref (attr))
21946         type_die = follow_die_ref (die, attr, &type_cu);
21947       if (type_die == NULL)
21948         return build_error_marker_type (cu, die);
21949       /* If we find the type now, it's probably because the type came
21950          from an inter-CU reference and the type's CU got expanded before
21951          ours.  */
21952       this_type = read_type_die (type_die, type_cu);
21953     }
21954
21955   /* If we still don't have a type use an error marker.  */
21956
21957   if (this_type == NULL)
21958     return build_error_marker_type (cu, die);
21959
21960   return this_type;
21961 }
21962
21963 /* Return the type in DIE, CU.
21964    Returns NULL for invalid types.
21965
21966    This first does a lookup in die_type_hash,
21967    and only reads the die in if necessary.
21968
21969    NOTE: This can be called when reading in partial or full symbols.  */
21970
21971 static struct type *
21972 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21973 {
21974   struct type *this_type;
21975
21976   this_type = get_die_type (die, cu);
21977   if (this_type)
21978     return this_type;
21979
21980   return read_type_die_1 (die, cu);
21981 }
21982
21983 /* Read the type in DIE, CU.
21984    Returns NULL for invalid types.  */
21985
21986 static struct type *
21987 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21988 {
21989   struct type *this_type = NULL;
21990
21991   switch (die->tag)
21992     {
21993     case DW_TAG_class_type:
21994     case DW_TAG_interface_type:
21995     case DW_TAG_structure_type:
21996     case DW_TAG_union_type:
21997       this_type = read_structure_type (die, cu);
21998       break;
21999     case DW_TAG_enumeration_type:
22000       this_type = read_enumeration_type (die, cu);
22001       break;
22002     case DW_TAG_subprogram:
22003     case DW_TAG_subroutine_type:
22004     case DW_TAG_inlined_subroutine:
22005       this_type = read_subroutine_type (die, cu);
22006       break;
22007     case DW_TAG_array_type:
22008       this_type = read_array_type (die, cu);
22009       break;
22010     case DW_TAG_set_type:
22011       this_type = read_set_type (die, cu);
22012       break;
22013     case DW_TAG_pointer_type:
22014       this_type = read_tag_pointer_type (die, cu);
22015       break;
22016     case DW_TAG_ptr_to_member_type:
22017       this_type = read_tag_ptr_to_member_type (die, cu);
22018       break;
22019     case DW_TAG_reference_type:
22020       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22021       break;
22022     case DW_TAG_rvalue_reference_type:
22023       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22024       break;
22025     case DW_TAG_const_type:
22026       this_type = read_tag_const_type (die, cu);
22027       break;
22028     case DW_TAG_volatile_type:
22029       this_type = read_tag_volatile_type (die, cu);
22030       break;
22031     case DW_TAG_restrict_type:
22032       this_type = read_tag_restrict_type (die, cu);
22033       break;
22034     case DW_TAG_string_type:
22035       this_type = read_tag_string_type (die, cu);
22036       break;
22037     case DW_TAG_typedef:
22038       this_type = read_typedef (die, cu);
22039       break;
22040     case DW_TAG_subrange_type:
22041       this_type = read_subrange_type (die, cu);
22042       break;
22043     case DW_TAG_base_type:
22044       this_type = read_base_type (die, cu);
22045       break;
22046     case DW_TAG_unspecified_type:
22047       this_type = read_unspecified_type (die, cu);
22048       break;
22049     case DW_TAG_namespace:
22050       this_type = read_namespace_type (die, cu);
22051       break;
22052     case DW_TAG_module:
22053       this_type = read_module_type (die, cu);
22054       break;
22055     case DW_TAG_atomic_type:
22056       this_type = read_tag_atomic_type (die, cu);
22057       break;
22058     default:
22059       complaint (&symfile_complaints,
22060                  _("unexpected tag in read_type_die: '%s'"),
22061                  dwarf_tag_name (die->tag));
22062       break;
22063     }
22064
22065   return this_type;
22066 }
22067
22068 /* See if we can figure out if the class lives in a namespace.  We do
22069    this by looking for a member function; its demangled name will
22070    contain namespace info, if there is any.
22071    Return the computed name or NULL.
22072    Space for the result is allocated on the objfile's obstack.
22073    This is the full-die version of guess_partial_die_structure_name.
22074    In this case we know DIE has no useful parent.  */
22075
22076 static char *
22077 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22078 {
22079   struct die_info *spec_die;
22080   struct dwarf2_cu *spec_cu;
22081   struct die_info *child;
22082   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22083
22084   spec_cu = cu;
22085   spec_die = die_specification (die, &spec_cu);
22086   if (spec_die != NULL)
22087     {
22088       die = spec_die;
22089       cu = spec_cu;
22090     }
22091
22092   for (child = die->child;
22093        child != NULL;
22094        child = child->sibling)
22095     {
22096       if (child->tag == DW_TAG_subprogram)
22097         {
22098           const char *linkage_name = dw2_linkage_name (child, cu);
22099
22100           if (linkage_name != NULL)
22101             {
22102               char *actual_name
22103                 = language_class_name_from_physname (cu->language_defn,
22104                                                      linkage_name);
22105               char *name = NULL;
22106
22107               if (actual_name != NULL)
22108                 {
22109                   const char *die_name = dwarf2_name (die, cu);
22110
22111                   if (die_name != NULL
22112                       && strcmp (die_name, actual_name) != 0)
22113                     {
22114                       /* Strip off the class name from the full name.
22115                          We want the prefix.  */
22116                       int die_name_len = strlen (die_name);
22117                       int actual_name_len = strlen (actual_name);
22118
22119                       /* Test for '::' as a sanity check.  */
22120                       if (actual_name_len > die_name_len + 2
22121                           && actual_name[actual_name_len
22122                                          - die_name_len - 1] == ':')
22123                         name = (char *) obstack_copy0 (
22124                           &objfile->per_bfd->storage_obstack,
22125                           actual_name, actual_name_len - die_name_len - 2);
22126                     }
22127                 }
22128               xfree (actual_name);
22129               return name;
22130             }
22131         }
22132     }
22133
22134   return NULL;
22135 }
22136
22137 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22138    prefix part in such case.  See
22139    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22140
22141 static const char *
22142 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22143 {
22144   struct attribute *attr;
22145   const char *base;
22146
22147   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22148       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22149     return NULL;
22150
22151   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22152     return NULL;
22153
22154   attr = dw2_linkage_name_attr (die, cu);
22155   if (attr == NULL || DW_STRING (attr) == NULL)
22156     return NULL;
22157
22158   /* dwarf2_name had to be already called.  */
22159   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22160
22161   /* Strip the base name, keep any leading namespaces/classes.  */
22162   base = strrchr (DW_STRING (attr), ':');
22163   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22164     return "";
22165
22166   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22167   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22168                                  DW_STRING (attr),
22169                                  &base[-1] - DW_STRING (attr));
22170 }
22171
22172 /* Return the name of the namespace/class that DIE is defined within,
22173    or "" if we can't tell.  The caller should not xfree the result.
22174
22175    For example, if we're within the method foo() in the following
22176    code:
22177
22178    namespace N {
22179      class C {
22180        void foo () {
22181        }
22182      };
22183    }
22184
22185    then determine_prefix on foo's die will return "N::C".  */
22186
22187 static const char *
22188 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22189 {
22190   struct dwarf2_per_objfile *dwarf2_per_objfile
22191     = cu->per_cu->dwarf2_per_objfile;
22192   struct die_info *parent, *spec_die;
22193   struct dwarf2_cu *spec_cu;
22194   struct type *parent_type;
22195   const char *retval;
22196
22197   if (cu->language != language_cplus
22198       && cu->language != language_fortran && cu->language != language_d
22199       && cu->language != language_rust)
22200     return "";
22201
22202   retval = anonymous_struct_prefix (die, cu);
22203   if (retval)
22204     return retval;
22205
22206   /* We have to be careful in the presence of DW_AT_specification.
22207      For example, with GCC 3.4, given the code
22208
22209      namespace N {
22210        void foo() {
22211          // Definition of N::foo.
22212        }
22213      }
22214
22215      then we'll have a tree of DIEs like this:
22216
22217      1: DW_TAG_compile_unit
22218        2: DW_TAG_namespace        // N
22219          3: DW_TAG_subprogram     // declaration of N::foo
22220        4: DW_TAG_subprogram       // definition of N::foo
22221             DW_AT_specification   // refers to die #3
22222
22223      Thus, when processing die #4, we have to pretend that we're in
22224      the context of its DW_AT_specification, namely the contex of die
22225      #3.  */
22226   spec_cu = cu;
22227   spec_die = die_specification (die, &spec_cu);
22228   if (spec_die == NULL)
22229     parent = die->parent;
22230   else
22231     {
22232       parent = spec_die->parent;
22233       cu = spec_cu;
22234     }
22235
22236   if (parent == NULL)
22237     return "";
22238   else if (parent->building_fullname)
22239     {
22240       const char *name;
22241       const char *parent_name;
22242
22243       /* It has been seen on RealView 2.2 built binaries,
22244          DW_TAG_template_type_param types actually _defined_ as
22245          children of the parent class:
22246
22247          enum E {};
22248          template class <class Enum> Class{};
22249          Class<enum E> class_e;
22250
22251          1: DW_TAG_class_type (Class)
22252            2: DW_TAG_enumeration_type (E)
22253              3: DW_TAG_enumerator (enum1:0)
22254              3: DW_TAG_enumerator (enum2:1)
22255              ...
22256            2: DW_TAG_template_type_param
22257               DW_AT_type  DW_FORM_ref_udata (E)
22258
22259          Besides being broken debug info, it can put GDB into an
22260          infinite loop.  Consider:
22261
22262          When we're building the full name for Class<E>, we'll start
22263          at Class, and go look over its template type parameters,
22264          finding E.  We'll then try to build the full name of E, and
22265          reach here.  We're now trying to build the full name of E,
22266          and look over the parent DIE for containing scope.  In the
22267          broken case, if we followed the parent DIE of E, we'd again
22268          find Class, and once again go look at its template type
22269          arguments, etc., etc.  Simply don't consider such parent die
22270          as source-level parent of this die (it can't be, the language
22271          doesn't allow it), and break the loop here.  */
22272       name = dwarf2_name (die, cu);
22273       parent_name = dwarf2_name (parent, cu);
22274       complaint (&symfile_complaints,
22275                  _("template param type '%s' defined within parent '%s'"),
22276                  name ? name : "<unknown>",
22277                  parent_name ? parent_name : "<unknown>");
22278       return "";
22279     }
22280   else
22281     switch (parent->tag)
22282       {
22283       case DW_TAG_namespace:
22284         parent_type = read_type_die (parent, cu);
22285         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22286            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22287            Work around this problem here.  */
22288         if (cu->language == language_cplus
22289             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22290           return "";
22291         /* We give a name to even anonymous namespaces.  */
22292         return TYPE_TAG_NAME (parent_type);
22293       case DW_TAG_class_type:
22294       case DW_TAG_interface_type:
22295       case DW_TAG_structure_type:
22296       case DW_TAG_union_type:
22297       case DW_TAG_module:
22298         parent_type = read_type_die (parent, cu);
22299         if (TYPE_TAG_NAME (parent_type) != NULL)
22300           return TYPE_TAG_NAME (parent_type);
22301         else
22302           /* An anonymous structure is only allowed non-static data
22303              members; no typedefs, no member functions, et cetera.
22304              So it does not need a prefix.  */
22305           return "";
22306       case DW_TAG_compile_unit:
22307       case DW_TAG_partial_unit:
22308         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22309         if (cu->language == language_cplus
22310             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22311             && die->child != NULL
22312             && (die->tag == DW_TAG_class_type
22313                 || die->tag == DW_TAG_structure_type
22314                 || die->tag == DW_TAG_union_type))
22315           {
22316             char *name = guess_full_die_structure_name (die, cu);
22317             if (name != NULL)
22318               return name;
22319           }
22320         return "";
22321       case DW_TAG_enumeration_type:
22322         parent_type = read_type_die (parent, cu);
22323         if (TYPE_DECLARED_CLASS (parent_type))
22324           {
22325             if (TYPE_TAG_NAME (parent_type) != NULL)
22326               return TYPE_TAG_NAME (parent_type);
22327             return "";
22328           }
22329         /* Fall through.  */
22330       default:
22331         return determine_prefix (parent, cu);
22332       }
22333 }
22334
22335 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22336    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22337    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22338    an obconcat, otherwise allocate storage for the result.  The CU argument is
22339    used to determine the language and hence, the appropriate separator.  */
22340
22341 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22342
22343 static char *
22344 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22345                  int physname, struct dwarf2_cu *cu)
22346 {
22347   const char *lead = "";
22348   const char *sep;
22349
22350   if (suffix == NULL || suffix[0] == '\0'
22351       || prefix == NULL || prefix[0] == '\0')
22352     sep = "";
22353   else if (cu->language == language_d)
22354     {
22355       /* For D, the 'main' function could be defined in any module, but it
22356          should never be prefixed.  */
22357       if (strcmp (suffix, "D main") == 0)
22358         {
22359           prefix = "";
22360           sep = "";
22361         }
22362       else
22363         sep = ".";
22364     }
22365   else if (cu->language == language_fortran && physname)
22366     {
22367       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22368          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22369
22370       lead = "__";
22371       sep = "_MOD_";
22372     }
22373   else
22374     sep = "::";
22375
22376   if (prefix == NULL)
22377     prefix = "";
22378   if (suffix == NULL)
22379     suffix = "";
22380
22381   if (obs == NULL)
22382     {
22383       char *retval
22384         = ((char *)
22385            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22386
22387       strcpy (retval, lead);
22388       strcat (retval, prefix);
22389       strcat (retval, sep);
22390       strcat (retval, suffix);
22391       return retval;
22392     }
22393   else
22394     {
22395       /* We have an obstack.  */
22396       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22397     }
22398 }
22399
22400 /* Return sibling of die, NULL if no sibling.  */
22401
22402 static struct die_info *
22403 sibling_die (struct die_info *die)
22404 {
22405   return die->sibling;
22406 }
22407
22408 /* Get name of a die, return NULL if not found.  */
22409
22410 static const char *
22411 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22412                           struct obstack *obstack)
22413 {
22414   if (name && cu->language == language_cplus)
22415     {
22416       std::string canon_name = cp_canonicalize_string (name);
22417
22418       if (!canon_name.empty ())
22419         {
22420           if (canon_name != name)
22421             name = (const char *) obstack_copy0 (obstack,
22422                                                  canon_name.c_str (),
22423                                                  canon_name.length ());
22424         }
22425     }
22426
22427   return name;
22428 }
22429
22430 /* Get name of a die, return NULL if not found.
22431    Anonymous namespaces are converted to their magic string.  */
22432
22433 static const char *
22434 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22435 {
22436   struct attribute *attr;
22437   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22438
22439   attr = dwarf2_attr (die, DW_AT_name, cu);
22440   if ((!attr || !DW_STRING (attr))
22441       && die->tag != DW_TAG_namespace
22442       && die->tag != DW_TAG_class_type
22443       && die->tag != DW_TAG_interface_type
22444       && die->tag != DW_TAG_structure_type
22445       && die->tag != DW_TAG_union_type)
22446     return NULL;
22447
22448   switch (die->tag)
22449     {
22450     case DW_TAG_compile_unit:
22451     case DW_TAG_partial_unit:
22452       /* Compilation units have a DW_AT_name that is a filename, not
22453          a source language identifier.  */
22454     case DW_TAG_enumeration_type:
22455     case DW_TAG_enumerator:
22456       /* These tags always have simple identifiers already; no need
22457          to canonicalize them.  */
22458       return DW_STRING (attr);
22459
22460     case DW_TAG_namespace:
22461       if (attr != NULL && DW_STRING (attr) != NULL)
22462         return DW_STRING (attr);
22463       return CP_ANONYMOUS_NAMESPACE_STR;
22464
22465     case DW_TAG_class_type:
22466     case DW_TAG_interface_type:
22467     case DW_TAG_structure_type:
22468     case DW_TAG_union_type:
22469       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22470          structures or unions.  These were of the form "._%d" in GCC 4.1,
22471          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22472          and GCC 4.4.  We work around this problem by ignoring these.  */
22473       if (attr && DW_STRING (attr)
22474           && (startswith (DW_STRING (attr), "._")
22475               || startswith (DW_STRING (attr), "<anonymous")))
22476         return NULL;
22477
22478       /* GCC might emit a nameless typedef that has a linkage name.  See
22479          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22480       if (!attr || DW_STRING (attr) == NULL)
22481         {
22482           char *demangled = NULL;
22483
22484           attr = dw2_linkage_name_attr (die, cu);
22485           if (attr == NULL || DW_STRING (attr) == NULL)
22486             return NULL;
22487
22488           /* Avoid demangling DW_STRING (attr) the second time on a second
22489              call for the same DIE.  */
22490           if (!DW_STRING_IS_CANONICAL (attr))
22491             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22492
22493           if (demangled)
22494             {
22495               const char *base;
22496
22497               /* FIXME: we already did this for the partial symbol... */
22498               DW_STRING (attr)
22499                 = ((const char *)
22500                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22501                                   demangled, strlen (demangled)));
22502               DW_STRING_IS_CANONICAL (attr) = 1;
22503               xfree (demangled);
22504
22505               /* Strip any leading namespaces/classes, keep only the base name.
22506                  DW_AT_name for named DIEs does not contain the prefixes.  */
22507               base = strrchr (DW_STRING (attr), ':');
22508               if (base && base > DW_STRING (attr) && base[-1] == ':')
22509                 return &base[1];
22510               else
22511                 return DW_STRING (attr);
22512             }
22513         }
22514       break;
22515
22516     default:
22517       break;
22518     }
22519
22520   if (!DW_STRING_IS_CANONICAL (attr))
22521     {
22522       DW_STRING (attr)
22523         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22524                                     &objfile->per_bfd->storage_obstack);
22525       DW_STRING_IS_CANONICAL (attr) = 1;
22526     }
22527   return DW_STRING (attr);
22528 }
22529
22530 /* Return the die that this die in an extension of, or NULL if there
22531    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22532    containing the return value on output.  */
22533
22534 static struct die_info *
22535 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22536 {
22537   struct attribute *attr;
22538
22539   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22540   if (attr == NULL)
22541     return NULL;
22542
22543   return follow_die_ref (die, attr, ext_cu);
22544 }
22545
22546 /* Convert a DIE tag into its string name.  */
22547
22548 static const char *
22549 dwarf_tag_name (unsigned tag)
22550 {
22551   const char *name = get_DW_TAG_name (tag);
22552
22553   if (name == NULL)
22554     return "DW_TAG_<unknown>";
22555
22556   return name;
22557 }
22558
22559 /* Convert a DWARF attribute code into its string name.  */
22560
22561 static const char *
22562 dwarf_attr_name (unsigned attr)
22563 {
22564   const char *name;
22565
22566 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22567   if (attr == DW_AT_MIPS_fde)
22568     return "DW_AT_MIPS_fde";
22569 #else
22570   if (attr == DW_AT_HP_block_index)
22571     return "DW_AT_HP_block_index";
22572 #endif
22573
22574   name = get_DW_AT_name (attr);
22575
22576   if (name == NULL)
22577     return "DW_AT_<unknown>";
22578
22579   return name;
22580 }
22581
22582 /* Convert a DWARF value form code into its string name.  */
22583
22584 static const char *
22585 dwarf_form_name (unsigned form)
22586 {
22587   const char *name = get_DW_FORM_name (form);
22588
22589   if (name == NULL)
22590     return "DW_FORM_<unknown>";
22591
22592   return name;
22593 }
22594
22595 static const char *
22596 dwarf_bool_name (unsigned mybool)
22597 {
22598   if (mybool)
22599     return "TRUE";
22600   else
22601     return "FALSE";
22602 }
22603
22604 /* Convert a DWARF type code into its string name.  */
22605
22606 static const char *
22607 dwarf_type_encoding_name (unsigned enc)
22608 {
22609   const char *name = get_DW_ATE_name (enc);
22610
22611   if (name == NULL)
22612     return "DW_ATE_<unknown>";
22613
22614   return name;
22615 }
22616
22617 static void
22618 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22619 {
22620   unsigned int i;
22621
22622   print_spaces (indent, f);
22623   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22624                       dwarf_tag_name (die->tag), die->abbrev,
22625                       sect_offset_str (die->sect_off));
22626
22627   if (die->parent != NULL)
22628     {
22629       print_spaces (indent, f);
22630       fprintf_unfiltered (f, "  parent at offset: %s\n",
22631                           sect_offset_str (die->parent->sect_off));
22632     }
22633
22634   print_spaces (indent, f);
22635   fprintf_unfiltered (f, "  has children: %s\n",
22636            dwarf_bool_name (die->child != NULL));
22637
22638   print_spaces (indent, f);
22639   fprintf_unfiltered (f, "  attributes:\n");
22640
22641   for (i = 0; i < die->num_attrs; ++i)
22642     {
22643       print_spaces (indent, f);
22644       fprintf_unfiltered (f, "    %s (%s) ",
22645                dwarf_attr_name (die->attrs[i].name),
22646                dwarf_form_name (die->attrs[i].form));
22647
22648       switch (die->attrs[i].form)
22649         {
22650         case DW_FORM_addr:
22651         case DW_FORM_GNU_addr_index:
22652           fprintf_unfiltered (f, "address: ");
22653           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22654           break;
22655         case DW_FORM_block2:
22656         case DW_FORM_block4:
22657         case DW_FORM_block:
22658         case DW_FORM_block1:
22659           fprintf_unfiltered (f, "block: size %s",
22660                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22661           break;
22662         case DW_FORM_exprloc:
22663           fprintf_unfiltered (f, "expression: size %s",
22664                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22665           break;
22666         case DW_FORM_data16:
22667           fprintf_unfiltered (f, "constant of 16 bytes");
22668           break;
22669         case DW_FORM_ref_addr:
22670           fprintf_unfiltered (f, "ref address: ");
22671           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22672           break;
22673         case DW_FORM_GNU_ref_alt:
22674           fprintf_unfiltered (f, "alt ref address: ");
22675           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22676           break;
22677         case DW_FORM_ref1:
22678         case DW_FORM_ref2:
22679         case DW_FORM_ref4:
22680         case DW_FORM_ref8:
22681         case DW_FORM_ref_udata:
22682           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22683                               (long) (DW_UNSND (&die->attrs[i])));
22684           break;
22685         case DW_FORM_data1:
22686         case DW_FORM_data2:
22687         case DW_FORM_data4:
22688         case DW_FORM_data8:
22689         case DW_FORM_udata:
22690         case DW_FORM_sdata:
22691           fprintf_unfiltered (f, "constant: %s",
22692                               pulongest (DW_UNSND (&die->attrs[i])));
22693           break;
22694         case DW_FORM_sec_offset:
22695           fprintf_unfiltered (f, "section offset: %s",
22696                               pulongest (DW_UNSND (&die->attrs[i])));
22697           break;
22698         case DW_FORM_ref_sig8:
22699           fprintf_unfiltered (f, "signature: %s",
22700                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22701           break;
22702         case DW_FORM_string:
22703         case DW_FORM_strp:
22704         case DW_FORM_line_strp:
22705         case DW_FORM_GNU_str_index:
22706         case DW_FORM_GNU_strp_alt:
22707           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22708                    DW_STRING (&die->attrs[i])
22709                    ? DW_STRING (&die->attrs[i]) : "",
22710                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22711           break;
22712         case DW_FORM_flag:
22713           if (DW_UNSND (&die->attrs[i]))
22714             fprintf_unfiltered (f, "flag: TRUE");
22715           else
22716             fprintf_unfiltered (f, "flag: FALSE");
22717           break;
22718         case DW_FORM_flag_present:
22719           fprintf_unfiltered (f, "flag: TRUE");
22720           break;
22721         case DW_FORM_indirect:
22722           /* The reader will have reduced the indirect form to
22723              the "base form" so this form should not occur.  */
22724           fprintf_unfiltered (f, 
22725                               "unexpected attribute form: DW_FORM_indirect");
22726           break;
22727         case DW_FORM_implicit_const:
22728           fprintf_unfiltered (f, "constant: %s",
22729                               plongest (DW_SND (&die->attrs[i])));
22730           break;
22731         default:
22732           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22733                    die->attrs[i].form);
22734           break;
22735         }
22736       fprintf_unfiltered (f, "\n");
22737     }
22738 }
22739
22740 static void
22741 dump_die_for_error (struct die_info *die)
22742 {
22743   dump_die_shallow (gdb_stderr, 0, die);
22744 }
22745
22746 static void
22747 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22748 {
22749   int indent = level * 4;
22750
22751   gdb_assert (die != NULL);
22752
22753   if (level >= max_level)
22754     return;
22755
22756   dump_die_shallow (f, indent, die);
22757
22758   if (die->child != NULL)
22759     {
22760       print_spaces (indent, f);
22761       fprintf_unfiltered (f, "  Children:");
22762       if (level + 1 < max_level)
22763         {
22764           fprintf_unfiltered (f, "\n");
22765           dump_die_1 (f, level + 1, max_level, die->child);
22766         }
22767       else
22768         {
22769           fprintf_unfiltered (f,
22770                               " [not printed, max nesting level reached]\n");
22771         }
22772     }
22773
22774   if (die->sibling != NULL && level > 0)
22775     {
22776       dump_die_1 (f, level, max_level, die->sibling);
22777     }
22778 }
22779
22780 /* This is called from the pdie macro in gdbinit.in.
22781    It's not static so gcc will keep a copy callable from gdb.  */
22782
22783 void
22784 dump_die (struct die_info *die, int max_level)
22785 {
22786   dump_die_1 (gdb_stdlog, 0, max_level, die);
22787 }
22788
22789 static void
22790 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22791 {
22792   void **slot;
22793
22794   slot = htab_find_slot_with_hash (cu->die_hash, die,
22795                                    to_underlying (die->sect_off),
22796                                    INSERT);
22797
22798   *slot = die;
22799 }
22800
22801 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22802    required kind.  */
22803
22804 static sect_offset
22805 dwarf2_get_ref_die_offset (const struct attribute *attr)
22806 {
22807   if (attr_form_is_ref (attr))
22808     return (sect_offset) DW_UNSND (attr);
22809
22810   complaint (&symfile_complaints,
22811              _("unsupported die ref attribute form: '%s'"),
22812              dwarf_form_name (attr->form));
22813   return {};
22814 }
22815
22816 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22817  * the value held by the attribute is not constant.  */
22818
22819 static LONGEST
22820 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22821 {
22822   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22823     return DW_SND (attr);
22824   else if (attr->form == DW_FORM_udata
22825            || attr->form == DW_FORM_data1
22826            || attr->form == DW_FORM_data2
22827            || attr->form == DW_FORM_data4
22828            || attr->form == DW_FORM_data8)
22829     return DW_UNSND (attr);
22830   else
22831     {
22832       /* For DW_FORM_data16 see attr_form_is_constant.  */
22833       complaint (&symfile_complaints,
22834                  _("Attribute value is not a constant (%s)"),
22835                  dwarf_form_name (attr->form));
22836       return default_value;
22837     }
22838 }
22839
22840 /* Follow reference or signature attribute ATTR of SRC_DIE.
22841    On entry *REF_CU is the CU of SRC_DIE.
22842    On exit *REF_CU is the CU of the result.  */
22843
22844 static struct die_info *
22845 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22846                        struct dwarf2_cu **ref_cu)
22847 {
22848   struct die_info *die;
22849
22850   if (attr_form_is_ref (attr))
22851     die = follow_die_ref (src_die, attr, ref_cu);
22852   else if (attr->form == DW_FORM_ref_sig8)
22853     die = follow_die_sig (src_die, attr, ref_cu);
22854   else
22855     {
22856       dump_die_for_error (src_die);
22857       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22858              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22859     }
22860
22861   return die;
22862 }
22863
22864 /* Follow reference OFFSET.
22865    On entry *REF_CU is the CU of the source die referencing OFFSET.
22866    On exit *REF_CU is the CU of the result.
22867    Returns NULL if OFFSET is invalid.  */
22868
22869 static struct die_info *
22870 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22871                    struct dwarf2_cu **ref_cu)
22872 {
22873   struct die_info temp_die;
22874   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22875   struct dwarf2_per_objfile *dwarf2_per_objfile
22876     = cu->per_cu->dwarf2_per_objfile;
22877
22878   gdb_assert (cu->per_cu != NULL);
22879
22880   target_cu = cu;
22881
22882   if (cu->per_cu->is_debug_types)
22883     {
22884       /* .debug_types CUs cannot reference anything outside their CU.
22885          If they need to, they have to reference a signatured type via
22886          DW_FORM_ref_sig8.  */
22887       if (!offset_in_cu_p (&cu->header, sect_off))
22888         return NULL;
22889     }
22890   else if (offset_in_dwz != cu->per_cu->is_dwz
22891            || !offset_in_cu_p (&cu->header, sect_off))
22892     {
22893       struct dwarf2_per_cu_data *per_cu;
22894
22895       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22896                                                  dwarf2_per_objfile);
22897
22898       /* If necessary, add it to the queue and load its DIEs.  */
22899       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22900         load_full_comp_unit (per_cu, false, cu->language);
22901
22902       target_cu = per_cu->cu;
22903     }
22904   else if (cu->dies == NULL)
22905     {
22906       /* We're loading full DIEs during partial symbol reading.  */
22907       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22908       load_full_comp_unit (cu->per_cu, false, language_minimal);
22909     }
22910
22911   *ref_cu = target_cu;
22912   temp_die.sect_off = sect_off;
22913   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22914                                                   &temp_die,
22915                                                   to_underlying (sect_off));
22916 }
22917
22918 /* Follow reference attribute ATTR of SRC_DIE.
22919    On entry *REF_CU is the CU of SRC_DIE.
22920    On exit *REF_CU is the CU of the result.  */
22921
22922 static struct die_info *
22923 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22924                 struct dwarf2_cu **ref_cu)
22925 {
22926   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22927   struct dwarf2_cu *cu = *ref_cu;
22928   struct die_info *die;
22929
22930   die = follow_die_offset (sect_off,
22931                            (attr->form == DW_FORM_GNU_ref_alt
22932                             || cu->per_cu->is_dwz),
22933                            ref_cu);
22934   if (!die)
22935     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22936            "at %s [in module %s]"),
22937            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22938            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22939
22940   return die;
22941 }
22942
22943 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22944    Returned value is intended for DW_OP_call*.  Returned
22945    dwarf2_locexpr_baton->data has lifetime of
22946    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22947
22948 struct dwarf2_locexpr_baton
22949 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22950                                struct dwarf2_per_cu_data *per_cu,
22951                                CORE_ADDR (*get_frame_pc) (void *baton),
22952                                void *baton)
22953 {
22954   struct dwarf2_cu *cu;
22955   struct die_info *die;
22956   struct attribute *attr;
22957   struct dwarf2_locexpr_baton retval;
22958   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22959   struct objfile *objfile = dwarf2_per_objfile->objfile;
22960
22961   if (per_cu->cu == NULL)
22962     load_cu (per_cu, false);
22963   cu = per_cu->cu;
22964   if (cu == NULL)
22965     {
22966       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22967          Instead just throw an error, not much else we can do.  */
22968       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22969              sect_offset_str (sect_off), objfile_name (objfile));
22970     }
22971
22972   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22973   if (!die)
22974     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22975            sect_offset_str (sect_off), objfile_name (objfile));
22976
22977   attr = dwarf2_attr (die, DW_AT_location, cu);
22978   if (!attr)
22979     {
22980       /* DWARF: "If there is no such attribute, then there is no effect.".
22981          DATA is ignored if SIZE is 0.  */
22982
22983       retval.data = NULL;
22984       retval.size = 0;
22985     }
22986   else if (attr_form_is_section_offset (attr))
22987     {
22988       struct dwarf2_loclist_baton loclist_baton;
22989       CORE_ADDR pc = (*get_frame_pc) (baton);
22990       size_t size;
22991
22992       fill_in_loclist_baton (cu, &loclist_baton, attr);
22993
22994       retval.data = dwarf2_find_location_expression (&loclist_baton,
22995                                                      &size, pc);
22996       retval.size = size;
22997     }
22998   else
22999     {
23000       if (!attr_form_is_block (attr))
23001         error (_("Dwarf Error: DIE at %s referenced in module %s "
23002                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23003                sect_offset_str (sect_off), objfile_name (objfile));
23004
23005       retval.data = DW_BLOCK (attr)->data;
23006       retval.size = DW_BLOCK (attr)->size;
23007     }
23008   retval.per_cu = cu->per_cu;
23009
23010   age_cached_comp_units (dwarf2_per_objfile);
23011
23012   return retval;
23013 }
23014
23015 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23016    offset.  */
23017
23018 struct dwarf2_locexpr_baton
23019 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23020                              struct dwarf2_per_cu_data *per_cu,
23021                              CORE_ADDR (*get_frame_pc) (void *baton),
23022                              void *baton)
23023 {
23024   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23025
23026   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23027 }
23028
23029 /* Write a constant of a given type as target-ordered bytes into
23030    OBSTACK.  */
23031
23032 static const gdb_byte *
23033 write_constant_as_bytes (struct obstack *obstack,
23034                          enum bfd_endian byte_order,
23035                          struct type *type,
23036                          ULONGEST value,
23037                          LONGEST *len)
23038 {
23039   gdb_byte *result;
23040
23041   *len = TYPE_LENGTH (type);
23042   result = (gdb_byte *) obstack_alloc (obstack, *len);
23043   store_unsigned_integer (result, *len, byte_order, value);
23044
23045   return result;
23046 }
23047
23048 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23049    pointer to the constant bytes and set LEN to the length of the
23050    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23051    does not have a DW_AT_const_value, return NULL.  */
23052
23053 const gdb_byte *
23054 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23055                              struct dwarf2_per_cu_data *per_cu,
23056                              struct obstack *obstack,
23057                              LONGEST *len)
23058 {
23059   struct dwarf2_cu *cu;
23060   struct die_info *die;
23061   struct attribute *attr;
23062   const gdb_byte *result = NULL;
23063   struct type *type;
23064   LONGEST value;
23065   enum bfd_endian byte_order;
23066   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23067
23068   if (per_cu->cu == NULL)
23069     load_cu (per_cu, false);
23070   cu = per_cu->cu;
23071   if (cu == NULL)
23072     {
23073       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23074          Instead just throw an error, not much else we can do.  */
23075       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23076              sect_offset_str (sect_off), objfile_name (objfile));
23077     }
23078
23079   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23080   if (!die)
23081     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23082            sect_offset_str (sect_off), objfile_name (objfile));
23083
23084   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23085   if (attr == NULL)
23086     return NULL;
23087
23088   byte_order = (bfd_big_endian (objfile->obfd)
23089                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23090
23091   switch (attr->form)
23092     {
23093     case DW_FORM_addr:
23094     case DW_FORM_GNU_addr_index:
23095       {
23096         gdb_byte *tem;
23097
23098         *len = cu->header.addr_size;
23099         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23100         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23101         result = tem;
23102       }
23103       break;
23104     case DW_FORM_string:
23105     case DW_FORM_strp:
23106     case DW_FORM_GNU_str_index:
23107     case DW_FORM_GNU_strp_alt:
23108       /* DW_STRING is already allocated on the objfile obstack, point
23109          directly to it.  */
23110       result = (const gdb_byte *) DW_STRING (attr);
23111       *len = strlen (DW_STRING (attr));
23112       break;
23113     case DW_FORM_block1:
23114     case DW_FORM_block2:
23115     case DW_FORM_block4:
23116     case DW_FORM_block:
23117     case DW_FORM_exprloc:
23118     case DW_FORM_data16:
23119       result = DW_BLOCK (attr)->data;
23120       *len = DW_BLOCK (attr)->size;
23121       break;
23122
23123       /* The DW_AT_const_value attributes are supposed to carry the
23124          symbol's value "represented as it would be on the target
23125          architecture."  By the time we get here, it's already been
23126          converted to host endianness, so we just need to sign- or
23127          zero-extend it as appropriate.  */
23128     case DW_FORM_data1:
23129       type = die_type (die, cu);
23130       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23131       if (result == NULL)
23132         result = write_constant_as_bytes (obstack, byte_order,
23133                                           type, value, len);
23134       break;
23135     case DW_FORM_data2:
23136       type = die_type (die, cu);
23137       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23138       if (result == NULL)
23139         result = write_constant_as_bytes (obstack, byte_order,
23140                                           type, value, len);
23141       break;
23142     case DW_FORM_data4:
23143       type = die_type (die, cu);
23144       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23145       if (result == NULL)
23146         result = write_constant_as_bytes (obstack, byte_order,
23147                                           type, value, len);
23148       break;
23149     case DW_FORM_data8:
23150       type = die_type (die, cu);
23151       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23152       if (result == NULL)
23153         result = write_constant_as_bytes (obstack, byte_order,
23154                                           type, value, len);
23155       break;
23156
23157     case DW_FORM_sdata:
23158     case DW_FORM_implicit_const:
23159       type = die_type (die, cu);
23160       result = write_constant_as_bytes (obstack, byte_order,
23161                                         type, DW_SND (attr), len);
23162       break;
23163
23164     case DW_FORM_udata:
23165       type = die_type (die, cu);
23166       result = write_constant_as_bytes (obstack, byte_order,
23167                                         type, DW_UNSND (attr), len);
23168       break;
23169
23170     default:
23171       complaint (&symfile_complaints,
23172                  _("unsupported const value attribute form: '%s'"),
23173                  dwarf_form_name (attr->form));
23174       break;
23175     }
23176
23177   return result;
23178 }
23179
23180 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23181    valid type for this die is found.  */
23182
23183 struct type *
23184 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23185                                 struct dwarf2_per_cu_data *per_cu)
23186 {
23187   struct dwarf2_cu *cu;
23188   struct die_info *die;
23189
23190   if (per_cu->cu == NULL)
23191     load_cu (per_cu, false);
23192   cu = per_cu->cu;
23193   if (!cu)
23194     return NULL;
23195
23196   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23197   if (!die)
23198     return NULL;
23199
23200   return die_type (die, cu);
23201 }
23202
23203 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23204    PER_CU.  */
23205
23206 struct type *
23207 dwarf2_get_die_type (cu_offset die_offset,
23208                      struct dwarf2_per_cu_data *per_cu)
23209 {
23210   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23211   return get_die_type_at_offset (die_offset_sect, per_cu);
23212 }
23213
23214 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23215    On entry *REF_CU is the CU of SRC_DIE.
23216    On exit *REF_CU is the CU of the result.
23217    Returns NULL if the referenced DIE isn't found.  */
23218
23219 static struct die_info *
23220 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23221                   struct dwarf2_cu **ref_cu)
23222 {
23223   struct die_info temp_die;
23224   struct dwarf2_cu *sig_cu;
23225   struct die_info *die;
23226
23227   /* While it might be nice to assert sig_type->type == NULL here,
23228      we can get here for DW_AT_imported_declaration where we need
23229      the DIE not the type.  */
23230
23231   /* If necessary, add it to the queue and load its DIEs.  */
23232
23233   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23234     read_signatured_type (sig_type);
23235
23236   sig_cu = sig_type->per_cu.cu;
23237   gdb_assert (sig_cu != NULL);
23238   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23239   temp_die.sect_off = sig_type->type_offset_in_section;
23240   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23241                                                  to_underlying (temp_die.sect_off));
23242   if (die)
23243     {
23244       struct dwarf2_per_objfile *dwarf2_per_objfile
23245         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23246
23247       /* For .gdb_index version 7 keep track of included TUs.
23248          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23249       if (dwarf2_per_objfile->index_table != NULL
23250           && dwarf2_per_objfile->index_table->version <= 7)
23251         {
23252           VEC_safe_push (dwarf2_per_cu_ptr,
23253                          (*ref_cu)->per_cu->imported_symtabs,
23254                          sig_cu->per_cu);
23255         }
23256
23257       *ref_cu = sig_cu;
23258       return die;
23259     }
23260
23261   return NULL;
23262 }
23263
23264 /* Follow signatured type referenced by ATTR in SRC_DIE.
23265    On entry *REF_CU is the CU of SRC_DIE.
23266    On exit *REF_CU is the CU of the result.
23267    The result is the DIE of the type.
23268    If the referenced type cannot be found an error is thrown.  */
23269
23270 static struct die_info *
23271 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23272                 struct dwarf2_cu **ref_cu)
23273 {
23274   ULONGEST signature = DW_SIGNATURE (attr);
23275   struct signatured_type *sig_type;
23276   struct die_info *die;
23277
23278   gdb_assert (attr->form == DW_FORM_ref_sig8);
23279
23280   sig_type = lookup_signatured_type (*ref_cu, signature);
23281   /* sig_type will be NULL if the signatured type is missing from
23282      the debug info.  */
23283   if (sig_type == NULL)
23284     {
23285       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23286                " from DIE at %s [in module %s]"),
23287              hex_string (signature), sect_offset_str (src_die->sect_off),
23288              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23289     }
23290
23291   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23292   if (die == NULL)
23293     {
23294       dump_die_for_error (src_die);
23295       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23296                " from DIE at %s [in module %s]"),
23297              hex_string (signature), sect_offset_str (src_die->sect_off),
23298              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23299     }
23300
23301   return die;
23302 }
23303
23304 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23305    reading in and processing the type unit if necessary.  */
23306
23307 static struct type *
23308 get_signatured_type (struct die_info *die, ULONGEST signature,
23309                      struct dwarf2_cu *cu)
23310 {
23311   struct dwarf2_per_objfile *dwarf2_per_objfile
23312     = cu->per_cu->dwarf2_per_objfile;
23313   struct signatured_type *sig_type;
23314   struct dwarf2_cu *type_cu;
23315   struct die_info *type_die;
23316   struct type *type;
23317
23318   sig_type = lookup_signatured_type (cu, signature);
23319   /* sig_type will be NULL if the signatured type is missing from
23320      the debug info.  */
23321   if (sig_type == NULL)
23322     {
23323       complaint (&symfile_complaints,
23324                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23325                    " from DIE at %s [in module %s]"),
23326                  hex_string (signature), sect_offset_str (die->sect_off),
23327                  objfile_name (dwarf2_per_objfile->objfile));
23328       return build_error_marker_type (cu, die);
23329     }
23330
23331   /* If we already know the type we're done.  */
23332   if (sig_type->type != NULL)
23333     return sig_type->type;
23334
23335   type_cu = cu;
23336   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23337   if (type_die != NULL)
23338     {
23339       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23340          is created.  This is important, for example, because for c++ classes
23341          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23342       type = read_type_die (type_die, type_cu);
23343       if (type == NULL)
23344         {
23345           complaint (&symfile_complaints,
23346                      _("Dwarf Error: Cannot build signatured type %s"
23347                        " referenced from DIE at %s [in module %s]"),
23348                      hex_string (signature), sect_offset_str (die->sect_off),
23349                      objfile_name (dwarf2_per_objfile->objfile));
23350           type = build_error_marker_type (cu, die);
23351         }
23352     }
23353   else
23354     {
23355       complaint (&symfile_complaints,
23356                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23357                    " from DIE at %s [in module %s]"),
23358                  hex_string (signature), sect_offset_str (die->sect_off),
23359                  objfile_name (dwarf2_per_objfile->objfile));
23360       type = build_error_marker_type (cu, die);
23361     }
23362   sig_type->type = type;
23363
23364   return type;
23365 }
23366
23367 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23368    reading in and processing the type unit if necessary.  */
23369
23370 static struct type *
23371 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23372                           struct dwarf2_cu *cu) /* ARI: editCase function */
23373 {
23374   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23375   if (attr_form_is_ref (attr))
23376     {
23377       struct dwarf2_cu *type_cu = cu;
23378       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23379
23380       return read_type_die (type_die, type_cu);
23381     }
23382   else if (attr->form == DW_FORM_ref_sig8)
23383     {
23384       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23385     }
23386   else
23387     {
23388       struct dwarf2_per_objfile *dwarf2_per_objfile
23389         = cu->per_cu->dwarf2_per_objfile;
23390
23391       complaint (&symfile_complaints,
23392                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23393                    " at %s [in module %s]"),
23394                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23395                  objfile_name (dwarf2_per_objfile->objfile));
23396       return build_error_marker_type (cu, die);
23397     }
23398 }
23399
23400 /* Load the DIEs associated with type unit PER_CU into memory.  */
23401
23402 static void
23403 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23404 {
23405   struct signatured_type *sig_type;
23406
23407   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23408   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23409
23410   /* We have the per_cu, but we need the signatured_type.
23411      Fortunately this is an easy translation.  */
23412   gdb_assert (per_cu->is_debug_types);
23413   sig_type = (struct signatured_type *) per_cu;
23414
23415   gdb_assert (per_cu->cu == NULL);
23416
23417   read_signatured_type (sig_type);
23418
23419   gdb_assert (per_cu->cu != NULL);
23420 }
23421
23422 /* die_reader_func for read_signatured_type.
23423    This is identical to load_full_comp_unit_reader,
23424    but is kept separate for now.  */
23425
23426 static void
23427 read_signatured_type_reader (const struct die_reader_specs *reader,
23428                              const gdb_byte *info_ptr,
23429                              struct die_info *comp_unit_die,
23430                              int has_children,
23431                              void *data)
23432 {
23433   struct dwarf2_cu *cu = reader->cu;
23434
23435   gdb_assert (cu->die_hash == NULL);
23436   cu->die_hash =
23437     htab_create_alloc_ex (cu->header.length / 12,
23438                           die_hash,
23439                           die_eq,
23440                           NULL,
23441                           &cu->comp_unit_obstack,
23442                           hashtab_obstack_allocate,
23443                           dummy_obstack_deallocate);
23444
23445   if (has_children)
23446     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23447                                                   &info_ptr, comp_unit_die);
23448   cu->dies = comp_unit_die;
23449   /* comp_unit_die is not stored in die_hash, no need.  */
23450
23451   /* We try not to read any attributes in this function, because not
23452      all CUs needed for references have been loaded yet, and symbol
23453      table processing isn't initialized.  But we have to set the CU language,
23454      or we won't be able to build types correctly.
23455      Similarly, if we do not read the producer, we can not apply
23456      producer-specific interpretation.  */
23457   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23458 }
23459
23460 /* Read in a signatured type and build its CU and DIEs.
23461    If the type is a stub for the real type in a DWO file,
23462    read in the real type from the DWO file as well.  */
23463
23464 static void
23465 read_signatured_type (struct signatured_type *sig_type)
23466 {
23467   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23468
23469   gdb_assert (per_cu->is_debug_types);
23470   gdb_assert (per_cu->cu == NULL);
23471
23472   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23473                            read_signatured_type_reader, NULL);
23474   sig_type->per_cu.tu_read = 1;
23475 }
23476
23477 /* Decode simple location descriptions.
23478    Given a pointer to a dwarf block that defines a location, compute
23479    the location and return the value.
23480
23481    NOTE drow/2003-11-18: This function is called in two situations
23482    now: for the address of static or global variables (partial symbols
23483    only) and for offsets into structures which are expected to be
23484    (more or less) constant.  The partial symbol case should go away,
23485    and only the constant case should remain.  That will let this
23486    function complain more accurately.  A few special modes are allowed
23487    without complaint for global variables (for instance, global
23488    register values and thread-local values).
23489
23490    A location description containing no operations indicates that the
23491    object is optimized out.  The return value is 0 for that case.
23492    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23493    callers will only want a very basic result and this can become a
23494    complaint.
23495
23496    Note that stack[0] is unused except as a default error return.  */
23497
23498 static CORE_ADDR
23499 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23500 {
23501   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23502   size_t i;
23503   size_t size = blk->size;
23504   const gdb_byte *data = blk->data;
23505   CORE_ADDR stack[64];
23506   int stacki;
23507   unsigned int bytes_read, unsnd;
23508   gdb_byte op;
23509
23510   i = 0;
23511   stacki = 0;
23512   stack[stacki] = 0;
23513   stack[++stacki] = 0;
23514
23515   while (i < size)
23516     {
23517       op = data[i++];
23518       switch (op)
23519         {
23520         case DW_OP_lit0:
23521         case DW_OP_lit1:
23522         case DW_OP_lit2:
23523         case DW_OP_lit3:
23524         case DW_OP_lit4:
23525         case DW_OP_lit5:
23526         case DW_OP_lit6:
23527         case DW_OP_lit7:
23528         case DW_OP_lit8:
23529         case DW_OP_lit9:
23530         case DW_OP_lit10:
23531         case DW_OP_lit11:
23532         case DW_OP_lit12:
23533         case DW_OP_lit13:
23534         case DW_OP_lit14:
23535         case DW_OP_lit15:
23536         case DW_OP_lit16:
23537         case DW_OP_lit17:
23538         case DW_OP_lit18:
23539         case DW_OP_lit19:
23540         case DW_OP_lit20:
23541         case DW_OP_lit21:
23542         case DW_OP_lit22:
23543         case DW_OP_lit23:
23544         case DW_OP_lit24:
23545         case DW_OP_lit25:
23546         case DW_OP_lit26:
23547         case DW_OP_lit27:
23548         case DW_OP_lit28:
23549         case DW_OP_lit29:
23550         case DW_OP_lit30:
23551         case DW_OP_lit31:
23552           stack[++stacki] = op - DW_OP_lit0;
23553           break;
23554
23555         case DW_OP_reg0:
23556         case DW_OP_reg1:
23557         case DW_OP_reg2:
23558         case DW_OP_reg3:
23559         case DW_OP_reg4:
23560         case DW_OP_reg5:
23561         case DW_OP_reg6:
23562         case DW_OP_reg7:
23563         case DW_OP_reg8:
23564         case DW_OP_reg9:
23565         case DW_OP_reg10:
23566         case DW_OP_reg11:
23567         case DW_OP_reg12:
23568         case DW_OP_reg13:
23569         case DW_OP_reg14:
23570         case DW_OP_reg15:
23571         case DW_OP_reg16:
23572         case DW_OP_reg17:
23573         case DW_OP_reg18:
23574         case DW_OP_reg19:
23575         case DW_OP_reg20:
23576         case DW_OP_reg21:
23577         case DW_OP_reg22:
23578         case DW_OP_reg23:
23579         case DW_OP_reg24:
23580         case DW_OP_reg25:
23581         case DW_OP_reg26:
23582         case DW_OP_reg27:
23583         case DW_OP_reg28:
23584         case DW_OP_reg29:
23585         case DW_OP_reg30:
23586         case DW_OP_reg31:
23587           stack[++stacki] = op - DW_OP_reg0;
23588           if (i < size)
23589             dwarf2_complex_location_expr_complaint ();
23590           break;
23591
23592         case DW_OP_regx:
23593           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23594           i += bytes_read;
23595           stack[++stacki] = unsnd;
23596           if (i < size)
23597             dwarf2_complex_location_expr_complaint ();
23598           break;
23599
23600         case DW_OP_addr:
23601           stack[++stacki] = read_address (objfile->obfd, &data[i],
23602                                           cu, &bytes_read);
23603           i += bytes_read;
23604           break;
23605
23606         case DW_OP_const1u:
23607           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23608           i += 1;
23609           break;
23610
23611         case DW_OP_const1s:
23612           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23613           i += 1;
23614           break;
23615
23616         case DW_OP_const2u:
23617           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23618           i += 2;
23619           break;
23620
23621         case DW_OP_const2s:
23622           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23623           i += 2;
23624           break;
23625
23626         case DW_OP_const4u:
23627           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23628           i += 4;
23629           break;
23630
23631         case DW_OP_const4s:
23632           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23633           i += 4;
23634           break;
23635
23636         case DW_OP_const8u:
23637           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23638           i += 8;
23639           break;
23640
23641         case DW_OP_constu:
23642           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23643                                                   &bytes_read);
23644           i += bytes_read;
23645           break;
23646
23647         case DW_OP_consts:
23648           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23649           i += bytes_read;
23650           break;
23651
23652         case DW_OP_dup:
23653           stack[stacki + 1] = stack[stacki];
23654           stacki++;
23655           break;
23656
23657         case DW_OP_plus:
23658           stack[stacki - 1] += stack[stacki];
23659           stacki--;
23660           break;
23661
23662         case DW_OP_plus_uconst:
23663           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23664                                                  &bytes_read);
23665           i += bytes_read;
23666           break;
23667
23668         case DW_OP_minus:
23669           stack[stacki - 1] -= stack[stacki];
23670           stacki--;
23671           break;
23672
23673         case DW_OP_deref:
23674           /* If we're not the last op, then we definitely can't encode
23675              this using GDB's address_class enum.  This is valid for partial
23676              global symbols, although the variable's address will be bogus
23677              in the psymtab.  */
23678           if (i < size)
23679             dwarf2_complex_location_expr_complaint ();
23680           break;
23681
23682         case DW_OP_GNU_push_tls_address:
23683         case DW_OP_form_tls_address:
23684           /* The top of the stack has the offset from the beginning
23685              of the thread control block at which the variable is located.  */
23686           /* Nothing should follow this operator, so the top of stack would
23687              be returned.  */
23688           /* This is valid for partial global symbols, but the variable's
23689              address will be bogus in the psymtab.  Make it always at least
23690              non-zero to not look as a variable garbage collected by linker
23691              which have DW_OP_addr 0.  */
23692           if (i < size)
23693             dwarf2_complex_location_expr_complaint ();
23694           stack[stacki]++;
23695           break;
23696
23697         case DW_OP_GNU_uninit:
23698           break;
23699
23700         case DW_OP_GNU_addr_index:
23701         case DW_OP_GNU_const_index:
23702           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23703                                                          &bytes_read);
23704           i += bytes_read;
23705           break;
23706
23707         default:
23708           {
23709             const char *name = get_DW_OP_name (op);
23710
23711             if (name)
23712               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23713                          name);
23714             else
23715               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23716                          op);
23717           }
23718
23719           return (stack[stacki]);
23720         }
23721
23722       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23723          outside of the allocated space.  Also enforce minimum>0.  */
23724       if (stacki >= ARRAY_SIZE (stack) - 1)
23725         {
23726           complaint (&symfile_complaints,
23727                      _("location description stack overflow"));
23728           return 0;
23729         }
23730
23731       if (stacki <= 0)
23732         {
23733           complaint (&symfile_complaints,
23734                      _("location description stack underflow"));
23735           return 0;
23736         }
23737     }
23738   return (stack[stacki]);
23739 }
23740
23741 /* memory allocation interface */
23742
23743 static struct dwarf_block *
23744 dwarf_alloc_block (struct dwarf2_cu *cu)
23745 {
23746   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23747 }
23748
23749 static struct die_info *
23750 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23751 {
23752   struct die_info *die;
23753   size_t size = sizeof (struct die_info);
23754
23755   if (num_attrs > 1)
23756     size += (num_attrs - 1) * sizeof (struct attribute);
23757
23758   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23759   memset (die, 0, sizeof (struct die_info));
23760   return (die);
23761 }
23762
23763 \f
23764 /* Macro support.  */
23765
23766 /* Return file name relative to the compilation directory of file number I in
23767    *LH's file name table.  The result is allocated using xmalloc; the caller is
23768    responsible for freeing it.  */
23769
23770 static char *
23771 file_file_name (int file, struct line_header *lh)
23772 {
23773   /* Is the file number a valid index into the line header's file name
23774      table?  Remember that file numbers start with one, not zero.  */
23775   if (1 <= file && file <= lh->file_names.size ())
23776     {
23777       const file_entry &fe = lh->file_names[file - 1];
23778
23779       if (!IS_ABSOLUTE_PATH (fe.name))
23780         {
23781           const char *dir = fe.include_dir (lh);
23782           if (dir != NULL)
23783             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23784         }
23785       return xstrdup (fe.name);
23786     }
23787   else
23788     {
23789       /* The compiler produced a bogus file number.  We can at least
23790          record the macro definitions made in the file, even if we
23791          won't be able to find the file by name.  */
23792       char fake_name[80];
23793
23794       xsnprintf (fake_name, sizeof (fake_name),
23795                  "<bad macro file number %d>", file);
23796
23797       complaint (&symfile_complaints,
23798                  _("bad file number in macro information (%d)"),
23799                  file);
23800
23801       return xstrdup (fake_name);
23802     }
23803 }
23804
23805 /* Return the full name of file number I in *LH's file name table.
23806    Use COMP_DIR as the name of the current directory of the
23807    compilation.  The result is allocated using xmalloc; the caller is
23808    responsible for freeing it.  */
23809 static char *
23810 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23811 {
23812   /* Is the file number a valid index into the line header's file name
23813      table?  Remember that file numbers start with one, not zero.  */
23814   if (1 <= file && file <= lh->file_names.size ())
23815     {
23816       char *relative = file_file_name (file, lh);
23817
23818       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23819         return relative;
23820       return reconcat (relative, comp_dir, SLASH_STRING,
23821                        relative, (char *) NULL);
23822     }
23823   else
23824     return file_file_name (file, lh);
23825 }
23826
23827
23828 static struct macro_source_file *
23829 macro_start_file (int file, int line,
23830                   struct macro_source_file *current_file,
23831                   struct line_header *lh)
23832 {
23833   /* File name relative to the compilation directory of this source file.  */
23834   char *file_name = file_file_name (file, lh);
23835
23836   if (! current_file)
23837     {
23838       /* Note: We don't create a macro table for this compilation unit
23839          at all until we actually get a filename.  */
23840       struct macro_table *macro_table = get_macro_table ();
23841
23842       /* If we have no current file, then this must be the start_file
23843          directive for the compilation unit's main source file.  */
23844       current_file = macro_set_main (macro_table, file_name);
23845       macro_define_special (macro_table);
23846     }
23847   else
23848     current_file = macro_include (current_file, line, file_name);
23849
23850   xfree (file_name);
23851
23852   return current_file;
23853 }
23854
23855 static const char *
23856 consume_improper_spaces (const char *p, const char *body)
23857 {
23858   if (*p == ' ')
23859     {
23860       complaint (&symfile_complaints,
23861                  _("macro definition contains spaces "
23862                    "in formal argument list:\n`%s'"),
23863                  body);
23864
23865       while (*p == ' ')
23866         p++;
23867     }
23868
23869   return p;
23870 }
23871
23872
23873 static void
23874 parse_macro_definition (struct macro_source_file *file, int line,
23875                         const char *body)
23876 {
23877   const char *p;
23878
23879   /* The body string takes one of two forms.  For object-like macro
23880      definitions, it should be:
23881
23882         <macro name> " " <definition>
23883
23884      For function-like macro definitions, it should be:
23885
23886         <macro name> "() " <definition>
23887      or
23888         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23889
23890      Spaces may appear only where explicitly indicated, and in the
23891      <definition>.
23892
23893      The Dwarf 2 spec says that an object-like macro's name is always
23894      followed by a space, but versions of GCC around March 2002 omit
23895      the space when the macro's definition is the empty string.
23896
23897      The Dwarf 2 spec says that there should be no spaces between the
23898      formal arguments in a function-like macro's formal argument list,
23899      but versions of GCC around March 2002 include spaces after the
23900      commas.  */
23901
23902
23903   /* Find the extent of the macro name.  The macro name is terminated
23904      by either a space or null character (for an object-like macro) or
23905      an opening paren (for a function-like macro).  */
23906   for (p = body; *p; p++)
23907     if (*p == ' ' || *p == '(')
23908       break;
23909
23910   if (*p == ' ' || *p == '\0')
23911     {
23912       /* It's an object-like macro.  */
23913       int name_len = p - body;
23914       char *name = savestring (body, name_len);
23915       const char *replacement;
23916
23917       if (*p == ' ')
23918         replacement = body + name_len + 1;
23919       else
23920         {
23921           dwarf2_macro_malformed_definition_complaint (body);
23922           replacement = body + name_len;
23923         }
23924
23925       macro_define_object (file, line, name, replacement);
23926
23927       xfree (name);
23928     }
23929   else if (*p == '(')
23930     {
23931       /* It's a function-like macro.  */
23932       char *name = savestring (body, p - body);
23933       int argc = 0;
23934       int argv_size = 1;
23935       char **argv = XNEWVEC (char *, argv_size);
23936
23937       p++;
23938
23939       p = consume_improper_spaces (p, body);
23940
23941       /* Parse the formal argument list.  */
23942       while (*p && *p != ')')
23943         {
23944           /* Find the extent of the current argument name.  */
23945           const char *arg_start = p;
23946
23947           while (*p && *p != ',' && *p != ')' && *p != ' ')
23948             p++;
23949
23950           if (! *p || p == arg_start)
23951             dwarf2_macro_malformed_definition_complaint (body);
23952           else
23953             {
23954               /* Make sure argv has room for the new argument.  */
23955               if (argc >= argv_size)
23956                 {
23957                   argv_size *= 2;
23958                   argv = XRESIZEVEC (char *, argv, argv_size);
23959                 }
23960
23961               argv[argc++] = savestring (arg_start, p - arg_start);
23962             }
23963
23964           p = consume_improper_spaces (p, body);
23965
23966           /* Consume the comma, if present.  */
23967           if (*p == ',')
23968             {
23969               p++;
23970
23971               p = consume_improper_spaces (p, body);
23972             }
23973         }
23974
23975       if (*p == ')')
23976         {
23977           p++;
23978
23979           if (*p == ' ')
23980             /* Perfectly formed definition, no complaints.  */
23981             macro_define_function (file, line, name,
23982                                    argc, (const char **) argv,
23983                                    p + 1);
23984           else if (*p == '\0')
23985             {
23986               /* Complain, but do define it.  */
23987               dwarf2_macro_malformed_definition_complaint (body);
23988               macro_define_function (file, line, name,
23989                                      argc, (const char **) argv,
23990                                      p);
23991             }
23992           else
23993             /* Just complain.  */
23994             dwarf2_macro_malformed_definition_complaint (body);
23995         }
23996       else
23997         /* Just complain.  */
23998         dwarf2_macro_malformed_definition_complaint (body);
23999
24000       xfree (name);
24001       {
24002         int i;
24003
24004         for (i = 0; i < argc; i++)
24005           xfree (argv[i]);
24006       }
24007       xfree (argv);
24008     }
24009   else
24010     dwarf2_macro_malformed_definition_complaint (body);
24011 }
24012
24013 /* Skip some bytes from BYTES according to the form given in FORM.
24014    Returns the new pointer.  */
24015
24016 static const gdb_byte *
24017 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24018                  enum dwarf_form form,
24019                  unsigned int offset_size,
24020                  struct dwarf2_section_info *section)
24021 {
24022   unsigned int bytes_read;
24023
24024   switch (form)
24025     {
24026     case DW_FORM_data1:
24027     case DW_FORM_flag:
24028       ++bytes;
24029       break;
24030
24031     case DW_FORM_data2:
24032       bytes += 2;
24033       break;
24034
24035     case DW_FORM_data4:
24036       bytes += 4;
24037       break;
24038
24039     case DW_FORM_data8:
24040       bytes += 8;
24041       break;
24042
24043     case DW_FORM_data16:
24044       bytes += 16;
24045       break;
24046
24047     case DW_FORM_string:
24048       read_direct_string (abfd, bytes, &bytes_read);
24049       bytes += bytes_read;
24050       break;
24051
24052     case DW_FORM_sec_offset:
24053     case DW_FORM_strp:
24054     case DW_FORM_GNU_strp_alt:
24055       bytes += offset_size;
24056       break;
24057
24058     case DW_FORM_block:
24059       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24060       bytes += bytes_read;
24061       break;
24062
24063     case DW_FORM_block1:
24064       bytes += 1 + read_1_byte (abfd, bytes);
24065       break;
24066     case DW_FORM_block2:
24067       bytes += 2 + read_2_bytes (abfd, bytes);
24068       break;
24069     case DW_FORM_block4:
24070       bytes += 4 + read_4_bytes (abfd, bytes);
24071       break;
24072
24073     case DW_FORM_sdata:
24074     case DW_FORM_udata:
24075     case DW_FORM_GNU_addr_index:
24076     case DW_FORM_GNU_str_index:
24077       bytes = gdb_skip_leb128 (bytes, buffer_end);
24078       if (bytes == NULL)
24079         {
24080           dwarf2_section_buffer_overflow_complaint (section);
24081           return NULL;
24082         }
24083       break;
24084
24085     case DW_FORM_implicit_const:
24086       break;
24087
24088     default:
24089       {
24090         complaint (&symfile_complaints,
24091                    _("invalid form 0x%x in `%s'"),
24092                    form, get_section_name (section));
24093         return NULL;
24094       }
24095     }
24096
24097   return bytes;
24098 }
24099
24100 /* A helper for dwarf_decode_macros that handles skipping an unknown
24101    opcode.  Returns an updated pointer to the macro data buffer; or,
24102    on error, issues a complaint and returns NULL.  */
24103
24104 static const gdb_byte *
24105 skip_unknown_opcode (unsigned int opcode,
24106                      const gdb_byte **opcode_definitions,
24107                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24108                      bfd *abfd,
24109                      unsigned int offset_size,
24110                      struct dwarf2_section_info *section)
24111 {
24112   unsigned int bytes_read, i;
24113   unsigned long arg;
24114   const gdb_byte *defn;
24115
24116   if (opcode_definitions[opcode] == NULL)
24117     {
24118       complaint (&symfile_complaints,
24119                  _("unrecognized DW_MACFINO opcode 0x%x"),
24120                  opcode);
24121       return NULL;
24122     }
24123
24124   defn = opcode_definitions[opcode];
24125   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24126   defn += bytes_read;
24127
24128   for (i = 0; i < arg; ++i)
24129     {
24130       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24131                                  (enum dwarf_form) defn[i], offset_size,
24132                                  section);
24133       if (mac_ptr == NULL)
24134         {
24135           /* skip_form_bytes already issued the complaint.  */
24136           return NULL;
24137         }
24138     }
24139
24140   return mac_ptr;
24141 }
24142
24143 /* A helper function which parses the header of a macro section.
24144    If the macro section is the extended (for now called "GNU") type,
24145    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24146    the header, or issues a complaint and returns NULL on error.  */
24147
24148 static const gdb_byte *
24149 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24150                           bfd *abfd,
24151                           const gdb_byte *mac_ptr,
24152                           unsigned int *offset_size,
24153                           int section_is_gnu)
24154 {
24155   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24156
24157   if (section_is_gnu)
24158     {
24159       unsigned int version, flags;
24160
24161       version = read_2_bytes (abfd, mac_ptr);
24162       if (version != 4 && version != 5)
24163         {
24164           complaint (&symfile_complaints,
24165                      _("unrecognized version `%d' in .debug_macro section"),
24166                      version);
24167           return NULL;
24168         }
24169       mac_ptr += 2;
24170
24171       flags = read_1_byte (abfd, mac_ptr);
24172       ++mac_ptr;
24173       *offset_size = (flags & 1) ? 8 : 4;
24174
24175       if ((flags & 2) != 0)
24176         /* We don't need the line table offset.  */
24177         mac_ptr += *offset_size;
24178
24179       /* Vendor opcode descriptions.  */
24180       if ((flags & 4) != 0)
24181         {
24182           unsigned int i, count;
24183
24184           count = read_1_byte (abfd, mac_ptr);
24185           ++mac_ptr;
24186           for (i = 0; i < count; ++i)
24187             {
24188               unsigned int opcode, bytes_read;
24189               unsigned long arg;
24190
24191               opcode = read_1_byte (abfd, mac_ptr);
24192               ++mac_ptr;
24193               opcode_definitions[opcode] = mac_ptr;
24194               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24195               mac_ptr += bytes_read;
24196               mac_ptr += arg;
24197             }
24198         }
24199     }
24200
24201   return mac_ptr;
24202 }
24203
24204 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24205    including DW_MACRO_import.  */
24206
24207 static void
24208 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24209                           bfd *abfd,
24210                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24211                           struct macro_source_file *current_file,
24212                           struct line_header *lh,
24213                           struct dwarf2_section_info *section,
24214                           int section_is_gnu, int section_is_dwz,
24215                           unsigned int offset_size,
24216                           htab_t include_hash)
24217 {
24218   struct objfile *objfile = dwarf2_per_objfile->objfile;
24219   enum dwarf_macro_record_type macinfo_type;
24220   int at_commandline;
24221   const gdb_byte *opcode_definitions[256];
24222
24223   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24224                                       &offset_size, section_is_gnu);
24225   if (mac_ptr == NULL)
24226     {
24227       /* We already issued a complaint.  */
24228       return;
24229     }
24230
24231   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24232      GDB is still reading the definitions from command line.  First
24233      DW_MACINFO_start_file will need to be ignored as it was already executed
24234      to create CURRENT_FILE for the main source holding also the command line
24235      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24236      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24237
24238   at_commandline = 1;
24239
24240   do
24241     {
24242       /* Do we at least have room for a macinfo type byte?  */
24243       if (mac_ptr >= mac_end)
24244         {
24245           dwarf2_section_buffer_overflow_complaint (section);
24246           break;
24247         }
24248
24249       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24250       mac_ptr++;
24251
24252       /* Note that we rely on the fact that the corresponding GNU and
24253          DWARF constants are the same.  */
24254       DIAGNOSTIC_PUSH
24255       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24256       switch (macinfo_type)
24257         {
24258           /* A zero macinfo type indicates the end of the macro
24259              information.  */
24260         case 0:
24261           break;
24262
24263         case DW_MACRO_define:
24264         case DW_MACRO_undef:
24265         case DW_MACRO_define_strp:
24266         case DW_MACRO_undef_strp:
24267         case DW_MACRO_define_sup:
24268         case DW_MACRO_undef_sup:
24269           {
24270             unsigned int bytes_read;
24271             int line;
24272             const char *body;
24273             int is_define;
24274
24275             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24276             mac_ptr += bytes_read;
24277
24278             if (macinfo_type == DW_MACRO_define
24279                 || macinfo_type == DW_MACRO_undef)
24280               {
24281                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24282                 mac_ptr += bytes_read;
24283               }
24284             else
24285               {
24286                 LONGEST str_offset;
24287
24288                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24289                 mac_ptr += offset_size;
24290
24291                 if (macinfo_type == DW_MACRO_define_sup
24292                     || macinfo_type == DW_MACRO_undef_sup
24293                     || section_is_dwz)
24294                   {
24295                     struct dwz_file *dwz
24296                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24297
24298                     body = read_indirect_string_from_dwz (objfile,
24299                                                           dwz, str_offset);
24300                   }
24301                 else
24302                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24303                                                          abfd, str_offset);
24304               }
24305
24306             is_define = (macinfo_type == DW_MACRO_define
24307                          || macinfo_type == DW_MACRO_define_strp
24308                          || macinfo_type == DW_MACRO_define_sup);
24309             if (! current_file)
24310               {
24311                 /* DWARF violation as no main source is present.  */
24312                 complaint (&symfile_complaints,
24313                            _("debug info with no main source gives macro %s "
24314                              "on line %d: %s"),
24315                            is_define ? _("definition") : _("undefinition"),
24316                            line, body);
24317                 break;
24318               }
24319             if ((line == 0 && !at_commandline)
24320                 || (line != 0 && at_commandline))
24321               complaint (&symfile_complaints,
24322                          _("debug info gives %s macro %s with %s line %d: %s"),
24323                          at_commandline ? _("command-line") : _("in-file"),
24324                          is_define ? _("definition") : _("undefinition"),
24325                          line == 0 ? _("zero") : _("non-zero"), line, body);
24326
24327             if (is_define)
24328               parse_macro_definition (current_file, line, body);
24329             else
24330               {
24331                 gdb_assert (macinfo_type == DW_MACRO_undef
24332                             || macinfo_type == DW_MACRO_undef_strp
24333                             || macinfo_type == DW_MACRO_undef_sup);
24334                 macro_undef (current_file, line, body);
24335               }
24336           }
24337           break;
24338
24339         case DW_MACRO_start_file:
24340           {
24341             unsigned int bytes_read;
24342             int line, file;
24343
24344             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24345             mac_ptr += bytes_read;
24346             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24347             mac_ptr += bytes_read;
24348
24349             if ((line == 0 && !at_commandline)
24350                 || (line != 0 && at_commandline))
24351               complaint (&symfile_complaints,
24352                          _("debug info gives source %d included "
24353                            "from %s at %s line %d"),
24354                          file, at_commandline ? _("command-line") : _("file"),
24355                          line == 0 ? _("zero") : _("non-zero"), line);
24356
24357             if (at_commandline)
24358               {
24359                 /* This DW_MACRO_start_file was executed in the
24360                    pass one.  */
24361                 at_commandline = 0;
24362               }
24363             else
24364               current_file = macro_start_file (file, line, current_file, lh);
24365           }
24366           break;
24367
24368         case DW_MACRO_end_file:
24369           if (! current_file)
24370             complaint (&symfile_complaints,
24371                        _("macro debug info has an unmatched "
24372                          "`close_file' directive"));
24373           else
24374             {
24375               current_file = current_file->included_by;
24376               if (! current_file)
24377                 {
24378                   enum dwarf_macro_record_type next_type;
24379
24380                   /* GCC circa March 2002 doesn't produce the zero
24381                      type byte marking the end of the compilation
24382                      unit.  Complain if it's not there, but exit no
24383                      matter what.  */
24384
24385                   /* Do we at least have room for a macinfo type byte?  */
24386                   if (mac_ptr >= mac_end)
24387                     {
24388                       dwarf2_section_buffer_overflow_complaint (section);
24389                       return;
24390                     }
24391
24392                   /* We don't increment mac_ptr here, so this is just
24393                      a look-ahead.  */
24394                   next_type
24395                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24396                                                                   mac_ptr);
24397                   if (next_type != 0)
24398                     complaint (&symfile_complaints,
24399                                _("no terminating 0-type entry for "
24400                                  "macros in `.debug_macinfo' section"));
24401
24402                   return;
24403                 }
24404             }
24405           break;
24406
24407         case DW_MACRO_import:
24408         case DW_MACRO_import_sup:
24409           {
24410             LONGEST offset;
24411             void **slot;
24412             bfd *include_bfd = abfd;
24413             struct dwarf2_section_info *include_section = section;
24414             const gdb_byte *include_mac_end = mac_end;
24415             int is_dwz = section_is_dwz;
24416             const gdb_byte *new_mac_ptr;
24417
24418             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24419             mac_ptr += offset_size;
24420
24421             if (macinfo_type == DW_MACRO_import_sup)
24422               {
24423                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24424
24425                 dwarf2_read_section (objfile, &dwz->macro);
24426
24427                 include_section = &dwz->macro;
24428                 include_bfd = get_section_bfd_owner (include_section);
24429                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24430                 is_dwz = 1;
24431               }
24432
24433             new_mac_ptr = include_section->buffer + offset;
24434             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24435
24436             if (*slot != NULL)
24437               {
24438                 /* This has actually happened; see
24439                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24440                 complaint (&symfile_complaints,
24441                            _("recursive DW_MACRO_import in "
24442                              ".debug_macro section"));
24443               }
24444             else
24445               {
24446                 *slot = (void *) new_mac_ptr;
24447
24448                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24449                                           include_bfd, new_mac_ptr,
24450                                           include_mac_end, current_file, lh,
24451                                           section, section_is_gnu, is_dwz,
24452                                           offset_size, include_hash);
24453
24454                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24455               }
24456           }
24457           break;
24458
24459         case DW_MACINFO_vendor_ext:
24460           if (!section_is_gnu)
24461             {
24462               unsigned int bytes_read;
24463
24464               /* This reads the constant, but since we don't recognize
24465                  any vendor extensions, we ignore it.  */
24466               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24467               mac_ptr += bytes_read;
24468               read_direct_string (abfd, mac_ptr, &bytes_read);
24469               mac_ptr += bytes_read;
24470
24471               /* We don't recognize any vendor extensions.  */
24472               break;
24473             }
24474           /* FALLTHROUGH */
24475
24476         default:
24477           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24478                                          mac_ptr, mac_end, abfd, offset_size,
24479                                          section);
24480           if (mac_ptr == NULL)
24481             return;
24482           break;
24483         }
24484       DIAGNOSTIC_POP
24485     } while (macinfo_type != 0);
24486 }
24487
24488 static void
24489 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24490                      int section_is_gnu)
24491 {
24492   struct dwarf2_per_objfile *dwarf2_per_objfile
24493     = cu->per_cu->dwarf2_per_objfile;
24494   struct objfile *objfile = dwarf2_per_objfile->objfile;
24495   struct line_header *lh = cu->line_header;
24496   bfd *abfd;
24497   const gdb_byte *mac_ptr, *mac_end;
24498   struct macro_source_file *current_file = 0;
24499   enum dwarf_macro_record_type macinfo_type;
24500   unsigned int offset_size = cu->header.offset_size;
24501   const gdb_byte *opcode_definitions[256];
24502   void **slot;
24503   struct dwarf2_section_info *section;
24504   const char *section_name;
24505
24506   if (cu->dwo_unit != NULL)
24507     {
24508       if (section_is_gnu)
24509         {
24510           section = &cu->dwo_unit->dwo_file->sections.macro;
24511           section_name = ".debug_macro.dwo";
24512         }
24513       else
24514         {
24515           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24516           section_name = ".debug_macinfo.dwo";
24517         }
24518     }
24519   else
24520     {
24521       if (section_is_gnu)
24522         {
24523           section = &dwarf2_per_objfile->macro;
24524           section_name = ".debug_macro";
24525         }
24526       else
24527         {
24528           section = &dwarf2_per_objfile->macinfo;
24529           section_name = ".debug_macinfo";
24530         }
24531     }
24532
24533   dwarf2_read_section (objfile, section);
24534   if (section->buffer == NULL)
24535     {
24536       complaint (&symfile_complaints, _("missing %s section"), section_name);
24537       return;
24538     }
24539   abfd = get_section_bfd_owner (section);
24540
24541   /* First pass: Find the name of the base filename.
24542      This filename is needed in order to process all macros whose definition
24543      (or undefinition) comes from the command line.  These macros are defined
24544      before the first DW_MACINFO_start_file entry, and yet still need to be
24545      associated to the base file.
24546
24547      To determine the base file name, we scan the macro definitions until we
24548      reach the first DW_MACINFO_start_file entry.  We then initialize
24549      CURRENT_FILE accordingly so that any macro definition found before the
24550      first DW_MACINFO_start_file can still be associated to the base file.  */
24551
24552   mac_ptr = section->buffer + offset;
24553   mac_end = section->buffer + section->size;
24554
24555   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24556                                       &offset_size, section_is_gnu);
24557   if (mac_ptr == NULL)
24558     {
24559       /* We already issued a complaint.  */
24560       return;
24561     }
24562
24563   do
24564     {
24565       /* Do we at least have room for a macinfo type byte?  */
24566       if (mac_ptr >= mac_end)
24567         {
24568           /* Complaint is printed during the second pass as GDB will probably
24569              stop the first pass earlier upon finding
24570              DW_MACINFO_start_file.  */
24571           break;
24572         }
24573
24574       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24575       mac_ptr++;
24576
24577       /* Note that we rely on the fact that the corresponding GNU and
24578          DWARF constants are the same.  */
24579       DIAGNOSTIC_PUSH
24580       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24581       switch (macinfo_type)
24582         {
24583           /* A zero macinfo type indicates the end of the macro
24584              information.  */
24585         case 0:
24586           break;
24587
24588         case DW_MACRO_define:
24589         case DW_MACRO_undef:
24590           /* Only skip the data by MAC_PTR.  */
24591           {
24592             unsigned int bytes_read;
24593
24594             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24595             mac_ptr += bytes_read;
24596             read_direct_string (abfd, mac_ptr, &bytes_read);
24597             mac_ptr += bytes_read;
24598           }
24599           break;
24600
24601         case DW_MACRO_start_file:
24602           {
24603             unsigned int bytes_read;
24604             int line, file;
24605
24606             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24607             mac_ptr += bytes_read;
24608             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24609             mac_ptr += bytes_read;
24610
24611             current_file = macro_start_file (file, line, current_file, lh);
24612           }
24613           break;
24614
24615         case DW_MACRO_end_file:
24616           /* No data to skip by MAC_PTR.  */
24617           break;
24618
24619         case DW_MACRO_define_strp:
24620         case DW_MACRO_undef_strp:
24621         case DW_MACRO_define_sup:
24622         case DW_MACRO_undef_sup:
24623           {
24624             unsigned int bytes_read;
24625
24626             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24627             mac_ptr += bytes_read;
24628             mac_ptr += offset_size;
24629           }
24630           break;
24631
24632         case DW_MACRO_import:
24633         case DW_MACRO_import_sup:
24634           /* Note that, according to the spec, a transparent include
24635              chain cannot call DW_MACRO_start_file.  So, we can just
24636              skip this opcode.  */
24637           mac_ptr += offset_size;
24638           break;
24639
24640         case DW_MACINFO_vendor_ext:
24641           /* Only skip the data by MAC_PTR.  */
24642           if (!section_is_gnu)
24643             {
24644               unsigned int bytes_read;
24645
24646               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24647               mac_ptr += bytes_read;
24648               read_direct_string (abfd, mac_ptr, &bytes_read);
24649               mac_ptr += bytes_read;
24650             }
24651           /* FALLTHROUGH */
24652
24653         default:
24654           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24655                                          mac_ptr, mac_end, abfd, offset_size,
24656                                          section);
24657           if (mac_ptr == NULL)
24658             return;
24659           break;
24660         }
24661       DIAGNOSTIC_POP
24662     } while (macinfo_type != 0 && current_file == NULL);
24663
24664   /* Second pass: Process all entries.
24665
24666      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24667      command-line macro definitions/undefinitions.  This flag is unset when we
24668      reach the first DW_MACINFO_start_file entry.  */
24669
24670   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24671                                            htab_eq_pointer,
24672                                            NULL, xcalloc, xfree));
24673   mac_ptr = section->buffer + offset;
24674   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24675   *slot = (void *) mac_ptr;
24676   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24677                             abfd, mac_ptr, mac_end,
24678                             current_file, lh, section,
24679                             section_is_gnu, 0, offset_size,
24680                             include_hash.get ());
24681 }
24682
24683 /* Check if the attribute's form is a DW_FORM_block*
24684    if so return true else false.  */
24685
24686 static int
24687 attr_form_is_block (const struct attribute *attr)
24688 {
24689   return (attr == NULL ? 0 :
24690       attr->form == DW_FORM_block1
24691       || attr->form == DW_FORM_block2
24692       || attr->form == DW_FORM_block4
24693       || attr->form == DW_FORM_block
24694       || attr->form == DW_FORM_exprloc);
24695 }
24696
24697 /* Return non-zero if ATTR's value is a section offset --- classes
24698    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24699    You may use DW_UNSND (attr) to retrieve such offsets.
24700
24701    Section 7.5.4, "Attribute Encodings", explains that no attribute
24702    may have a value that belongs to more than one of these classes; it
24703    would be ambiguous if we did, because we use the same forms for all
24704    of them.  */
24705
24706 static int
24707 attr_form_is_section_offset (const struct attribute *attr)
24708 {
24709   return (attr->form == DW_FORM_data4
24710           || attr->form == DW_FORM_data8
24711           || attr->form == DW_FORM_sec_offset);
24712 }
24713
24714 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24715    zero otherwise.  When this function returns true, you can apply
24716    dwarf2_get_attr_constant_value to it.
24717
24718    However, note that for some attributes you must check
24719    attr_form_is_section_offset before using this test.  DW_FORM_data4
24720    and DW_FORM_data8 are members of both the constant class, and of
24721    the classes that contain offsets into other debug sections
24722    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24723    that, if an attribute's can be either a constant or one of the
24724    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24725    taken as section offsets, not constants.
24726
24727    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24728    cannot handle that.  */
24729
24730 static int
24731 attr_form_is_constant (const struct attribute *attr)
24732 {
24733   switch (attr->form)
24734     {
24735     case DW_FORM_sdata:
24736     case DW_FORM_udata:
24737     case DW_FORM_data1:
24738     case DW_FORM_data2:
24739     case DW_FORM_data4:
24740     case DW_FORM_data8:
24741     case DW_FORM_implicit_const:
24742       return 1;
24743     default:
24744       return 0;
24745     }
24746 }
24747
24748
24749 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24750    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24751
24752 static int
24753 attr_form_is_ref (const struct attribute *attr)
24754 {
24755   switch (attr->form)
24756     {
24757     case DW_FORM_ref_addr:
24758     case DW_FORM_ref1:
24759     case DW_FORM_ref2:
24760     case DW_FORM_ref4:
24761     case DW_FORM_ref8:
24762     case DW_FORM_ref_udata:
24763     case DW_FORM_GNU_ref_alt:
24764       return 1;
24765     default:
24766       return 0;
24767     }
24768 }
24769
24770 /* Return the .debug_loc section to use for CU.
24771    For DWO files use .debug_loc.dwo.  */
24772
24773 static struct dwarf2_section_info *
24774 cu_debug_loc_section (struct dwarf2_cu *cu)
24775 {
24776   struct dwarf2_per_objfile *dwarf2_per_objfile
24777     = cu->per_cu->dwarf2_per_objfile;
24778
24779   if (cu->dwo_unit)
24780     {
24781       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24782       
24783       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24784     }
24785   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24786                                   : &dwarf2_per_objfile->loc);
24787 }
24788
24789 /* A helper function that fills in a dwarf2_loclist_baton.  */
24790
24791 static void
24792 fill_in_loclist_baton (struct dwarf2_cu *cu,
24793                        struct dwarf2_loclist_baton *baton,
24794                        const struct attribute *attr)
24795 {
24796   struct dwarf2_per_objfile *dwarf2_per_objfile
24797     = cu->per_cu->dwarf2_per_objfile;
24798   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24799
24800   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24801
24802   baton->per_cu = cu->per_cu;
24803   gdb_assert (baton->per_cu);
24804   /* We don't know how long the location list is, but make sure we
24805      don't run off the edge of the section.  */
24806   baton->size = section->size - DW_UNSND (attr);
24807   baton->data = section->buffer + DW_UNSND (attr);
24808   baton->base_address = cu->base_address;
24809   baton->from_dwo = cu->dwo_unit != NULL;
24810 }
24811
24812 static void
24813 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24814                              struct dwarf2_cu *cu, int is_block)
24815 {
24816   struct dwarf2_per_objfile *dwarf2_per_objfile
24817     = cu->per_cu->dwarf2_per_objfile;
24818   struct objfile *objfile = dwarf2_per_objfile->objfile;
24819   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24820
24821   if (attr_form_is_section_offset (attr)
24822       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24823          the section.  If so, fall through to the complaint in the
24824          other branch.  */
24825       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24826     {
24827       struct dwarf2_loclist_baton *baton;
24828
24829       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24830
24831       fill_in_loclist_baton (cu, baton, attr);
24832
24833       if (cu->base_known == 0)
24834         complaint (&symfile_complaints,
24835                    _("Location list used without "
24836                      "specifying the CU base address."));
24837
24838       SYMBOL_ACLASS_INDEX (sym) = (is_block
24839                                    ? dwarf2_loclist_block_index
24840                                    : dwarf2_loclist_index);
24841       SYMBOL_LOCATION_BATON (sym) = baton;
24842     }
24843   else
24844     {
24845       struct dwarf2_locexpr_baton *baton;
24846
24847       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24848       baton->per_cu = cu->per_cu;
24849       gdb_assert (baton->per_cu);
24850
24851       if (attr_form_is_block (attr))
24852         {
24853           /* Note that we're just copying the block's data pointer
24854              here, not the actual data.  We're still pointing into the
24855              info_buffer for SYM's objfile; right now we never release
24856              that buffer, but when we do clean up properly this may
24857              need to change.  */
24858           baton->size = DW_BLOCK (attr)->size;
24859           baton->data = DW_BLOCK (attr)->data;
24860         }
24861       else
24862         {
24863           dwarf2_invalid_attrib_class_complaint ("location description",
24864                                                  SYMBOL_NATURAL_NAME (sym));
24865           baton->size = 0;
24866         }
24867
24868       SYMBOL_ACLASS_INDEX (sym) = (is_block
24869                                    ? dwarf2_locexpr_block_index
24870                                    : dwarf2_locexpr_index);
24871       SYMBOL_LOCATION_BATON (sym) = baton;
24872     }
24873 }
24874
24875 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24876    came from a separate debuginfo file, then the master objfile is
24877    returned.  */
24878
24879 struct objfile *
24880 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24881 {
24882   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24883
24884   /* Return the master objfile, so that we can report and look up the
24885      correct file containing this variable.  */
24886   if (objfile->separate_debug_objfile_backlink)
24887     objfile = objfile->separate_debug_objfile_backlink;
24888
24889   return objfile;
24890 }
24891
24892 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24893    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24894    CU_HEADERP first.  */
24895
24896 static const struct comp_unit_head *
24897 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24898                        struct dwarf2_per_cu_data *per_cu)
24899 {
24900   const gdb_byte *info_ptr;
24901
24902   if (per_cu->cu)
24903     return &per_cu->cu->header;
24904
24905   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24906
24907   memset (cu_headerp, 0, sizeof (*cu_headerp));
24908   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24909                        rcuh_kind::COMPILE);
24910
24911   return cu_headerp;
24912 }
24913
24914 /* Return the address size given in the compilation unit header for CU.  */
24915
24916 int
24917 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24918 {
24919   struct comp_unit_head cu_header_local;
24920   const struct comp_unit_head *cu_headerp;
24921
24922   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24923
24924   return cu_headerp->addr_size;
24925 }
24926
24927 /* Return the offset size given in the compilation unit header for CU.  */
24928
24929 int
24930 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24931 {
24932   struct comp_unit_head cu_header_local;
24933   const struct comp_unit_head *cu_headerp;
24934
24935   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24936
24937   return cu_headerp->offset_size;
24938 }
24939
24940 /* See its dwarf2loc.h declaration.  */
24941
24942 int
24943 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24944 {
24945   struct comp_unit_head cu_header_local;
24946   const struct comp_unit_head *cu_headerp;
24947
24948   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24949
24950   if (cu_headerp->version == 2)
24951     return cu_headerp->addr_size;
24952   else
24953     return cu_headerp->offset_size;
24954 }
24955
24956 /* Return the text offset of the CU.  The returned offset comes from
24957    this CU's objfile.  If this objfile came from a separate debuginfo
24958    file, then the offset may be different from the corresponding
24959    offset in the parent objfile.  */
24960
24961 CORE_ADDR
24962 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24963 {
24964   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24965
24966   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24967 }
24968
24969 /* Return DWARF version number of PER_CU.  */
24970
24971 short
24972 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24973 {
24974   return per_cu->dwarf_version;
24975 }
24976
24977 /* Locate the .debug_info compilation unit from CU's objfile which contains
24978    the DIE at OFFSET.  Raises an error on failure.  */
24979
24980 static struct dwarf2_per_cu_data *
24981 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24982                                   unsigned int offset_in_dwz,
24983                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24984 {
24985   struct dwarf2_per_cu_data *this_cu;
24986   int low, high;
24987   const sect_offset *cu_off;
24988
24989   low = 0;
24990   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24991   while (high > low)
24992     {
24993       struct dwarf2_per_cu_data *mid_cu;
24994       int mid = low + (high - low) / 2;
24995
24996       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24997       cu_off = &mid_cu->sect_off;
24998       if (mid_cu->is_dwz > offset_in_dwz
24999           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25000         high = mid;
25001       else
25002         low = mid + 1;
25003     }
25004   gdb_assert (low == high);
25005   this_cu = dwarf2_per_objfile->all_comp_units[low];
25006   cu_off = &this_cu->sect_off;
25007   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25008     {
25009       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25010         error (_("Dwarf Error: could not find partial DIE containing "
25011                "offset %s [in module %s]"),
25012                sect_offset_str (sect_off),
25013                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25014
25015       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25016                   <= sect_off);
25017       return dwarf2_per_objfile->all_comp_units[low-1];
25018     }
25019   else
25020     {
25021       this_cu = dwarf2_per_objfile->all_comp_units[low];
25022       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25023           && sect_off >= this_cu->sect_off + this_cu->length)
25024         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25025       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25026       return this_cu;
25027     }
25028 }
25029
25030 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25031
25032 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25033   : per_cu (per_cu_),
25034     mark (0),
25035     has_loclist (0),
25036     checked_producer (0),
25037     producer_is_gxx_lt_4_6 (0),
25038     producer_is_gcc_lt_4_3 (0),
25039     producer_is_icc_lt_14 (0),
25040     processing_has_namespace_info (0)
25041 {
25042   per_cu->cu = this;
25043 }
25044
25045 /* Destroy a dwarf2_cu.  */
25046
25047 dwarf2_cu::~dwarf2_cu ()
25048 {
25049   per_cu->cu = NULL;
25050 }
25051
25052 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25053
25054 static void
25055 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25056                        enum language pretend_language)
25057 {
25058   struct attribute *attr;
25059
25060   /* Set the language we're debugging.  */
25061   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25062   if (attr)
25063     set_cu_language (DW_UNSND (attr), cu);
25064   else
25065     {
25066       cu->language = pretend_language;
25067       cu->language_defn = language_def (cu->language);
25068     }
25069
25070   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25071 }
25072
25073 /* Increase the age counter on each cached compilation unit, and free
25074    any that are too old.  */
25075
25076 static void
25077 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25078 {
25079   struct dwarf2_per_cu_data *per_cu, **last_chain;
25080
25081   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25082   per_cu = dwarf2_per_objfile->read_in_chain;
25083   while (per_cu != NULL)
25084     {
25085       per_cu->cu->last_used ++;
25086       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25087         dwarf2_mark (per_cu->cu);
25088       per_cu = per_cu->cu->read_in_chain;
25089     }
25090
25091   per_cu = dwarf2_per_objfile->read_in_chain;
25092   last_chain = &dwarf2_per_objfile->read_in_chain;
25093   while (per_cu != NULL)
25094     {
25095       struct dwarf2_per_cu_data *next_cu;
25096
25097       next_cu = per_cu->cu->read_in_chain;
25098
25099       if (!per_cu->cu->mark)
25100         {
25101           delete per_cu->cu;
25102           *last_chain = next_cu;
25103         }
25104       else
25105         last_chain = &per_cu->cu->read_in_chain;
25106
25107       per_cu = next_cu;
25108     }
25109 }
25110
25111 /* Remove a single compilation unit from the cache.  */
25112
25113 static void
25114 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25115 {
25116   struct dwarf2_per_cu_data *per_cu, **last_chain;
25117   struct dwarf2_per_objfile *dwarf2_per_objfile
25118     = target_per_cu->dwarf2_per_objfile;
25119
25120   per_cu = dwarf2_per_objfile->read_in_chain;
25121   last_chain = &dwarf2_per_objfile->read_in_chain;
25122   while (per_cu != NULL)
25123     {
25124       struct dwarf2_per_cu_data *next_cu;
25125
25126       next_cu = per_cu->cu->read_in_chain;
25127
25128       if (per_cu == target_per_cu)
25129         {
25130           delete per_cu->cu;
25131           per_cu->cu = NULL;
25132           *last_chain = next_cu;
25133           break;
25134         }
25135       else
25136         last_chain = &per_cu->cu->read_in_chain;
25137
25138       per_cu = next_cu;
25139     }
25140 }
25141
25142 /* Release all extra memory associated with OBJFILE.  */
25143
25144 void
25145 dwarf2_free_objfile (struct objfile *objfile)
25146 {
25147   struct dwarf2_per_objfile *dwarf2_per_objfile
25148     = get_dwarf2_per_objfile (objfile);
25149
25150   delete dwarf2_per_objfile;
25151 }
25152
25153 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25154    We store these in a hash table separate from the DIEs, and preserve them
25155    when the DIEs are flushed out of cache.
25156
25157    The CU "per_cu" pointer is needed because offset alone is not enough to
25158    uniquely identify the type.  A file may have multiple .debug_types sections,
25159    or the type may come from a DWO file.  Furthermore, while it's more logical
25160    to use per_cu->section+offset, with Fission the section with the data is in
25161    the DWO file but we don't know that section at the point we need it.
25162    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25163    because we can enter the lookup routine, get_die_type_at_offset, from
25164    outside this file, and thus won't necessarily have PER_CU->cu.
25165    Fortunately, PER_CU is stable for the life of the objfile.  */
25166
25167 struct dwarf2_per_cu_offset_and_type
25168 {
25169   const struct dwarf2_per_cu_data *per_cu;
25170   sect_offset sect_off;
25171   struct type *type;
25172 };
25173
25174 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25175
25176 static hashval_t
25177 per_cu_offset_and_type_hash (const void *item)
25178 {
25179   const struct dwarf2_per_cu_offset_and_type *ofs
25180     = (const struct dwarf2_per_cu_offset_and_type *) item;
25181
25182   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25183 }
25184
25185 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25186
25187 static int
25188 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25189 {
25190   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25191     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25192   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25193     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25194
25195   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25196           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25197 }
25198
25199 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25200    table if necessary.  For convenience, return TYPE.
25201
25202    The DIEs reading must have careful ordering to:
25203     * Not cause infite loops trying to read in DIEs as a prerequisite for
25204       reading current DIE.
25205     * Not trying to dereference contents of still incompletely read in types
25206       while reading in other DIEs.
25207     * Enable referencing still incompletely read in types just by a pointer to
25208       the type without accessing its fields.
25209
25210    Therefore caller should follow these rules:
25211      * Try to fetch any prerequisite types we may need to build this DIE type
25212        before building the type and calling set_die_type.
25213      * After building type call set_die_type for current DIE as soon as
25214        possible before fetching more types to complete the current type.
25215      * Make the type as complete as possible before fetching more types.  */
25216
25217 static struct type *
25218 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25219 {
25220   struct dwarf2_per_objfile *dwarf2_per_objfile
25221     = cu->per_cu->dwarf2_per_objfile;
25222   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25223   struct objfile *objfile = dwarf2_per_objfile->objfile;
25224   struct attribute *attr;
25225   struct dynamic_prop prop;
25226
25227   /* For Ada types, make sure that the gnat-specific data is always
25228      initialized (if not already set).  There are a few types where
25229      we should not be doing so, because the type-specific area is
25230      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25231      where the type-specific area is used to store the floatformat).
25232      But this is not a problem, because the gnat-specific information
25233      is actually not needed for these types.  */
25234   if (need_gnat_info (cu)
25235       && TYPE_CODE (type) != TYPE_CODE_FUNC
25236       && TYPE_CODE (type) != TYPE_CODE_FLT
25237       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25238       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25239       && TYPE_CODE (type) != TYPE_CODE_METHOD
25240       && !HAVE_GNAT_AUX_INFO (type))
25241     INIT_GNAT_SPECIFIC (type);
25242
25243   /* Read DW_AT_allocated and set in type.  */
25244   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25245   if (attr_form_is_block (attr))
25246     {
25247       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25248         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25249     }
25250   else if (attr != NULL)
25251     {
25252       complaint (&symfile_complaints,
25253                  _("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25254                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25255                  sect_offset_str (die->sect_off));
25256     }
25257
25258   /* Read DW_AT_associated and set in type.  */
25259   attr = dwarf2_attr (die, DW_AT_associated, cu);
25260   if (attr_form_is_block (attr))
25261     {
25262       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25263         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25264     }
25265   else if (attr != NULL)
25266     {
25267       complaint (&symfile_complaints,
25268                  _("DW_AT_associated has the wrong form (%s) at DIE %s"),
25269                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25270                  sect_offset_str (die->sect_off));
25271     }
25272
25273   /* Read DW_AT_data_location and set in type.  */
25274   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25275   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25276     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25277
25278   if (dwarf2_per_objfile->die_type_hash == NULL)
25279     {
25280       dwarf2_per_objfile->die_type_hash =
25281         htab_create_alloc_ex (127,
25282                               per_cu_offset_and_type_hash,
25283                               per_cu_offset_and_type_eq,
25284                               NULL,
25285                               &objfile->objfile_obstack,
25286                               hashtab_obstack_allocate,
25287                               dummy_obstack_deallocate);
25288     }
25289
25290   ofs.per_cu = cu->per_cu;
25291   ofs.sect_off = die->sect_off;
25292   ofs.type = type;
25293   slot = (struct dwarf2_per_cu_offset_and_type **)
25294     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25295   if (*slot)
25296     complaint (&symfile_complaints,
25297                _("A problem internal to GDB: DIE %s has type already set"),
25298                sect_offset_str (die->sect_off));
25299   *slot = XOBNEW (&objfile->objfile_obstack,
25300                   struct dwarf2_per_cu_offset_and_type);
25301   **slot = ofs;
25302   return type;
25303 }
25304
25305 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25306    or return NULL if the die does not have a saved type.  */
25307
25308 static struct type *
25309 get_die_type_at_offset (sect_offset sect_off,
25310                         struct dwarf2_per_cu_data *per_cu)
25311 {
25312   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25313   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25314
25315   if (dwarf2_per_objfile->die_type_hash == NULL)
25316     return NULL;
25317
25318   ofs.per_cu = per_cu;
25319   ofs.sect_off = sect_off;
25320   slot = ((struct dwarf2_per_cu_offset_and_type *)
25321           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25322   if (slot)
25323     return slot->type;
25324   else
25325     return NULL;
25326 }
25327
25328 /* Look up the type for DIE in CU in die_type_hash,
25329    or return NULL if DIE does not have a saved type.  */
25330
25331 static struct type *
25332 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25333 {
25334   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25335 }
25336
25337 /* Add a dependence relationship from CU to REF_PER_CU.  */
25338
25339 static void
25340 dwarf2_add_dependence (struct dwarf2_cu *cu,
25341                        struct dwarf2_per_cu_data *ref_per_cu)
25342 {
25343   void **slot;
25344
25345   if (cu->dependencies == NULL)
25346     cu->dependencies
25347       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25348                               NULL, &cu->comp_unit_obstack,
25349                               hashtab_obstack_allocate,
25350                               dummy_obstack_deallocate);
25351
25352   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25353   if (*slot == NULL)
25354     *slot = ref_per_cu;
25355 }
25356
25357 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25358    Set the mark field in every compilation unit in the
25359    cache that we must keep because we are keeping CU.  */
25360
25361 static int
25362 dwarf2_mark_helper (void **slot, void *data)
25363 {
25364   struct dwarf2_per_cu_data *per_cu;
25365
25366   per_cu = (struct dwarf2_per_cu_data *) *slot;
25367
25368   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25369      reading of the chain.  As such dependencies remain valid it is not much
25370      useful to track and undo them during QUIT cleanups.  */
25371   if (per_cu->cu == NULL)
25372     return 1;
25373
25374   if (per_cu->cu->mark)
25375     return 1;
25376   per_cu->cu->mark = 1;
25377
25378   if (per_cu->cu->dependencies != NULL)
25379     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25380
25381   return 1;
25382 }
25383
25384 /* Set the mark field in CU and in every other compilation unit in the
25385    cache that we must keep because we are keeping CU.  */
25386
25387 static void
25388 dwarf2_mark (struct dwarf2_cu *cu)
25389 {
25390   if (cu->mark)
25391     return;
25392   cu->mark = 1;
25393   if (cu->dependencies != NULL)
25394     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25395 }
25396
25397 static void
25398 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25399 {
25400   while (per_cu)
25401     {
25402       per_cu->cu->mark = 0;
25403       per_cu = per_cu->cu->read_in_chain;
25404     }
25405 }
25406
25407 /* Trivial hash function for partial_die_info: the hash value of a DIE
25408    is its offset in .debug_info for this objfile.  */
25409
25410 static hashval_t
25411 partial_die_hash (const void *item)
25412 {
25413   const struct partial_die_info *part_die
25414     = (const struct partial_die_info *) item;
25415
25416   return to_underlying (part_die->sect_off);
25417 }
25418
25419 /* Trivial comparison function for partial_die_info structures: two DIEs
25420    are equal if they have the same offset.  */
25421
25422 static int
25423 partial_die_eq (const void *item_lhs, const void *item_rhs)
25424 {
25425   const struct partial_die_info *part_die_lhs
25426     = (const struct partial_die_info *) item_lhs;
25427   const struct partial_die_info *part_die_rhs
25428     = (const struct partial_die_info *) item_rhs;
25429
25430   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25431 }
25432
25433 static struct cmd_list_element *set_dwarf_cmdlist;
25434 static struct cmd_list_element *show_dwarf_cmdlist;
25435
25436 static void
25437 set_dwarf_cmd (const char *args, int from_tty)
25438 {
25439   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25440              gdb_stdout);
25441 }
25442
25443 static void
25444 show_dwarf_cmd (const char *args, int from_tty)
25445 {
25446   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25447 }
25448
25449 int dwarf_always_disassemble;
25450
25451 static void
25452 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25453                                struct cmd_list_element *c, const char *value)
25454 {
25455   fprintf_filtered (file,
25456                     _("Whether to always disassemble "
25457                       "DWARF expressions is %s.\n"),
25458                     value);
25459 }
25460
25461 static void
25462 show_check_physname (struct ui_file *file, int from_tty,
25463                      struct cmd_list_element *c, const char *value)
25464 {
25465   fprintf_filtered (file,
25466                     _("Whether to check \"physname\" is %s.\n"),
25467                     value);
25468 }
25469
25470 void
25471 _initialize_dwarf2_read (void)
25472 {
25473
25474   dwarf2_objfile_data_key = register_objfile_data ();
25475
25476   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25477 Set DWARF specific variables.\n\
25478 Configure DWARF variables such as the cache size"),
25479                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25480                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25481
25482   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25483 Show DWARF specific variables\n\
25484 Show DWARF variables such as the cache size"),
25485                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25486                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25487
25488   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25489                             &dwarf_max_cache_age, _("\
25490 Set the upper bound on the age of cached DWARF compilation units."), _("\
25491 Show the upper bound on the age of cached DWARF compilation units."), _("\
25492 A higher limit means that cached compilation units will be stored\n\
25493 in memory longer, and more total memory will be used.  Zero disables\n\
25494 caching, which can slow down startup."),
25495                             NULL,
25496                             show_dwarf_max_cache_age,
25497                             &set_dwarf_cmdlist,
25498                             &show_dwarf_cmdlist);
25499
25500   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25501                            &dwarf_always_disassemble, _("\
25502 Set whether `info address' always disassembles DWARF expressions."), _("\
25503 Show whether `info address' always disassembles DWARF expressions."), _("\
25504 When enabled, DWARF expressions are always printed in an assembly-like\n\
25505 syntax.  When disabled, expressions will be printed in a more\n\
25506 conversational style, when possible."),
25507                            NULL,
25508                            show_dwarf_always_disassemble,
25509                            &set_dwarf_cmdlist,
25510                            &show_dwarf_cmdlist);
25511
25512   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25513 Set debugging of the DWARF reader."), _("\
25514 Show debugging of the DWARF reader."), _("\
25515 When enabled (non-zero), debugging messages are printed during DWARF\n\
25516 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25517 information.  A value greater than 1 provides more verbose information."),
25518                             NULL,
25519                             NULL,
25520                             &setdebuglist, &showdebuglist);
25521
25522   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25523 Set debugging of the DWARF DIE reader."), _("\
25524 Show debugging of the DWARF DIE reader."), _("\
25525 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25526 The value is the maximum depth to print."),
25527                              NULL,
25528                              NULL,
25529                              &setdebuglist, &showdebuglist);
25530
25531   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25532 Set debugging of the dwarf line reader."), _("\
25533 Show debugging of the dwarf line reader."), _("\
25534 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25535 A value of 1 (one) provides basic information.\n\
25536 A value greater than 1 provides more verbose information."),
25537                              NULL,
25538                              NULL,
25539                              &setdebuglist, &showdebuglist);
25540
25541   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25542 Set cross-checking of \"physname\" code against demangler."), _("\
25543 Show cross-checking of \"physname\" code against demangler."), _("\
25544 When enabled, GDB's internal \"physname\" code is checked against\n\
25545 the demangler."),
25546                            NULL, show_check_physname,
25547                            &setdebuglist, &showdebuglist);
25548
25549   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25550                            no_class, &use_deprecated_index_sections, _("\
25551 Set whether to use deprecated gdb_index sections."), _("\
25552 Show whether to use deprecated gdb_index sections."), _("\
25553 When enabled, deprecated .gdb_index sections are used anyway.\n\
25554 Normally they are ignored either because of a missing feature or\n\
25555 performance issue.\n\
25556 Warning: This option must be enabled before gdb reads the file."),
25557                            NULL,
25558                            NULL,
25559                            &setlist, &showlist);
25560
25561   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25562                                                         &dwarf2_locexpr_funcs);
25563   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25564                                                         &dwarf2_loclist_funcs);
25565
25566   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25567                                         &dwarf2_block_frame_base_locexpr_funcs);
25568   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25569                                         &dwarf2_block_frame_base_loclist_funcs);
25570
25571 #if GDB_SELF_TEST
25572   selftests::register_test ("dw2_expand_symtabs_matching",
25573                             selftests::dw2_expand_symtabs_matching::run_test);
25574 #endif
25575 }