DWARF-5: .debug_names index consumer
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 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 "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 typedef struct symbol *symbolp;
91 DEF_VEC_P (symbolp);
92
93 /* When == 1, print basic high level tracing messages.
94    When > 1, be more verbose.
95    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
96 static unsigned int dwarf_read_debug = 0;
97
98 /* When non-zero, dump DIEs after they are read in.  */
99 static unsigned int dwarf_die_debug = 0;
100
101 /* When non-zero, dump line number entries as they are read in.  */
102 static unsigned int dwarf_line_debug = 0;
103
104 /* When non-zero, cross-check physname against demangler.  */
105 static int check_physname = 0;
106
107 /* When non-zero, do not reject deprecated .gdb_index sections.  */
108 static int use_deprecated_index_sections = 0;
109
110 static const struct objfile_data *dwarf2_objfile_data_key;
111
112 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
113
114 static int dwarf2_locexpr_index;
115 static int dwarf2_loclist_index;
116 static int dwarf2_locexpr_block_index;
117 static int dwarf2_loclist_block_index;
118
119 /* A descriptor for dwarf sections.
120
121    S.ASECTION, SIZE are typically initialized when the objfile is first
122    scanned.  BUFFER, READIN are filled in later when the section is read.
123    If the section contained compressed data then SIZE is updated to record
124    the uncompressed size of the section.
125
126    DWP file format V2 introduces a wrinkle that is easiest to handle by
127    creating the concept of virtual sections contained within a real section.
128    In DWP V2 the sections of the input DWO files are concatenated together
129    into one section, but section offsets are kept relative to the original
130    input section.
131    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
132    the real section this "virtual" section is contained in, and BUFFER,SIZE
133    describe the virtual section.  */
134
135 struct dwarf2_section_info
136 {
137   union
138   {
139     /* If this is a real section, the bfd section.  */
140     asection *section;
141     /* If this is a virtual section, pointer to the containing ("real")
142        section.  */
143     struct dwarf2_section_info *containing_section;
144   } s;
145   /* Pointer to section data, only valid if readin.  */
146   const gdb_byte *buffer;
147   /* The size of the section, real or virtual.  */
148   bfd_size_type size;
149   /* If this is a virtual section, the offset in the real section.
150      Only valid if is_virtual.  */
151   bfd_size_type virtual_offset;
152   /* True if we have tried to read this section.  */
153   char readin;
154   /* True if this is a virtual section, False otherwise.
155      This specifies which of s.section and s.containing_section to use.  */
156   char is_virtual;
157 };
158
159 typedef struct dwarf2_section_info dwarf2_section_info_def;
160 DEF_VEC_O (dwarf2_section_info_def);
161
162 /* All offsets in the index are of this type.  It must be
163    architecture-independent.  */
164 typedef uint32_t offset_type;
165
166 DEF_VEC_I (offset_type);
167
168 /* Ensure only legit values are used.  */
169 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert ((unsigned int) (value) <= 1); \
172     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
173   } while (0)
174
175 /* Ensure only legit values are used.  */
176 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
177   do { \
178     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
179                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
180     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
181   } while (0)
182
183 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
184 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
185   do { \
186     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
187     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
188   } while (0)
189
190 #if WORDS_BIGENDIAN
191
192 /* Convert VALUE between big- and little-endian.  */
193
194 static offset_type
195 byte_swap (offset_type value)
196 {
197   offset_type result;
198
199   result = (value & 0xff) << 24;
200   result |= (value & 0xff00) << 8;
201   result |= (value & 0xff0000) >> 8;
202   result |= (value & 0xff000000) >> 24;
203   return result;
204 }
205
206 #define MAYBE_SWAP(V)  byte_swap (V)
207
208 #else
209 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
210 #endif /* WORDS_BIGENDIAN */
211
212 /* An index into a (C++) symbol name component in a symbol name as
213    recorded in the mapped_index's symbol table.  For each C++ symbol
214    in the symbol table, we record one entry for the start of each
215    component in the symbol in a table of name components, and then
216    sort the table, in order to be able to binary search symbol names,
217    ignoring leading namespaces, both completion and regular look up.
218    For example, for symbol "A::B::C", we'll have an entry that points
219    to "A::B::C", another that points to "B::C", and another for "C".
220    Note that function symbols in GDB index have no parameter
221    information, just the function/method names.  You can convert a
222    name_component to a "const char *" using the
223    'mapped_index::symbol_name_at(offset_type)' method.  */
224
225 struct name_component
226 {
227   /* Offset in the symbol name where the component starts.  Stored as
228      a (32-bit) offset instead of a pointer to save memory and improve
229      locality on 64-bit architectures.  */
230   offset_type name_offset;
231
232   /* The symbol's index in the symbol and constant pool tables of a
233      mapped_index.  */
234   offset_type idx;
235 };
236
237 /* A description of the mapped index.  The file format is described in
238    a comment by the code that writes the index.  */
239 struct mapped_index
240 {
241   /* Index data format version.  */
242   int version;
243
244   /* The total length of the buffer.  */
245   off_t total_size;
246
247   /* A pointer to the address table data.  */
248   const gdb_byte *address_table;
249
250   /* Size of the address table data in bytes.  */
251   offset_type address_table_size;
252
253   /* The symbol table, implemented as a hash table.  */
254   const offset_type *symbol_table;
255
256   /* Size in slots, each slot is 2 offset_types.  */
257   offset_type symbol_table_slots;
258
259   /* A pointer to the constant pool.  */
260   const char *constant_pool;
261
262   /* The name_component table (a sorted vector).  See name_component's
263      description above.  */
264   std::vector<name_component> name_components;
265
266   /* How NAME_COMPONENTS is sorted.  */
267   enum case_sensitivity name_components_casing;
268
269   /* Convenience method to get at the name of the symbol at IDX in the
270      symbol table.  */
271   const char *symbol_name_at (offset_type idx) const
272   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx]); }
273
274   /* Build the symbol name component sorted vector, if we haven't
275      yet.  */
276   void build_name_components ();
277
278   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
279      possible matches for LN_NO_PARAMS in the name component
280      vector.  */
281   std::pair<std::vector<name_component>::const_iterator,
282             std::vector<name_component>::const_iterator>
283     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
284 };
285
286 /* A description of the mapped .debug_names.
287    Uninitialized map has CU_COUNT 0.  */
288 struct mapped_debug_names
289 {
290   bfd_endian dwarf5_byte_order;
291   bool dwarf5_is_dwarf64;
292   bool augmentation_is_gdb;
293   uint8_t offset_size;
294   uint32_t cu_count = 0;
295   uint32_t tu_count, bucket_count, name_count;
296   const gdb_byte *cu_table_reordered, *tu_table_reordered;
297   const uint32_t *bucket_table_reordered, *hash_table_reordered;
298   const gdb_byte *name_table_string_offs_reordered;
299   const gdb_byte *name_table_entry_offs_reordered;
300   const gdb_byte *entry_pool;
301
302   struct index_val
303   {
304     ULONGEST dwarf_tag;
305     struct attr
306     {
307       /* Attribute name DW_IDX_*.  */
308       ULONGEST dw_idx;
309
310       /* Attribute form DW_FORM_*.  */
311       ULONGEST form;
312
313       /* Value if FORM is DW_FORM_implicit_const.  */
314       LONGEST implicit_const;
315     };
316     std::vector<attr> attr_vec;
317   };
318
319   std::unordered_map<ULONGEST, index_val> abbrev_map;
320
321   const char *namei_to_name (uint32_t namei) const;
322 };
323
324 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
325 DEF_VEC_P (dwarf2_per_cu_ptr);
326
327 struct tu_stats
328 {
329   int nr_uniq_abbrev_tables;
330   int nr_symtabs;
331   int nr_symtab_sharers;
332   int nr_stmt_less_type_units;
333   int nr_all_type_units_reallocs;
334 };
335
336 /* Collection of data recorded per objfile.
337    This hangs off of dwarf2_objfile_data_key.  */
338
339 struct dwarf2_per_objfile
340 {
341   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
342      dwarf2 section names, or is NULL if the standard ELF names are
343      used.  */
344   dwarf2_per_objfile (struct objfile *objfile,
345                       const dwarf2_debug_sections *names);
346
347   ~dwarf2_per_objfile ();
348
349   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
350
351   /* Free all cached compilation units.  */
352   void free_cached_comp_units ();
353 private:
354   /* This function is mapped across the sections and remembers the
355      offset and size of each of the debugging sections we are
356      interested in.  */
357   void locate_sections (bfd *abfd, asection *sectp,
358                         const dwarf2_debug_sections &names);
359
360 public:
361   dwarf2_section_info info {};
362   dwarf2_section_info abbrev {};
363   dwarf2_section_info line {};
364   dwarf2_section_info loc {};
365   dwarf2_section_info loclists {};
366   dwarf2_section_info macinfo {};
367   dwarf2_section_info macro {};
368   dwarf2_section_info str {};
369   dwarf2_section_info line_str {};
370   dwarf2_section_info ranges {};
371   dwarf2_section_info rnglists {};
372   dwarf2_section_info addr {};
373   dwarf2_section_info frame {};
374   dwarf2_section_info eh_frame {};
375   dwarf2_section_info gdb_index {};
376   dwarf2_section_info debug_names {};
377   dwarf2_section_info debug_aranges {};
378
379   VEC (dwarf2_section_info_def) *types = NULL;
380
381   /* Back link.  */
382   struct objfile *objfile = NULL;
383
384   /* Table of all the compilation units.  This is used to locate
385      the target compilation unit of a particular reference.  */
386   struct dwarf2_per_cu_data **all_comp_units = NULL;
387
388   /* The number of compilation units in ALL_COMP_UNITS.  */
389   int n_comp_units = 0;
390
391   /* The number of .debug_types-related CUs.  */
392   int n_type_units = 0;
393
394   /* The number of elements allocated in all_type_units.
395      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
396   int n_allocated_type_units = 0;
397
398   /* The .debug_types-related CUs (TUs).
399      This is stored in malloc space because we may realloc it.  */
400   struct signatured_type **all_type_units = NULL;
401
402   /* Table of struct type_unit_group objects.
403      The hash key is the DW_AT_stmt_list value.  */
404   htab_t type_unit_groups {};
405
406   /* A table mapping .debug_types signatures to its signatured_type entry.
407      This is NULL if the .debug_types section hasn't been read in yet.  */
408   htab_t signatured_types {};
409
410   /* Type unit statistics, to see how well the scaling improvements
411      are doing.  */
412   struct tu_stats tu_stats {};
413
414   /* A chain of compilation units that are currently read in, so that
415      they can be freed later.  */
416   dwarf2_per_cu_data *read_in_chain = NULL;
417
418   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
419      This is NULL if the table hasn't been allocated yet.  */
420   htab_t dwo_files {};
421
422   /* True if we've checked for whether there is a DWP file.  */
423   bool dwp_checked = false;
424
425   /* The DWP file if there is one, or NULL.  */
426   struct dwp_file *dwp_file = NULL;
427
428   /* The shared '.dwz' file, if one exists.  This is used when the
429      original data was compressed using 'dwz -m'.  */
430   struct dwz_file *dwz_file = NULL;
431
432   /* A flag indicating whether this objfile has a section loaded at a
433      VMA of 0.  */
434   bool has_section_at_zero = false;
435
436   /* True if we are using the mapped index,
437      or we are faking it for OBJF_READNOW's sake.  */
438   bool using_index = false;
439
440   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
441   mapped_index *index_table = NULL;
442
443   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
444   std::unique_ptr<mapped_debug_names> debug_names_table;
445
446   /* When using index_table, this keeps track of all quick_file_names entries.
447      TUs typically share line table entries with a CU, so we maintain a
448      separate table of all line table entries to support the sharing.
449      Note that while there can be way more TUs than CUs, we've already
450      sorted all the TUs into "type unit groups", grouped by their
451      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
452      CU and its associated TU group if there is one.  */
453   htab_t quick_file_names_table {};
454
455   /* Set during partial symbol reading, to prevent queueing of full
456      symbols.  */
457   bool reading_partial_symbols = false;
458
459   /* Table mapping type DIEs to their struct type *.
460      This is NULL if not allocated yet.
461      The mapping is done via (CU/TU + DIE offset) -> type.  */
462   htab_t die_type_hash {};
463
464   /* The CUs we recently read.  */
465   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
466
467   /* Table containing line_header indexed by offset and offset_in_dwz.  */
468   htab_t line_header_hash {};
469
470   /* Table containing all filenames.  This is an optional because the
471      table is lazily constructed on first access.  */
472   gdb::optional<filename_seen_cache> filenames_cache;
473 };
474
475 static struct dwarf2_per_objfile *dwarf2_per_objfile;
476
477 /* Default names of the debugging sections.  */
478
479 /* Note that if the debugging section has been compressed, it might
480    have a name like .zdebug_info.  */
481
482 static const struct dwarf2_debug_sections dwarf2_elf_names =
483 {
484   { ".debug_info", ".zdebug_info" },
485   { ".debug_abbrev", ".zdebug_abbrev" },
486   { ".debug_line", ".zdebug_line" },
487   { ".debug_loc", ".zdebug_loc" },
488   { ".debug_loclists", ".zdebug_loclists" },
489   { ".debug_macinfo", ".zdebug_macinfo" },
490   { ".debug_macro", ".zdebug_macro" },
491   { ".debug_str", ".zdebug_str" },
492   { ".debug_line_str", ".zdebug_line_str" },
493   { ".debug_ranges", ".zdebug_ranges" },
494   { ".debug_rnglists", ".zdebug_rnglists" },
495   { ".debug_types", ".zdebug_types" },
496   { ".debug_addr", ".zdebug_addr" },
497   { ".debug_frame", ".zdebug_frame" },
498   { ".eh_frame", NULL },
499   { ".gdb_index", ".zgdb_index" },
500   { ".debug_names", ".zdebug_names" },
501   { ".debug_aranges", ".zdebug_aranges" },
502   23
503 };
504
505 /* List of DWO/DWP sections.  */
506
507 static const struct dwop_section_names
508 {
509   struct dwarf2_section_names abbrev_dwo;
510   struct dwarf2_section_names info_dwo;
511   struct dwarf2_section_names line_dwo;
512   struct dwarf2_section_names loc_dwo;
513   struct dwarf2_section_names loclists_dwo;
514   struct dwarf2_section_names macinfo_dwo;
515   struct dwarf2_section_names macro_dwo;
516   struct dwarf2_section_names str_dwo;
517   struct dwarf2_section_names str_offsets_dwo;
518   struct dwarf2_section_names types_dwo;
519   struct dwarf2_section_names cu_index;
520   struct dwarf2_section_names tu_index;
521 }
522 dwop_section_names =
523 {
524   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
525   { ".debug_info.dwo", ".zdebug_info.dwo" },
526   { ".debug_line.dwo", ".zdebug_line.dwo" },
527   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
528   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
529   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
530   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
531   { ".debug_str.dwo", ".zdebug_str.dwo" },
532   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
533   { ".debug_types.dwo", ".zdebug_types.dwo" },
534   { ".debug_cu_index", ".zdebug_cu_index" },
535   { ".debug_tu_index", ".zdebug_tu_index" },
536 };
537
538 /* local data types */
539
540 /* The data in a compilation unit header, after target2host
541    translation, looks like this.  */
542 struct comp_unit_head
543 {
544   unsigned int length;
545   short version;
546   unsigned char addr_size;
547   unsigned char signed_addr_p;
548   sect_offset abbrev_sect_off;
549
550   /* Size of file offsets; either 4 or 8.  */
551   unsigned int offset_size;
552
553   /* Size of the length field; either 4 or 12.  */
554   unsigned int initial_length_size;
555
556   enum dwarf_unit_type unit_type;
557
558   /* Offset to the first byte of this compilation unit header in the
559      .debug_info section, for resolving relative reference dies.  */
560   sect_offset sect_off;
561
562   /* Offset to first die in this cu from the start of the cu.
563      This will be the first byte following the compilation unit header.  */
564   cu_offset first_die_cu_offset;
565
566   /* 64-bit signature of this type unit - it is valid only for
567      UNIT_TYPE DW_UT_type.  */
568   ULONGEST signature;
569
570   /* For types, offset in the type's DIE of the type defined by this TU.  */
571   cu_offset type_cu_offset_in_tu;
572 };
573
574 /* Type used for delaying computation of method physnames.
575    See comments for compute_delayed_physnames.  */
576 struct delayed_method_info
577 {
578   /* The type to which the method is attached, i.e., its parent class.  */
579   struct type *type;
580
581   /* The index of the method in the type's function fieldlists.  */
582   int fnfield_index;
583
584   /* The index of the method in the fieldlist.  */
585   int index;
586
587   /* The name of the DIE.  */
588   const char *name;
589
590   /*  The DIE associated with this method.  */
591   struct die_info *die;
592 };
593
594 typedef struct delayed_method_info delayed_method_info;
595 DEF_VEC_O (delayed_method_info);
596
597 /* Internal state when decoding a particular compilation unit.  */
598 struct dwarf2_cu
599 {
600   /* The objfile containing this compilation unit.  */
601   struct objfile *objfile;
602
603   /* The header of the compilation unit.  */
604   struct comp_unit_head header;
605
606   /* Base address of this compilation unit.  */
607   CORE_ADDR base_address;
608
609   /* Non-zero if base_address has been set.  */
610   int base_known;
611
612   /* The language we are debugging.  */
613   enum language language;
614   const struct language_defn *language_defn;
615
616   const char *producer;
617
618   /* The generic symbol table building routines have separate lists for
619      file scope symbols and all all other scopes (local scopes).  So
620      we need to select the right one to pass to add_symbol_to_list().
621      We do it by keeping a pointer to the correct list in list_in_scope.
622
623      FIXME: The original dwarf code just treated the file scope as the
624      first local scope, and all other local scopes as nested local
625      scopes, and worked fine.  Check to see if we really need to
626      distinguish these in buildsym.c.  */
627   struct pending **list_in_scope;
628
629   /* The abbrev table for this CU.
630      Normally this points to the abbrev table in the objfile.
631      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
632   struct abbrev_table *abbrev_table;
633
634   /* Hash table holding all the loaded partial DIEs
635      with partial_die->offset.SECT_OFF as hash.  */
636   htab_t partial_dies;
637
638   /* Storage for things with the same lifetime as this read-in compilation
639      unit, including partial DIEs.  */
640   struct obstack comp_unit_obstack;
641
642   /* When multiple dwarf2_cu structures are living in memory, this field
643      chains them all together, so that they can be released efficiently.
644      We will probably also want a generation counter so that most-recently-used
645      compilation units are cached...  */
646   struct dwarf2_per_cu_data *read_in_chain;
647
648   /* Backlink to our per_cu entry.  */
649   struct dwarf2_per_cu_data *per_cu;
650
651   /* How many compilation units ago was this CU last referenced?  */
652   int last_used;
653
654   /* A hash table of DIE cu_offset for following references with
655      die_info->offset.sect_off as hash.  */
656   htab_t die_hash;
657
658   /* Full DIEs if read in.  */
659   struct die_info *dies;
660
661   /* A set of pointers to dwarf2_per_cu_data objects for compilation
662      units referenced by this one.  Only set during full symbol processing;
663      partial symbol tables do not have dependencies.  */
664   htab_t dependencies;
665
666   /* Header data from the line table, during full symbol processing.  */
667   struct line_header *line_header;
668   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
669      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
670      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
671      to the line header as long as this DIE is being processed.  See
672      process_die_scope.  */
673   die_info *line_header_die_owner;
674
675   /* A list of methods which need to have physnames computed
676      after all type information has been read.  */
677   VEC (delayed_method_info) *method_list;
678
679   /* To be copied to symtab->call_site_htab.  */
680   htab_t call_site_htab;
681
682   /* Non-NULL if this CU came from a DWO file.
683      There is an invariant here that is important to remember:
684      Except for attributes copied from the top level DIE in the "main"
685      (or "stub") file in preparation for reading the DWO file
686      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
687      Either there isn't a DWO file (in which case this is NULL and the point
688      is moot), or there is and either we're not going to read it (in which
689      case this is NULL) or there is and we are reading it (in which case this
690      is non-NULL).  */
691   struct dwo_unit *dwo_unit;
692
693   /* The DW_AT_addr_base attribute if present, zero otherwise
694      (zero is a valid value though).
695      Note this value comes from the Fission stub CU/TU's DIE.  */
696   ULONGEST addr_base;
697
698   /* The DW_AT_ranges_base attribute if present, zero otherwise
699      (zero is a valid value though).
700      Note this value comes from the Fission stub CU/TU's DIE.
701      Also note that the value is zero in the non-DWO case so this value can
702      be used without needing to know whether DWO files are in use or not.
703      N.B. This does not apply to DW_AT_ranges appearing in
704      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
705      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
706      DW_AT_ranges_base *would* have to be applied, and we'd have to care
707      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
708   ULONGEST ranges_base;
709
710   /* Mark used when releasing cached dies.  */
711   unsigned int mark : 1;
712
713   /* This CU references .debug_loc.  See the symtab->locations_valid field.
714      This test is imperfect as there may exist optimized debug code not using
715      any location list and still facing inlining issues if handled as
716      unoptimized code.  For a future better test see GCC PR other/32998.  */
717   unsigned int has_loclist : 1;
718
719   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
720      if all the producer_is_* fields are valid.  This information is cached
721      because profiling CU expansion showed excessive time spent in
722      producer_is_gxx_lt_4_6.  */
723   unsigned int checked_producer : 1;
724   unsigned int producer_is_gxx_lt_4_6 : 1;
725   unsigned int producer_is_gcc_lt_4_3 : 1;
726   unsigned int producer_is_icc_lt_14 : 1;
727
728   /* When set, the file that we're processing is known to have
729      debugging info for C++ namespaces.  GCC 3.3.x did not produce
730      this information, but later versions do.  */
731
732   unsigned int processing_has_namespace_info : 1;
733 };
734
735 /* Persistent data held for a compilation unit, even when not
736    processing it.  We put a pointer to this structure in the
737    read_symtab_private field of the psymtab.  */
738
739 struct dwarf2_per_cu_data
740 {
741   /* The start offset and length of this compilation unit.
742      NOTE: Unlike comp_unit_head.length, this length includes
743      initial_length_size.
744      If the DIE refers to a DWO file, this is always of the original die,
745      not the DWO file.  */
746   sect_offset sect_off;
747   unsigned int length;
748
749   /* DWARF standard version this data has been read from (such as 4 or 5).  */
750   short dwarf_version;
751
752   /* Flag indicating this compilation unit will be read in before
753      any of the current compilation units are processed.  */
754   unsigned int queued : 1;
755
756   /* This flag will be set when reading partial DIEs if we need to load
757      absolutely all DIEs for this compilation unit, instead of just the ones
758      we think are interesting.  It gets set if we look for a DIE in the
759      hash table and don't find it.  */
760   unsigned int load_all_dies : 1;
761
762   /* Non-zero if this CU is from .debug_types.
763      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
764      this is non-zero.  */
765   unsigned int is_debug_types : 1;
766
767   /* Non-zero if this CU is from the .dwz file.  */
768   unsigned int is_dwz : 1;
769
770   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
771      This flag is only valid if is_debug_types is true.
772      We can't read a CU directly from a DWO file: There are required
773      attributes in the stub.  */
774   unsigned int reading_dwo_directly : 1;
775
776   /* Non-zero if the TU has been read.
777      This is used to assist the "Stay in DWO Optimization" for Fission:
778      When reading a DWO, it's faster to read TUs from the DWO instead of
779      fetching them from random other DWOs (due to comdat folding).
780      If the TU has already been read, the optimization is unnecessary
781      (and unwise - we don't want to change where gdb thinks the TU lives
782      "midflight").
783      This flag is only valid if is_debug_types is true.  */
784   unsigned int tu_read : 1;
785
786   /* The section this CU/TU lives in.
787      If the DIE refers to a DWO file, this is always the original die,
788      not the DWO file.  */
789   struct dwarf2_section_info *section;
790
791   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
792      of the CU cache it gets reset to NULL again.  This is left as NULL for
793      dummy CUs (a CU header, but nothing else).  */
794   struct dwarf2_cu *cu;
795
796   /* The corresponding objfile.
797      Normally we can get the objfile from dwarf2_per_objfile.
798      However we can enter this file with just a "per_cu" handle.  */
799   struct objfile *objfile;
800
801   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
802      is active.  Otherwise, the 'psymtab' field is active.  */
803   union
804   {
805     /* The partial symbol table associated with this compilation unit,
806        or NULL for unread partial units.  */
807     struct partial_symtab *psymtab;
808
809     /* Data needed by the "quick" functions.  */
810     struct dwarf2_per_cu_quick_data *quick;
811   } v;
812
813   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
814      while reading psymtabs, used to compute the psymtab dependencies,
815      and then cleared.  Then it is filled in again while reading full
816      symbols, and only deleted when the objfile is destroyed.
817
818      This is also used to work around a difference between the way gold
819      generates .gdb_index version <=7 and the way gdb does.  Arguably this
820      is a gold bug.  For symbols coming from TUs, gold records in the index
821      the CU that includes the TU instead of the TU itself.  This breaks
822      dw2_lookup_symbol: It assumes that if the index says symbol X lives
823      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
824      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
825      we need to look in TU Z to find X.  Fortunately, this is akin to
826      DW_TAG_imported_unit, so we just use the same mechanism: For
827      .gdb_index version <=7 this also records the TUs that the CU referred
828      to.  Concurrently with this change gdb was modified to emit version 8
829      indices so we only pay a price for gold generated indices.
830      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
831   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
832 };
833
834 /* Entry in the signatured_types hash table.  */
835
836 struct signatured_type
837 {
838   /* The "per_cu" object of this type.
839      This struct is used iff per_cu.is_debug_types.
840      N.B.: This is the first member so that it's easy to convert pointers
841      between them.  */
842   struct dwarf2_per_cu_data per_cu;
843
844   /* The type's signature.  */
845   ULONGEST signature;
846
847   /* Offset in the TU of the type's DIE, as read from the TU header.
848      If this TU is a DWO stub and the definition lives in a DWO file
849      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
850   cu_offset type_offset_in_tu;
851
852   /* Offset in the section of the type's DIE.
853      If the definition lives in a DWO file, this is the offset in the
854      .debug_types.dwo section.
855      The value is zero until the actual value is known.
856      Zero is otherwise not a valid section offset.  */
857   sect_offset type_offset_in_section;
858
859   /* Type units are grouped by their DW_AT_stmt_list entry so that they
860      can share them.  This points to the containing symtab.  */
861   struct type_unit_group *type_unit_group;
862
863   /* The type.
864      The first time we encounter this type we fully read it in and install it
865      in the symbol tables.  Subsequent times we only need the type.  */
866   struct type *type;
867
868   /* Containing DWO unit.
869      This field is valid iff per_cu.reading_dwo_directly.  */
870   struct dwo_unit *dwo_unit;
871 };
872
873 typedef struct signatured_type *sig_type_ptr;
874 DEF_VEC_P (sig_type_ptr);
875
876 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
877    This includes type_unit_group and quick_file_names.  */
878
879 struct stmt_list_hash
880 {
881   /* The DWO unit this table is from or NULL if there is none.  */
882   struct dwo_unit *dwo_unit;
883
884   /* Offset in .debug_line or .debug_line.dwo.  */
885   sect_offset line_sect_off;
886 };
887
888 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
889    an object of this type.  */
890
891 struct type_unit_group
892 {
893   /* dwarf2read.c's main "handle" on a TU symtab.
894      To simplify things we create an artificial CU that "includes" all the
895      type units using this stmt_list so that the rest of the code still has
896      a "per_cu" handle on the symtab.
897      This PER_CU is recognized by having no section.  */
898 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
899   struct dwarf2_per_cu_data per_cu;
900
901   /* The TUs that share this DW_AT_stmt_list entry.
902      This is added to while parsing type units to build partial symtabs,
903      and is deleted afterwards and not used again.  */
904   VEC (sig_type_ptr) *tus;
905
906   /* The compunit symtab.
907      Type units in a group needn't all be defined in the same source file,
908      so we create an essentially anonymous symtab as the compunit symtab.  */
909   struct compunit_symtab *compunit_symtab;
910
911   /* The data used to construct the hash key.  */
912   struct stmt_list_hash hash;
913
914   /* The number of symtabs from the line header.
915      The value here must match line_header.num_file_names.  */
916   unsigned int num_symtabs;
917
918   /* The symbol tables for this TU (obtained from the files listed in
919      DW_AT_stmt_list).
920      WARNING: The order of entries here must match the order of entries
921      in the line header.  After the first TU using this type_unit_group, the
922      line header for the subsequent TUs is recreated from this.  This is done
923      because we need to use the same symtabs for each TU using the same
924      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
925      there's no guarantee the line header doesn't have duplicate entries.  */
926   struct symtab **symtabs;
927 };
928
929 /* These sections are what may appear in a (real or virtual) DWO file.  */
930
931 struct dwo_sections
932 {
933   struct dwarf2_section_info abbrev;
934   struct dwarf2_section_info line;
935   struct dwarf2_section_info loc;
936   struct dwarf2_section_info loclists;
937   struct dwarf2_section_info macinfo;
938   struct dwarf2_section_info macro;
939   struct dwarf2_section_info str;
940   struct dwarf2_section_info str_offsets;
941   /* In the case of a virtual DWO file, these two are unused.  */
942   struct dwarf2_section_info info;
943   VEC (dwarf2_section_info_def) *types;
944 };
945
946 /* CUs/TUs in DWP/DWO files.  */
947
948 struct dwo_unit
949 {
950   /* Backlink to the containing struct dwo_file.  */
951   struct dwo_file *dwo_file;
952
953   /* The "id" that distinguishes this CU/TU.
954      .debug_info calls this "dwo_id", .debug_types calls this "signature".
955      Since signatures came first, we stick with it for consistency.  */
956   ULONGEST signature;
957
958   /* The section this CU/TU lives in, in the DWO file.  */
959   struct dwarf2_section_info *section;
960
961   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
962   sect_offset sect_off;
963   unsigned int length;
964
965   /* For types, offset in the type's DIE of the type defined by this TU.  */
966   cu_offset type_offset_in_tu;
967 };
968
969 /* include/dwarf2.h defines the DWP section codes.
970    It defines a max value but it doesn't define a min value, which we
971    use for error checking, so provide one.  */
972
973 enum dwp_v2_section_ids
974 {
975   DW_SECT_MIN = 1
976 };
977
978 /* Data for one DWO file.
979
980    This includes virtual DWO files (a virtual DWO file is a DWO file as it
981    appears in a DWP file).  DWP files don't really have DWO files per se -
982    comdat folding of types "loses" the DWO file they came from, and from
983    a high level view DWP files appear to contain a mass of random types.
984    However, to maintain consistency with the non-DWP case we pretend DWP
985    files contain virtual DWO files, and we assign each TU with one virtual
986    DWO file (generally based on the line and abbrev section offsets -
987    a heuristic that seems to work in practice).  */
988
989 struct dwo_file
990 {
991   /* The DW_AT_GNU_dwo_name attribute.
992      For virtual DWO files the name is constructed from the section offsets
993      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
994      from related CU+TUs.  */
995   const char *dwo_name;
996
997   /* The DW_AT_comp_dir attribute.  */
998   const char *comp_dir;
999
1000   /* The bfd, when the file is open.  Otherwise this is NULL.
1001      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1002   bfd *dbfd;
1003
1004   /* The sections that make up this DWO file.
1005      Remember that for virtual DWO files in DWP V2, these are virtual
1006      sections (for lack of a better name).  */
1007   struct dwo_sections sections;
1008
1009   /* The CUs in the file.
1010      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1011      an extension to handle LLVM's Link Time Optimization output (where
1012      multiple source files may be compiled into a single object/dwo pair). */
1013   htab_t cus;
1014
1015   /* Table of TUs in the file.
1016      Each element is a struct dwo_unit.  */
1017   htab_t tus;
1018 };
1019
1020 /* These sections are what may appear in a DWP file.  */
1021
1022 struct dwp_sections
1023 {
1024   /* These are used by both DWP version 1 and 2.  */
1025   struct dwarf2_section_info str;
1026   struct dwarf2_section_info cu_index;
1027   struct dwarf2_section_info tu_index;
1028
1029   /* These are only used by DWP version 2 files.
1030      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1031      sections are referenced by section number, and are not recorded here.
1032      In DWP version 2 there is at most one copy of all these sections, each
1033      section being (effectively) comprised of the concatenation of all of the
1034      individual sections that exist in the version 1 format.
1035      To keep the code simple we treat each of these concatenated pieces as a
1036      section itself (a virtual section?).  */
1037   struct dwarf2_section_info abbrev;
1038   struct dwarf2_section_info info;
1039   struct dwarf2_section_info line;
1040   struct dwarf2_section_info loc;
1041   struct dwarf2_section_info macinfo;
1042   struct dwarf2_section_info macro;
1043   struct dwarf2_section_info str_offsets;
1044   struct dwarf2_section_info types;
1045 };
1046
1047 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1048    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1049
1050 struct virtual_v1_dwo_sections
1051 {
1052   struct dwarf2_section_info abbrev;
1053   struct dwarf2_section_info line;
1054   struct dwarf2_section_info loc;
1055   struct dwarf2_section_info macinfo;
1056   struct dwarf2_section_info macro;
1057   struct dwarf2_section_info str_offsets;
1058   /* Each DWP hash table entry records one CU or one TU.
1059      That is recorded here, and copied to dwo_unit.section.  */
1060   struct dwarf2_section_info info_or_types;
1061 };
1062
1063 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1064    In version 2, the sections of the DWO files are concatenated together
1065    and stored in one section of that name.  Thus each ELF section contains
1066    several "virtual" sections.  */
1067
1068 struct virtual_v2_dwo_sections
1069 {
1070   bfd_size_type abbrev_offset;
1071   bfd_size_type abbrev_size;
1072
1073   bfd_size_type line_offset;
1074   bfd_size_type line_size;
1075
1076   bfd_size_type loc_offset;
1077   bfd_size_type loc_size;
1078
1079   bfd_size_type macinfo_offset;
1080   bfd_size_type macinfo_size;
1081
1082   bfd_size_type macro_offset;
1083   bfd_size_type macro_size;
1084
1085   bfd_size_type str_offsets_offset;
1086   bfd_size_type str_offsets_size;
1087
1088   /* Each DWP hash table entry records one CU or one TU.
1089      That is recorded here, and copied to dwo_unit.section.  */
1090   bfd_size_type info_or_types_offset;
1091   bfd_size_type info_or_types_size;
1092 };
1093
1094 /* Contents of DWP hash tables.  */
1095
1096 struct dwp_hash_table
1097 {
1098   uint32_t version, nr_columns;
1099   uint32_t nr_units, nr_slots;
1100   const gdb_byte *hash_table, *unit_table;
1101   union
1102   {
1103     struct
1104     {
1105       const gdb_byte *indices;
1106     } v1;
1107     struct
1108     {
1109       /* This is indexed by column number and gives the id of the section
1110          in that column.  */
1111 #define MAX_NR_V2_DWO_SECTIONS \
1112   (1 /* .debug_info or .debug_types */ \
1113    + 1 /* .debug_abbrev */ \
1114    + 1 /* .debug_line */ \
1115    + 1 /* .debug_loc */ \
1116    + 1 /* .debug_str_offsets */ \
1117    + 1 /* .debug_macro or .debug_macinfo */)
1118       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1119       const gdb_byte *offsets;
1120       const gdb_byte *sizes;
1121     } v2;
1122   } section_pool;
1123 };
1124
1125 /* Data for one DWP file.  */
1126
1127 struct dwp_file
1128 {
1129   /* Name of the file.  */
1130   const char *name;
1131
1132   /* File format version.  */
1133   int version;
1134
1135   /* The bfd.  */
1136   bfd *dbfd;
1137
1138   /* Section info for this file.  */
1139   struct dwp_sections sections;
1140
1141   /* Table of CUs in the file.  */
1142   const struct dwp_hash_table *cus;
1143
1144   /* Table of TUs in the file.  */
1145   const struct dwp_hash_table *tus;
1146
1147   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1148   htab_t loaded_cus;
1149   htab_t loaded_tus;
1150
1151   /* Table to map ELF section numbers to their sections.
1152      This is only needed for the DWP V1 file format.  */
1153   unsigned int num_sections;
1154   asection **elf_sections;
1155 };
1156
1157 /* This represents a '.dwz' file.  */
1158
1159 struct dwz_file
1160 {
1161   /* A dwz file can only contain a few sections.  */
1162   struct dwarf2_section_info abbrev;
1163   struct dwarf2_section_info info;
1164   struct dwarf2_section_info str;
1165   struct dwarf2_section_info line;
1166   struct dwarf2_section_info macro;
1167   struct dwarf2_section_info gdb_index;
1168   struct dwarf2_section_info debug_names;
1169
1170   /* The dwz's BFD.  */
1171   bfd *dwz_bfd;
1172 };
1173
1174 /* Struct used to pass misc. parameters to read_die_and_children, et
1175    al.  which are used for both .debug_info and .debug_types dies.
1176    All parameters here are unchanging for the life of the call.  This
1177    struct exists to abstract away the constant parameters of die reading.  */
1178
1179 struct die_reader_specs
1180 {
1181   /* The bfd of die_section.  */
1182   bfd* abfd;
1183
1184   /* The CU of the DIE we are parsing.  */
1185   struct dwarf2_cu *cu;
1186
1187   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1188   struct dwo_file *dwo_file;
1189
1190   /* The section the die comes from.
1191      This is either .debug_info or .debug_types, or the .dwo variants.  */
1192   struct dwarf2_section_info *die_section;
1193
1194   /* die_section->buffer.  */
1195   const gdb_byte *buffer;
1196
1197   /* The end of the buffer.  */
1198   const gdb_byte *buffer_end;
1199
1200   /* The value of the DW_AT_comp_dir attribute.  */
1201   const char *comp_dir;
1202 };
1203
1204 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1205 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1206                                       const gdb_byte *info_ptr,
1207                                       struct die_info *comp_unit_die,
1208                                       int has_children,
1209                                       void *data);
1210
1211 /* A 1-based directory index.  This is a strong typedef to prevent
1212    accidentally using a directory index as a 0-based index into an
1213    array/vector.  */
1214 enum class dir_index : unsigned int {};
1215
1216 /* Likewise, a 1-based file name index.  */
1217 enum class file_name_index : unsigned int {};
1218
1219 struct file_entry
1220 {
1221   file_entry () = default;
1222
1223   file_entry (const char *name_, dir_index d_index_,
1224               unsigned int mod_time_, unsigned int length_)
1225     : name (name_),
1226       d_index (d_index_),
1227       mod_time (mod_time_),
1228       length (length_)
1229   {}
1230
1231   /* Return the include directory at D_INDEX stored in LH.  Returns
1232      NULL if D_INDEX is out of bounds.  */
1233   const char *include_dir (const line_header *lh) const;
1234
1235   /* The file name.  Note this is an observing pointer.  The memory is
1236      owned by debug_line_buffer.  */
1237   const char *name {};
1238
1239   /* The directory index (1-based).  */
1240   dir_index d_index {};
1241
1242   unsigned int mod_time {};
1243
1244   unsigned int length {};
1245
1246   /* True if referenced by the Line Number Program.  */
1247   bool included_p {};
1248
1249   /* The associated symbol table, if any.  */
1250   struct symtab *symtab {};
1251 };
1252
1253 /* The line number information for a compilation unit (found in the
1254    .debug_line section) begins with a "statement program header",
1255    which contains the following information.  */
1256 struct line_header
1257 {
1258   line_header ()
1259     : offset_in_dwz {}
1260   {}
1261
1262   /* Add an entry to the include directory table.  */
1263   void add_include_dir (const char *include_dir);
1264
1265   /* Add an entry to the file name table.  */
1266   void add_file_name (const char *name, dir_index d_index,
1267                       unsigned int mod_time, unsigned int length);
1268
1269   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1270      is out of bounds.  */
1271   const char *include_dir_at (dir_index index) const
1272   {
1273     /* Convert directory index number (1-based) to vector index
1274        (0-based).  */
1275     size_t vec_index = to_underlying (index) - 1;
1276
1277     if (vec_index >= include_dirs.size ())
1278       return NULL;
1279     return include_dirs[vec_index];
1280   }
1281
1282   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1283      is out of bounds.  */
1284   file_entry *file_name_at (file_name_index index)
1285   {
1286     /* Convert file name index number (1-based) to vector index
1287        (0-based).  */
1288     size_t vec_index = to_underlying (index) - 1;
1289
1290     if (vec_index >= file_names.size ())
1291       return NULL;
1292     return &file_names[vec_index];
1293   }
1294
1295   /* Const version of the above.  */
1296   const file_entry *file_name_at (unsigned int index) const
1297   {
1298     if (index >= file_names.size ())
1299       return NULL;
1300     return &file_names[index];
1301   }
1302
1303   /* Offset of line number information in .debug_line section.  */
1304   sect_offset sect_off {};
1305
1306   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1307   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1308
1309   unsigned int total_length {};
1310   unsigned short version {};
1311   unsigned int header_length {};
1312   unsigned char minimum_instruction_length {};
1313   unsigned char maximum_ops_per_instruction {};
1314   unsigned char default_is_stmt {};
1315   int line_base {};
1316   unsigned char line_range {};
1317   unsigned char opcode_base {};
1318
1319   /* standard_opcode_lengths[i] is the number of operands for the
1320      standard opcode whose value is i.  This means that
1321      standard_opcode_lengths[0] is unused, and the last meaningful
1322      element is standard_opcode_lengths[opcode_base - 1].  */
1323   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1324
1325   /* The include_directories table.  Note these are observing
1326      pointers.  The memory is owned by debug_line_buffer.  */
1327   std::vector<const char *> include_dirs;
1328
1329   /* The file_names table.  */
1330   std::vector<file_entry> file_names;
1331
1332   /* The start and end of the statement program following this
1333      header.  These point into dwarf2_per_objfile->line_buffer.  */
1334   const gdb_byte *statement_program_start {}, *statement_program_end {};
1335 };
1336
1337 typedef std::unique_ptr<line_header> line_header_up;
1338
1339 const char *
1340 file_entry::include_dir (const line_header *lh) const
1341 {
1342   return lh->include_dir_at (d_index);
1343 }
1344
1345 /* When we construct a partial symbol table entry we only
1346    need this much information.  */
1347 struct partial_die_info
1348   {
1349     /* Offset of this DIE.  */
1350     sect_offset sect_off;
1351
1352     /* DWARF-2 tag for this DIE.  */
1353     ENUM_BITFIELD(dwarf_tag) tag : 16;
1354
1355     /* Assorted flags describing the data found in this DIE.  */
1356     unsigned int has_children : 1;
1357     unsigned int is_external : 1;
1358     unsigned int is_declaration : 1;
1359     unsigned int has_type : 1;
1360     unsigned int has_specification : 1;
1361     unsigned int has_pc_info : 1;
1362     unsigned int may_be_inlined : 1;
1363
1364     /* This DIE has been marked DW_AT_main_subprogram.  */
1365     unsigned int main_subprogram : 1;
1366
1367     /* Flag set if the SCOPE field of this structure has been
1368        computed.  */
1369     unsigned int scope_set : 1;
1370
1371     /* Flag set if the DIE has a byte_size attribute.  */
1372     unsigned int has_byte_size : 1;
1373
1374     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1375     unsigned int has_const_value : 1;
1376
1377     /* Flag set if any of the DIE's children are template arguments.  */
1378     unsigned int has_template_arguments : 1;
1379
1380     /* Flag set if fixup_partial_die has been called on this die.  */
1381     unsigned int fixup_called : 1;
1382
1383     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1384     unsigned int is_dwz : 1;
1385
1386     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1387     unsigned int spec_is_dwz : 1;
1388
1389     /* The name of this DIE.  Normally the value of DW_AT_name, but
1390        sometimes a default name for unnamed DIEs.  */
1391     const char *name;
1392
1393     /* The linkage name, if present.  */
1394     const char *linkage_name;
1395
1396     /* The scope to prepend to our children.  This is generally
1397        allocated on the comp_unit_obstack, so will disappear
1398        when this compilation unit leaves the cache.  */
1399     const char *scope;
1400
1401     /* Some data associated with the partial DIE.  The tag determines
1402        which field is live.  */
1403     union
1404     {
1405       /* The location description associated with this DIE, if any.  */
1406       struct dwarf_block *locdesc;
1407       /* The offset of an import, for DW_TAG_imported_unit.  */
1408       sect_offset sect_off;
1409     } d;
1410
1411     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1412     CORE_ADDR lowpc;
1413     CORE_ADDR highpc;
1414
1415     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1416        DW_AT_sibling, if any.  */
1417     /* NOTE: This member isn't strictly necessary, read_partial_die could
1418        return DW_AT_sibling values to its caller load_partial_dies.  */
1419     const gdb_byte *sibling;
1420
1421     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1422        DW_AT_specification (or DW_AT_abstract_origin or
1423        DW_AT_extension).  */
1424     sect_offset spec_offset;
1425
1426     /* Pointers to this DIE's parent, first child, and next sibling,
1427        if any.  */
1428     struct partial_die_info *die_parent, *die_child, *die_sibling;
1429   };
1430
1431 /* This data structure holds the information of an abbrev.  */
1432 struct abbrev_info
1433   {
1434     unsigned int number;        /* number identifying abbrev */
1435     enum dwarf_tag tag;         /* dwarf tag */
1436     unsigned short has_children;                /* boolean */
1437     unsigned short num_attrs;   /* number of attributes */
1438     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1439     struct abbrev_info *next;   /* next in chain */
1440   };
1441
1442 struct attr_abbrev
1443   {
1444     ENUM_BITFIELD(dwarf_attribute) name : 16;
1445     ENUM_BITFIELD(dwarf_form) form : 16;
1446
1447     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1448     LONGEST implicit_const;
1449   };
1450
1451 /* Size of abbrev_table.abbrev_hash_table.  */
1452 #define ABBREV_HASH_SIZE 121
1453
1454 /* Top level data structure to contain an abbreviation table.  */
1455
1456 struct abbrev_table
1457 {
1458   /* Where the abbrev table came from.
1459      This is used as a sanity check when the table is used.  */
1460   sect_offset sect_off;
1461
1462   /* Storage for the abbrev table.  */
1463   struct obstack abbrev_obstack;
1464
1465   /* Hash table of abbrevs.
1466      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1467      It could be statically allocated, but the previous code didn't so we
1468      don't either.  */
1469   struct abbrev_info **abbrevs;
1470 };
1471
1472 /* Attributes have a name and a value.  */
1473 struct attribute
1474   {
1475     ENUM_BITFIELD(dwarf_attribute) name : 16;
1476     ENUM_BITFIELD(dwarf_form) form : 15;
1477
1478     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1479        field should be in u.str (existing only for DW_STRING) but it is kept
1480        here for better struct attribute alignment.  */
1481     unsigned int string_is_canonical : 1;
1482
1483     union
1484       {
1485         const char *str;
1486         struct dwarf_block *blk;
1487         ULONGEST unsnd;
1488         LONGEST snd;
1489         CORE_ADDR addr;
1490         ULONGEST signature;
1491       }
1492     u;
1493   };
1494
1495 /* This data structure holds a complete die structure.  */
1496 struct die_info
1497   {
1498     /* DWARF-2 tag for this DIE.  */
1499     ENUM_BITFIELD(dwarf_tag) tag : 16;
1500
1501     /* Number of attributes */
1502     unsigned char num_attrs;
1503
1504     /* True if we're presently building the full type name for the
1505        type derived from this DIE.  */
1506     unsigned char building_fullname : 1;
1507
1508     /* True if this die is in process.  PR 16581.  */
1509     unsigned char in_process : 1;
1510
1511     /* Abbrev number */
1512     unsigned int abbrev;
1513
1514     /* Offset in .debug_info or .debug_types section.  */
1515     sect_offset sect_off;
1516
1517     /* The dies in a compilation unit form an n-ary tree.  PARENT
1518        points to this die's parent; CHILD points to the first child of
1519        this node; and all the children of a given node are chained
1520        together via their SIBLING fields.  */
1521     struct die_info *child;     /* Its first child, if any.  */
1522     struct die_info *sibling;   /* Its next sibling, if any.  */
1523     struct die_info *parent;    /* Its parent, if any.  */
1524
1525     /* An array of attributes, with NUM_ATTRS elements.  There may be
1526        zero, but it's not common and zero-sized arrays are not
1527        sufficiently portable C.  */
1528     struct attribute attrs[1];
1529   };
1530
1531 /* Get at parts of an attribute structure.  */
1532
1533 #define DW_STRING(attr)    ((attr)->u.str)
1534 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1535 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1536 #define DW_BLOCK(attr)     ((attr)->u.blk)
1537 #define DW_SND(attr)       ((attr)->u.snd)
1538 #define DW_ADDR(attr)      ((attr)->u.addr)
1539 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1540
1541 /* Blocks are a bunch of untyped bytes.  */
1542 struct dwarf_block
1543   {
1544     size_t size;
1545
1546     /* Valid only if SIZE is not zero.  */
1547     const gdb_byte *data;
1548   };
1549
1550 #ifndef ATTR_ALLOC_CHUNK
1551 #define ATTR_ALLOC_CHUNK 4
1552 #endif
1553
1554 /* Allocate fields for structs, unions and enums in this size.  */
1555 #ifndef DW_FIELD_ALLOC_CHUNK
1556 #define DW_FIELD_ALLOC_CHUNK 4
1557 #endif
1558
1559 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1560    but this would require a corresponding change in unpack_field_as_long
1561    and friends.  */
1562 static int bits_per_byte = 8;
1563
1564 struct nextfield
1565 {
1566   struct nextfield *next;
1567   int accessibility;
1568   int virtuality;
1569   struct field field;
1570 };
1571
1572 struct nextfnfield
1573 {
1574   struct nextfnfield *next;
1575   struct fn_field fnfield;
1576 };
1577
1578 struct fnfieldlist
1579 {
1580   const char *name;
1581   int length;
1582   struct nextfnfield *head;
1583 };
1584
1585 struct decl_field_list
1586 {
1587   struct decl_field field;
1588   struct decl_field_list *next;
1589 };
1590
1591 /* The routines that read and process dies for a C struct or C++ class
1592    pass lists of data member fields and lists of member function fields
1593    in an instance of a field_info structure, as defined below.  */
1594 struct field_info
1595   {
1596     /* List of data member and baseclasses fields.  */
1597     struct nextfield *fields, *baseclasses;
1598
1599     /* Number of fields (including baseclasses).  */
1600     int nfields;
1601
1602     /* Number of baseclasses.  */
1603     int nbaseclasses;
1604
1605     /* Set if the accesibility of one of the fields is not public.  */
1606     int non_public_fields;
1607
1608     /* Member function fieldlist array, contains name of possibly overloaded
1609        member function, number of overloaded member functions and a pointer
1610        to the head of the member function field chain.  */
1611     struct fnfieldlist *fnfieldlists;
1612
1613     /* Number of entries in the fnfieldlists array.  */
1614     int nfnfields;
1615
1616     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1617        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1618     struct decl_field_list *typedef_field_list;
1619     unsigned typedef_field_list_count;
1620
1621     /* Nested types defined by this class and the number of elements in this
1622        list.  */
1623     struct decl_field_list *nested_types_list;
1624     unsigned nested_types_list_count;
1625   };
1626
1627 /* One item on the queue of compilation units to read in full symbols
1628    for.  */
1629 struct dwarf2_queue_item
1630 {
1631   struct dwarf2_per_cu_data *per_cu;
1632   enum language pretend_language;
1633   struct dwarf2_queue_item *next;
1634 };
1635
1636 /* The current queue.  */
1637 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1638
1639 /* Loaded secondary compilation units are kept in memory until they
1640    have not been referenced for the processing of this many
1641    compilation units.  Set this to zero to disable caching.  Cache
1642    sizes of up to at least twenty will improve startup time for
1643    typical inter-CU-reference binaries, at an obvious memory cost.  */
1644 static int dwarf_max_cache_age = 5;
1645 static void
1646 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1647                           struct cmd_list_element *c, const char *value)
1648 {
1649   fprintf_filtered (file, _("The upper bound on the age of cached "
1650                             "DWARF compilation units is %s.\n"),
1651                     value);
1652 }
1653 \f
1654 /* local function prototypes */
1655
1656 static const char *get_section_name (const struct dwarf2_section_info *);
1657
1658 static const char *get_section_file_name (const struct dwarf2_section_info *);
1659
1660 static void dwarf2_find_base_address (struct die_info *die,
1661                                       struct dwarf2_cu *cu);
1662
1663 static struct partial_symtab *create_partial_symtab
1664   (struct dwarf2_per_cu_data *per_cu, const char *name);
1665
1666 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1667                                         const gdb_byte *info_ptr,
1668                                         struct die_info *type_unit_die,
1669                                         int has_children, void *data);
1670
1671 static void dwarf2_build_psymtabs_hard (struct objfile *);
1672
1673 static void scan_partial_symbols (struct partial_die_info *,
1674                                   CORE_ADDR *, CORE_ADDR *,
1675                                   int, struct dwarf2_cu *);
1676
1677 static void add_partial_symbol (struct partial_die_info *,
1678                                 struct dwarf2_cu *);
1679
1680 static void add_partial_namespace (struct partial_die_info *pdi,
1681                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1682                                    int set_addrmap, struct dwarf2_cu *cu);
1683
1684 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1685                                 CORE_ADDR *highpc, int set_addrmap,
1686                                 struct dwarf2_cu *cu);
1687
1688 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1689                                      struct dwarf2_cu *cu);
1690
1691 static void add_partial_subprogram (struct partial_die_info *pdi,
1692                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1693                                     int need_pc, struct dwarf2_cu *cu);
1694
1695 static void dwarf2_read_symtab (struct partial_symtab *,
1696                                 struct objfile *);
1697
1698 static void psymtab_to_symtab_1 (struct partial_symtab *);
1699
1700 static struct abbrev_info *abbrev_table_lookup_abbrev
1701   (const struct abbrev_table *, unsigned int);
1702
1703 static struct abbrev_table *abbrev_table_read_table
1704   (struct dwarf2_section_info *, sect_offset);
1705
1706 static void abbrev_table_free (struct abbrev_table *);
1707
1708 static void abbrev_table_free_cleanup (void *);
1709
1710 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1711                                  struct dwarf2_section_info *);
1712
1713 static void dwarf2_free_abbrev_table (void *);
1714
1715 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1716
1717 static struct partial_die_info *load_partial_dies
1718   (const struct die_reader_specs *, const gdb_byte *, int);
1719
1720 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1721                                          struct partial_die_info *,
1722                                          struct abbrev_info *,
1723                                          unsigned int,
1724                                          const gdb_byte *);
1725
1726 static struct partial_die_info *find_partial_die (sect_offset, int,
1727                                                   struct dwarf2_cu *);
1728
1729 static void fixup_partial_die (struct partial_die_info *,
1730                                struct dwarf2_cu *);
1731
1732 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1733                                        struct attribute *, struct attr_abbrev *,
1734                                        const gdb_byte *);
1735
1736 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1737
1738 static int read_1_signed_byte (bfd *, const gdb_byte *);
1739
1740 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1741
1742 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1743
1744 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1745
1746 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1747                                unsigned int *);
1748
1749 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1750
1751 static LONGEST read_checked_initial_length_and_offset
1752   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1753    unsigned int *, unsigned int *);
1754
1755 static LONGEST read_offset (bfd *, const gdb_byte *,
1756                             const struct comp_unit_head *,
1757                             unsigned int *);
1758
1759 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1760
1761 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1762                                        sect_offset);
1763
1764 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1765
1766 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1767
1768 static const char *read_indirect_string (bfd *, const gdb_byte *,
1769                                          const struct comp_unit_head *,
1770                                          unsigned int *);
1771
1772 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1773                                               const struct comp_unit_head *,
1774                                               unsigned int *);
1775
1776 static const char *read_indirect_string_at_offset (bfd *abfd,
1777                                                    LONGEST str_offset);
1778
1779 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1780
1781 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1782
1783 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1784                                               const gdb_byte *,
1785                                               unsigned int *);
1786
1787 static const char *read_str_index (const struct die_reader_specs *reader,
1788                                    ULONGEST str_index);
1789
1790 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1791
1792 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1793                                       struct dwarf2_cu *);
1794
1795 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1796                                                 unsigned int);
1797
1798 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1799                                        struct dwarf2_cu *cu);
1800
1801 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1802                                struct dwarf2_cu *cu);
1803
1804 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1805
1806 static struct die_info *die_specification (struct die_info *die,
1807                                            struct dwarf2_cu **);
1808
1809 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1810                                                 struct dwarf2_cu *cu);
1811
1812 static void dwarf_decode_lines (struct line_header *, const char *,
1813                                 struct dwarf2_cu *, struct partial_symtab *,
1814                                 CORE_ADDR, int decode_mapping);
1815
1816 static void dwarf2_start_subfile (const char *, const char *);
1817
1818 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1819                                                     const char *, const char *,
1820                                                     CORE_ADDR);
1821
1822 static struct symbol *new_symbol (struct die_info *, struct type *,
1823                                   struct dwarf2_cu *);
1824
1825 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1826                                        struct dwarf2_cu *, struct symbol *);
1827
1828 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1829                                 struct dwarf2_cu *);
1830
1831 static void dwarf2_const_value_attr (const struct attribute *attr,
1832                                      struct type *type,
1833                                      const char *name,
1834                                      struct obstack *obstack,
1835                                      struct dwarf2_cu *cu, LONGEST *value,
1836                                      const gdb_byte **bytes,
1837                                      struct dwarf2_locexpr_baton **baton);
1838
1839 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1840
1841 static int need_gnat_info (struct dwarf2_cu *);
1842
1843 static struct type *die_descriptive_type (struct die_info *,
1844                                           struct dwarf2_cu *);
1845
1846 static void set_descriptive_type (struct type *, struct die_info *,
1847                                   struct dwarf2_cu *);
1848
1849 static struct type *die_containing_type (struct die_info *,
1850                                          struct dwarf2_cu *);
1851
1852 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1853                                      struct dwarf2_cu *);
1854
1855 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1856
1857 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1858
1859 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1860
1861 static char *typename_concat (struct obstack *obs, const char *prefix,
1862                               const char *suffix, int physname,
1863                               struct dwarf2_cu *cu);
1864
1865 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1866
1867 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1868
1869 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1870
1871 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1872
1873 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1874
1875 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1876
1877 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1878                                struct dwarf2_cu *, struct partial_symtab *);
1879
1880 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1881    values.  Keep the items ordered with increasing constraints compliance.  */
1882 enum pc_bounds_kind
1883 {
1884   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1885   PC_BOUNDS_NOT_PRESENT,
1886
1887   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1888      were present but they do not form a valid range of PC addresses.  */
1889   PC_BOUNDS_INVALID,
1890
1891   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1892   PC_BOUNDS_RANGES,
1893
1894   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1895   PC_BOUNDS_HIGH_LOW,
1896 };
1897
1898 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1899                                                  CORE_ADDR *, CORE_ADDR *,
1900                                                  struct dwarf2_cu *,
1901                                                  struct partial_symtab *);
1902
1903 static void get_scope_pc_bounds (struct die_info *,
1904                                  CORE_ADDR *, CORE_ADDR *,
1905                                  struct dwarf2_cu *);
1906
1907 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1908                                         CORE_ADDR, struct dwarf2_cu *);
1909
1910 static void dwarf2_add_field (struct field_info *, struct die_info *,
1911                               struct dwarf2_cu *);
1912
1913 static void dwarf2_attach_fields_to_type (struct field_info *,
1914                                           struct type *, struct dwarf2_cu *);
1915
1916 static void dwarf2_add_member_fn (struct field_info *,
1917                                   struct die_info *, struct type *,
1918                                   struct dwarf2_cu *);
1919
1920 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1921                                              struct type *,
1922                                              struct dwarf2_cu *);
1923
1924 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1925
1926 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1927
1928 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1929
1930 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1931
1932 static struct using_direct **using_directives (enum language);
1933
1934 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1935
1936 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1937
1938 static struct type *read_module_type (struct die_info *die,
1939                                       struct dwarf2_cu *cu);
1940
1941 static const char *namespace_name (struct die_info *die,
1942                                    int *is_anonymous, struct dwarf2_cu *);
1943
1944 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1945
1946 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1947
1948 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1949                                                        struct dwarf2_cu *);
1950
1951 static struct die_info *read_die_and_siblings_1
1952   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1953    struct die_info *);
1954
1955 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1956                                                const gdb_byte *info_ptr,
1957                                                const gdb_byte **new_info_ptr,
1958                                                struct die_info *parent);
1959
1960 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1961                                         struct die_info **, const gdb_byte *,
1962                                         int *, int);
1963
1964 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1965                                       struct die_info **, const gdb_byte *,
1966                                       int *);
1967
1968 static void process_die (struct die_info *, struct dwarf2_cu *);
1969
1970 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1971                                              struct obstack *);
1972
1973 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1974
1975 static const char *dwarf2_full_name (const char *name,
1976                                      struct die_info *die,
1977                                      struct dwarf2_cu *cu);
1978
1979 static const char *dwarf2_physname (const char *name, struct die_info *die,
1980                                     struct dwarf2_cu *cu);
1981
1982 static struct die_info *dwarf2_extension (struct die_info *die,
1983                                           struct dwarf2_cu **);
1984
1985 static const char *dwarf_tag_name (unsigned int);
1986
1987 static const char *dwarf_attr_name (unsigned int);
1988
1989 static const char *dwarf_form_name (unsigned int);
1990
1991 static const char *dwarf_bool_name (unsigned int);
1992
1993 static const char *dwarf_type_encoding_name (unsigned int);
1994
1995 static struct die_info *sibling_die (struct die_info *);
1996
1997 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1998
1999 static void dump_die_for_error (struct die_info *);
2000
2001 static void dump_die_1 (struct ui_file *, int level, int max_level,
2002                         struct die_info *);
2003
2004 /*static*/ void dump_die (struct die_info *, int max_level);
2005
2006 static void store_in_ref_table (struct die_info *,
2007                                 struct dwarf2_cu *);
2008
2009 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2010
2011 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2012
2013 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2014                                                const struct attribute *,
2015                                                struct dwarf2_cu **);
2016
2017 static struct die_info *follow_die_ref (struct die_info *,
2018                                         const struct attribute *,
2019                                         struct dwarf2_cu **);
2020
2021 static struct die_info *follow_die_sig (struct die_info *,
2022                                         const struct attribute *,
2023                                         struct dwarf2_cu **);
2024
2025 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2026                                          struct dwarf2_cu *);
2027
2028 static struct type *get_DW_AT_signature_type (struct die_info *,
2029                                               const struct attribute *,
2030                                               struct dwarf2_cu *);
2031
2032 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2033
2034 static void read_signatured_type (struct signatured_type *);
2035
2036 static int attr_to_dynamic_prop (const struct attribute *attr,
2037                                  struct die_info *die, struct dwarf2_cu *cu,
2038                                  struct dynamic_prop *prop);
2039
2040 /* memory allocation interface */
2041
2042 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2043
2044 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2045
2046 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2047
2048 static int attr_form_is_block (const struct attribute *);
2049
2050 static int attr_form_is_section_offset (const struct attribute *);
2051
2052 static int attr_form_is_constant (const struct attribute *);
2053
2054 static int attr_form_is_ref (const struct attribute *);
2055
2056 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2057                                    struct dwarf2_loclist_baton *baton,
2058                                    const struct attribute *attr);
2059
2060 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2061                                          struct symbol *sym,
2062                                          struct dwarf2_cu *cu,
2063                                          int is_block);
2064
2065 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2066                                      const gdb_byte *info_ptr,
2067                                      struct abbrev_info *abbrev);
2068
2069 static void free_stack_comp_unit (void *);
2070
2071 static hashval_t partial_die_hash (const void *item);
2072
2073 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2074
2075 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2076   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2077
2078 static void init_one_comp_unit (struct dwarf2_cu *cu,
2079                                 struct dwarf2_per_cu_data *per_cu);
2080
2081 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2082                                    struct die_info *comp_unit_die,
2083                                    enum language pretend_language);
2084
2085 static void free_heap_comp_unit (void *);
2086
2087 static void free_cached_comp_units (void *);
2088
2089 static void age_cached_comp_units (void);
2090
2091 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2092
2093 static struct type *set_die_type (struct die_info *, struct type *,
2094                                   struct dwarf2_cu *);
2095
2096 static void create_all_comp_units (struct objfile *);
2097
2098 static int create_all_type_units (struct objfile *);
2099
2100 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2101                                  enum language);
2102
2103 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2104                                     enum language);
2105
2106 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2107                                     enum language);
2108
2109 static void dwarf2_add_dependence (struct dwarf2_cu *,
2110                                    struct dwarf2_per_cu_data *);
2111
2112 static void dwarf2_mark (struct dwarf2_cu *);
2113
2114 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2115
2116 static struct type *get_die_type_at_offset (sect_offset,
2117                                             struct dwarf2_per_cu_data *);
2118
2119 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2120
2121 static void dwarf2_release_queue (void *dummy);
2122
2123 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2124                              enum language pretend_language);
2125
2126 static void process_queue (void);
2127
2128 /* The return type of find_file_and_directory.  Note, the enclosed
2129    string pointers are only valid while this object is valid.  */
2130
2131 struct file_and_directory
2132 {
2133   /* The filename.  This is never NULL.  */
2134   const char *name;
2135
2136   /* The compilation directory.  NULL if not known.  If we needed to
2137      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2138      points directly to the DW_AT_comp_dir string attribute owned by
2139      the obstack that owns the DIE.  */
2140   const char *comp_dir;
2141
2142   /* If we needed to build a new string for comp_dir, this is what
2143      owns the storage.  */
2144   std::string comp_dir_storage;
2145 };
2146
2147 static file_and_directory find_file_and_directory (struct die_info *die,
2148                                                    struct dwarf2_cu *cu);
2149
2150 static char *file_full_name (int file, struct line_header *lh,
2151                              const char *comp_dir);
2152
2153 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2154 enum class rcuh_kind { COMPILE, TYPE };
2155
2156 static const gdb_byte *read_and_check_comp_unit_head
2157   (struct comp_unit_head *header,
2158    struct dwarf2_section_info *section,
2159    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2160    rcuh_kind section_kind);
2161
2162 static void init_cutu_and_read_dies
2163   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2164    int use_existing_cu, int keep,
2165    die_reader_func_ftype *die_reader_func, void *data);
2166
2167 static void init_cutu_and_read_dies_simple
2168   (struct dwarf2_per_cu_data *this_cu,
2169    die_reader_func_ftype *die_reader_func, void *data);
2170
2171 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2172
2173 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2174
2175 static struct dwo_unit *lookup_dwo_unit_in_dwp
2176   (struct dwp_file *dwp_file, const char *comp_dir,
2177    ULONGEST signature, int is_debug_types);
2178
2179 static struct dwp_file *get_dwp_file (void);
2180
2181 static struct dwo_unit *lookup_dwo_comp_unit
2182   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2183
2184 static struct dwo_unit *lookup_dwo_type_unit
2185   (struct signatured_type *, const char *, const char *);
2186
2187 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2188
2189 static void free_dwo_file_cleanup (void *);
2190
2191 static void process_cu_includes (void);
2192
2193 static void check_producer (struct dwarf2_cu *cu);
2194
2195 static void free_line_header_voidp (void *arg);
2196 \f
2197 /* Various complaints about symbol reading that don't abort the process.  */
2198
2199 static void
2200 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2201 {
2202   complaint (&symfile_complaints,
2203              _("statement list doesn't fit in .debug_line section"));
2204 }
2205
2206 static void
2207 dwarf2_debug_line_missing_file_complaint (void)
2208 {
2209   complaint (&symfile_complaints,
2210              _(".debug_line section has line data without a file"));
2211 }
2212
2213 static void
2214 dwarf2_debug_line_missing_end_sequence_complaint (void)
2215 {
2216   complaint (&symfile_complaints,
2217              _(".debug_line section has line "
2218                "program sequence without an end"));
2219 }
2220
2221 static void
2222 dwarf2_complex_location_expr_complaint (void)
2223 {
2224   complaint (&symfile_complaints, _("location expression too complex"));
2225 }
2226
2227 static void
2228 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2229                                               int arg3)
2230 {
2231   complaint (&symfile_complaints,
2232              _("const value length mismatch for '%s', got %d, expected %d"),
2233              arg1, arg2, arg3);
2234 }
2235
2236 static void
2237 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2238 {
2239   complaint (&symfile_complaints,
2240              _("debug info runs off end of %s section"
2241                " [in module %s]"),
2242              get_section_name (section),
2243              get_section_file_name (section));
2244 }
2245
2246 static void
2247 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2248 {
2249   complaint (&symfile_complaints,
2250              _("macro debug info contains a "
2251                "malformed macro definition:\n`%s'"),
2252              arg1);
2253 }
2254
2255 static void
2256 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2257 {
2258   complaint (&symfile_complaints,
2259              _("invalid attribute class or form for '%s' in '%s'"),
2260              arg1, arg2);
2261 }
2262
2263 /* Hash function for line_header_hash.  */
2264
2265 static hashval_t
2266 line_header_hash (const struct line_header *ofs)
2267 {
2268   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2269 }
2270
2271 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2272
2273 static hashval_t
2274 line_header_hash_voidp (const void *item)
2275 {
2276   const struct line_header *ofs = (const struct line_header *) item;
2277
2278   return line_header_hash (ofs);
2279 }
2280
2281 /* Equality function for line_header_hash.  */
2282
2283 static int
2284 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2285 {
2286   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2287   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2288
2289   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2290           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2291 }
2292
2293 \f
2294
2295 /* Read the given attribute value as an address, taking the attribute's
2296    form into account.  */
2297
2298 static CORE_ADDR
2299 attr_value_as_address (struct attribute *attr)
2300 {
2301   CORE_ADDR addr;
2302
2303   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2304     {
2305       /* Aside from a few clearly defined exceptions, attributes that
2306          contain an address must always be in DW_FORM_addr form.
2307          Unfortunately, some compilers happen to be violating this
2308          requirement by encoding addresses using other forms, such
2309          as DW_FORM_data4 for example.  For those broken compilers,
2310          we try to do our best, without any guarantee of success,
2311          to interpret the address correctly.  It would also be nice
2312          to generate a complaint, but that would require us to maintain
2313          a list of legitimate cases where a non-address form is allowed,
2314          as well as update callers to pass in at least the CU's DWARF
2315          version.  This is more overhead than what we're willing to
2316          expand for a pretty rare case.  */
2317       addr = DW_UNSND (attr);
2318     }
2319   else
2320     addr = DW_ADDR (attr);
2321
2322   return addr;
2323 }
2324
2325 /* The suffix for an index file.  */
2326 #define INDEX4_SUFFIX ".gdb-index"
2327 #define INDEX5_SUFFIX ".debug_names"
2328 #define DEBUG_STR_SUFFIX ".debug_str"
2329
2330 /* See declaration.  */
2331
2332 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2333                                         const dwarf2_debug_sections *names)
2334   : objfile (objfile_)
2335 {
2336   if (names == NULL)
2337     names = &dwarf2_elf_names;
2338
2339   bfd *obfd = objfile->obfd;
2340
2341   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2342     locate_sections (obfd, sec, *names);
2343 }
2344
2345 dwarf2_per_objfile::~dwarf2_per_objfile ()
2346 {
2347   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2348   free_cached_comp_units ();
2349
2350   if (quick_file_names_table)
2351     htab_delete (quick_file_names_table);
2352
2353   if (line_header_hash)
2354     htab_delete (line_header_hash);
2355
2356   /* Everything else should be on the objfile obstack.  */
2357 }
2358
2359 /* See declaration.  */
2360
2361 void
2362 dwarf2_per_objfile::free_cached_comp_units ()
2363 {
2364   dwarf2_per_cu_data *per_cu = read_in_chain;
2365   dwarf2_per_cu_data **last_chain = &read_in_chain;
2366   while (per_cu != NULL)
2367     {
2368       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2369
2370       free_heap_comp_unit (per_cu->cu);
2371       *last_chain = next_cu;
2372       per_cu = next_cu;
2373     }
2374 }
2375
2376 /* Try to locate the sections we need for DWARF 2 debugging
2377    information and return true if we have enough to do something.
2378    NAMES points to the dwarf2 section names, or is NULL if the standard
2379    ELF names are used.  */
2380
2381 int
2382 dwarf2_has_info (struct objfile *objfile,
2383                  const struct dwarf2_debug_sections *names)
2384 {
2385   if (objfile->flags & OBJF_READNEVER)
2386     return 0;
2387
2388   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2389                         objfile_data (objfile, dwarf2_objfile_data_key));
2390   if (!dwarf2_per_objfile)
2391     {
2392       /* Initialize per-objfile state.  */
2393       struct dwarf2_per_objfile *data
2394         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2395
2396       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2397       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2398     }
2399   return (!dwarf2_per_objfile->info.is_virtual
2400           && dwarf2_per_objfile->info.s.section != NULL
2401           && !dwarf2_per_objfile->abbrev.is_virtual
2402           && dwarf2_per_objfile->abbrev.s.section != NULL);
2403 }
2404
2405 /* Return the containing section of virtual section SECTION.  */
2406
2407 static struct dwarf2_section_info *
2408 get_containing_section (const struct dwarf2_section_info *section)
2409 {
2410   gdb_assert (section->is_virtual);
2411   return section->s.containing_section;
2412 }
2413
2414 /* Return the bfd owner of SECTION.  */
2415
2416 static struct bfd *
2417 get_section_bfd_owner (const struct dwarf2_section_info *section)
2418 {
2419   if (section->is_virtual)
2420     {
2421       section = get_containing_section (section);
2422       gdb_assert (!section->is_virtual);
2423     }
2424   return section->s.section->owner;
2425 }
2426
2427 /* Return the bfd section of SECTION.
2428    Returns NULL if the section is not present.  */
2429
2430 static asection *
2431 get_section_bfd_section (const struct dwarf2_section_info *section)
2432 {
2433   if (section->is_virtual)
2434     {
2435       section = get_containing_section (section);
2436       gdb_assert (!section->is_virtual);
2437     }
2438   return section->s.section;
2439 }
2440
2441 /* Return the name of SECTION.  */
2442
2443 static const char *
2444 get_section_name (const struct dwarf2_section_info *section)
2445 {
2446   asection *sectp = get_section_bfd_section (section);
2447
2448   gdb_assert (sectp != NULL);
2449   return bfd_section_name (get_section_bfd_owner (section), sectp);
2450 }
2451
2452 /* Return the name of the file SECTION is in.  */
2453
2454 static const char *
2455 get_section_file_name (const struct dwarf2_section_info *section)
2456 {
2457   bfd *abfd = get_section_bfd_owner (section);
2458
2459   return bfd_get_filename (abfd);
2460 }
2461
2462 /* Return the id of SECTION.
2463    Returns 0 if SECTION doesn't exist.  */
2464
2465 static int
2466 get_section_id (const struct dwarf2_section_info *section)
2467 {
2468   asection *sectp = get_section_bfd_section (section);
2469
2470   if (sectp == NULL)
2471     return 0;
2472   return sectp->id;
2473 }
2474
2475 /* Return the flags of SECTION.
2476    SECTION (or containing section if this is a virtual section) must exist.  */
2477
2478 static int
2479 get_section_flags (const struct dwarf2_section_info *section)
2480 {
2481   asection *sectp = get_section_bfd_section (section);
2482
2483   gdb_assert (sectp != NULL);
2484   return bfd_get_section_flags (sectp->owner, sectp);
2485 }
2486
2487 /* When loading sections, we look either for uncompressed section or for
2488    compressed section names.  */
2489
2490 static int
2491 section_is_p (const char *section_name,
2492               const struct dwarf2_section_names *names)
2493 {
2494   if (names->normal != NULL
2495       && strcmp (section_name, names->normal) == 0)
2496     return 1;
2497   if (names->compressed != NULL
2498       && strcmp (section_name, names->compressed) == 0)
2499     return 1;
2500   return 0;
2501 }
2502
2503 /* See declaration.  */
2504
2505 void
2506 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2507                                      const dwarf2_debug_sections &names)
2508 {
2509   flagword aflag = bfd_get_section_flags (abfd, sectp);
2510
2511   if ((aflag & SEC_HAS_CONTENTS) == 0)
2512     {
2513     }
2514   else if (section_is_p (sectp->name, &names.info))
2515     {
2516       this->info.s.section = sectp;
2517       this->info.size = bfd_get_section_size (sectp);
2518     }
2519   else if (section_is_p (sectp->name, &names.abbrev))
2520     {
2521       this->abbrev.s.section = sectp;
2522       this->abbrev.size = bfd_get_section_size (sectp);
2523     }
2524   else if (section_is_p (sectp->name, &names.line))
2525     {
2526       this->line.s.section = sectp;
2527       this->line.size = bfd_get_section_size (sectp);
2528     }
2529   else if (section_is_p (sectp->name, &names.loc))
2530     {
2531       this->loc.s.section = sectp;
2532       this->loc.size = bfd_get_section_size (sectp);
2533     }
2534   else if (section_is_p (sectp->name, &names.loclists))
2535     {
2536       this->loclists.s.section = sectp;
2537       this->loclists.size = bfd_get_section_size (sectp);
2538     }
2539   else if (section_is_p (sectp->name, &names.macinfo))
2540     {
2541       this->macinfo.s.section = sectp;
2542       this->macinfo.size = bfd_get_section_size (sectp);
2543     }
2544   else if (section_is_p (sectp->name, &names.macro))
2545     {
2546       this->macro.s.section = sectp;
2547       this->macro.size = bfd_get_section_size (sectp);
2548     }
2549   else if (section_is_p (sectp->name, &names.str))
2550     {
2551       this->str.s.section = sectp;
2552       this->str.size = bfd_get_section_size (sectp);
2553     }
2554   else if (section_is_p (sectp->name, &names.line_str))
2555     {
2556       this->line_str.s.section = sectp;
2557       this->line_str.size = bfd_get_section_size (sectp);
2558     }
2559   else if (section_is_p (sectp->name, &names.addr))
2560     {
2561       this->addr.s.section = sectp;
2562       this->addr.size = bfd_get_section_size (sectp);
2563     }
2564   else if (section_is_p (sectp->name, &names.frame))
2565     {
2566       this->frame.s.section = sectp;
2567       this->frame.size = bfd_get_section_size (sectp);
2568     }
2569   else if (section_is_p (sectp->name, &names.eh_frame))
2570     {
2571       this->eh_frame.s.section = sectp;
2572       this->eh_frame.size = bfd_get_section_size (sectp);
2573     }
2574   else if (section_is_p (sectp->name, &names.ranges))
2575     {
2576       this->ranges.s.section = sectp;
2577       this->ranges.size = bfd_get_section_size (sectp);
2578     }
2579   else if (section_is_p (sectp->name, &names.rnglists))
2580     {
2581       this->rnglists.s.section = sectp;
2582       this->rnglists.size = bfd_get_section_size (sectp);
2583     }
2584   else if (section_is_p (sectp->name, &names.types))
2585     {
2586       struct dwarf2_section_info type_section;
2587
2588       memset (&type_section, 0, sizeof (type_section));
2589       type_section.s.section = sectp;
2590       type_section.size = bfd_get_section_size (sectp);
2591
2592       VEC_safe_push (dwarf2_section_info_def, this->types,
2593                      &type_section);
2594     }
2595   else if (section_is_p (sectp->name, &names.gdb_index))
2596     {
2597       this->gdb_index.s.section = sectp;
2598       this->gdb_index.size = bfd_get_section_size (sectp);
2599     }
2600   else if (section_is_p (sectp->name, &names.debug_names))
2601     {
2602       this->debug_names.s.section = sectp;
2603       this->debug_names.size = bfd_get_section_size (sectp);
2604     }
2605   else if (section_is_p (sectp->name, &names.debug_aranges))
2606     {
2607       this->debug_aranges.s.section = sectp;
2608       this->debug_aranges.size = bfd_get_section_size (sectp);
2609     }
2610
2611   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2612       && bfd_section_vma (abfd, sectp) == 0)
2613     this->has_section_at_zero = true;
2614 }
2615
2616 /* A helper function that decides whether a section is empty,
2617    or not present.  */
2618
2619 static int
2620 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2621 {
2622   if (section->is_virtual)
2623     return section->size == 0;
2624   return section->s.section == NULL || section->size == 0;
2625 }
2626
2627 /* Read the contents of the section INFO.
2628    OBJFILE is the main object file, but not necessarily the file where
2629    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2630    of the DWO file.
2631    If the section is compressed, uncompress it before returning.  */
2632
2633 static void
2634 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2635 {
2636   asection *sectp;
2637   bfd *abfd;
2638   gdb_byte *buf, *retbuf;
2639
2640   if (info->readin)
2641     return;
2642   info->buffer = NULL;
2643   info->readin = 1;
2644
2645   if (dwarf2_section_empty_p (info))
2646     return;
2647
2648   sectp = get_section_bfd_section (info);
2649
2650   /* If this is a virtual section we need to read in the real one first.  */
2651   if (info->is_virtual)
2652     {
2653       struct dwarf2_section_info *containing_section =
2654         get_containing_section (info);
2655
2656       gdb_assert (sectp != NULL);
2657       if ((sectp->flags & SEC_RELOC) != 0)
2658         {
2659           error (_("Dwarf Error: DWP format V2 with relocations is not"
2660                    " supported in section %s [in module %s]"),
2661                  get_section_name (info), get_section_file_name (info));
2662         }
2663       dwarf2_read_section (objfile, containing_section);
2664       /* Other code should have already caught virtual sections that don't
2665          fit.  */
2666       gdb_assert (info->virtual_offset + info->size
2667                   <= containing_section->size);
2668       /* If the real section is empty or there was a problem reading the
2669          section we shouldn't get here.  */
2670       gdb_assert (containing_section->buffer != NULL);
2671       info->buffer = containing_section->buffer + info->virtual_offset;
2672       return;
2673     }
2674
2675   /* If the section has relocations, we must read it ourselves.
2676      Otherwise we attach it to the BFD.  */
2677   if ((sectp->flags & SEC_RELOC) == 0)
2678     {
2679       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2680       return;
2681     }
2682
2683   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2684   info->buffer = buf;
2685
2686   /* When debugging .o files, we may need to apply relocations; see
2687      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2688      We never compress sections in .o files, so we only need to
2689      try this when the section is not compressed.  */
2690   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2691   if (retbuf != NULL)
2692     {
2693       info->buffer = retbuf;
2694       return;
2695     }
2696
2697   abfd = get_section_bfd_owner (info);
2698   gdb_assert (abfd != NULL);
2699
2700   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2701       || bfd_bread (buf, info->size, abfd) != info->size)
2702     {
2703       error (_("Dwarf Error: Can't read DWARF data"
2704                " in section %s [in module %s]"),
2705              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2706     }
2707 }
2708
2709 /* A helper function that returns the size of a section in a safe way.
2710    If you are positive that the section has been read before using the
2711    size, then it is safe to refer to the dwarf2_section_info object's
2712    "size" field directly.  In other cases, you must call this
2713    function, because for compressed sections the size field is not set
2714    correctly until the section has been read.  */
2715
2716 static bfd_size_type
2717 dwarf2_section_size (struct objfile *objfile,
2718                      struct dwarf2_section_info *info)
2719 {
2720   if (!info->readin)
2721     dwarf2_read_section (objfile, info);
2722   return info->size;
2723 }
2724
2725 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2726    SECTION_NAME.  */
2727
2728 void
2729 dwarf2_get_section_info (struct objfile *objfile,
2730                          enum dwarf2_section_enum sect,
2731                          asection **sectp, const gdb_byte **bufp,
2732                          bfd_size_type *sizep)
2733 {
2734   struct dwarf2_per_objfile *data
2735     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2736                                                   dwarf2_objfile_data_key);
2737   struct dwarf2_section_info *info;
2738
2739   /* We may see an objfile without any DWARF, in which case we just
2740      return nothing.  */
2741   if (data == NULL)
2742     {
2743       *sectp = NULL;
2744       *bufp = NULL;
2745       *sizep = 0;
2746       return;
2747     }
2748   switch (sect)
2749     {
2750     case DWARF2_DEBUG_FRAME:
2751       info = &data->frame;
2752       break;
2753     case DWARF2_EH_FRAME:
2754       info = &data->eh_frame;
2755       break;
2756     default:
2757       gdb_assert_not_reached ("unexpected section");
2758     }
2759
2760   dwarf2_read_section (objfile, info);
2761
2762   *sectp = get_section_bfd_section (info);
2763   *bufp = info->buffer;
2764   *sizep = info->size;
2765 }
2766
2767 /* A helper function to find the sections for a .dwz file.  */
2768
2769 static void
2770 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2771 {
2772   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2773
2774   /* Note that we only support the standard ELF names, because .dwz
2775      is ELF-only (at the time of writing).  */
2776   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2777     {
2778       dwz_file->abbrev.s.section = sectp;
2779       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2780     }
2781   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2782     {
2783       dwz_file->info.s.section = sectp;
2784       dwz_file->info.size = bfd_get_section_size (sectp);
2785     }
2786   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2787     {
2788       dwz_file->str.s.section = sectp;
2789       dwz_file->str.size = bfd_get_section_size (sectp);
2790     }
2791   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2792     {
2793       dwz_file->line.s.section = sectp;
2794       dwz_file->line.size = bfd_get_section_size (sectp);
2795     }
2796   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2797     {
2798       dwz_file->macro.s.section = sectp;
2799       dwz_file->macro.size = bfd_get_section_size (sectp);
2800     }
2801   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2802     {
2803       dwz_file->gdb_index.s.section = sectp;
2804       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2805     }
2806   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2807     {
2808       dwz_file->debug_names.s.section = sectp;
2809       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2810     }
2811 }
2812
2813 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2814    there is no .gnu_debugaltlink section in the file.  Error if there
2815    is such a section but the file cannot be found.  */
2816
2817 static struct dwz_file *
2818 dwarf2_get_dwz_file (void)
2819 {
2820   const char *filename;
2821   struct dwz_file *result;
2822   bfd_size_type buildid_len_arg;
2823   size_t buildid_len;
2824   bfd_byte *buildid;
2825
2826   if (dwarf2_per_objfile->dwz_file != NULL)
2827     return dwarf2_per_objfile->dwz_file;
2828
2829   bfd_set_error (bfd_error_no_error);
2830   gdb::unique_xmalloc_ptr<char> data
2831     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2832                                   &buildid_len_arg, &buildid));
2833   if (data == NULL)
2834     {
2835       if (bfd_get_error () == bfd_error_no_error)
2836         return NULL;
2837       error (_("could not read '.gnu_debugaltlink' section: %s"),
2838              bfd_errmsg (bfd_get_error ()));
2839     }
2840
2841   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2842
2843   buildid_len = (size_t) buildid_len_arg;
2844
2845   filename = data.get ();
2846
2847   std::string abs_storage;
2848   if (!IS_ABSOLUTE_PATH (filename))
2849     {
2850       gdb::unique_xmalloc_ptr<char> abs
2851         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2852
2853       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2854       filename = abs_storage.c_str ();
2855     }
2856
2857   /* First try the file name given in the section.  If that doesn't
2858      work, try to use the build-id instead.  */
2859   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2860   if (dwz_bfd != NULL)
2861     {
2862       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2863         dwz_bfd.release ();
2864     }
2865
2866   if (dwz_bfd == NULL)
2867     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2868
2869   if (dwz_bfd == NULL)
2870     error (_("could not find '.gnu_debugaltlink' file for %s"),
2871            objfile_name (dwarf2_per_objfile->objfile));
2872
2873   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2874                            struct dwz_file);
2875   result->dwz_bfd = dwz_bfd.release ();
2876
2877   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2878
2879   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2880   dwarf2_per_objfile->dwz_file = result;
2881   return result;
2882 }
2883 \f
2884 /* DWARF quick_symbols_functions support.  */
2885
2886 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2887    unique line tables, so we maintain a separate table of all .debug_line
2888    derived entries to support the sharing.
2889    All the quick functions need is the list of file names.  We discard the
2890    line_header when we're done and don't need to record it here.  */
2891 struct quick_file_names
2892 {
2893   /* The data used to construct the hash key.  */
2894   struct stmt_list_hash hash;
2895
2896   /* The number of entries in file_names, real_names.  */
2897   unsigned int num_file_names;
2898
2899   /* The file names from the line table, after being run through
2900      file_full_name.  */
2901   const char **file_names;
2902
2903   /* The file names from the line table after being run through
2904      gdb_realpath.  These are computed lazily.  */
2905   const char **real_names;
2906 };
2907
2908 /* When using the index (and thus not using psymtabs), each CU has an
2909    object of this type.  This is used to hold information needed by
2910    the various "quick" methods.  */
2911 struct dwarf2_per_cu_quick_data
2912 {
2913   /* The file table.  This can be NULL if there was no file table
2914      or it's currently not read in.
2915      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2916   struct quick_file_names *file_names;
2917
2918   /* The corresponding symbol table.  This is NULL if symbols for this
2919      CU have not yet been read.  */
2920   struct compunit_symtab *compunit_symtab;
2921
2922   /* A temporary mark bit used when iterating over all CUs in
2923      expand_symtabs_matching.  */
2924   unsigned int mark : 1;
2925
2926   /* True if we've tried to read the file table and found there isn't one.
2927      There will be no point in trying to read it again next time.  */
2928   unsigned int no_file_data : 1;
2929 };
2930
2931 /* Utility hash function for a stmt_list_hash.  */
2932
2933 static hashval_t
2934 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2935 {
2936   hashval_t v = 0;
2937
2938   if (stmt_list_hash->dwo_unit != NULL)
2939     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2940   v += to_underlying (stmt_list_hash->line_sect_off);
2941   return v;
2942 }
2943
2944 /* Utility equality function for a stmt_list_hash.  */
2945
2946 static int
2947 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2948                     const struct stmt_list_hash *rhs)
2949 {
2950   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2951     return 0;
2952   if (lhs->dwo_unit != NULL
2953       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2954     return 0;
2955
2956   return lhs->line_sect_off == rhs->line_sect_off;
2957 }
2958
2959 /* Hash function for a quick_file_names.  */
2960
2961 static hashval_t
2962 hash_file_name_entry (const void *e)
2963 {
2964   const struct quick_file_names *file_data
2965     = (const struct quick_file_names *) e;
2966
2967   return hash_stmt_list_entry (&file_data->hash);
2968 }
2969
2970 /* Equality function for a quick_file_names.  */
2971
2972 static int
2973 eq_file_name_entry (const void *a, const void *b)
2974 {
2975   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2976   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2977
2978   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2979 }
2980
2981 /* Delete function for a quick_file_names.  */
2982
2983 static void
2984 delete_file_name_entry (void *e)
2985 {
2986   struct quick_file_names *file_data = (struct quick_file_names *) e;
2987   int i;
2988
2989   for (i = 0; i < file_data->num_file_names; ++i)
2990     {
2991       xfree ((void*) file_data->file_names[i]);
2992       if (file_data->real_names)
2993         xfree ((void*) file_data->real_names[i]);
2994     }
2995
2996   /* The space for the struct itself lives on objfile_obstack,
2997      so we don't free it here.  */
2998 }
2999
3000 /* Create a quick_file_names hash table.  */
3001
3002 static htab_t
3003 create_quick_file_names_table (unsigned int nr_initial_entries)
3004 {
3005   return htab_create_alloc (nr_initial_entries,
3006                             hash_file_name_entry, eq_file_name_entry,
3007                             delete_file_name_entry, xcalloc, xfree);
3008 }
3009
3010 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3011    have to be created afterwards.  You should call age_cached_comp_units after
3012    processing PER_CU->CU.  dw2_setup must have been already called.  */
3013
3014 static void
3015 load_cu (struct dwarf2_per_cu_data *per_cu)
3016 {
3017   if (per_cu->is_debug_types)
3018     load_full_type_unit (per_cu);
3019   else
3020     load_full_comp_unit (per_cu, language_minimal);
3021
3022   if (per_cu->cu == NULL)
3023     return;  /* Dummy CU.  */
3024
3025   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3026 }
3027
3028 /* Read in the symbols for PER_CU.  */
3029
3030 static void
3031 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3032 {
3033   struct cleanup *back_to;
3034
3035   /* Skip type_unit_groups, reading the type units they contain
3036      is handled elsewhere.  */
3037   if (IS_TYPE_UNIT_GROUP (per_cu))
3038     return;
3039
3040   back_to = make_cleanup (dwarf2_release_queue, NULL);
3041
3042   if (dwarf2_per_objfile->using_index
3043       ? per_cu->v.quick->compunit_symtab == NULL
3044       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3045     {
3046       queue_comp_unit (per_cu, language_minimal);
3047       load_cu (per_cu);
3048
3049       /* If we just loaded a CU from a DWO, and we're working with an index
3050          that may badly handle TUs, load all the TUs in that DWO as well.
3051          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3052       if (!per_cu->is_debug_types
3053           && per_cu->cu != NULL
3054           && per_cu->cu->dwo_unit != NULL
3055           && dwarf2_per_objfile->index_table != NULL
3056           && dwarf2_per_objfile->index_table->version <= 7
3057           /* DWP files aren't supported yet.  */
3058           && get_dwp_file () == NULL)
3059         queue_and_load_all_dwo_tus (per_cu);
3060     }
3061
3062   process_queue ();
3063
3064   /* Age the cache, releasing compilation units that have not
3065      been used recently.  */
3066   age_cached_comp_units ();
3067
3068   do_cleanups (back_to);
3069 }
3070
3071 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3072    the objfile from which this CU came.  Returns the resulting symbol
3073    table.  */
3074
3075 static struct compunit_symtab *
3076 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3077 {
3078   gdb_assert (dwarf2_per_objfile->using_index);
3079   if (!per_cu->v.quick->compunit_symtab)
3080     {
3081       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
3082       scoped_restore decrementer = increment_reading_symtab ();
3083       dw2_do_instantiate_symtab (per_cu);
3084       process_cu_includes ();
3085       do_cleanups (back_to);
3086     }
3087
3088   return per_cu->v.quick->compunit_symtab;
3089 }
3090
3091 /* Return the CU/TU given its index.
3092
3093    This is intended for loops like:
3094
3095    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3096                     + dwarf2_per_objfile->n_type_units); ++i)
3097      {
3098        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3099
3100        ...;
3101      }
3102 */
3103
3104 static struct dwarf2_per_cu_data *
3105 dw2_get_cutu (int index)
3106 {
3107   if (index >= dwarf2_per_objfile->n_comp_units)
3108     {
3109       index -= dwarf2_per_objfile->n_comp_units;
3110       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3111       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3112     }
3113
3114   return dwarf2_per_objfile->all_comp_units[index];
3115 }
3116
3117 /* Return the CU given its index.
3118    This differs from dw2_get_cutu in that it's for when you know INDEX
3119    refers to a CU.  */
3120
3121 static struct dwarf2_per_cu_data *
3122 dw2_get_cu (int index)
3123 {
3124   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3125
3126   return dwarf2_per_objfile->all_comp_units[index];
3127 }
3128
3129 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3130    objfile_obstack, and constructed with the specified field
3131    values.  */
3132
3133 static dwarf2_per_cu_data *
3134 create_cu_from_index_list (struct objfile *objfile,
3135                           struct dwarf2_section_info *section,
3136                           int is_dwz,
3137                           sect_offset sect_off, ULONGEST length)
3138 {
3139   dwarf2_per_cu_data *the_cu
3140     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3141                      struct dwarf2_per_cu_data);
3142   the_cu->sect_off = sect_off;
3143   the_cu->length = length;
3144   the_cu->objfile = objfile;
3145   the_cu->section = section;
3146   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3147                                    struct dwarf2_per_cu_quick_data);
3148   the_cu->is_dwz = is_dwz;
3149   return the_cu;
3150 }
3151
3152 /* A helper for create_cus_from_index that handles a given list of
3153    CUs.  */
3154
3155 static void
3156 create_cus_from_index_list (struct objfile *objfile,
3157                             const gdb_byte *cu_list, offset_type n_elements,
3158                             struct dwarf2_section_info *section,
3159                             int is_dwz,
3160                             int base_offset)
3161 {
3162   offset_type i;
3163
3164   for (i = 0; i < n_elements; i += 2)
3165     {
3166       gdb_static_assert (sizeof (ULONGEST) >= 8);
3167
3168       sect_offset sect_off
3169         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3170       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3171       cu_list += 2 * 8;
3172
3173       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3174         = create_cu_from_index_list (objfile, section, is_dwz, sect_off, length);
3175     }
3176 }
3177
3178 /* Read the CU list from the mapped index, and use it to create all
3179    the CU objects for this objfile.  */
3180
3181 static void
3182 create_cus_from_index (struct objfile *objfile,
3183                        const gdb_byte *cu_list, offset_type cu_list_elements,
3184                        const gdb_byte *dwz_list, offset_type dwz_elements)
3185 {
3186   struct dwz_file *dwz;
3187
3188   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3189   dwarf2_per_objfile->all_comp_units =
3190     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3191                dwarf2_per_objfile->n_comp_units);
3192
3193   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3194                               &dwarf2_per_objfile->info, 0, 0);
3195
3196   if (dwz_elements == 0)
3197     return;
3198
3199   dwz = dwarf2_get_dwz_file ();
3200   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3201                               cu_list_elements / 2);
3202 }
3203
3204 /* Create the signatured type hash table from the index.  */
3205
3206 static void
3207 create_signatured_type_table_from_index (struct objfile *objfile,
3208                                          struct dwarf2_section_info *section,
3209                                          const gdb_byte *bytes,
3210                                          offset_type elements)
3211 {
3212   offset_type i;
3213   htab_t sig_types_hash;
3214
3215   dwarf2_per_objfile->n_type_units
3216     = dwarf2_per_objfile->n_allocated_type_units
3217     = elements / 3;
3218   dwarf2_per_objfile->all_type_units =
3219     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3220
3221   sig_types_hash = allocate_signatured_type_table (objfile);
3222
3223   for (i = 0; i < elements; i += 3)
3224     {
3225       struct signatured_type *sig_type;
3226       ULONGEST signature;
3227       void **slot;
3228       cu_offset type_offset_in_tu;
3229
3230       gdb_static_assert (sizeof (ULONGEST) >= 8);
3231       sect_offset sect_off
3232         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3233       type_offset_in_tu
3234         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3235                                                 BFD_ENDIAN_LITTLE);
3236       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3237       bytes += 3 * 8;
3238
3239       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3240                                  struct signatured_type);
3241       sig_type->signature = signature;
3242       sig_type->type_offset_in_tu = type_offset_in_tu;
3243       sig_type->per_cu.is_debug_types = 1;
3244       sig_type->per_cu.section = section;
3245       sig_type->per_cu.sect_off = sect_off;
3246       sig_type->per_cu.objfile = objfile;
3247       sig_type->per_cu.v.quick
3248         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3249                           struct dwarf2_per_cu_quick_data);
3250
3251       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3252       *slot = sig_type;
3253
3254       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3255     }
3256
3257   dwarf2_per_objfile->signatured_types = sig_types_hash;
3258 }
3259
3260 /* Create the signatured type hash table from .debug_names.  */
3261
3262 static void
3263 create_signatured_type_table_from_debug_names
3264   (struct objfile *objfile,
3265    const mapped_debug_names &map,
3266    struct dwarf2_section_info *section,
3267    struct dwarf2_section_info *abbrev_section)
3268 {
3269   dwarf2_read_section (objfile, section);
3270   dwarf2_read_section (objfile, abbrev_section);
3271
3272   dwarf2_per_objfile->n_type_units
3273     = dwarf2_per_objfile->n_allocated_type_units
3274     = map.tu_count;
3275   dwarf2_per_objfile->all_type_units
3276     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3277
3278   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3279
3280   for (uint32_t i = 0; i < map.tu_count; ++i)
3281     {
3282       struct signatured_type *sig_type;
3283       ULONGEST signature;
3284       void **slot;
3285       cu_offset type_offset_in_tu;
3286
3287       sect_offset sect_off
3288         = (sect_offset) (extract_unsigned_integer
3289                          (map.tu_table_reordered + i * map.offset_size,
3290                           map.offset_size,
3291                           map.dwarf5_byte_order));
3292
3293       comp_unit_head cu_header;
3294       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
3295                                      section->buffer + to_underlying (sect_off),
3296                                      rcuh_kind::TYPE);
3297
3298       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3299                                  struct signatured_type);
3300       sig_type->signature = cu_header.signature;
3301       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3302       sig_type->per_cu.is_debug_types = 1;
3303       sig_type->per_cu.section = section;
3304       sig_type->per_cu.sect_off = sect_off;
3305       sig_type->per_cu.objfile = objfile;
3306       sig_type->per_cu.v.quick
3307         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3308                           struct dwarf2_per_cu_quick_data);
3309
3310       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3311       *slot = sig_type;
3312
3313       dwarf2_per_objfile->all_type_units[i] = sig_type;
3314     }
3315
3316   dwarf2_per_objfile->signatured_types = sig_types_hash;
3317 }
3318
3319 /* Read the address map data from the mapped index, and use it to
3320    populate the objfile's psymtabs_addrmap.  */
3321
3322 static void
3323 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3324 {
3325   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3326   const gdb_byte *iter, *end;
3327   struct addrmap *mutable_map;
3328   CORE_ADDR baseaddr;
3329
3330   auto_obstack temp_obstack;
3331
3332   mutable_map = addrmap_create_mutable (&temp_obstack);
3333
3334   iter = index->address_table;
3335   end = iter + index->address_table_size;
3336
3337   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3338
3339   while (iter < end)
3340     {
3341       ULONGEST hi, lo, cu_index;
3342       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3343       iter += 8;
3344       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3345       iter += 8;
3346       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3347       iter += 4;
3348
3349       if (lo > hi)
3350         {
3351           complaint (&symfile_complaints,
3352                      _(".gdb_index address table has invalid range (%s - %s)"),
3353                      hex_string (lo), hex_string (hi));
3354           continue;
3355         }
3356
3357       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3358         {
3359           complaint (&symfile_complaints,
3360                      _(".gdb_index address table has invalid CU number %u"),
3361                      (unsigned) cu_index);
3362           continue;
3363         }
3364
3365       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3366       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3367       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3368     }
3369
3370   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3371                                                     &objfile->objfile_obstack);
3372 }
3373
3374 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3375    populate the objfile's psymtabs_addrmap.  */
3376
3377 static void
3378 create_addrmap_from_aranges (struct objfile *objfile,
3379                              struct dwarf2_section_info *section)
3380 {
3381   bfd *abfd = objfile->obfd;
3382   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3383   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3384                                        SECT_OFF_TEXT (objfile));
3385
3386   auto_obstack temp_obstack;
3387   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3388
3389   std::unordered_map<sect_offset,
3390                      dwarf2_per_cu_data *,
3391                      gdb::hash_enum<sect_offset>>
3392     debug_info_offset_to_per_cu;
3393   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3394     {
3395       dwarf2_per_cu_data *per_cu = dw2_get_cutu (cui);
3396       const auto insertpair
3397         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3398       if (!insertpair.second)
3399         {
3400           warning (_("Section .debug_aranges in %s has duplicate "
3401                      "debug_info_offset %u, ignoring .debug_aranges."),
3402                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3403           return;
3404         }
3405     }
3406
3407   dwarf2_read_section (objfile, section);
3408
3409   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3410
3411   const gdb_byte *addr = section->buffer;
3412
3413   while (addr < section->buffer + section->size)
3414     {
3415       const gdb_byte *const entry_addr = addr;
3416       unsigned int bytes_read;
3417
3418       const LONGEST entry_length = read_initial_length (abfd, addr,
3419                                                         &bytes_read);
3420       addr += bytes_read;
3421
3422       const gdb_byte *const entry_end = addr + entry_length;
3423       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3424       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3425       if (addr + entry_length > section->buffer + section->size)
3426         {
3427           warning (_("Section .debug_aranges in %s entry at offset %zu "
3428                      "length %s exceeds section length %s, "
3429                      "ignoring .debug_aranges."),
3430                    objfile_name (objfile), entry_addr - section->buffer,
3431                    plongest (bytes_read + entry_length),
3432                    pulongest (section->size));
3433           return;
3434         }
3435
3436       /* The version number.  */
3437       const uint16_t version = read_2_bytes (abfd, addr);
3438       addr += 2;
3439       if (version != 2)
3440         {
3441           warning (_("Section .debug_aranges in %s entry at offset %zu "
3442                      "has unsupported version %d, ignoring .debug_aranges."),
3443                    objfile_name (objfile), entry_addr - section->buffer,
3444                    version);
3445           return;
3446         }
3447
3448       const uint64_t debug_info_offset
3449         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3450       addr += offset_size;
3451       const auto per_cu_it
3452         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3453       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3454         {
3455           warning (_("Section .debug_aranges in %s entry at offset %zu "
3456                      "debug_info_offset %s does not exists, "
3457                      "ignoring .debug_aranges."),
3458                    objfile_name (objfile), entry_addr - section->buffer,
3459                    pulongest (debug_info_offset));
3460           return;
3461         }
3462       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3463
3464       const uint8_t address_size = *addr++;
3465       if (address_size < 1 || address_size > 8)
3466         {
3467           warning (_("Section .debug_aranges in %s entry at offset %zu "
3468                      "address_size %u is invalid, ignoring .debug_aranges."),
3469                    objfile_name (objfile), entry_addr - section->buffer,
3470                    address_size);
3471           return;
3472         }
3473
3474       const uint8_t segment_selector_size = *addr++;
3475       if (segment_selector_size != 0)
3476         {
3477           warning (_("Section .debug_aranges in %s entry at offset %zu "
3478                      "segment_selector_size %u is not supported, "
3479                      "ignoring .debug_aranges."),
3480                    objfile_name (objfile), entry_addr - section->buffer,
3481                    segment_selector_size);
3482           return;
3483         }
3484
3485       /* Must pad to an alignment boundary that is twice the address
3486          size.  It is undocumented by the DWARF standard but GCC does
3487          use it.  */
3488       for (size_t padding = ((-(addr - section->buffer))
3489                              & (2 * address_size - 1));
3490            padding > 0; padding--)
3491         if (*addr++ != 0)
3492           {
3493             warning (_("Section .debug_aranges in %s entry at offset %zu "
3494                        "padding is not zero, ignoring .debug_aranges."),
3495                      objfile_name (objfile), entry_addr - section->buffer);
3496             return;
3497           }
3498
3499       for (;;)
3500         {
3501           if (addr + 2 * address_size > entry_end)
3502             {
3503               warning (_("Section .debug_aranges in %s entry at offset %zu "
3504                          "address list is not properly terminated, "
3505                          "ignoring .debug_aranges."),
3506                        objfile_name (objfile), entry_addr - section->buffer);
3507               return;
3508             }
3509           ULONGEST start = extract_unsigned_integer (addr, address_size,
3510                                                      dwarf5_byte_order);
3511           addr += address_size;
3512           ULONGEST length = extract_unsigned_integer (addr, address_size,
3513                                                       dwarf5_byte_order);
3514           addr += address_size;
3515           if (start == 0 && length == 0)
3516             break;
3517           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3518             {
3519               /* Symbol was eliminated due to a COMDAT group.  */
3520               continue;
3521             }
3522           ULONGEST end = start + length;
3523           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3524           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3525           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3526         }
3527     }
3528
3529   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3530                                                     &objfile->objfile_obstack);
3531 }
3532
3533 /* The hash function for strings in the mapped index.  This is the same as
3534    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3535    implementation.  This is necessary because the hash function is tied to the
3536    format of the mapped index file.  The hash values do not have to match with
3537    SYMBOL_HASH_NEXT.
3538    
3539    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3540
3541 static hashval_t
3542 mapped_index_string_hash (int index_version, const void *p)
3543 {
3544   const unsigned char *str = (const unsigned char *) p;
3545   hashval_t r = 0;
3546   unsigned char c;
3547
3548   while ((c = *str++) != 0)
3549     {
3550       if (index_version >= 5)
3551         c = tolower (c);
3552       r = r * 67 + c - 113;
3553     }
3554
3555   return r;
3556 }
3557
3558 /* Find a slot in the mapped index INDEX for the object named NAME.
3559    If NAME is found, set *VEC_OUT to point to the CU vector in the
3560    constant pool and return true.  If NAME cannot be found, return
3561    false.  */
3562
3563 static bool
3564 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3565                           offset_type **vec_out)
3566 {
3567   offset_type hash;
3568   offset_type slot, step;
3569   int (*cmp) (const char *, const char *);
3570
3571   gdb::unique_xmalloc_ptr<char> without_params;
3572   if (current_language->la_language == language_cplus
3573       || current_language->la_language == language_fortran
3574       || current_language->la_language == language_d)
3575     {
3576       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3577          not contain any.  */
3578
3579       if (strchr (name, '(') != NULL)
3580         {
3581           without_params = cp_remove_params (name);
3582
3583           if (without_params != NULL)
3584             name = without_params.get ();
3585         }
3586     }
3587
3588   /* Index version 4 did not support case insensitive searches.  But the
3589      indices for case insensitive languages are built in lowercase, therefore
3590      simulate our NAME being searched is also lowercased.  */
3591   hash = mapped_index_string_hash ((index->version == 4
3592                                     && case_sensitivity == case_sensitive_off
3593                                     ? 5 : index->version),
3594                                    name);
3595
3596   slot = hash & (index->symbol_table_slots - 1);
3597   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3598   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3599
3600   for (;;)
3601     {
3602       /* Convert a slot number to an offset into the table.  */
3603       offset_type i = 2 * slot;
3604       const char *str;
3605       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3606         return false;
3607
3608       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3609       if (!cmp (name, str))
3610         {
3611           *vec_out = (offset_type *) (index->constant_pool
3612                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3613           return true;
3614         }
3615
3616       slot = (slot + step) & (index->symbol_table_slots - 1);
3617     }
3618 }
3619
3620 /* A helper function that reads the .gdb_index from SECTION and fills
3621    in MAP.  FILENAME is the name of the file containing the section;
3622    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3623    ok to use deprecated sections.
3624
3625    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3626    out parameters that are filled in with information about the CU and
3627    TU lists in the section.
3628
3629    Returns 1 if all went well, 0 otherwise.  */
3630
3631 static int
3632 read_index_from_section (struct objfile *objfile,
3633                          const char *filename,
3634                          int deprecated_ok,
3635                          struct dwarf2_section_info *section,
3636                          struct mapped_index *map,
3637                          const gdb_byte **cu_list,
3638                          offset_type *cu_list_elements,
3639                          const gdb_byte **types_list,
3640                          offset_type *types_list_elements)
3641 {
3642   const gdb_byte *addr;
3643   offset_type version;
3644   offset_type *metadata;
3645   int i;
3646
3647   if (dwarf2_section_empty_p (section))
3648     return 0;
3649
3650   /* Older elfutils strip versions could keep the section in the main
3651      executable while splitting it for the separate debug info file.  */
3652   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3653     return 0;
3654
3655   dwarf2_read_section (objfile, section);
3656
3657   addr = section->buffer;
3658   /* Version check.  */
3659   version = MAYBE_SWAP (*(offset_type *) addr);
3660   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3661      causes the index to behave very poorly for certain requests.  Version 3
3662      contained incomplete addrmap.  So, it seems better to just ignore such
3663      indices.  */
3664   if (version < 4)
3665     {
3666       static int warning_printed = 0;
3667       if (!warning_printed)
3668         {
3669           warning (_("Skipping obsolete .gdb_index section in %s."),
3670                    filename);
3671           warning_printed = 1;
3672         }
3673       return 0;
3674     }
3675   /* Index version 4 uses a different hash function than index version
3676      5 and later.
3677
3678      Versions earlier than 6 did not emit psymbols for inlined
3679      functions.  Using these files will cause GDB not to be able to
3680      set breakpoints on inlined functions by name, so we ignore these
3681      indices unless the user has done
3682      "set use-deprecated-index-sections on".  */
3683   if (version < 6 && !deprecated_ok)
3684     {
3685       static int warning_printed = 0;
3686       if (!warning_printed)
3687         {
3688           warning (_("\
3689 Skipping deprecated .gdb_index section in %s.\n\
3690 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3691 to use the section anyway."),
3692                    filename);
3693           warning_printed = 1;
3694         }
3695       return 0;
3696     }
3697   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3698      of the TU (for symbols coming from TUs),
3699      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3700      Plus gold-generated indices can have duplicate entries for global symbols,
3701      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3702      These are just performance bugs, and we can't distinguish gdb-generated
3703      indices from gold-generated ones, so issue no warning here.  */
3704
3705   /* Indexes with higher version than the one supported by GDB may be no
3706      longer backward compatible.  */
3707   if (version > 8)
3708     return 0;
3709
3710   map->version = version;
3711   map->total_size = section->size;
3712
3713   metadata = (offset_type *) (addr + sizeof (offset_type));
3714
3715   i = 0;
3716   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3717   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3718                        / 8);
3719   ++i;
3720
3721   *types_list = addr + MAYBE_SWAP (metadata[i]);
3722   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3723                            - MAYBE_SWAP (metadata[i]))
3724                           / 8);
3725   ++i;
3726
3727   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3728   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3729                              - MAYBE_SWAP (metadata[i]));
3730   ++i;
3731
3732   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3733   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3734                               - MAYBE_SWAP (metadata[i]))
3735                              / (2 * sizeof (offset_type)));
3736   ++i;
3737
3738   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3739
3740   return 1;
3741 }
3742
3743 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3744    elements of all the CUs and return 1.  Otherwise, return 0.  */
3745
3746 static int
3747 dwarf2_read_index (struct objfile *objfile)
3748 {
3749   struct mapped_index local_map, *map;
3750   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3751   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3752   struct dwz_file *dwz;
3753
3754   if (!read_index_from_section (objfile, objfile_name (objfile),
3755                                 use_deprecated_index_sections,
3756                                 &dwarf2_per_objfile->gdb_index, &local_map,
3757                                 &cu_list, &cu_list_elements,
3758                                 &types_list, &types_list_elements))
3759     return 0;
3760
3761   /* Don't use the index if it's empty.  */
3762   if (local_map.symbol_table_slots == 0)
3763     return 0;
3764
3765   /* If there is a .dwz file, read it so we can get its CU list as
3766      well.  */
3767   dwz = dwarf2_get_dwz_file ();
3768   if (dwz != NULL)
3769     {
3770       struct mapped_index dwz_map;
3771       const gdb_byte *dwz_types_ignore;
3772       offset_type dwz_types_elements_ignore;
3773
3774       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3775                                     1,
3776                                     &dwz->gdb_index, &dwz_map,
3777                                     &dwz_list, &dwz_list_elements,
3778                                     &dwz_types_ignore,
3779                                     &dwz_types_elements_ignore))
3780         {
3781           warning (_("could not read '.gdb_index' section from %s; skipping"),
3782                    bfd_get_filename (dwz->dwz_bfd));
3783           return 0;
3784         }
3785     }
3786
3787   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3788                          dwz_list_elements);
3789
3790   if (types_list_elements)
3791     {
3792       struct dwarf2_section_info *section;
3793
3794       /* We can only handle a single .debug_types when we have an
3795          index.  */
3796       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3797         return 0;
3798
3799       section = VEC_index (dwarf2_section_info_def,
3800                            dwarf2_per_objfile->types, 0);
3801
3802       create_signatured_type_table_from_index (objfile, section, types_list,
3803                                                types_list_elements);
3804     }
3805
3806   create_addrmap_from_index (objfile, &local_map);
3807
3808   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3809   map = new (map) mapped_index ();
3810   *map = local_map;
3811
3812   dwarf2_per_objfile->index_table = map;
3813   dwarf2_per_objfile->using_index = 1;
3814   dwarf2_per_objfile->quick_file_names_table =
3815     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3816
3817   return 1;
3818 }
3819
3820 /* A helper for the "quick" functions which sets the global
3821    dwarf2_per_objfile according to OBJFILE.  */
3822
3823 static void
3824 dw2_setup (struct objfile *objfile)
3825 {
3826   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3827                         objfile_data (objfile, dwarf2_objfile_data_key));
3828   gdb_assert (dwarf2_per_objfile);
3829 }
3830
3831 /* die_reader_func for dw2_get_file_names.  */
3832
3833 static void
3834 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3835                            const gdb_byte *info_ptr,
3836                            struct die_info *comp_unit_die,
3837                            int has_children,
3838                            void *data)
3839 {
3840   struct dwarf2_cu *cu = reader->cu;
3841   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3842   struct objfile *objfile = dwarf2_per_objfile->objfile;
3843   struct dwarf2_per_cu_data *lh_cu;
3844   struct attribute *attr;
3845   int i;
3846   void **slot;
3847   struct quick_file_names *qfn;
3848
3849   gdb_assert (! this_cu->is_debug_types);
3850
3851   /* Our callers never want to match partial units -- instead they
3852      will match the enclosing full CU.  */
3853   if (comp_unit_die->tag == DW_TAG_partial_unit)
3854     {
3855       this_cu->v.quick->no_file_data = 1;
3856       return;
3857     }
3858
3859   lh_cu = this_cu;
3860   slot = NULL;
3861
3862   line_header_up lh;
3863   sect_offset line_offset {};
3864
3865   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3866   if (attr)
3867     {
3868       struct quick_file_names find_entry;
3869
3870       line_offset = (sect_offset) DW_UNSND (attr);
3871
3872       /* We may have already read in this line header (TU line header sharing).
3873          If we have we're done.  */
3874       find_entry.hash.dwo_unit = cu->dwo_unit;
3875       find_entry.hash.line_sect_off = line_offset;
3876       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3877                              &find_entry, INSERT);
3878       if (*slot != NULL)
3879         {
3880           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3881           return;
3882         }
3883
3884       lh = dwarf_decode_line_header (line_offset, cu);
3885     }
3886   if (lh == NULL)
3887     {
3888       lh_cu->v.quick->no_file_data = 1;
3889       return;
3890     }
3891
3892   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3893   qfn->hash.dwo_unit = cu->dwo_unit;
3894   qfn->hash.line_sect_off = line_offset;
3895   gdb_assert (slot != NULL);
3896   *slot = qfn;
3897
3898   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3899
3900   qfn->num_file_names = lh->file_names.size ();
3901   qfn->file_names =
3902     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3903   for (i = 0; i < lh->file_names.size (); ++i)
3904     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3905   qfn->real_names = NULL;
3906
3907   lh_cu->v.quick->file_names = qfn;
3908 }
3909
3910 /* A helper for the "quick" functions which attempts to read the line
3911    table for THIS_CU.  */
3912
3913 static struct quick_file_names *
3914 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3915 {
3916   /* This should never be called for TUs.  */
3917   gdb_assert (! this_cu->is_debug_types);
3918   /* Nor type unit groups.  */
3919   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3920
3921   if (this_cu->v.quick->file_names != NULL)
3922     return this_cu->v.quick->file_names;
3923   /* If we know there is no line data, no point in looking again.  */
3924   if (this_cu->v.quick->no_file_data)
3925     return NULL;
3926
3927   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3928
3929   if (this_cu->v.quick->no_file_data)
3930     return NULL;
3931   return this_cu->v.quick->file_names;
3932 }
3933
3934 /* A helper for the "quick" functions which computes and caches the
3935    real path for a given file name from the line table.  */
3936
3937 static const char *
3938 dw2_get_real_path (struct objfile *objfile,
3939                    struct quick_file_names *qfn, int index)
3940 {
3941   if (qfn->real_names == NULL)
3942     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3943                                       qfn->num_file_names, const char *);
3944
3945   if (qfn->real_names[index] == NULL)
3946     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3947
3948   return qfn->real_names[index];
3949 }
3950
3951 static struct symtab *
3952 dw2_find_last_source_symtab (struct objfile *objfile)
3953 {
3954   struct compunit_symtab *cust;
3955   int index;
3956
3957   dw2_setup (objfile);
3958   index = dwarf2_per_objfile->n_comp_units - 1;
3959   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3960   if (cust == NULL)
3961     return NULL;
3962   return compunit_primary_filetab (cust);
3963 }
3964
3965 /* Traversal function for dw2_forget_cached_source_info.  */
3966
3967 static int
3968 dw2_free_cached_file_names (void **slot, void *info)
3969 {
3970   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3971
3972   if (file_data->real_names)
3973     {
3974       int i;
3975
3976       for (i = 0; i < file_data->num_file_names; ++i)
3977         {
3978           xfree ((void*) file_data->real_names[i]);
3979           file_data->real_names[i] = NULL;
3980         }
3981     }
3982
3983   return 1;
3984 }
3985
3986 static void
3987 dw2_forget_cached_source_info (struct objfile *objfile)
3988 {
3989   dw2_setup (objfile);
3990
3991   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3992                           dw2_free_cached_file_names, NULL);
3993 }
3994
3995 /* Helper function for dw2_map_symtabs_matching_filename that expands
3996    the symtabs and calls the iterator.  */
3997
3998 static int
3999 dw2_map_expand_apply (struct objfile *objfile,
4000                       struct dwarf2_per_cu_data *per_cu,
4001                       const char *name, const char *real_path,
4002                       gdb::function_view<bool (symtab *)> callback)
4003 {
4004   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4005
4006   /* Don't visit already-expanded CUs.  */
4007   if (per_cu->v.quick->compunit_symtab)
4008     return 0;
4009
4010   /* This may expand more than one symtab, and we want to iterate over
4011      all of them.  */
4012   dw2_instantiate_symtab (per_cu);
4013
4014   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4015                                     last_made, callback);
4016 }
4017
4018 /* Implementation of the map_symtabs_matching_filename method.  */
4019
4020 static bool
4021 dw2_map_symtabs_matching_filename
4022   (struct objfile *objfile, const char *name, const char *real_path,
4023    gdb::function_view<bool (symtab *)> callback)
4024 {
4025   int i;
4026   const char *name_basename = lbasename (name);
4027
4028   dw2_setup (objfile);
4029
4030   /* The rule is CUs specify all the files, including those used by
4031      any TU, so there's no need to scan TUs here.  */
4032
4033   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4034     {
4035       int j;
4036       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4037       struct quick_file_names *file_data;
4038
4039       /* We only need to look at symtabs not already expanded.  */
4040       if (per_cu->v.quick->compunit_symtab)
4041         continue;
4042
4043       file_data = dw2_get_file_names (per_cu);
4044       if (file_data == NULL)
4045         continue;
4046
4047       for (j = 0; j < file_data->num_file_names; ++j)
4048         {
4049           const char *this_name = file_data->file_names[j];
4050           const char *this_real_name;
4051
4052           if (compare_filenames_for_search (this_name, name))
4053             {
4054               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4055                                         callback))
4056                 return true;
4057               continue;
4058             }
4059
4060           /* Before we invoke realpath, which can get expensive when many
4061              files are involved, do a quick comparison of the basenames.  */
4062           if (! basenames_may_differ
4063               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4064             continue;
4065
4066           this_real_name = dw2_get_real_path (objfile, file_data, j);
4067           if (compare_filenames_for_search (this_real_name, name))
4068             {
4069               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4070                                         callback))
4071                 return true;
4072               continue;
4073             }
4074
4075           if (real_path != NULL)
4076             {
4077               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4078               gdb_assert (IS_ABSOLUTE_PATH (name));
4079               if (this_real_name != NULL
4080                   && FILENAME_CMP (real_path, this_real_name) == 0)
4081                 {
4082                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4083                                             callback))
4084                     return true;
4085                   continue;
4086                 }
4087             }
4088         }
4089     }
4090
4091   return false;
4092 }
4093
4094 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4095
4096 struct dw2_symtab_iterator
4097 {
4098   /* The internalized form of .gdb_index.  */
4099   struct mapped_index *index;
4100   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4101   int want_specific_block;
4102   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4103      Unused if !WANT_SPECIFIC_BLOCK.  */
4104   int block_index;
4105   /* The kind of symbol we're looking for.  */
4106   domain_enum domain;
4107   /* The list of CUs from the index entry of the symbol,
4108      or NULL if not found.  */
4109   offset_type *vec;
4110   /* The next element in VEC to look at.  */
4111   int next;
4112   /* The number of elements in VEC, or zero if there is no match.  */
4113   int length;
4114   /* Have we seen a global version of the symbol?
4115      If so we can ignore all further global instances.
4116      This is to work around gold/15646, inefficient gold-generated
4117      indices.  */
4118   int global_seen;
4119 };
4120
4121 /* Initialize the index symtab iterator ITER.
4122    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4123    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4124
4125 static void
4126 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4127                       struct mapped_index *index,
4128                       int want_specific_block,
4129                       int block_index,
4130                       domain_enum domain,
4131                       const char *name)
4132 {
4133   iter->index = index;
4134   iter->want_specific_block = want_specific_block;
4135   iter->block_index = block_index;
4136   iter->domain = domain;
4137   iter->next = 0;
4138   iter->global_seen = 0;
4139
4140   if (find_slot_in_mapped_hash (index, name, &iter->vec))
4141     iter->length = MAYBE_SWAP (*iter->vec);
4142   else
4143     {
4144       iter->vec = NULL;
4145       iter->length = 0;
4146     }
4147 }
4148
4149 /* Return the next matching CU or NULL if there are no more.  */
4150
4151 static struct dwarf2_per_cu_data *
4152 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4153 {
4154   for ( ; iter->next < iter->length; ++iter->next)
4155     {
4156       offset_type cu_index_and_attrs =
4157         MAYBE_SWAP (iter->vec[iter->next + 1]);
4158       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4159       struct dwarf2_per_cu_data *per_cu;
4160       int want_static = iter->block_index != GLOBAL_BLOCK;
4161       /* This value is only valid for index versions >= 7.  */
4162       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4163       gdb_index_symbol_kind symbol_kind =
4164         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4165       /* Only check the symbol attributes if they're present.
4166          Indices prior to version 7 don't record them,
4167          and indices >= 7 may elide them for certain symbols
4168          (gold does this).  */
4169       int attrs_valid =
4170         (iter->index->version >= 7
4171          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4172
4173       /* Don't crash on bad data.  */
4174       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4175                        + dwarf2_per_objfile->n_type_units))
4176         {
4177           complaint (&symfile_complaints,
4178                      _(".gdb_index entry has bad CU index"
4179                        " [in module %s]"),
4180                      objfile_name (dwarf2_per_objfile->objfile));
4181           continue;
4182         }
4183
4184       per_cu = dw2_get_cutu (cu_index);
4185
4186       /* Skip if already read in.  */
4187       if (per_cu->v.quick->compunit_symtab)
4188         continue;
4189
4190       /* Check static vs global.  */
4191       if (attrs_valid)
4192         {
4193           if (iter->want_specific_block
4194               && want_static != is_static)
4195             continue;
4196           /* Work around gold/15646.  */
4197           if (!is_static && iter->global_seen)
4198             continue;
4199           if (!is_static)
4200             iter->global_seen = 1;
4201         }
4202
4203       /* Only check the symbol's kind if it has one.  */
4204       if (attrs_valid)
4205         {
4206           switch (iter->domain)
4207             {
4208             case VAR_DOMAIN:
4209               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4210                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4211                   /* Some types are also in VAR_DOMAIN.  */
4212                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4213                 continue;
4214               break;
4215             case STRUCT_DOMAIN:
4216               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4217                 continue;
4218               break;
4219             case LABEL_DOMAIN:
4220               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4221                 continue;
4222               break;
4223             default:
4224               break;
4225             }
4226         }
4227
4228       ++iter->next;
4229       return per_cu;
4230     }
4231
4232   return NULL;
4233 }
4234
4235 static struct compunit_symtab *
4236 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4237                    const char *name, domain_enum domain)
4238 {
4239   struct compunit_symtab *stab_best = NULL;
4240   struct mapped_index *index;
4241
4242   dw2_setup (objfile);
4243
4244   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4245
4246   index = dwarf2_per_objfile->index_table;
4247
4248   /* index is NULL if OBJF_READNOW.  */
4249   if (index)
4250     {
4251       struct dw2_symtab_iterator iter;
4252       struct dwarf2_per_cu_data *per_cu;
4253
4254       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
4255
4256       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4257         {
4258           struct symbol *sym, *with_opaque = NULL;
4259           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4260           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4261           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4262
4263           sym = block_find_symbol (block, name, domain,
4264                                    block_find_non_opaque_type_preferred,
4265                                    &with_opaque);
4266
4267           /* Some caution must be observed with overloaded functions
4268              and methods, since the index will not contain any overload
4269              information (but NAME might contain it).  */
4270
4271           if (sym != NULL
4272               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4273             return stab;
4274           if (with_opaque != NULL
4275               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4276             stab_best = stab;
4277
4278           /* Keep looking through other CUs.  */
4279         }
4280     }
4281
4282   return stab_best;
4283 }
4284
4285 static void
4286 dw2_print_stats (struct objfile *objfile)
4287 {
4288   int i, total, count;
4289
4290   dw2_setup (objfile);
4291   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4292   count = 0;
4293   for (i = 0; i < total; ++i)
4294     {
4295       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4296
4297       if (!per_cu->v.quick->compunit_symtab)
4298         ++count;
4299     }
4300   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4301   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4302 }
4303
4304 /* This dumps minimal information about the index.
4305    It is called via "mt print objfiles".
4306    One use is to verify .gdb_index has been loaded by the
4307    gdb.dwarf2/gdb-index.exp testcase.  */
4308
4309 static void
4310 dw2_dump (struct objfile *objfile)
4311 {
4312   dw2_setup (objfile);
4313   gdb_assert (dwarf2_per_objfile->using_index);
4314   printf_filtered (".gdb_index:");
4315   if (dwarf2_per_objfile->index_table != NULL)
4316     {
4317       printf_filtered (" version %d\n",
4318                        dwarf2_per_objfile->index_table->version);
4319     }
4320   else
4321     printf_filtered (" faked for \"readnow\"\n");
4322   printf_filtered ("\n");
4323 }
4324
4325 static void
4326 dw2_relocate (struct objfile *objfile,
4327               const struct section_offsets *new_offsets,
4328               const struct section_offsets *delta)
4329 {
4330   /* There's nothing to relocate here.  */
4331 }
4332
4333 static void
4334 dw2_expand_symtabs_for_function (struct objfile *objfile,
4335                                  const char *func_name)
4336 {
4337   struct mapped_index *index;
4338
4339   dw2_setup (objfile);
4340
4341   index = dwarf2_per_objfile->index_table;
4342
4343   /* index is NULL if OBJF_READNOW.  */
4344   if (index)
4345     {
4346       struct dw2_symtab_iterator iter;
4347       struct dwarf2_per_cu_data *per_cu;
4348
4349       /* Note: It doesn't matter what we pass for block_index here.  */
4350       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4351                             func_name);
4352
4353       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4354         dw2_instantiate_symtab (per_cu);
4355     }
4356 }
4357
4358 static void
4359 dw2_expand_all_symtabs (struct objfile *objfile)
4360 {
4361   int i;
4362
4363   dw2_setup (objfile);
4364
4365   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4366                    + dwarf2_per_objfile->n_type_units); ++i)
4367     {
4368       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4369
4370       dw2_instantiate_symtab (per_cu);
4371     }
4372 }
4373
4374 static void
4375 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4376                                   const char *fullname)
4377 {
4378   int i;
4379
4380   dw2_setup (objfile);
4381
4382   /* We don't need to consider type units here.
4383      This is only called for examining code, e.g. expand_line_sal.
4384      There can be an order of magnitude (or more) more type units
4385      than comp units, and we avoid them if we can.  */
4386
4387   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4388     {
4389       int j;
4390       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4391       struct quick_file_names *file_data;
4392
4393       /* We only need to look at symtabs not already expanded.  */
4394       if (per_cu->v.quick->compunit_symtab)
4395         continue;
4396
4397       file_data = dw2_get_file_names (per_cu);
4398       if (file_data == NULL)
4399         continue;
4400
4401       for (j = 0; j < file_data->num_file_names; ++j)
4402         {
4403           const char *this_fullname = file_data->file_names[j];
4404
4405           if (filename_cmp (this_fullname, fullname) == 0)
4406             {
4407               dw2_instantiate_symtab (per_cu);
4408               break;
4409             }
4410         }
4411     }
4412 }
4413
4414 static void
4415 dw2_map_matching_symbols (struct objfile *objfile,
4416                           const char * name, domain_enum domain,
4417                           int global,
4418                           int (*callback) (struct block *,
4419                                            struct symbol *, void *),
4420                           void *data, symbol_name_match_type match,
4421                           symbol_compare_ftype *ordered_compare)
4422 {
4423   /* Currently unimplemented; used for Ada.  The function can be called if the
4424      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4425      does not look for non-Ada symbols this function should just return.  */
4426 }
4427
4428 /* Symbol name matcher for .gdb_index names.
4429
4430    Symbol names in .gdb_index have a few particularities:
4431
4432    - There's no indication of which is the language of each symbol.
4433
4434      Since each language has its own symbol name matching algorithm,
4435      and we don't know which language is the right one, we must match
4436      each symbol against all languages.  This would be a potential
4437      performance problem if it were not mitigated by the
4438      mapped_index::name_components lookup table, which significantly
4439      reduces the number of times we need to call into this matcher,
4440      making it a non-issue.
4441
4442    - Symbol names in the index have no overload (parameter)
4443      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4444      appear as "foo" in the index, for example.
4445
4446      This means that the lookup names passed to the symbol name
4447      matcher functions must have no parameter information either
4448      because (e.g.) symbol search name "foo" does not match
4449      lookup-name "foo(int)" [while swapping search name for lookup
4450      name would match].
4451 */
4452 class gdb_index_symbol_name_matcher
4453 {
4454 public:
4455   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4456   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4457
4458   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4459      Returns true if any matcher matches.  */
4460   bool matches (const char *symbol_name);
4461
4462 private:
4463   /* A reference to the lookup name we're matching against.  */
4464   const lookup_name_info &m_lookup_name;
4465
4466   /* A vector holding all the different symbol name matchers, for all
4467      languages.  */
4468   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4469 };
4470
4471 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4472   (const lookup_name_info &lookup_name)
4473     : m_lookup_name (lookup_name)
4474 {
4475   /* Prepare the vector of comparison functions upfront, to avoid
4476      doing the same work for each symbol.  Care is taken to avoid
4477      matching with the same matcher more than once if/when multiple
4478      languages use the same matcher function.  */
4479   auto &matchers = m_symbol_name_matcher_funcs;
4480   matchers.reserve (nr_languages);
4481
4482   matchers.push_back (default_symbol_name_matcher);
4483
4484   for (int i = 0; i < nr_languages; i++)
4485     {
4486       const language_defn *lang = language_def ((enum language) i);
4487       if (lang->la_get_symbol_name_matcher != NULL)
4488         {
4489           symbol_name_matcher_ftype *name_matcher
4490             = lang->la_get_symbol_name_matcher (m_lookup_name);
4491
4492           /* Don't insert the same comparison routine more than once.
4493              Note that we do this linear walk instead of a cheaper
4494              sorted insert, or use a std::set or something like that,
4495              because relative order of function addresses is not
4496              stable.  This is not a problem in practice because the
4497              number of supported languages is low, and the cost here
4498              is tiny compared to the number of searches we'll do
4499              afterwards using this object.  */
4500           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4501               == matchers.end ())
4502             matchers.push_back (name_matcher);
4503         }
4504     }
4505 }
4506
4507 bool
4508 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4509 {
4510   for (auto matches_name : m_symbol_name_matcher_funcs)
4511     if (matches_name (symbol_name, m_lookup_name, NULL))
4512       return true;
4513
4514   return false;
4515 }
4516
4517 /* Starting from a search name, return the string that finds the upper
4518    bound of all strings that start with SEARCH_NAME in a sorted name
4519    list.  Returns the empty string to indicate that the upper bound is
4520    the end of the list.  */
4521
4522 static std::string
4523 make_sort_after_prefix_name (const char *search_name)
4524 {
4525   /* When looking to complete "func", we find the upper bound of all
4526      symbols that start with "func" by looking for where we'd insert
4527      the closest string that would follow "func" in lexicographical
4528      order.  Usually, that's "func"-with-last-character-incremented,
4529      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4530      will be UTF-8 multi-byte sequences, but we can't be certain.
4531      Especially mind the 0xff character, which is a valid character in
4532      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4533      rule out compilers allowing it in identifiers.  Note that
4534      conveniently, strcmp/strcasecmp are specified to compare
4535      characters interpreted as unsigned char.  So what we do is treat
4536      the whole string as a base 256 number composed of a sequence of
4537      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4538      to 0, and carries 1 to the following more-significant position.
4539      If the very first character in SEARCH_NAME ends up incremented
4540      and carries/overflows, then the upper bound is the end of the
4541      list.  The string after the empty string is also the empty
4542      string.
4543
4544      Some examples of this operation:
4545
4546        SEARCH_NAME  => "+1" RESULT
4547
4548        "abc"              => "abd"
4549        "ab\xff"           => "ac"
4550        "\xff" "a" "\xff"  => "\xff" "b"
4551        "\xff"             => ""
4552        "\xff\xff"         => ""
4553        ""                 => ""
4554
4555      Then, with these symbols for example:
4556
4557       func
4558       func1
4559       fund
4560
4561      completing "func" looks for symbols between "func" and
4562      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4563      which finds "func" and "func1", but not "fund".
4564
4565      And with:
4566
4567       funcÿ     (Latin1 'ÿ' [0xff])
4568       funcÿ1
4569       fund
4570
4571      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4572      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4573
4574      And with:
4575
4576       ÿÿ        (Latin1 'ÿ' [0xff])
4577       ÿÿ1
4578
4579      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4580      the end of the list.
4581   */
4582   std::string after = search_name;
4583   while (!after.empty () && (unsigned char) after.back () == 0xff)
4584     after.pop_back ();
4585   if (!after.empty ())
4586     after.back () = (unsigned char) after.back () + 1;
4587   return after;
4588 }
4589
4590 /* See declaration.  */
4591
4592 std::pair<std::vector<name_component>::const_iterator,
4593           std::vector<name_component>::const_iterator>
4594 mapped_index::find_name_components_bounds
4595   (const lookup_name_info &lookup_name_without_params) const
4596 {
4597   auto *name_cmp
4598     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4599
4600   const char *cplus
4601     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4602
4603   /* Comparison function object for lower_bound that matches against a
4604      given symbol name.  */
4605   auto lookup_compare_lower = [&] (const name_component &elem,
4606                                    const char *name)
4607     {
4608       const char *elem_qualified = this->symbol_name_at (elem.idx);
4609       const char *elem_name = elem_qualified + elem.name_offset;
4610       return name_cmp (elem_name, name) < 0;
4611     };
4612
4613   /* Comparison function object for upper_bound that matches against a
4614      given symbol name.  */
4615   auto lookup_compare_upper = [&] (const char *name,
4616                                    const name_component &elem)
4617     {
4618       const char *elem_qualified = this->symbol_name_at (elem.idx);
4619       const char *elem_name = elem_qualified + elem.name_offset;
4620       return name_cmp (name, elem_name) < 0;
4621     };
4622
4623   auto begin = this->name_components.begin ();
4624   auto end = this->name_components.end ();
4625
4626   /* Find the lower bound.  */
4627   auto lower = [&] ()
4628     {
4629       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4630         return begin;
4631       else
4632         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4633     } ();
4634
4635   /* Find the upper bound.  */
4636   auto upper = [&] ()
4637     {
4638       if (lookup_name_without_params.completion_mode ())
4639         {
4640           /* In completion mode, we want UPPER to point past all
4641              symbols names that have the same prefix.  I.e., with
4642              these symbols, and completing "func":
4643
4644               function        << lower bound
4645               function1
4646               other_function  << upper bound
4647
4648              We find the upper bound by looking for the insertion
4649              point of "func"-with-last-character-incremented,
4650              i.e. "fund".  */
4651           std::string after = make_sort_after_prefix_name (cplus);
4652           if (after.empty ())
4653             return end;
4654           return std::lower_bound (lower, end, after.c_str (),
4655                                    lookup_compare_lower);
4656         }
4657       else
4658         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4659     } ();
4660
4661   return {lower, upper};
4662 }
4663
4664 /* See declaration.  */
4665
4666 void
4667 mapped_index::build_name_components ()
4668 {
4669   if (!this->name_components.empty ())
4670     return;
4671
4672   this->name_components_casing = case_sensitivity;
4673   auto *name_cmp
4674     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4675
4676   /* The code below only knows how to break apart components of C++
4677      symbol names (and other languages that use '::' as
4678      namespace/module separator).  If we add support for wild matching
4679      to some language that uses some other operator (E.g., Ada, Go and
4680      D use '.'), then we'll need to try splitting the symbol name
4681      according to that language too.  Note that Ada does support wild
4682      matching, but doesn't currently support .gdb_index.  */
4683   for (size_t iter = 0; iter < this->symbol_table_slots; ++iter)
4684     {
4685       offset_type idx = 2 * iter;
4686
4687       if (this->symbol_table[idx] == 0
4688           && this->symbol_table[idx + 1] == 0)
4689         continue;
4690
4691       const char *name = this->symbol_name_at (idx);
4692
4693       /* Add each name component to the name component table.  */
4694       unsigned int previous_len = 0;
4695       for (unsigned int current_len = cp_find_first_component (name);
4696            name[current_len] != '\0';
4697            current_len += cp_find_first_component (name + current_len))
4698         {
4699           gdb_assert (name[current_len] == ':');
4700           this->name_components.push_back ({previous_len, idx});
4701           /* Skip the '::'.  */
4702           current_len += 2;
4703           previous_len = current_len;
4704         }
4705       this->name_components.push_back ({previous_len, idx});
4706     }
4707
4708   /* Sort name_components elements by name.  */
4709   auto name_comp_compare = [&] (const name_component &left,
4710                                 const name_component &right)
4711     {
4712       const char *left_qualified = this->symbol_name_at (left.idx);
4713       const char *right_qualified = this->symbol_name_at (right.idx);
4714
4715       const char *left_name = left_qualified + left.name_offset;
4716       const char *right_name = right_qualified + right.name_offset;
4717
4718       return name_cmp (left_name, right_name) < 0;
4719     };
4720
4721   std::sort (this->name_components.begin (),
4722              this->name_components.end (),
4723              name_comp_compare);
4724 }
4725
4726 /* Helper for dw2_expand_symtabs_matching that works with a
4727    mapped_index instead of the containing objfile.  This is split to a
4728    separate function in order to be able to unit test the
4729    name_components matching using a mock mapped_index.  For each
4730    symbol name that matches, calls MATCH_CALLBACK, passing it the
4731    symbol's index in the mapped_index symbol table.  */
4732
4733 static void
4734 dw2_expand_symtabs_matching_symbol
4735   (mapped_index &index,
4736    const lookup_name_info &lookup_name_in,
4737    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4738    enum search_domain kind,
4739    gdb::function_view<void (offset_type)> match_callback)
4740 {
4741   lookup_name_info lookup_name_without_params
4742     = lookup_name_in.make_ignore_params ();
4743   gdb_index_symbol_name_matcher lookup_name_matcher
4744     (lookup_name_without_params);
4745
4746   /* Build the symbol name component sorted vector, if we haven't
4747      yet.  */
4748   index.build_name_components ();
4749
4750   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4751
4752   /* Now for each symbol name in range, check to see if we have a name
4753      match, and if so, call the MATCH_CALLBACK callback.  */
4754
4755   /* The same symbol may appear more than once in the range though.
4756      E.g., if we're looking for symbols that complete "w", and we have
4757      a symbol named "w1::w2", we'll find the two name components for
4758      that same symbol in the range.  To be sure we only call the
4759      callback once per symbol, we first collect the symbol name
4760      indexes that matched in a temporary vector and ignore
4761      duplicates.  */
4762   std::vector<offset_type> matches;
4763   matches.reserve (std::distance (bounds.first, bounds.second));
4764
4765   for (; bounds.first != bounds.second; ++bounds.first)
4766     {
4767       const char *qualified = index.symbol_name_at (bounds.first->idx);
4768
4769       if (!lookup_name_matcher.matches (qualified)
4770           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4771         continue;
4772
4773       matches.push_back (bounds.first->idx);
4774     }
4775
4776   std::sort (matches.begin (), matches.end ());
4777
4778   /* Finally call the callback, once per match.  */
4779   ULONGEST prev = -1;
4780   for (offset_type idx : matches)
4781     {
4782       if (prev != idx)
4783         {
4784           match_callback (idx);
4785           prev = idx;
4786         }
4787     }
4788
4789   /* Above we use a type wider than idx's for 'prev', since 0 and
4790      (offset_type)-1 are both possible values.  */
4791   static_assert (sizeof (prev) > sizeof (offset_type), "");
4792 }
4793
4794 #if GDB_SELF_TEST
4795
4796 namespace selftests { namespace dw2_expand_symtabs_matching {
4797
4798 /* A wrapper around mapped_index that builds a mock mapped_index, from
4799    the symbol list passed as parameter to the constructor.  */
4800 class mock_mapped_index
4801 {
4802 public:
4803   template<size_t N>
4804   mock_mapped_index (const char *(&symbols)[N])
4805     : mock_mapped_index (symbols, N)
4806   {}
4807
4808   /* Access the built index.  */
4809   mapped_index &index ()
4810   { return m_index; }
4811
4812   /* Disable copy.  */
4813   mock_mapped_index(const mock_mapped_index &) = delete;
4814   void operator= (const mock_mapped_index &) = delete;
4815
4816 private:
4817   mock_mapped_index (const char **symbols, size_t symbols_size)
4818   {
4819     /* No string can live at offset zero.  Add a dummy entry.  */
4820     obstack_grow_str0 (&m_constant_pool, "");
4821
4822     for (size_t i = 0; i < symbols_size; i++)
4823       {
4824         const char *sym = symbols[i];
4825         size_t offset = obstack_object_size (&m_constant_pool);
4826         obstack_grow_str0 (&m_constant_pool, sym);
4827         m_symbol_table.push_back (offset);
4828         m_symbol_table.push_back (0);
4829       };
4830
4831     m_index.constant_pool = (const char *) obstack_base (&m_constant_pool);
4832     m_index.symbol_table = m_symbol_table.data ();
4833     m_index.symbol_table_slots = m_symbol_table.size () / 2;
4834   }
4835
4836 public:
4837   /* The built mapped_index.  */
4838   mapped_index m_index{};
4839
4840   /* The storage that the built mapped_index uses for symbol and
4841      constant pool tables.  */
4842   std::vector<offset_type> m_symbol_table;
4843   auto_obstack m_constant_pool;
4844 };
4845
4846 /* Convenience function that converts a NULL pointer to a "<null>"
4847    string, to pass to print routines.  */
4848
4849 static const char *
4850 string_or_null (const char *str)
4851 {
4852   return str != NULL ? str : "<null>";
4853 }
4854
4855 /* Check if a lookup_name_info built from
4856    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4857    index.  EXPECTED_LIST is the list of expected matches, in expected
4858    matching order.  If no match expected, then an empty list is
4859    specified.  Returns true on success.  On failure prints a warning
4860    indicating the file:line that failed, and returns false.  */
4861
4862 static bool
4863 check_match (const char *file, int line,
4864              mock_mapped_index &mock_index,
4865              const char *name, symbol_name_match_type match_type,
4866              bool completion_mode,
4867              std::initializer_list<const char *> expected_list)
4868 {
4869   lookup_name_info lookup_name (name, match_type, completion_mode);
4870
4871   bool matched = true;
4872
4873   auto mismatch = [&] (const char *expected_str,
4874                        const char *got)
4875   {
4876     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4877                "expected=\"%s\", got=\"%s\"\n"),
4878              file, line,
4879              (match_type == symbol_name_match_type::FULL
4880               ? "FULL" : "WILD"),
4881              name, string_or_null (expected_str), string_or_null (got));
4882     matched = false;
4883   };
4884
4885   auto expected_it = expected_list.begin ();
4886   auto expected_end = expected_list.end ();
4887
4888   dw2_expand_symtabs_matching_symbol (mock_index.index (), lookup_name,
4889                                       NULL, ALL_DOMAIN,
4890                                       [&] (offset_type idx)
4891   {
4892     const char *matched_name = mock_index.index ().symbol_name_at (idx);
4893     const char *expected_str
4894       = expected_it == expected_end ? NULL : *expected_it++;
4895
4896     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4897       mismatch (expected_str, matched_name);
4898   });
4899
4900   const char *expected_str
4901   = expected_it == expected_end ? NULL : *expected_it++;
4902   if (expected_str != NULL)
4903     mismatch (expected_str, NULL);
4904
4905   return matched;
4906 }
4907
4908 /* The symbols added to the mock mapped_index for testing (in
4909    canonical form).  */
4910 static const char *test_symbols[] = {
4911   "function",
4912   "std::bar",
4913   "std::zfunction",
4914   "std::zfunction2",
4915   "w1::w2",
4916   "ns::foo<char*>",
4917   "ns::foo<int>",
4918   "ns::foo<long>",
4919   "ns2::tmpl<int>::foo2",
4920   "(anonymous namespace)::A::B::C",
4921
4922   /* These are used to check that the increment-last-char in the
4923      matching algorithm for completion doesn't match "t1_fund" when
4924      completing "t1_func".  */
4925   "t1_func",
4926   "t1_func1",
4927   "t1_fund",
4928   "t1_fund1",
4929
4930   /* A UTF-8 name with multi-byte sequences to make sure that
4931      cp-name-parser understands this as a single identifier ("função"
4932      is "function" in PT).  */
4933   u8"u8função",
4934
4935   /* \377 (0xff) is Latin1 'ÿ'.  */
4936   "yfunc\377",
4937
4938   /* \377 (0xff) is Latin1 'ÿ'.  */
4939   "\377",
4940   "\377\377123",
4941
4942   /* A name with all sorts of complications.  Starts with "z" to make
4943      it easier for the completion tests below.  */
4944 #define Z_SYM_NAME \
4945   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4946     "::tuple<(anonymous namespace)::ui*, " \
4947     "std::default_delete<(anonymous namespace)::ui>, void>"
4948
4949   Z_SYM_NAME
4950 };
4951
4952 /* Returns true if the mapped_index::find_name_component_bounds method
4953    finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME, in
4954    completion mode.  */
4955
4956 static bool
4957 check_find_bounds_finds (mapped_index &index,
4958                          const char *search_name,
4959                          gdb::array_view<const char *> expected_syms)
4960 {
4961   lookup_name_info lookup_name (search_name,
4962                                 symbol_name_match_type::FULL, true);
4963
4964   auto bounds = index.find_name_components_bounds (lookup_name);
4965
4966   size_t distance = std::distance (bounds.first, bounds.second);
4967   if (distance != expected_syms.size ())
4968     return false;
4969
4970   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4971     {
4972       auto nc_elem = bounds.first + exp_elem;
4973       const char *qualified = index.symbol_name_at (nc_elem->idx);
4974       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4975         return false;
4976     }
4977
4978   return true;
4979 }
4980
4981 /* Test the lower-level mapped_index::find_name_component_bounds
4982    method.  */
4983
4984 static void
4985 test_mapped_index_find_name_component_bounds ()
4986 {
4987   mock_mapped_index mock_index (test_symbols);
4988
4989   mock_index.index ().build_name_components ();
4990
4991   /* Test the lower-level mapped_index::find_name_component_bounds
4992      method in completion mode.  */
4993   {
4994     static const char *expected_syms[] = {
4995       "t1_func",
4996       "t1_func1",
4997     };
4998
4999     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
5000                                          "t1_func", expected_syms));
5001   }
5002
5003   /* Check that the increment-last-char in the name matching algorithm
5004      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5005   {
5006     static const char *expected_syms1[] = {
5007       "\377",
5008       "\377\377123",
5009     };
5010     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
5011                                          "\377", expected_syms1));
5012
5013     static const char *expected_syms2[] = {
5014       "\377\377123",
5015     };
5016     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
5017                                          "\377\377", expected_syms2));
5018   }
5019 }
5020
5021 /* Test dw2_expand_symtabs_matching_symbol.  */
5022
5023 static void
5024 test_dw2_expand_symtabs_matching_symbol ()
5025 {
5026   mock_mapped_index mock_index (test_symbols);
5027
5028   /* We let all tests run until the end even if some fails, for debug
5029      convenience.  */
5030   bool any_mismatch = false;
5031
5032   /* Create the expected symbols list (an initializer_list).  Needed
5033      because lists have commas, and we need to pass them to CHECK,
5034      which is a macro.  */
5035 #define EXPECT(...) { __VA_ARGS__ }
5036
5037   /* Wrapper for check_match that passes down the current
5038      __FILE__/__LINE__.  */
5039 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5040   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5041                                 mock_index,                             \
5042                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5043                                 EXPECTED_LIST)
5044
5045   /* Identity checks.  */
5046   for (const char *sym : test_symbols)
5047     {
5048       /* Should be able to match all existing symbols.  */
5049       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5050                    EXPECT (sym));
5051
5052       /* Should be able to match all existing symbols with
5053          parameters.  */
5054       std::string with_params = std::string (sym) + "(int)";
5055       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5056                    EXPECT (sym));
5057
5058       /* Should be able to match all existing symbols with
5059          parameters and qualifiers.  */
5060       with_params = std::string (sym) + " ( int ) const";
5061       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5062                    EXPECT (sym));
5063
5064       /* This should really find sym, but cp-name-parser.y doesn't
5065          know about lvalue/rvalue qualifiers yet.  */
5066       with_params = std::string (sym) + " ( int ) &&";
5067       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5068                    {});
5069     }
5070
5071   /* Check that the name matching algorithm for completion doesn't get
5072      confused with Latin1 'ÿ' / 0xff.  */
5073   {
5074     static const char str[] = "\377";
5075     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5076                  EXPECT ("\377", "\377\377123"));
5077   }
5078
5079   /* Check that the increment-last-char in the matching algorithm for
5080      completion doesn't match "t1_fund" when completing "t1_func".  */
5081   {
5082     static const char str[] = "t1_func";
5083     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5084                  EXPECT ("t1_func", "t1_func1"));
5085   }
5086
5087   /* Check that completion mode works at each prefix of the expected
5088      symbol name.  */
5089   {
5090     static const char str[] = "function(int)";
5091     size_t len = strlen (str);
5092     std::string lookup;
5093
5094     for (size_t i = 1; i < len; i++)
5095       {
5096         lookup.assign (str, i);
5097         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5098                      EXPECT ("function"));
5099       }
5100   }
5101
5102   /* While "w" is a prefix of both components, the match function
5103      should still only be called once.  */
5104   {
5105     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5106                  EXPECT ("w1::w2"));
5107     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5108                  EXPECT ("w1::w2"));
5109   }
5110
5111   /* Same, with a "complicated" symbol.  */
5112   {
5113     static const char str[] = Z_SYM_NAME;
5114     size_t len = strlen (str);
5115     std::string lookup;
5116
5117     for (size_t i = 1; i < len; i++)
5118       {
5119         lookup.assign (str, i);
5120         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5121                      EXPECT (Z_SYM_NAME));
5122       }
5123   }
5124
5125   /* In FULL mode, an incomplete symbol doesn't match.  */
5126   {
5127     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5128                  {});
5129   }
5130
5131   /* A complete symbol with parameters matches any overload, since the
5132      index has no overload info.  */
5133   {
5134     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5135                  EXPECT ("std::zfunction", "std::zfunction2"));
5136     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5137                  EXPECT ("std::zfunction", "std::zfunction2"));
5138     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5139                  EXPECT ("std::zfunction", "std::zfunction2"));
5140   }
5141
5142   /* Check that whitespace is ignored appropriately.  A symbol with a
5143      template argument list. */
5144   {
5145     static const char expected[] = "ns::foo<int>";
5146     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5147                  EXPECT (expected));
5148     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5149                  EXPECT (expected));
5150   }
5151
5152   /* Check that whitespace is ignored appropriately.  A symbol with a
5153      template argument list that includes a pointer.  */
5154   {
5155     static const char expected[] = "ns::foo<char*>";
5156     /* Try both completion and non-completion modes.  */
5157     static const bool completion_mode[2] = {false, true};
5158     for (size_t i = 0; i < 2; i++)
5159       {
5160         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5161                      completion_mode[i], EXPECT (expected));
5162         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5163                      completion_mode[i], EXPECT (expected));
5164
5165         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5166                      completion_mode[i], EXPECT (expected));
5167         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5168                      completion_mode[i], EXPECT (expected));
5169       }
5170   }
5171
5172   {
5173     /* Check method qualifiers are ignored.  */
5174     static const char expected[] = "ns::foo<char*>";
5175     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5176                  symbol_name_match_type::FULL, true, EXPECT (expected));
5177     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5178                  symbol_name_match_type::FULL, true, EXPECT (expected));
5179     CHECK_MATCH ("foo < char * >  ( int ) const",
5180                  symbol_name_match_type::WILD, true, EXPECT (expected));
5181     CHECK_MATCH ("foo < char * >  ( int ) &&",
5182                  symbol_name_match_type::WILD, true, EXPECT (expected));
5183   }
5184
5185   /* Test lookup names that don't match anything.  */
5186   {
5187     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5188                  {});
5189
5190     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5191                  {});
5192   }
5193
5194   /* Some wild matching tests, exercising "(anonymous namespace)",
5195      which should not be confused with a parameter list.  */
5196   {
5197     static const char *syms[] = {
5198       "A::B::C",
5199       "B::C",
5200       "C",
5201       "A :: B :: C ( int )",
5202       "B :: C ( int )",
5203       "C ( int )",
5204     };
5205
5206     for (const char *s : syms)
5207       {
5208         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5209                      EXPECT ("(anonymous namespace)::A::B::C"));
5210       }
5211   }
5212
5213   {
5214     static const char expected[] = "ns2::tmpl<int>::foo2";
5215     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5216                  EXPECT (expected));
5217     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5218                  EXPECT (expected));
5219   }
5220
5221   SELF_CHECK (!any_mismatch);
5222
5223 #undef EXPECT
5224 #undef CHECK_MATCH
5225 }
5226
5227 static void
5228 run_test ()
5229 {
5230   test_mapped_index_find_name_component_bounds ();
5231   test_dw2_expand_symtabs_matching_symbol ();
5232 }
5233
5234 }} // namespace selftests::dw2_expand_symtabs_matching
5235
5236 #endif /* GDB_SELF_TEST */
5237
5238 /* If FILE_MATCHER is NULL or if PER_CU has
5239    dwarf2_per_cu_quick_data::MARK set (see
5240    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5241    EXPANSION_NOTIFY on it.  */
5242
5243 static void
5244 dw2_expand_symtabs_matching_one
5245   (struct dwarf2_per_cu_data *per_cu,
5246    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5247    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5248 {
5249   if (file_matcher == NULL || per_cu->v.quick->mark)
5250     {
5251       bool symtab_was_null
5252         = (per_cu->v.quick->compunit_symtab == NULL);
5253
5254       dw2_instantiate_symtab (per_cu);
5255
5256       if (expansion_notify != NULL
5257           && symtab_was_null
5258           && per_cu->v.quick->compunit_symtab != NULL)
5259         expansion_notify (per_cu->v.quick->compunit_symtab);
5260     }
5261 }
5262
5263 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5264    matched, to expand corresponding CUs that were marked.  IDX is the
5265    index of the symbol name that matched.  */
5266
5267 static void
5268 dw2_expand_marked_cus
5269   (mapped_index &index, offset_type idx,
5270    struct objfile *objfile,
5271    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5272    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5273    search_domain kind)
5274 {
5275   offset_type *vec, vec_len, vec_idx;
5276   bool global_seen = false;
5277
5278   vec = (offset_type *) (index.constant_pool
5279                          + MAYBE_SWAP (index.symbol_table[idx + 1]));
5280   vec_len = MAYBE_SWAP (vec[0]);
5281   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5282     {
5283       struct dwarf2_per_cu_data *per_cu;
5284       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5285       /* This value is only valid for index versions >= 7.  */
5286       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5287       gdb_index_symbol_kind symbol_kind =
5288         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5289       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5290       /* Only check the symbol attributes if they're present.
5291          Indices prior to version 7 don't record them,
5292          and indices >= 7 may elide them for certain symbols
5293          (gold does this).  */
5294       int attrs_valid =
5295         (index.version >= 7
5296          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5297
5298       /* Work around gold/15646.  */
5299       if (attrs_valid)
5300         {
5301           if (!is_static && global_seen)
5302             continue;
5303           if (!is_static)
5304             global_seen = true;
5305         }
5306
5307       /* Only check the symbol's kind if it has one.  */
5308       if (attrs_valid)
5309         {
5310           switch (kind)
5311             {
5312             case VARIABLES_DOMAIN:
5313               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5314                 continue;
5315               break;
5316             case FUNCTIONS_DOMAIN:
5317               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5318                 continue;
5319               break;
5320             case TYPES_DOMAIN:
5321               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5322                 continue;
5323               break;
5324             default:
5325               break;
5326             }
5327         }
5328
5329       /* Don't crash on bad data.  */
5330       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5331                        + dwarf2_per_objfile->n_type_units))
5332         {
5333           complaint (&symfile_complaints,
5334                      _(".gdb_index entry has bad CU index"
5335                        " [in module %s]"), objfile_name (objfile));
5336           continue;
5337         }
5338
5339       per_cu = dw2_get_cutu (cu_index);
5340       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5341                                        expansion_notify);
5342     }
5343 }
5344
5345 /* If FILE_MATCHER is non-NULL, set all the
5346    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5347    that match FILE_MATCHER.  */
5348
5349 static void
5350 dw_expand_symtabs_matching_file_matcher
5351   (gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5352 {
5353   if (file_matcher == NULL)
5354     return;
5355
5356   objfile *const objfile = dwarf2_per_objfile->objfile;
5357
5358   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5359                                             htab_eq_pointer,
5360                                             NULL, xcalloc, xfree));
5361   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5362                                                 htab_eq_pointer,
5363                                                 NULL, xcalloc, xfree));
5364
5365   /* The rule is CUs specify all the files, including those used by
5366      any TU, so there's no need to scan TUs here.  */
5367
5368   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5369     {
5370       int j;
5371       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5372       struct quick_file_names *file_data;
5373       void **slot;
5374
5375       QUIT;
5376
5377       per_cu->v.quick->mark = 0;
5378
5379       /* We only need to look at symtabs not already expanded.  */
5380       if (per_cu->v.quick->compunit_symtab)
5381         continue;
5382
5383       file_data = dw2_get_file_names (per_cu);
5384       if (file_data == NULL)
5385         continue;
5386
5387       if (htab_find (visited_not_found.get (), file_data) != NULL)
5388         continue;
5389       else if (htab_find (visited_found.get (), file_data) != NULL)
5390         {
5391           per_cu->v.quick->mark = 1;
5392           continue;
5393         }
5394
5395       for (j = 0; j < file_data->num_file_names; ++j)
5396         {
5397           const char *this_real_name;
5398
5399           if (file_matcher (file_data->file_names[j], false))
5400             {
5401               per_cu->v.quick->mark = 1;
5402               break;
5403             }
5404
5405           /* Before we invoke realpath, which can get expensive when many
5406              files are involved, do a quick comparison of the basenames.  */
5407           if (!basenames_may_differ
5408               && !file_matcher (lbasename (file_data->file_names[j]),
5409                                 true))
5410             continue;
5411
5412           this_real_name = dw2_get_real_path (objfile, file_data, j);
5413           if (file_matcher (this_real_name, false))
5414             {
5415               per_cu->v.quick->mark = 1;
5416               break;
5417             }
5418         }
5419
5420       slot = htab_find_slot (per_cu->v.quick->mark
5421                              ? visited_found.get ()
5422                              : visited_not_found.get (),
5423                              file_data, INSERT);
5424       *slot = file_data;
5425     }
5426 }
5427
5428 static void
5429 dw2_expand_symtabs_matching
5430   (struct objfile *objfile,
5431    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5432    const lookup_name_info &lookup_name,
5433    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5434    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5435    enum search_domain kind)
5436 {
5437   int i;
5438
5439   dw2_setup (objfile);
5440
5441   /* index_table is NULL if OBJF_READNOW.  */
5442   if (!dwarf2_per_objfile->index_table)
5443     return;
5444
5445   dw_expand_symtabs_matching_file_matcher (file_matcher);
5446
5447   mapped_index &index = *dwarf2_per_objfile->index_table;
5448
5449   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5450                                       symbol_matcher,
5451                                       kind, [&] (offset_type idx)
5452     {
5453       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
5454                              expansion_notify, kind);
5455     });
5456 }
5457
5458 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5459    symtab.  */
5460
5461 static struct compunit_symtab *
5462 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5463                                           CORE_ADDR pc)
5464 {
5465   int i;
5466
5467   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5468       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5469     return cust;
5470
5471   if (cust->includes == NULL)
5472     return NULL;
5473
5474   for (i = 0; cust->includes[i]; ++i)
5475     {
5476       struct compunit_symtab *s = cust->includes[i];
5477
5478       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5479       if (s != NULL)
5480         return s;
5481     }
5482
5483   return NULL;
5484 }
5485
5486 static struct compunit_symtab *
5487 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5488                                   struct bound_minimal_symbol msymbol,
5489                                   CORE_ADDR pc,
5490                                   struct obj_section *section,
5491                                   int warn_if_readin)
5492 {
5493   struct dwarf2_per_cu_data *data;
5494   struct compunit_symtab *result;
5495
5496   dw2_setup (objfile);
5497
5498   if (!objfile->psymtabs_addrmap)
5499     return NULL;
5500
5501   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5502                                                      pc);
5503   if (!data)
5504     return NULL;
5505
5506   if (warn_if_readin && data->v.quick->compunit_symtab)
5507     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5508              paddress (get_objfile_arch (objfile), pc));
5509
5510   result
5511     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5512                                                 pc);
5513   gdb_assert (result != NULL);
5514   return result;
5515 }
5516
5517 static void
5518 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5519                           void *data, int need_fullname)
5520 {
5521   dw2_setup (objfile);
5522
5523   if (!dwarf2_per_objfile->filenames_cache)
5524     {
5525       dwarf2_per_objfile->filenames_cache.emplace ();
5526
5527       htab_up visited (htab_create_alloc (10,
5528                                           htab_hash_pointer, htab_eq_pointer,
5529                                           NULL, xcalloc, xfree));
5530
5531       /* The rule is CUs specify all the files, including those used
5532          by any TU, so there's no need to scan TUs here.  We can
5533          ignore file names coming from already-expanded CUs.  */
5534
5535       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5536         {
5537           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5538
5539           if (per_cu->v.quick->compunit_symtab)
5540             {
5541               void **slot = htab_find_slot (visited.get (),
5542                                             per_cu->v.quick->file_names,
5543                                             INSERT);
5544
5545               *slot = per_cu->v.quick->file_names;
5546             }
5547         }
5548
5549       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5550         {
5551           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5552           struct quick_file_names *file_data;
5553           void **slot;
5554
5555           /* We only need to look at symtabs not already expanded.  */
5556           if (per_cu->v.quick->compunit_symtab)
5557             continue;
5558
5559           file_data = dw2_get_file_names (per_cu);
5560           if (file_data == NULL)
5561             continue;
5562
5563           slot = htab_find_slot (visited.get (), file_data, INSERT);
5564           if (*slot)
5565             {
5566               /* Already visited.  */
5567               continue;
5568             }
5569           *slot = file_data;
5570
5571           for (int j = 0; j < file_data->num_file_names; ++j)
5572             {
5573               const char *filename = file_data->file_names[j];
5574               dwarf2_per_objfile->filenames_cache->seen (filename);
5575             }
5576         }
5577     }
5578
5579   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5580     {
5581       gdb::unique_xmalloc_ptr<char> this_real_name;
5582
5583       if (need_fullname)
5584         this_real_name = gdb_realpath (filename);
5585       (*fun) (filename, this_real_name.get (), data);
5586     });
5587 }
5588
5589 static int
5590 dw2_has_symbols (struct objfile *objfile)
5591 {
5592   return 1;
5593 }
5594
5595 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5596 {
5597   dw2_has_symbols,
5598   dw2_find_last_source_symtab,
5599   dw2_forget_cached_source_info,
5600   dw2_map_symtabs_matching_filename,
5601   dw2_lookup_symbol,
5602   dw2_print_stats,
5603   dw2_dump,
5604   dw2_relocate,
5605   dw2_expand_symtabs_for_function,
5606   dw2_expand_all_symtabs,
5607   dw2_expand_symtabs_with_fullname,
5608   dw2_map_matching_symbols,
5609   dw2_expand_symtabs_matching,
5610   dw2_find_pc_sect_compunit_symtab,
5611   NULL,
5612   dw2_map_symbol_filenames
5613 };
5614
5615 /* DWARF-5 debug_names reader.  */
5616
5617 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5618 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5619
5620 /* A helper function that reads the .debug_names section in SECTION
5621    and fills in MAP.  FILENAME is the name of the file containing the
5622    section; it is used for error reporting.
5623
5624    Returns true if all went well, false otherwise.  */
5625
5626 static bool
5627 read_debug_names_from_section (struct objfile *objfile,
5628                                const char *filename,
5629                                struct dwarf2_section_info *section,
5630                                mapped_debug_names &map)
5631 {
5632   if (dwarf2_section_empty_p (section))
5633     return false;
5634
5635   /* Older elfutils strip versions could keep the section in the main
5636      executable while splitting it for the separate debug info file.  */
5637   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5638     return false;
5639
5640   dwarf2_read_section (objfile, section);
5641
5642   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5643
5644   const gdb_byte *addr = section->buffer;
5645
5646   bfd *const abfd = get_section_bfd_owner (section);
5647
5648   unsigned int bytes_read;
5649   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5650   addr += bytes_read;
5651
5652   map.dwarf5_is_dwarf64 = bytes_read != 4;
5653   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5654   if (bytes_read + length != section->size)
5655     {
5656       /* There may be multiple per-CU indices.  */
5657       warning (_("Section .debug_names in %s length %s does not match "
5658                  "section length %s, ignoring .debug_names."),
5659                filename, plongest (bytes_read + length),
5660                pulongest (section->size));
5661       return false;
5662     }
5663
5664   /* The version number.  */
5665   uint16_t version = read_2_bytes (abfd, addr);
5666   addr += 2;
5667   if (version != 5)
5668     {
5669       warning (_("Section .debug_names in %s has unsupported version %d, "
5670                  "ignoring .debug_names."),
5671                filename, version);
5672       return false;
5673     }
5674
5675   /* Padding.  */
5676   uint16_t padding = read_2_bytes (abfd, addr);
5677   addr += 2;
5678   if (padding != 0)
5679     {
5680       warning (_("Section .debug_names in %s has unsupported padding %d, "
5681                  "ignoring .debug_names."),
5682                filename, padding);
5683       return false;
5684     }
5685
5686   /* comp_unit_count - The number of CUs in the CU list.  */
5687   map.cu_count = read_4_bytes (abfd, addr);
5688   addr += 4;
5689
5690   /* local_type_unit_count - The number of TUs in the local TU
5691      list.  */
5692   map.tu_count = read_4_bytes (abfd, addr);
5693   addr += 4;
5694
5695   /* foreign_type_unit_count - The number of TUs in the foreign TU
5696      list.  */
5697   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5698   addr += 4;
5699   if (foreign_tu_count != 0)
5700     {
5701       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5702                  "ignoring .debug_names."),
5703                filename, static_cast<unsigned long> (foreign_tu_count));
5704       return false;
5705     }
5706
5707   /* bucket_count - The number of hash buckets in the hash lookup
5708      table.  */
5709   map.bucket_count = read_4_bytes (abfd, addr);
5710   addr += 4;
5711
5712   /* name_count - The number of unique names in the index.  */
5713   map.name_count = read_4_bytes (abfd, addr);
5714   addr += 4;
5715
5716   /* abbrev_table_size - The size in bytes of the abbreviations
5717      table.  */
5718   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5719   addr += 4;
5720
5721   /* augmentation_string_size - The size in bytes of the augmentation
5722      string.  This value is rounded up to a multiple of 4.  */
5723   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5724   addr += 4;
5725   map.augmentation_is_gdb = ((augmentation_string_size
5726                               == sizeof (dwarf5_augmentation))
5727                              && memcmp (addr, dwarf5_augmentation,
5728                                         sizeof (dwarf5_augmentation)) == 0);
5729   augmentation_string_size += (-augmentation_string_size) & 3;
5730   addr += augmentation_string_size;
5731
5732   /* List of CUs */
5733   map.cu_table_reordered = addr;
5734   addr += map.cu_count * map.offset_size;
5735
5736   /* List of Local TUs */
5737   map.tu_table_reordered = addr;
5738   addr += map.tu_count * map.offset_size;
5739
5740   /* Hash Lookup Table */
5741   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5742   addr += map.bucket_count * 4;
5743   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5744   addr += map.name_count * 4;
5745
5746   /* Name Table */
5747   map.name_table_string_offs_reordered = addr;
5748   addr += map.name_count * map.offset_size;
5749   map.name_table_entry_offs_reordered = addr;
5750   addr += map.name_count * map.offset_size;
5751
5752   const gdb_byte *abbrev_table_start = addr;
5753   for (;;)
5754     {
5755       unsigned int bytes_read;
5756       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5757       addr += bytes_read;
5758       if (index_num == 0)
5759         break;
5760
5761       const auto insertpair
5762         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5763       if (!insertpair.second)
5764         {
5765           warning (_("Section .debug_names in %s has duplicate index %s, "
5766                      "ignoring .debug_names."),
5767                    filename, pulongest (index_num));
5768           return false;
5769         }
5770       mapped_debug_names::index_val &indexval = insertpair.first->second;
5771       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5772       addr += bytes_read;
5773
5774       for (;;)
5775         {
5776           mapped_debug_names::index_val::attr attr;
5777           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5778           addr += bytes_read;
5779           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5780           addr += bytes_read;
5781           if (attr.form == DW_FORM_implicit_const)
5782             {
5783               attr.implicit_const = read_signed_leb128 (abfd, addr,
5784                                                         &bytes_read);
5785               addr += bytes_read;
5786             }
5787           if (attr.dw_idx == 0 && attr.form == 0)
5788             break;
5789           indexval.attr_vec.push_back (std::move (attr));
5790         }
5791     }
5792   if (addr != abbrev_table_start + abbrev_table_size)
5793     {
5794       warning (_("Section .debug_names in %s has abbreviation_table "
5795                  "of size %zu vs. written as %u, ignoring .debug_names."),
5796                filename, addr - abbrev_table_start, abbrev_table_size);
5797       return false;
5798     }
5799   map.entry_pool = addr;
5800
5801   return true;
5802 }
5803
5804 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5805    list.  */
5806
5807 static void
5808 create_cus_from_debug_names_list (struct objfile *objfile,
5809                                   const mapped_debug_names &map,
5810                                   dwarf2_section_info &section,
5811                                   bool is_dwz, int base_offset)
5812 {
5813   sect_offset sect_off_prev;
5814   for (uint32_t i = 0; i <= map.cu_count; ++i)
5815     {
5816       sect_offset sect_off_next;
5817       if (i < map.cu_count)
5818         {
5819           sect_off_next
5820             = (sect_offset) (extract_unsigned_integer
5821                              (map.cu_table_reordered + i * map.offset_size,
5822                               map.offset_size,
5823                               map.dwarf5_byte_order));
5824         }
5825       else
5826         sect_off_next = (sect_offset) section.size;
5827       if (i >= 1)
5828         {
5829           const ULONGEST length = sect_off_next - sect_off_prev;
5830           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5831             = create_cu_from_index_list (objfile, &section, is_dwz,
5832                                          sect_off_prev, length);
5833         }
5834       sect_off_prev = sect_off_next;
5835     }
5836 }
5837
5838 /* Read the CU list from the mapped index, and use it to create all
5839    the CU objects for this objfile.  */
5840
5841 static void
5842 create_cus_from_debug_names (struct objfile *objfile,
5843                              const mapped_debug_names &map,
5844                              const mapped_debug_names &dwz_map)
5845 {
5846
5847   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5848   dwarf2_per_objfile->all_comp_units
5849     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5850                  dwarf2_per_objfile->n_comp_units);
5851
5852   create_cus_from_debug_names_list (objfile, map, dwarf2_per_objfile->info,
5853                                     false /* is_dwz */,
5854                                     0 /* base_offset */);
5855
5856   if (dwz_map.cu_count == 0)
5857     return;
5858
5859   dwz_file *dwz = dwarf2_get_dwz_file ();
5860   create_cus_from_debug_names_list (objfile, dwz_map, dwz->info,
5861                                     true /* is_dwz */,
5862                                     map.cu_count /* base_offset */);
5863 }
5864
5865 /* Read .debug_names.  If everything went ok, initialize the "quick"
5866    elements of all the CUs and return true.  Otherwise, return false.  */
5867
5868 static bool
5869 dwarf2_read_debug_names (struct objfile *objfile)
5870 {
5871   mapped_debug_names local_map, dwz_map;
5872
5873   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5874                                       &dwarf2_per_objfile->debug_names,
5875                                       local_map))
5876     return false;
5877
5878   /* Don't use the index if it's empty.  */
5879   if (local_map.name_count == 0)
5880     return false;
5881
5882   /* If there is a .dwz file, read it so we can get its CU list as
5883      well.  */
5884   dwz_file *dwz = dwarf2_get_dwz_file ();
5885   if (dwz != NULL)
5886     {
5887       if (!read_debug_names_from_section (objfile,
5888                                           bfd_get_filename (dwz->dwz_bfd),
5889                                           &dwz->debug_names, dwz_map))
5890         {
5891           warning (_("could not read '.debug_names' section from %s; skipping"),
5892                    bfd_get_filename (dwz->dwz_bfd));
5893           return false;
5894         }
5895     }
5896
5897   create_cus_from_debug_names (objfile, local_map, dwz_map);
5898
5899   if (local_map.tu_count != 0)
5900     {
5901       /* We can only handle a single .debug_types when we have an
5902          index.  */
5903       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5904         return false;
5905
5906       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5907                                                 dwarf2_per_objfile->types, 0);
5908
5909       create_signatured_type_table_from_debug_names
5910         (objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5911     }
5912
5913   create_addrmap_from_aranges (objfile, &dwarf2_per_objfile->debug_aranges);
5914
5915   dwarf2_per_objfile->debug_names_table.reset (new mapped_debug_names);
5916   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5917   dwarf2_per_objfile->using_index = 1;
5918   dwarf2_per_objfile->quick_file_names_table =
5919     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5920
5921   return true;
5922 }
5923
5924 /* Symbol name hashing function as specified by DWARF-5.  */
5925
5926 static uint32_t
5927 dwarf5_djb_hash (const char *str_)
5928 {
5929   const unsigned char *str = (const unsigned char *) str_;
5930
5931   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
5932      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
5933
5934   uint32_t hash = 5381;
5935   while (int c = *str++)
5936     hash = hash * 33 + tolower (c);
5937   return hash;
5938 }
5939
5940 /* Type used to manage iterating over all CUs looking for a symbol for
5941    .debug_names.  */
5942
5943 class dw2_debug_names_iterator
5944 {
5945 public:
5946   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5947      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5948   dw2_debug_names_iterator (const mapped_debug_names &map,
5949                             bool want_specific_block,
5950                             block_enum block_index, domain_enum domain,
5951                             const char *name)
5952     : m_map (map), m_want_specific_block (want_specific_block),
5953       m_block_index (block_index), m_domain (domain),
5954       m_addr (find_vec_in_debug_names (map, name))
5955   {}
5956
5957   dw2_debug_names_iterator (const mapped_debug_names &map,
5958                             search_domain search, uint32_t namei)
5959     : m_map (map),
5960       m_search (search),
5961       m_addr (find_vec_in_debug_names (map, namei))
5962   {}
5963
5964   /* Return the next matching CU or NULL if there are no more.  */
5965   dwarf2_per_cu_data *next ();
5966
5967 private:
5968   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5969                                                   const char *name);
5970   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5971                                                   uint32_t namei);
5972
5973   /* The internalized form of .debug_names.  */
5974   const mapped_debug_names &m_map;
5975
5976   /* If true, only look for symbols that match BLOCK_INDEX.  */
5977   const bool m_want_specific_block = false;
5978
5979   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5980      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5981      value.  */
5982   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5983
5984   /* The kind of symbol we're looking for.  */
5985   const domain_enum m_domain = UNDEF_DOMAIN;
5986   const search_domain m_search = ALL_DOMAIN;
5987
5988   /* The list of CUs from the index entry of the symbol, or NULL if
5989      not found.  */
5990   const gdb_byte *m_addr;
5991 };
5992
5993 const char *
5994 mapped_debug_names::namei_to_name (uint32_t namei) const
5995 {
5996   const ULONGEST namei_string_offs
5997     = extract_unsigned_integer ((name_table_string_offs_reordered
5998                                  + namei * offset_size),
5999                                 offset_size,
6000                                 dwarf5_byte_order);
6001   return read_indirect_string_at_offset
6002     (dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6003 }
6004
6005 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6006    found, return pointer to its pool data.  If NAME cannot be found,
6007    return NULL.  */
6008
6009 const gdb_byte *
6010 dw2_debug_names_iterator::find_vec_in_debug_names
6011   (const mapped_debug_names &map, const char *name)
6012 {
6013   int (*cmp) (const char *, const char *);
6014
6015   if (current_language->la_language == language_cplus
6016       || current_language->la_language == language_fortran
6017       || current_language->la_language == language_d)
6018     {
6019       /* NAME is already canonical.  Drop any qualifiers as
6020          .debug_names does not contain any.  */
6021
6022       if (strchr (name, '(') != NULL)
6023         {
6024           gdb::unique_xmalloc_ptr<char> without_params
6025             = cp_remove_params (name);
6026
6027           if (without_params != NULL)
6028             {
6029               name = without_params.get();
6030             }
6031         }
6032     }
6033
6034   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6035
6036   const uint32_t full_hash = dwarf5_djb_hash (name);
6037   uint32_t namei
6038     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6039                                 (map.bucket_table_reordered
6040                                  + (full_hash % map.bucket_count)), 4,
6041                                 map.dwarf5_byte_order);
6042   if (namei == 0)
6043     return NULL;
6044   --namei;
6045   if (namei >= map.name_count)
6046     {
6047       complaint (&symfile_complaints,
6048                  _("Wrong .debug_names with name index %u but name_count=%u "
6049                    "[in module %s]"),
6050                  namei, map.name_count,
6051                  objfile_name (dwarf2_per_objfile->objfile));
6052       return NULL;
6053     }
6054
6055   for (;;)
6056     {
6057       const uint32_t namei_full_hash
6058         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6059                                     (map.hash_table_reordered + namei), 4,
6060                                     map.dwarf5_byte_order);
6061       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6062         return NULL;
6063
6064       if (full_hash == namei_full_hash)
6065         {
6066           const char *const namei_string = map.namei_to_name (namei);
6067
6068 #if 0 /* An expensive sanity check.  */
6069           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6070             {
6071               complaint (&symfile_complaints,
6072                          _("Wrong .debug_names hash for string at index %u "
6073                            "[in module %s]"),
6074                          namei, objfile_name (dwarf2_per_objfile->objfile));
6075               return NULL;
6076             }
6077 #endif
6078
6079           if (cmp (namei_string, name) == 0)
6080             {
6081               const ULONGEST namei_entry_offs
6082                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6083                                              + namei * map.offset_size),
6084                                             map.offset_size, map.dwarf5_byte_order);
6085               return map.entry_pool + namei_entry_offs;
6086             }
6087         }
6088
6089       ++namei;
6090       if (namei >= map.name_count)
6091         return NULL;
6092     }
6093 }
6094
6095 const gdb_byte *
6096 dw2_debug_names_iterator::find_vec_in_debug_names
6097   (const mapped_debug_names &map, uint32_t namei)
6098 {
6099   if (namei >= map.name_count)
6100     {
6101       complaint (&symfile_complaints,
6102                  _("Wrong .debug_names with name index %u but name_count=%u "
6103                    "[in module %s]"),
6104                  namei, map.name_count,
6105                  objfile_name (dwarf2_per_objfile->objfile));
6106       return NULL;
6107     }
6108
6109   const ULONGEST namei_entry_offs
6110     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6111                                  + namei * map.offset_size),
6112                                 map.offset_size, map.dwarf5_byte_order);
6113   return map.entry_pool + namei_entry_offs;
6114 }
6115
6116 /* See dw2_debug_names_iterator.  */
6117
6118 dwarf2_per_cu_data *
6119 dw2_debug_names_iterator::next ()
6120 {
6121   if (m_addr == NULL)
6122     return NULL;
6123
6124   bfd *const abfd = dwarf2_per_objfile->objfile->obfd;
6125
6126  again:
6127
6128   unsigned int bytes_read;
6129   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6130   m_addr += bytes_read;
6131   if (abbrev == 0)
6132     return NULL;
6133
6134   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6135   if (indexval_it == m_map.abbrev_map.cend ())
6136     {
6137       complaint (&symfile_complaints,
6138                  _("Wrong .debug_names undefined abbrev code %s "
6139                    "[in module %s]"),
6140                  pulongest (abbrev), objfile_name (dwarf2_per_objfile->objfile));
6141       return NULL;
6142     }
6143   const mapped_debug_names::index_val &indexval = indexval_it->second;
6144   bool have_is_static = false;
6145   bool is_static;
6146   dwarf2_per_cu_data *per_cu = NULL;
6147   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6148     {
6149       ULONGEST ull;
6150       switch (attr.form)
6151         {
6152         case DW_FORM_implicit_const:
6153           ull = attr.implicit_const;
6154           break;
6155         case DW_FORM_flag_present:
6156           ull = 1;
6157           break;
6158         case DW_FORM_udata:
6159           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6160           m_addr += bytes_read;
6161           break;
6162         default:
6163           complaint (&symfile_complaints,
6164                      _("Unsupported .debug_names form %s [in module %s]"),
6165                      dwarf_form_name (attr.form),
6166                      objfile_name (dwarf2_per_objfile->objfile));
6167           return NULL;
6168         }
6169       switch (attr.dw_idx)
6170         {
6171         case DW_IDX_compile_unit:
6172           /* Don't crash on bad data.  */
6173           if (ull >= (dwarf2_per_objfile->n_comp_units
6174                       + dwarf2_per_objfile->n_type_units))
6175             {
6176               complaint (&symfile_complaints,
6177                          _(".debug_names entry has bad CU index %s"
6178                            " [in module %s]"),
6179                          pulongest (ull),
6180                          objfile_name (dwarf2_per_objfile->objfile));
6181               continue;
6182             }
6183           per_cu = dw2_get_cutu (ull);
6184           break;
6185         case DW_IDX_GNU_internal:
6186           if (!m_map.augmentation_is_gdb)
6187             break;
6188           have_is_static = true;
6189           is_static = true;
6190           break;
6191         case DW_IDX_GNU_external:
6192           if (!m_map.augmentation_is_gdb)
6193             break;
6194           have_is_static = true;
6195           is_static = false;
6196           break;
6197         }
6198     }
6199
6200   /* Skip if already read in.  */
6201   if (per_cu->v.quick->compunit_symtab)
6202     goto again;
6203
6204   /* Check static vs global.  */
6205   if (have_is_static)
6206     {
6207       const bool want_static = m_block_index != GLOBAL_BLOCK;
6208       if (m_want_specific_block && want_static != is_static)
6209         goto again;
6210     }
6211
6212   /* Match dw2_symtab_iter_next, symbol_kind
6213      and debug_names::psymbol_tag.  */
6214   switch (m_domain)
6215     {
6216     case VAR_DOMAIN:
6217       switch (indexval.dwarf_tag)
6218         {
6219         case DW_TAG_variable:
6220         case DW_TAG_subprogram:
6221         /* Some types are also in VAR_DOMAIN.  */
6222         case DW_TAG_typedef:
6223         case DW_TAG_structure_type:
6224           break;
6225         default:
6226           goto again;
6227         }
6228       break;
6229     case STRUCT_DOMAIN:
6230       switch (indexval.dwarf_tag)
6231         {
6232         case DW_TAG_typedef:
6233         case DW_TAG_structure_type:
6234           break;
6235         default:
6236           goto again;
6237         }
6238       break;
6239     case LABEL_DOMAIN:
6240       switch (indexval.dwarf_tag)
6241         {
6242         case 0:
6243         case DW_TAG_variable:
6244           break;
6245         default:
6246           goto again;
6247         }
6248       break;
6249     default:
6250       break;
6251     }
6252
6253   /* Match dw2_expand_symtabs_matching, symbol_kind and
6254      debug_names::psymbol_tag.  */
6255   switch (m_search)
6256     {
6257     case VARIABLES_DOMAIN:
6258       switch (indexval.dwarf_tag)
6259         {
6260         case DW_TAG_variable:
6261           break;
6262         default:
6263           goto again;
6264         }
6265       break;
6266     case FUNCTIONS_DOMAIN:
6267       switch (indexval.dwarf_tag)
6268         {
6269         case DW_TAG_subprogram:
6270           break;
6271         default:
6272           goto again;
6273         }
6274       break;
6275     case TYPES_DOMAIN:
6276       switch (indexval.dwarf_tag)
6277         {
6278         case DW_TAG_typedef:
6279         case DW_TAG_structure_type:
6280           break;
6281         default:
6282           goto again;
6283         }
6284       break;
6285     default:
6286       break;
6287     }
6288
6289   return per_cu;
6290 }
6291
6292 static struct compunit_symtab *
6293 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6294                                const char *name, domain_enum domain)
6295 {
6296   const block_enum block_index = static_cast<block_enum> (block_index_int);
6297   dw2_setup (objfile);
6298
6299   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6300   if (!mapp)
6301     {
6302       /* index is NULL if OBJF_READNOW.  */
6303       return NULL;
6304     }
6305   const auto &map = *mapp;
6306
6307   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6308                                  block_index, domain, name);
6309
6310   struct compunit_symtab *stab_best = NULL;
6311   struct dwarf2_per_cu_data *per_cu;
6312   while ((per_cu = iter.next ()) != NULL)
6313     {
6314       struct symbol *sym, *with_opaque = NULL;
6315       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6316       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6317       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6318
6319       sym = block_find_symbol (block, name, domain,
6320                                block_find_non_opaque_type_preferred,
6321                                &with_opaque);
6322
6323       /* Some caution must be observed with overloaded functions and
6324          methods, since the index will not contain any overload
6325          information (but NAME might contain it).  */
6326
6327       if (sym != NULL
6328           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6329         return stab;
6330       if (with_opaque != NULL
6331           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6332         stab_best = stab;
6333
6334       /* Keep looking through other CUs.  */
6335     }
6336
6337   return stab_best;
6338 }
6339
6340 /* This dumps minimal information about .debug_names.  It is called
6341    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6342    uses this to verify that .debug_names has been loaded.  */
6343
6344 static void
6345 dw2_debug_names_dump (struct objfile *objfile)
6346 {
6347   dw2_setup (objfile);
6348   gdb_assert (dwarf2_per_objfile->using_index);
6349   printf_filtered (".debug_names:");
6350   if (dwarf2_per_objfile->debug_names_table)
6351     printf_filtered (" exists\n");
6352   else
6353     printf_filtered (" faked for \"readnow\"\n");
6354   printf_filtered ("\n");
6355 }
6356
6357 static void
6358 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6359                                              const char *func_name)
6360 {
6361   dw2_setup (objfile);
6362
6363   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6364   if (dwarf2_per_objfile->debug_names_table)
6365     {
6366       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6367
6368       /* Note: It doesn't matter what we pass for block_index here.  */
6369       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6370                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6371
6372       struct dwarf2_per_cu_data *per_cu;
6373       while ((per_cu = iter.next ()) != NULL)
6374         dw2_instantiate_symtab (per_cu);
6375     }
6376 }
6377
6378 static void
6379 dw2_debug_names_expand_symtabs_matching
6380   (struct objfile *objfile,
6381    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6382    const lookup_name_info &lookup_name,
6383    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6384    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6385    enum search_domain kind)
6386 {
6387   dw2_setup (objfile);
6388
6389   /* debug_names_table is NULL if OBJF_READNOW.  */
6390   if (!dwarf2_per_objfile->debug_names_table)
6391     return;
6392
6393   dw_expand_symtabs_matching_file_matcher (file_matcher);
6394
6395   const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6396
6397   for (uint32_t namei = 0; namei < map.name_count; ++namei)
6398     {
6399       QUIT;
6400
6401       const char *const namei_string = map.namei_to_name (namei);
6402       if (symbol_matcher != NULL && !symbol_matcher (namei_string))
6403         continue;
6404
6405       /* The name was matched, now expand corresponding CUs that were
6406          marked.  */
6407       dw2_debug_names_iterator iter (map, kind, namei);
6408
6409       struct dwarf2_per_cu_data *per_cu;
6410       while ((per_cu = iter.next ()) != NULL)
6411         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6412                                          expansion_notify);
6413     }
6414 }
6415
6416 const struct quick_symbol_functions dwarf2_debug_names_functions =
6417 {
6418   dw2_has_symbols,
6419   dw2_find_last_source_symtab,
6420   dw2_forget_cached_source_info,
6421   dw2_map_symtabs_matching_filename,
6422   dw2_debug_names_lookup_symbol,
6423   dw2_print_stats,
6424   dw2_debug_names_dump,
6425   dw2_relocate,
6426   dw2_debug_names_expand_symtabs_for_function,
6427   dw2_expand_all_symtabs,
6428   dw2_expand_symtabs_with_fullname,
6429   dw2_map_matching_symbols,
6430   dw2_debug_names_expand_symtabs_matching,
6431   dw2_find_pc_sect_compunit_symtab,
6432   NULL,
6433   dw2_map_symbol_filenames
6434 };
6435
6436 /* Initialize for reading DWARF for this objfile.  Return 0 if this
6437    file will use psymtabs, or 1 if using the GNU index.  */
6438
6439 const sym_fns &
6440 dwarf2_initialize_objfile (struct objfile *objfile)
6441 {
6442   /* If we're about to read full symbols, don't bother with the
6443      indices.  In this case we also don't care if some other debug
6444      format is making psymtabs, because they are all about to be
6445      expanded anyway.  */
6446   if ((objfile->flags & OBJF_READNOW))
6447     {
6448       int i;
6449
6450       dwarf2_per_objfile->using_index = 1;
6451       create_all_comp_units (objfile);
6452       create_all_type_units (objfile);
6453       dwarf2_per_objfile->quick_file_names_table =
6454         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6455
6456       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6457                        + dwarf2_per_objfile->n_type_units); ++i)
6458         {
6459           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6460
6461           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6462                                             struct dwarf2_per_cu_quick_data);
6463         }
6464
6465       /* Return 1 so that gdb sees the "quick" functions.  However,
6466          these functions will be no-ops because we will have expanded
6467          all symtabs.  */
6468       return elf_sym_fns_gdb_index;
6469     }
6470
6471   if (dwarf2_read_debug_names (objfile))
6472     return elf_sym_fns_debug_names;
6473
6474   if (dwarf2_read_index (objfile))
6475     return elf_sym_fns_gdb_index;
6476
6477   return elf_sym_fns_lazy_psyms;
6478 }
6479
6480 \f
6481
6482 /* Build a partial symbol table.  */
6483
6484 void
6485 dwarf2_build_psymtabs (struct objfile *objfile)
6486 {
6487
6488   if (objfile->global_psymbols.capacity () == 0
6489       && objfile->static_psymbols.capacity () == 0)
6490     init_psymbol_list (objfile, 1024);
6491
6492   TRY
6493     {
6494       /* This isn't really ideal: all the data we allocate on the
6495          objfile's obstack is still uselessly kept around.  However,
6496          freeing it seems unsafe.  */
6497       psymtab_discarder psymtabs (objfile);
6498       dwarf2_build_psymtabs_hard (objfile);
6499       psymtabs.keep ();
6500     }
6501   CATCH (except, RETURN_MASK_ERROR)
6502     {
6503       exception_print (gdb_stderr, except);
6504     }
6505   END_CATCH
6506 }
6507
6508 /* Return the total length of the CU described by HEADER.  */
6509
6510 static unsigned int
6511 get_cu_length (const struct comp_unit_head *header)
6512 {
6513   return header->initial_length_size + header->length;
6514 }
6515
6516 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6517
6518 static inline bool
6519 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6520 {
6521   sect_offset bottom = cu_header->sect_off;
6522   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6523
6524   return sect_off >= bottom && sect_off < top;
6525 }
6526
6527 /* Find the base address of the compilation unit for range lists and
6528    location lists.  It will normally be specified by DW_AT_low_pc.
6529    In DWARF-3 draft 4, the base address could be overridden by
6530    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6531    compilation units with discontinuous ranges.  */
6532
6533 static void
6534 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6535 {
6536   struct attribute *attr;
6537
6538   cu->base_known = 0;
6539   cu->base_address = 0;
6540
6541   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6542   if (attr)
6543     {
6544       cu->base_address = attr_value_as_address (attr);
6545       cu->base_known = 1;
6546     }
6547   else
6548     {
6549       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6550       if (attr)
6551         {
6552           cu->base_address = attr_value_as_address (attr);
6553           cu->base_known = 1;
6554         }
6555     }
6556 }
6557
6558 /* Read in the comp unit header information from the debug_info at info_ptr.
6559    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6560    NOTE: This leaves members offset, first_die_offset to be filled in
6561    by the caller.  */
6562
6563 static const gdb_byte *
6564 read_comp_unit_head (struct comp_unit_head *cu_header,
6565                      const gdb_byte *info_ptr,
6566                      struct dwarf2_section_info *section,
6567                      rcuh_kind section_kind)
6568 {
6569   int signed_addr;
6570   unsigned int bytes_read;
6571   const char *filename = get_section_file_name (section);
6572   bfd *abfd = get_section_bfd_owner (section);
6573
6574   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6575   cu_header->initial_length_size = bytes_read;
6576   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6577   info_ptr += bytes_read;
6578   cu_header->version = read_2_bytes (abfd, info_ptr);
6579   info_ptr += 2;
6580   if (cu_header->version < 5)
6581     switch (section_kind)
6582       {
6583       case rcuh_kind::COMPILE:
6584         cu_header->unit_type = DW_UT_compile;
6585         break;
6586       case rcuh_kind::TYPE:
6587         cu_header->unit_type = DW_UT_type;
6588         break;
6589       default:
6590         internal_error (__FILE__, __LINE__,
6591                         _("read_comp_unit_head: invalid section_kind"));
6592       }
6593   else
6594     {
6595       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6596                                                  (read_1_byte (abfd, info_ptr));
6597       info_ptr += 1;
6598       switch (cu_header->unit_type)
6599         {
6600         case DW_UT_compile:
6601           if (section_kind != rcuh_kind::COMPILE)
6602             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6603                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6604                    filename);
6605           break;
6606         case DW_UT_type:
6607           section_kind = rcuh_kind::TYPE;
6608           break;
6609         default:
6610           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6611                  "(is %d, should be %d or %d) [in module %s]"),
6612                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6613         }
6614
6615       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6616       info_ptr += 1;
6617     }
6618   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6619                                                           cu_header,
6620                                                           &bytes_read);
6621   info_ptr += bytes_read;
6622   if (cu_header->version < 5)
6623     {
6624       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6625       info_ptr += 1;
6626     }
6627   signed_addr = bfd_get_sign_extend_vma (abfd);
6628   if (signed_addr < 0)
6629     internal_error (__FILE__, __LINE__,
6630                     _("read_comp_unit_head: dwarf from non elf file"));
6631   cu_header->signed_addr_p = signed_addr;
6632
6633   if (section_kind == rcuh_kind::TYPE)
6634     {
6635       LONGEST type_offset;
6636
6637       cu_header->signature = read_8_bytes (abfd, info_ptr);
6638       info_ptr += 8;
6639
6640       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6641       info_ptr += bytes_read;
6642       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6643       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6644         error (_("Dwarf Error: Too big type_offset in compilation unit "
6645                "header (is %s) [in module %s]"), plongest (type_offset),
6646                filename);
6647     }
6648
6649   return info_ptr;
6650 }
6651
6652 /* Helper function that returns the proper abbrev section for
6653    THIS_CU.  */
6654
6655 static struct dwarf2_section_info *
6656 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6657 {
6658   struct dwarf2_section_info *abbrev;
6659
6660   if (this_cu->is_dwz)
6661     abbrev = &dwarf2_get_dwz_file ()->abbrev;
6662   else
6663     abbrev = &dwarf2_per_objfile->abbrev;
6664
6665   return abbrev;
6666 }
6667
6668 /* Subroutine of read_and_check_comp_unit_head and
6669    read_and_check_type_unit_head to simplify them.
6670    Perform various error checking on the header.  */
6671
6672 static void
6673 error_check_comp_unit_head (struct comp_unit_head *header,
6674                             struct dwarf2_section_info *section,
6675                             struct dwarf2_section_info *abbrev_section)
6676 {
6677   const char *filename = get_section_file_name (section);
6678
6679   if (header->version < 2 || header->version > 5)
6680     error (_("Dwarf Error: wrong version in compilation unit header "
6681            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6682            filename);
6683
6684   if (to_underlying (header->abbrev_sect_off)
6685       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6686     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6687            "(offset 0x%x + 6) [in module %s]"),
6688            to_underlying (header->abbrev_sect_off),
6689            to_underlying (header->sect_off),
6690            filename);
6691
6692   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6693      avoid potential 32-bit overflow.  */
6694   if (((ULONGEST) header->sect_off + get_cu_length (header))
6695       > section->size)
6696     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6697            "(offset 0x%x + 0) [in module %s]"),
6698            header->length, to_underlying (header->sect_off),
6699            filename);
6700 }
6701
6702 /* Read in a CU/TU header and perform some basic error checking.
6703    The contents of the header are stored in HEADER.
6704    The result is a pointer to the start of the first DIE.  */
6705
6706 static const gdb_byte *
6707 read_and_check_comp_unit_head (struct comp_unit_head *header,
6708                                struct dwarf2_section_info *section,
6709                                struct dwarf2_section_info *abbrev_section,
6710                                const gdb_byte *info_ptr,
6711                                rcuh_kind section_kind)
6712 {
6713   const gdb_byte *beg_of_comp_unit = info_ptr;
6714
6715   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6716
6717   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6718
6719   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6720
6721   error_check_comp_unit_head (header, section, abbrev_section);
6722
6723   return info_ptr;
6724 }
6725
6726 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6727
6728 static sect_offset
6729 read_abbrev_offset (struct dwarf2_section_info *section,
6730                     sect_offset sect_off)
6731 {
6732   bfd *abfd = get_section_bfd_owner (section);
6733   const gdb_byte *info_ptr;
6734   unsigned int initial_length_size, offset_size;
6735   uint16_t version;
6736
6737   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6738   info_ptr = section->buffer + to_underlying (sect_off);
6739   read_initial_length (abfd, info_ptr, &initial_length_size);
6740   offset_size = initial_length_size == 4 ? 4 : 8;
6741   info_ptr += initial_length_size;
6742
6743   version = read_2_bytes (abfd, info_ptr);
6744   info_ptr += 2;
6745   if (version >= 5)
6746     {
6747       /* Skip unit type and address size.  */
6748       info_ptr += 2;
6749     }
6750
6751   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6752 }
6753
6754 /* Allocate a new partial symtab for file named NAME and mark this new
6755    partial symtab as being an include of PST.  */
6756
6757 static void
6758 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6759                                struct objfile *objfile)
6760 {
6761   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6762
6763   if (!IS_ABSOLUTE_PATH (subpst->filename))
6764     {
6765       /* It shares objfile->objfile_obstack.  */
6766       subpst->dirname = pst->dirname;
6767     }
6768
6769   subpst->textlow = 0;
6770   subpst->texthigh = 0;
6771
6772   subpst->dependencies
6773     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6774   subpst->dependencies[0] = pst;
6775   subpst->number_of_dependencies = 1;
6776
6777   subpst->globals_offset = 0;
6778   subpst->n_global_syms = 0;
6779   subpst->statics_offset = 0;
6780   subpst->n_static_syms = 0;
6781   subpst->compunit_symtab = NULL;
6782   subpst->read_symtab = pst->read_symtab;
6783   subpst->readin = 0;
6784
6785   /* No private part is necessary for include psymtabs.  This property
6786      can be used to differentiate between such include psymtabs and
6787      the regular ones.  */
6788   subpst->read_symtab_private = NULL;
6789 }
6790
6791 /* Read the Line Number Program data and extract the list of files
6792    included by the source file represented by PST.  Build an include
6793    partial symtab for each of these included files.  */
6794
6795 static void
6796 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6797                                struct die_info *die,
6798                                struct partial_symtab *pst)
6799 {
6800   line_header_up lh;
6801   struct attribute *attr;
6802
6803   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6804   if (attr)
6805     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6806   if (lh == NULL)
6807     return;  /* No linetable, so no includes.  */
6808
6809   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6810   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6811 }
6812
6813 static hashval_t
6814 hash_signatured_type (const void *item)
6815 {
6816   const struct signatured_type *sig_type
6817     = (const struct signatured_type *) item;
6818
6819   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6820   return sig_type->signature;
6821 }
6822
6823 static int
6824 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6825 {
6826   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6827   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6828
6829   return lhs->signature == rhs->signature;
6830 }
6831
6832 /* Allocate a hash table for signatured types.  */
6833
6834 static htab_t
6835 allocate_signatured_type_table (struct objfile *objfile)
6836 {
6837   return htab_create_alloc_ex (41,
6838                                hash_signatured_type,
6839                                eq_signatured_type,
6840                                NULL,
6841                                &objfile->objfile_obstack,
6842                                hashtab_obstack_allocate,
6843                                dummy_obstack_deallocate);
6844 }
6845
6846 /* A helper function to add a signatured type CU to a table.  */
6847
6848 static int
6849 add_signatured_type_cu_to_table (void **slot, void *datum)
6850 {
6851   struct signatured_type *sigt = (struct signatured_type *) *slot;
6852   struct signatured_type ***datap = (struct signatured_type ***) datum;
6853
6854   **datap = sigt;
6855   ++*datap;
6856
6857   return 1;
6858 }
6859
6860 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6861    and fill them into TYPES_HTAB.  It will process only type units,
6862    therefore DW_UT_type.  */
6863
6864 static void
6865 create_debug_type_hash_table (struct dwo_file *dwo_file,
6866                               dwarf2_section_info *section, htab_t &types_htab,
6867                               rcuh_kind section_kind)
6868 {
6869   struct objfile *objfile = dwarf2_per_objfile->objfile;
6870   struct dwarf2_section_info *abbrev_section;
6871   bfd *abfd;
6872   const gdb_byte *info_ptr, *end_ptr;
6873
6874   abbrev_section = (dwo_file != NULL
6875                     ? &dwo_file->sections.abbrev
6876                     : &dwarf2_per_objfile->abbrev);
6877
6878   if (dwarf_read_debug)
6879     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6880                         get_section_name (section),
6881                         get_section_file_name (abbrev_section));
6882
6883   dwarf2_read_section (objfile, section);
6884   info_ptr = section->buffer;
6885
6886   if (info_ptr == NULL)
6887     return;
6888
6889   /* We can't set abfd until now because the section may be empty or
6890      not present, in which case the bfd is unknown.  */
6891   abfd = get_section_bfd_owner (section);
6892
6893   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6894      because we don't need to read any dies: the signature is in the
6895      header.  */
6896
6897   end_ptr = info_ptr + section->size;
6898   while (info_ptr < end_ptr)
6899     {
6900       struct signatured_type *sig_type;
6901       struct dwo_unit *dwo_tu;
6902       void **slot;
6903       const gdb_byte *ptr = info_ptr;
6904       struct comp_unit_head header;
6905       unsigned int length;
6906
6907       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6908
6909       /* Initialize it due to a false compiler warning.  */
6910       header.signature = -1;
6911       header.type_cu_offset_in_tu = (cu_offset) -1;
6912
6913       /* We need to read the type's signature in order to build the hash
6914          table, but we don't need anything else just yet.  */
6915
6916       ptr = read_and_check_comp_unit_head (&header, section,
6917                                            abbrev_section, ptr, section_kind);
6918
6919       length = get_cu_length (&header);
6920
6921       /* Skip dummy type units.  */
6922       if (ptr >= info_ptr + length
6923           || peek_abbrev_code (abfd, ptr) == 0
6924           || header.unit_type != DW_UT_type)
6925         {
6926           info_ptr += length;
6927           continue;
6928         }
6929
6930       if (types_htab == NULL)
6931         {
6932           if (dwo_file)
6933             types_htab = allocate_dwo_unit_table (objfile);
6934           else
6935             types_htab = allocate_signatured_type_table (objfile);
6936         }
6937
6938       if (dwo_file)
6939         {
6940           sig_type = NULL;
6941           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6942                                    struct dwo_unit);
6943           dwo_tu->dwo_file = dwo_file;
6944           dwo_tu->signature = header.signature;
6945           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6946           dwo_tu->section = section;
6947           dwo_tu->sect_off = sect_off;
6948           dwo_tu->length = length;
6949         }
6950       else
6951         {
6952           /* N.B.: type_offset is not usable if this type uses a DWO file.
6953              The real type_offset is in the DWO file.  */
6954           dwo_tu = NULL;
6955           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6956                                      struct signatured_type);
6957           sig_type->signature = header.signature;
6958           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6959           sig_type->per_cu.objfile = objfile;
6960           sig_type->per_cu.is_debug_types = 1;
6961           sig_type->per_cu.section = section;
6962           sig_type->per_cu.sect_off = sect_off;
6963           sig_type->per_cu.length = length;
6964         }
6965
6966       slot = htab_find_slot (types_htab,
6967                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6968                              INSERT);
6969       gdb_assert (slot != NULL);
6970       if (*slot != NULL)
6971         {
6972           sect_offset dup_sect_off;
6973
6974           if (dwo_file)
6975             {
6976               const struct dwo_unit *dup_tu
6977                 = (const struct dwo_unit *) *slot;
6978
6979               dup_sect_off = dup_tu->sect_off;
6980             }
6981           else
6982             {
6983               const struct signatured_type *dup_tu
6984                 = (const struct signatured_type *) *slot;
6985
6986               dup_sect_off = dup_tu->per_cu.sect_off;
6987             }
6988
6989           complaint (&symfile_complaints,
6990                      _("debug type entry at offset 0x%x is duplicate to"
6991                        " the entry at offset 0x%x, signature %s"),
6992                      to_underlying (sect_off), to_underlying (dup_sect_off),
6993                      hex_string (header.signature));
6994         }
6995       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6996
6997       if (dwarf_read_debug > 1)
6998         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
6999                             to_underlying (sect_off),
7000                             hex_string (header.signature));
7001
7002       info_ptr += length;
7003     }
7004 }
7005
7006 /* Create the hash table of all entries in the .debug_types
7007    (or .debug_types.dwo) section(s).
7008    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7009    otherwise it is NULL.
7010
7011    The result is a pointer to the hash table or NULL if there are no types.
7012
7013    Note: This function processes DWO files only, not DWP files.  */
7014
7015 static void
7016 create_debug_types_hash_table (struct dwo_file *dwo_file,
7017                                VEC (dwarf2_section_info_def) *types,
7018                                htab_t &types_htab)
7019 {
7020   int ix;
7021   struct dwarf2_section_info *section;
7022
7023   if (VEC_empty (dwarf2_section_info_def, types))
7024     return;
7025
7026   for (ix = 0;
7027        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7028        ++ix)
7029     create_debug_type_hash_table (dwo_file, section, types_htab,
7030                                   rcuh_kind::TYPE);
7031 }
7032
7033 /* Create the hash table of all entries in the .debug_types section,
7034    and initialize all_type_units.
7035    The result is zero if there is an error (e.g. missing .debug_types section),
7036    otherwise non-zero.  */
7037
7038 static int
7039 create_all_type_units (struct objfile *objfile)
7040 {
7041   htab_t types_htab = NULL;
7042   struct signatured_type **iter;
7043
7044   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
7045                                 rcuh_kind::COMPILE);
7046   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
7047   if (types_htab == NULL)
7048     {
7049       dwarf2_per_objfile->signatured_types = NULL;
7050       return 0;
7051     }
7052
7053   dwarf2_per_objfile->signatured_types = types_htab;
7054
7055   dwarf2_per_objfile->n_type_units
7056     = dwarf2_per_objfile->n_allocated_type_units
7057     = htab_elements (types_htab);
7058   dwarf2_per_objfile->all_type_units =
7059     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7060   iter = &dwarf2_per_objfile->all_type_units[0];
7061   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7062   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7063               == dwarf2_per_objfile->n_type_units);
7064
7065   return 1;
7066 }
7067
7068 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7069    If SLOT is non-NULL, it is the entry to use in the hash table.
7070    Otherwise we find one.  */
7071
7072 static struct signatured_type *
7073 add_type_unit (ULONGEST sig, void **slot)
7074 {
7075   struct objfile *objfile = dwarf2_per_objfile->objfile;
7076   int n_type_units = dwarf2_per_objfile->n_type_units;
7077   struct signatured_type *sig_type;
7078
7079   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7080   ++n_type_units;
7081   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7082     {
7083       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7084         dwarf2_per_objfile->n_allocated_type_units = 1;
7085       dwarf2_per_objfile->n_allocated_type_units *= 2;
7086       dwarf2_per_objfile->all_type_units
7087         = XRESIZEVEC (struct signatured_type *,
7088                       dwarf2_per_objfile->all_type_units,
7089                       dwarf2_per_objfile->n_allocated_type_units);
7090       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7091     }
7092   dwarf2_per_objfile->n_type_units = n_type_units;
7093
7094   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7095                              struct signatured_type);
7096   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7097   sig_type->signature = sig;
7098   sig_type->per_cu.is_debug_types = 1;
7099   if (dwarf2_per_objfile->using_index)
7100     {
7101       sig_type->per_cu.v.quick =
7102         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7103                         struct dwarf2_per_cu_quick_data);
7104     }
7105
7106   if (slot == NULL)
7107     {
7108       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7109                              sig_type, INSERT);
7110     }
7111   gdb_assert (*slot == NULL);
7112   *slot = sig_type;
7113   /* The rest of sig_type must be filled in by the caller.  */
7114   return sig_type;
7115 }
7116
7117 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7118    Fill in SIG_ENTRY with DWO_ENTRY.  */
7119
7120 static void
7121 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
7122                                   struct signatured_type *sig_entry,
7123                                   struct dwo_unit *dwo_entry)
7124 {
7125   /* Make sure we're not clobbering something we don't expect to.  */
7126   gdb_assert (! sig_entry->per_cu.queued);
7127   gdb_assert (sig_entry->per_cu.cu == NULL);
7128   if (dwarf2_per_objfile->using_index)
7129     {
7130       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7131       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7132     }
7133   else
7134       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7135   gdb_assert (sig_entry->signature == dwo_entry->signature);
7136   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7137   gdb_assert (sig_entry->type_unit_group == NULL);
7138   gdb_assert (sig_entry->dwo_unit == NULL);
7139
7140   sig_entry->per_cu.section = dwo_entry->section;
7141   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7142   sig_entry->per_cu.length = dwo_entry->length;
7143   sig_entry->per_cu.reading_dwo_directly = 1;
7144   sig_entry->per_cu.objfile = objfile;
7145   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7146   sig_entry->dwo_unit = dwo_entry;
7147 }
7148
7149 /* Subroutine of lookup_signatured_type.
7150    If we haven't read the TU yet, create the signatured_type data structure
7151    for a TU to be read in directly from a DWO file, bypassing the stub.
7152    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7153    using .gdb_index, then when reading a CU we want to stay in the DWO file
7154    containing that CU.  Otherwise we could end up reading several other DWO
7155    files (due to comdat folding) to process the transitive closure of all the
7156    mentioned TUs, and that can be slow.  The current DWO file will have every
7157    type signature that it needs.
7158    We only do this for .gdb_index because in the psymtab case we already have
7159    to read all the DWOs to build the type unit groups.  */
7160
7161 static struct signatured_type *
7162 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7163 {
7164   struct objfile *objfile = dwarf2_per_objfile->objfile;
7165   struct dwo_file *dwo_file;
7166   struct dwo_unit find_dwo_entry, *dwo_entry;
7167   struct signatured_type find_sig_entry, *sig_entry;
7168   void **slot;
7169
7170   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7171
7172   /* If TU skeletons have been removed then we may not have read in any
7173      TUs yet.  */
7174   if (dwarf2_per_objfile->signatured_types == NULL)
7175     {
7176       dwarf2_per_objfile->signatured_types
7177         = allocate_signatured_type_table (objfile);
7178     }
7179
7180   /* We only ever need to read in one copy of a signatured type.
7181      Use the global signatured_types array to do our own comdat-folding
7182      of types.  If this is the first time we're reading this TU, and
7183      the TU has an entry in .gdb_index, replace the recorded data from
7184      .gdb_index with this TU.  */
7185
7186   find_sig_entry.signature = sig;
7187   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7188                          &find_sig_entry, INSERT);
7189   sig_entry = (struct signatured_type *) *slot;
7190
7191   /* We can get here with the TU already read, *or* in the process of being
7192      read.  Don't reassign the global entry to point to this DWO if that's
7193      the case.  Also note that if the TU is already being read, it may not
7194      have come from a DWO, the program may be a mix of Fission-compiled
7195      code and non-Fission-compiled code.  */
7196
7197   /* Have we already tried to read this TU?
7198      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7199      needn't exist in the global table yet).  */
7200   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7201     return sig_entry;
7202
7203   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7204      dwo_unit of the TU itself.  */
7205   dwo_file = cu->dwo_unit->dwo_file;
7206
7207   /* Ok, this is the first time we're reading this TU.  */
7208   if (dwo_file->tus == NULL)
7209     return NULL;
7210   find_dwo_entry.signature = sig;
7211   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7212   if (dwo_entry == NULL)
7213     return NULL;
7214
7215   /* If the global table doesn't have an entry for this TU, add one.  */
7216   if (sig_entry == NULL)
7217     sig_entry = add_type_unit (sig, slot);
7218
7219   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7220   sig_entry->per_cu.tu_read = 1;
7221   return sig_entry;
7222 }
7223
7224 /* Subroutine of lookup_signatured_type.
7225    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7226    then try the DWP file.  If the TU stub (skeleton) has been removed then
7227    it won't be in .gdb_index.  */
7228
7229 static struct signatured_type *
7230 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7231 {
7232   struct objfile *objfile = dwarf2_per_objfile->objfile;
7233   struct dwp_file *dwp_file = get_dwp_file ();
7234   struct dwo_unit *dwo_entry;
7235   struct signatured_type find_sig_entry, *sig_entry;
7236   void **slot;
7237
7238   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7239   gdb_assert (dwp_file != NULL);
7240
7241   /* If TU skeletons have been removed then we may not have read in any
7242      TUs yet.  */
7243   if (dwarf2_per_objfile->signatured_types == NULL)
7244     {
7245       dwarf2_per_objfile->signatured_types
7246         = allocate_signatured_type_table (objfile);
7247     }
7248
7249   find_sig_entry.signature = sig;
7250   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7251                          &find_sig_entry, INSERT);
7252   sig_entry = (struct signatured_type *) *slot;
7253
7254   /* Have we already tried to read this TU?
7255      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7256      needn't exist in the global table yet).  */
7257   if (sig_entry != NULL)
7258     return sig_entry;
7259
7260   if (dwp_file->tus == NULL)
7261     return NULL;
7262   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
7263                                       sig, 1 /* is_debug_types */);
7264   if (dwo_entry == NULL)
7265     return NULL;
7266
7267   sig_entry = add_type_unit (sig, slot);
7268   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7269
7270   return sig_entry;
7271 }
7272
7273 /* Lookup a signature based type for DW_FORM_ref_sig8.
7274    Returns NULL if signature SIG is not present in the table.
7275    It is up to the caller to complain about this.  */
7276
7277 static struct signatured_type *
7278 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7279 {
7280   if (cu->dwo_unit
7281       && dwarf2_per_objfile->using_index)
7282     {
7283       /* We're in a DWO/DWP file, and we're using .gdb_index.
7284          These cases require special processing.  */
7285       if (get_dwp_file () == NULL)
7286         return lookup_dwo_signatured_type (cu, sig);
7287       else
7288         return lookup_dwp_signatured_type (cu, sig);
7289     }
7290   else
7291     {
7292       struct signatured_type find_entry, *entry;
7293
7294       if (dwarf2_per_objfile->signatured_types == NULL)
7295         return NULL;
7296       find_entry.signature = sig;
7297       entry = ((struct signatured_type *)
7298                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7299       return entry;
7300     }
7301 }
7302 \f
7303 /* Low level DIE reading support.  */
7304
7305 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7306
7307 static void
7308 init_cu_die_reader (struct die_reader_specs *reader,
7309                     struct dwarf2_cu *cu,
7310                     struct dwarf2_section_info *section,
7311                     struct dwo_file *dwo_file)
7312 {
7313   gdb_assert (section->readin && section->buffer != NULL);
7314   reader->abfd = get_section_bfd_owner (section);
7315   reader->cu = cu;
7316   reader->dwo_file = dwo_file;
7317   reader->die_section = section;
7318   reader->buffer = section->buffer;
7319   reader->buffer_end = section->buffer + section->size;
7320   reader->comp_dir = NULL;
7321 }
7322
7323 /* Subroutine of init_cutu_and_read_dies to simplify it.
7324    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7325    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7326    already.
7327
7328    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7329    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7330    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7331    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7332    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7333    STUB_COMP_DIR may be non-NULL.
7334    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7335    are filled in with the info of the DIE from the DWO file.
7336    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
7337    provided an abbrev table to use.
7338    The result is non-zero if a valid (non-dummy) DIE was found.  */
7339
7340 static int
7341 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7342                         struct dwo_unit *dwo_unit,
7343                         int abbrev_table_provided,
7344                         struct die_info *stub_comp_unit_die,
7345                         const char *stub_comp_dir,
7346                         struct die_reader_specs *result_reader,
7347                         const gdb_byte **result_info_ptr,
7348                         struct die_info **result_comp_unit_die,
7349                         int *result_has_children)
7350 {
7351   struct objfile *objfile = dwarf2_per_objfile->objfile;
7352   struct dwarf2_cu *cu = this_cu->cu;
7353   struct dwarf2_section_info *section;
7354   bfd *abfd;
7355   const gdb_byte *begin_info_ptr, *info_ptr;
7356   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7357   int i,num_extra_attrs;
7358   struct dwarf2_section_info *dwo_abbrev_section;
7359   struct attribute *attr;
7360   struct die_info *comp_unit_die;
7361
7362   /* At most one of these may be provided.  */
7363   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7364
7365   /* These attributes aren't processed until later:
7366      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7367      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7368      referenced later.  However, these attributes are found in the stub
7369      which we won't have later.  In order to not impose this complication
7370      on the rest of the code, we read them here and copy them to the
7371      DWO CU/TU die.  */
7372
7373   stmt_list = NULL;
7374   low_pc = NULL;
7375   high_pc = NULL;
7376   ranges = NULL;
7377   comp_dir = NULL;
7378
7379   if (stub_comp_unit_die != NULL)
7380     {
7381       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7382          DWO file.  */
7383       if (! this_cu->is_debug_types)
7384         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7385       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7386       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7387       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7388       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7389
7390       /* There should be a DW_AT_addr_base attribute here (if needed).
7391          We need the value before we can process DW_FORM_GNU_addr_index.  */
7392       cu->addr_base = 0;
7393       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7394       if (attr)
7395         cu->addr_base = DW_UNSND (attr);
7396
7397       /* There should be a DW_AT_ranges_base attribute here (if needed).
7398          We need the value before we can process DW_AT_ranges.  */
7399       cu->ranges_base = 0;
7400       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7401       if (attr)
7402         cu->ranges_base = DW_UNSND (attr);
7403     }
7404   else if (stub_comp_dir != NULL)
7405     {
7406       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7407       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7408       comp_dir->name = DW_AT_comp_dir;
7409       comp_dir->form = DW_FORM_string;
7410       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7411       DW_STRING (comp_dir) = stub_comp_dir;
7412     }
7413
7414   /* Set up for reading the DWO CU/TU.  */
7415   cu->dwo_unit = dwo_unit;
7416   section = dwo_unit->section;
7417   dwarf2_read_section (objfile, section);
7418   abfd = get_section_bfd_owner (section);
7419   begin_info_ptr = info_ptr = (section->buffer
7420                                + to_underlying (dwo_unit->sect_off));
7421   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7422   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
7423
7424   if (this_cu->is_debug_types)
7425     {
7426       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7427
7428       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7429                                                 dwo_abbrev_section,
7430                                                 info_ptr, rcuh_kind::TYPE);
7431       /* This is not an assert because it can be caused by bad debug info.  */
7432       if (sig_type->signature != cu->header.signature)
7433         {
7434           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7435                    " TU at offset 0x%x [in module %s]"),
7436                  hex_string (sig_type->signature),
7437                  hex_string (cu->header.signature),
7438                  to_underlying (dwo_unit->sect_off),
7439                  bfd_get_filename (abfd));
7440         }
7441       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7442       /* For DWOs coming from DWP files, we don't know the CU length
7443          nor the type's offset in the TU until now.  */
7444       dwo_unit->length = get_cu_length (&cu->header);
7445       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7446
7447       /* Establish the type offset that can be used to lookup the type.
7448          For DWO files, we don't know it until now.  */
7449       sig_type->type_offset_in_section
7450         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7451     }
7452   else
7453     {
7454       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7455                                                 dwo_abbrev_section,
7456                                                 info_ptr, rcuh_kind::COMPILE);
7457       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7458       /* For DWOs coming from DWP files, we don't know the CU length
7459          until now.  */
7460       dwo_unit->length = get_cu_length (&cu->header);
7461     }
7462
7463   /* Replace the CU's original abbrev table with the DWO's.
7464      Reminder: We can't read the abbrev table until we've read the header.  */
7465   if (abbrev_table_provided)
7466     {
7467       /* Don't free the provided abbrev table, the caller of
7468          init_cutu_and_read_dies owns it.  */
7469       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7470       /* Ensure the DWO abbrev table gets freed.  */
7471       make_cleanup (dwarf2_free_abbrev_table, cu);
7472     }
7473   else
7474     {
7475       dwarf2_free_abbrev_table (cu);
7476       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7477       /* Leave any existing abbrev table cleanup as is.  */
7478     }
7479
7480   /* Read in the die, but leave space to copy over the attributes
7481      from the stub.  This has the benefit of simplifying the rest of
7482      the code - all the work to maintain the illusion of a single
7483      DW_TAG_{compile,type}_unit DIE is done here.  */
7484   num_extra_attrs = ((stmt_list != NULL)
7485                      + (low_pc != NULL)
7486                      + (high_pc != NULL)
7487                      + (ranges != NULL)
7488                      + (comp_dir != NULL));
7489   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7490                               result_has_children, num_extra_attrs);
7491
7492   /* Copy over the attributes from the stub to the DIE we just read in.  */
7493   comp_unit_die = *result_comp_unit_die;
7494   i = comp_unit_die->num_attrs;
7495   if (stmt_list != NULL)
7496     comp_unit_die->attrs[i++] = *stmt_list;
7497   if (low_pc != NULL)
7498     comp_unit_die->attrs[i++] = *low_pc;
7499   if (high_pc != NULL)
7500     comp_unit_die->attrs[i++] = *high_pc;
7501   if (ranges != NULL)
7502     comp_unit_die->attrs[i++] = *ranges;
7503   if (comp_dir != NULL)
7504     comp_unit_die->attrs[i++] = *comp_dir;
7505   comp_unit_die->num_attrs += num_extra_attrs;
7506
7507   if (dwarf_die_debug)
7508     {
7509       fprintf_unfiltered (gdb_stdlog,
7510                           "Read die from %s@0x%x of %s:\n",
7511                           get_section_name (section),
7512                           (unsigned) (begin_info_ptr - section->buffer),
7513                           bfd_get_filename (abfd));
7514       dump_die (comp_unit_die, dwarf_die_debug);
7515     }
7516
7517   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7518      TUs by skipping the stub and going directly to the entry in the DWO file.
7519      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7520      to get it via circuitous means.  Blech.  */
7521   if (comp_dir != NULL)
7522     result_reader->comp_dir = DW_STRING (comp_dir);
7523
7524   /* Skip dummy compilation units.  */
7525   if (info_ptr >= begin_info_ptr + dwo_unit->length
7526       || peek_abbrev_code (abfd, info_ptr) == 0)
7527     return 0;
7528
7529   *result_info_ptr = info_ptr;
7530   return 1;
7531 }
7532
7533 /* Subroutine of init_cutu_and_read_dies to simplify it.
7534    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7535    Returns NULL if the specified DWO unit cannot be found.  */
7536
7537 static struct dwo_unit *
7538 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7539                  struct die_info *comp_unit_die)
7540 {
7541   struct dwarf2_cu *cu = this_cu->cu;
7542   ULONGEST signature;
7543   struct dwo_unit *dwo_unit;
7544   const char *comp_dir, *dwo_name;
7545
7546   gdb_assert (cu != NULL);
7547
7548   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7549   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7550   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7551
7552   if (this_cu->is_debug_types)
7553     {
7554       struct signatured_type *sig_type;
7555
7556       /* Since this_cu is the first member of struct signatured_type,
7557          we can go from a pointer to one to a pointer to the other.  */
7558       sig_type = (struct signatured_type *) this_cu;
7559       signature = sig_type->signature;
7560       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7561     }
7562   else
7563     {
7564       struct attribute *attr;
7565
7566       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7567       if (! attr)
7568         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7569                  " [in module %s]"),
7570                dwo_name, objfile_name (this_cu->objfile));
7571       signature = DW_UNSND (attr);
7572       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7573                                        signature);
7574     }
7575
7576   return dwo_unit;
7577 }
7578
7579 /* Subroutine of init_cutu_and_read_dies to simplify it.
7580    See it for a description of the parameters.
7581    Read a TU directly from a DWO file, bypassing the stub.
7582
7583    Note: This function could be a little bit simpler if we shared cleanups
7584    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
7585    to do, so we keep this function self-contained.  Or we could move this
7586    into our caller, but it's complex enough already.  */
7587
7588 static void
7589 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7590                            int use_existing_cu, int keep,
7591                            die_reader_func_ftype *die_reader_func,
7592                            void *data)
7593 {
7594   struct dwarf2_cu *cu;
7595   struct signatured_type *sig_type;
7596   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7597   struct die_reader_specs reader;
7598   const gdb_byte *info_ptr;
7599   struct die_info *comp_unit_die;
7600   int has_children;
7601
7602   /* Verify we can do the following downcast, and that we have the
7603      data we need.  */
7604   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7605   sig_type = (struct signatured_type *) this_cu;
7606   gdb_assert (sig_type->dwo_unit != NULL);
7607
7608   cleanups = make_cleanup (null_cleanup, NULL);
7609
7610   if (use_existing_cu && this_cu->cu != NULL)
7611     {
7612       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7613       cu = this_cu->cu;
7614       /* There's no need to do the rereading_dwo_cu handling that
7615          init_cutu_and_read_dies does since we don't read the stub.  */
7616     }
7617   else
7618     {
7619       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7620       gdb_assert (this_cu->cu == NULL);
7621       cu = XNEW (struct dwarf2_cu);
7622       init_one_comp_unit (cu, this_cu);
7623       /* If an error occurs while loading, release our storage.  */
7624       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7625     }
7626
7627   /* A future optimization, if needed, would be to use an existing
7628      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7629      could share abbrev tables.  */
7630
7631   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7632                               0 /* abbrev_table_provided */,
7633                               NULL /* stub_comp_unit_die */,
7634                               sig_type->dwo_unit->dwo_file->comp_dir,
7635                               &reader, &info_ptr,
7636                               &comp_unit_die, &has_children) == 0)
7637     {
7638       /* Dummy die.  */
7639       do_cleanups (cleanups);
7640       return;
7641     }
7642
7643   /* All the "real" work is done here.  */
7644   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7645
7646   /* This duplicates the code in init_cutu_and_read_dies,
7647      but the alternative is making the latter more complex.
7648      This function is only for the special case of using DWO files directly:
7649      no point in overly complicating the general case just to handle this.  */
7650   if (free_cu_cleanup != NULL)
7651     {
7652       if (keep)
7653         {
7654           /* We've successfully allocated this compilation unit.  Let our
7655              caller clean it up when finished with it.  */
7656           discard_cleanups (free_cu_cleanup);
7657
7658           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7659              So we have to manually free the abbrev table.  */
7660           dwarf2_free_abbrev_table (cu);
7661
7662           /* Link this CU into read_in_chain.  */
7663           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7664           dwarf2_per_objfile->read_in_chain = this_cu;
7665         }
7666       else
7667         do_cleanups (free_cu_cleanup);
7668     }
7669
7670   do_cleanups (cleanups);
7671 }
7672
7673 /* Initialize a CU (or TU) and read its DIEs.
7674    If the CU defers to a DWO file, read the DWO file as well.
7675
7676    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7677    Otherwise the table specified in the comp unit header is read in and used.
7678    This is an optimization for when we already have the abbrev table.
7679
7680    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7681    Otherwise, a new CU is allocated with xmalloc.
7682
7683    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7684    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7685
7686    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7687    linker) then DIE_READER_FUNC will not get called.  */
7688
7689 static void
7690 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7691                          struct abbrev_table *abbrev_table,
7692                          int use_existing_cu, int keep,
7693                          die_reader_func_ftype *die_reader_func,
7694                          void *data)
7695 {
7696   struct objfile *objfile = dwarf2_per_objfile->objfile;
7697   struct dwarf2_section_info *section = this_cu->section;
7698   bfd *abfd = get_section_bfd_owner (section);
7699   struct dwarf2_cu *cu;
7700   const gdb_byte *begin_info_ptr, *info_ptr;
7701   struct die_reader_specs reader;
7702   struct die_info *comp_unit_die;
7703   int has_children;
7704   struct attribute *attr;
7705   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7706   struct signatured_type *sig_type = NULL;
7707   struct dwarf2_section_info *abbrev_section;
7708   /* Non-zero if CU currently points to a DWO file and we need to
7709      reread it.  When this happens we need to reread the skeleton die
7710      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7711   int rereading_dwo_cu = 0;
7712
7713   if (dwarf_die_debug)
7714     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7715                         this_cu->is_debug_types ? "type" : "comp",
7716                         to_underlying (this_cu->sect_off));
7717
7718   if (use_existing_cu)
7719     gdb_assert (keep);
7720
7721   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7722      file (instead of going through the stub), short-circuit all of this.  */
7723   if (this_cu->reading_dwo_directly)
7724     {
7725       /* Narrow down the scope of possibilities to have to understand.  */
7726       gdb_assert (this_cu->is_debug_types);
7727       gdb_assert (abbrev_table == NULL);
7728       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7729                                  die_reader_func, data);
7730       return;
7731     }
7732
7733   cleanups = make_cleanup (null_cleanup, NULL);
7734
7735   /* This is cheap if the section is already read in.  */
7736   dwarf2_read_section (objfile, section);
7737
7738   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7739
7740   abbrev_section = get_abbrev_section_for_cu (this_cu);
7741
7742   if (use_existing_cu && this_cu->cu != NULL)
7743     {
7744       cu = this_cu->cu;
7745       /* If this CU is from a DWO file we need to start over, we need to
7746          refetch the attributes from the skeleton CU.
7747          This could be optimized by retrieving those attributes from when we
7748          were here the first time: the previous comp_unit_die was stored in
7749          comp_unit_obstack.  But there's no data yet that we need this
7750          optimization.  */
7751       if (cu->dwo_unit != NULL)
7752         rereading_dwo_cu = 1;
7753     }
7754   else
7755     {
7756       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7757       gdb_assert (this_cu->cu == NULL);
7758       cu = XNEW (struct dwarf2_cu);
7759       init_one_comp_unit (cu, this_cu);
7760       /* If an error occurs while loading, release our storage.  */
7761       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7762     }
7763
7764   /* Get the header.  */
7765   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7766     {
7767       /* We already have the header, there's no need to read it in again.  */
7768       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7769     }
7770   else
7771     {
7772       if (this_cu->is_debug_types)
7773         {
7774           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7775                                                     abbrev_section, info_ptr,
7776                                                     rcuh_kind::TYPE);
7777
7778           /* Since per_cu is the first member of struct signatured_type,
7779              we can go from a pointer to one to a pointer to the other.  */
7780           sig_type = (struct signatured_type *) this_cu;
7781           gdb_assert (sig_type->signature == cu->header.signature);
7782           gdb_assert (sig_type->type_offset_in_tu
7783                       == cu->header.type_cu_offset_in_tu);
7784           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7785
7786           /* LENGTH has not been set yet for type units if we're
7787              using .gdb_index.  */
7788           this_cu->length = get_cu_length (&cu->header);
7789
7790           /* Establish the type offset that can be used to lookup the type.  */
7791           sig_type->type_offset_in_section =
7792             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7793
7794           this_cu->dwarf_version = cu->header.version;
7795         }
7796       else
7797         {
7798           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7799                                                     abbrev_section,
7800                                                     info_ptr,
7801                                                     rcuh_kind::COMPILE);
7802
7803           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7804           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7805           this_cu->dwarf_version = cu->header.version;
7806         }
7807     }
7808
7809   /* Skip dummy compilation units.  */
7810   if (info_ptr >= begin_info_ptr + this_cu->length
7811       || peek_abbrev_code (abfd, info_ptr) == 0)
7812     {
7813       do_cleanups (cleanups);
7814       return;
7815     }
7816
7817   /* If we don't have them yet, read the abbrevs for this compilation unit.
7818      And if we need to read them now, make sure they're freed when we're
7819      done.  Note that it's important that if the CU had an abbrev table
7820      on entry we don't free it when we're done: Somewhere up the call stack
7821      it may be in use.  */
7822   if (abbrev_table != NULL)
7823     {
7824       gdb_assert (cu->abbrev_table == NULL);
7825       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7826       cu->abbrev_table = abbrev_table;
7827     }
7828   else if (cu->abbrev_table == NULL)
7829     {
7830       dwarf2_read_abbrevs (cu, abbrev_section);
7831       make_cleanup (dwarf2_free_abbrev_table, cu);
7832     }
7833   else if (rereading_dwo_cu)
7834     {
7835       dwarf2_free_abbrev_table (cu);
7836       dwarf2_read_abbrevs (cu, abbrev_section);
7837     }
7838
7839   /* Read the top level CU/TU die.  */
7840   init_cu_die_reader (&reader, cu, section, NULL);
7841   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7842
7843   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7844      from the DWO file.
7845      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7846      DWO CU, that this test will fail (the attribute will not be present).  */
7847   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7848   if (attr)
7849     {
7850       struct dwo_unit *dwo_unit;
7851       struct die_info *dwo_comp_unit_die;
7852
7853       if (has_children)
7854         {
7855           complaint (&symfile_complaints,
7856                      _("compilation unit with DW_AT_GNU_dwo_name"
7857                        " has children (offset 0x%x) [in module %s]"),
7858                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7859         }
7860       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7861       if (dwo_unit != NULL)
7862         {
7863           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7864                                       abbrev_table != NULL,
7865                                       comp_unit_die, NULL,
7866                                       &reader, &info_ptr,
7867                                       &dwo_comp_unit_die, &has_children) == 0)
7868             {
7869               /* Dummy die.  */
7870               do_cleanups (cleanups);
7871               return;
7872             }
7873           comp_unit_die = dwo_comp_unit_die;
7874         }
7875       else
7876         {
7877           /* Yikes, we couldn't find the rest of the DIE, we only have
7878              the stub.  A complaint has already been logged.  There's
7879              not much more we can do except pass on the stub DIE to
7880              die_reader_func.  We don't want to throw an error on bad
7881              debug info.  */
7882         }
7883     }
7884
7885   /* All of the above is setup for this call.  Yikes.  */
7886   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7887
7888   /* Done, clean up.  */
7889   if (free_cu_cleanup != NULL)
7890     {
7891       if (keep)
7892         {
7893           /* We've successfully allocated this compilation unit.  Let our
7894              caller clean it up when finished with it.  */
7895           discard_cleanups (free_cu_cleanup);
7896
7897           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7898              So we have to manually free the abbrev table.  */
7899           dwarf2_free_abbrev_table (cu);
7900
7901           /* Link this CU into read_in_chain.  */
7902           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7903           dwarf2_per_objfile->read_in_chain = this_cu;
7904         }
7905       else
7906         do_cleanups (free_cu_cleanup);
7907     }
7908
7909   do_cleanups (cleanups);
7910 }
7911
7912 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7913    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7914    to have already done the lookup to find the DWO file).
7915
7916    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7917    THIS_CU->is_debug_types, but nothing else.
7918
7919    We fill in THIS_CU->length.
7920
7921    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7922    linker) then DIE_READER_FUNC will not get called.
7923
7924    THIS_CU->cu is always freed when done.
7925    This is done in order to not leave THIS_CU->cu in a state where we have
7926    to care whether it refers to the "main" CU or the DWO CU.  */
7927
7928 static void
7929 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7930                                    struct dwo_file *dwo_file,
7931                                    die_reader_func_ftype *die_reader_func,
7932                                    void *data)
7933 {
7934   struct objfile *objfile = dwarf2_per_objfile->objfile;
7935   struct dwarf2_section_info *section = this_cu->section;
7936   bfd *abfd = get_section_bfd_owner (section);
7937   struct dwarf2_section_info *abbrev_section;
7938   struct dwarf2_cu cu;
7939   const gdb_byte *begin_info_ptr, *info_ptr;
7940   struct die_reader_specs reader;
7941   struct cleanup *cleanups;
7942   struct die_info *comp_unit_die;
7943   int has_children;
7944
7945   if (dwarf_die_debug)
7946     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7947                         this_cu->is_debug_types ? "type" : "comp",
7948                         to_underlying (this_cu->sect_off));
7949
7950   gdb_assert (this_cu->cu == NULL);
7951
7952   abbrev_section = (dwo_file != NULL
7953                     ? &dwo_file->sections.abbrev
7954                     : get_abbrev_section_for_cu (this_cu));
7955
7956   /* This is cheap if the section is already read in.  */
7957   dwarf2_read_section (objfile, section);
7958
7959   init_one_comp_unit (&cu, this_cu);
7960
7961   cleanups = make_cleanup (free_stack_comp_unit, &cu);
7962
7963   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7964   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
7965                                             abbrev_section, info_ptr,
7966                                             (this_cu->is_debug_types
7967                                              ? rcuh_kind::TYPE
7968                                              : rcuh_kind::COMPILE));
7969
7970   this_cu->length = get_cu_length (&cu.header);
7971
7972   /* Skip dummy compilation units.  */
7973   if (info_ptr >= begin_info_ptr + this_cu->length
7974       || peek_abbrev_code (abfd, info_ptr) == 0)
7975     {
7976       do_cleanups (cleanups);
7977       return;
7978     }
7979
7980   dwarf2_read_abbrevs (&cu, abbrev_section);
7981   make_cleanup (dwarf2_free_abbrev_table, &cu);
7982
7983   init_cu_die_reader (&reader, &cu, section, dwo_file);
7984   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7985
7986   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7987
7988   do_cleanups (cleanups);
7989 }
7990
7991 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7992    does not lookup the specified DWO file.
7993    This cannot be used to read DWO files.
7994
7995    THIS_CU->cu is always freed when done.
7996    This is done in order to not leave THIS_CU->cu in a state where we have
7997    to care whether it refers to the "main" CU or the DWO CU.
7998    We can revisit this if the data shows there's a performance issue.  */
7999
8000 static void
8001 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8002                                 die_reader_func_ftype *die_reader_func,
8003                                 void *data)
8004 {
8005   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8006 }
8007 \f
8008 /* Type Unit Groups.
8009
8010    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8011    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8012    so that all types coming from the same compilation (.o file) are grouped
8013    together.  A future step could be to put the types in the same symtab as
8014    the CU the types ultimately came from.  */
8015
8016 static hashval_t
8017 hash_type_unit_group (const void *item)
8018 {
8019   const struct type_unit_group *tu_group
8020     = (const struct type_unit_group *) item;
8021
8022   return hash_stmt_list_entry (&tu_group->hash);
8023 }
8024
8025 static int
8026 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8027 {
8028   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8029   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8030
8031   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8032 }
8033
8034 /* Allocate a hash table for type unit groups.  */
8035
8036 static htab_t
8037 allocate_type_unit_groups_table (void)
8038 {
8039   return htab_create_alloc_ex (3,
8040                                hash_type_unit_group,
8041                                eq_type_unit_group,
8042                                NULL,
8043                                &dwarf2_per_objfile->objfile->objfile_obstack,
8044                                hashtab_obstack_allocate,
8045                                dummy_obstack_deallocate);
8046 }
8047
8048 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8049    partial symtabs.  We combine several TUs per psymtab to not let the size
8050    of any one psymtab grow too big.  */
8051 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8052 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8053
8054 /* Helper routine for get_type_unit_group.
8055    Create the type_unit_group object used to hold one or more TUs.  */
8056
8057 static struct type_unit_group *
8058 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8059 {
8060   struct objfile *objfile = dwarf2_per_objfile->objfile;
8061   struct dwarf2_per_cu_data *per_cu;
8062   struct type_unit_group *tu_group;
8063
8064   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8065                              struct type_unit_group);
8066   per_cu = &tu_group->per_cu;
8067   per_cu->objfile = objfile;
8068
8069   if (dwarf2_per_objfile->using_index)
8070     {
8071       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8072                                         struct dwarf2_per_cu_quick_data);
8073     }
8074   else
8075     {
8076       unsigned int line_offset = to_underlying (line_offset_struct);
8077       struct partial_symtab *pst;
8078       char *name;
8079
8080       /* Give the symtab a useful name for debug purposes.  */
8081       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8082         name = xstrprintf ("<type_units_%d>",
8083                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8084       else
8085         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8086
8087       pst = create_partial_symtab (per_cu, name);
8088       pst->anonymous = 1;
8089
8090       xfree (name);
8091     }
8092
8093   tu_group->hash.dwo_unit = cu->dwo_unit;
8094   tu_group->hash.line_sect_off = line_offset_struct;
8095
8096   return tu_group;
8097 }
8098
8099 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8100    STMT_LIST is a DW_AT_stmt_list attribute.  */
8101
8102 static struct type_unit_group *
8103 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8104 {
8105   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8106   struct type_unit_group *tu_group;
8107   void **slot;
8108   unsigned int line_offset;
8109   struct type_unit_group type_unit_group_for_lookup;
8110
8111   if (dwarf2_per_objfile->type_unit_groups == NULL)
8112     {
8113       dwarf2_per_objfile->type_unit_groups =
8114         allocate_type_unit_groups_table ();
8115     }
8116
8117   /* Do we need to create a new group, or can we use an existing one?  */
8118
8119   if (stmt_list)
8120     {
8121       line_offset = DW_UNSND (stmt_list);
8122       ++tu_stats->nr_symtab_sharers;
8123     }
8124   else
8125     {
8126       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8127          We can do various things here like create one group per TU or
8128          spread them over multiple groups to split up the expansion work.
8129          To avoid worst case scenarios (too many groups or too large groups)
8130          we, umm, group them in bunches.  */
8131       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8132                      | (tu_stats->nr_stmt_less_type_units
8133                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8134       ++tu_stats->nr_stmt_less_type_units;
8135     }
8136
8137   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8138   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8139   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8140                          &type_unit_group_for_lookup, INSERT);
8141   if (*slot != NULL)
8142     {
8143       tu_group = (struct type_unit_group *) *slot;
8144       gdb_assert (tu_group != NULL);
8145     }
8146   else
8147     {
8148       sect_offset line_offset_struct = (sect_offset) line_offset;
8149       tu_group = create_type_unit_group (cu, line_offset_struct);
8150       *slot = tu_group;
8151       ++tu_stats->nr_symtabs;
8152     }
8153
8154   return tu_group;
8155 }
8156 \f
8157 /* Partial symbol tables.  */
8158
8159 /* Create a psymtab named NAME and assign it to PER_CU.
8160
8161    The caller must fill in the following details:
8162    dirname, textlow, texthigh.  */
8163
8164 static struct partial_symtab *
8165 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8166 {
8167   struct objfile *objfile = per_cu->objfile;
8168   struct partial_symtab *pst;
8169
8170   pst = start_psymtab_common (objfile, name, 0,
8171                               objfile->global_psymbols,
8172                               objfile->static_psymbols);
8173
8174   pst->psymtabs_addrmap_supported = 1;
8175
8176   /* This is the glue that links PST into GDB's symbol API.  */
8177   pst->read_symtab_private = per_cu;
8178   pst->read_symtab = dwarf2_read_symtab;
8179   per_cu->v.psymtab = pst;
8180
8181   return pst;
8182 }
8183
8184 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8185    type.  */
8186
8187 struct process_psymtab_comp_unit_data
8188 {
8189   /* True if we are reading a DW_TAG_partial_unit.  */
8190
8191   int want_partial_unit;
8192
8193   /* The "pretend" language that is used if the CU doesn't declare a
8194      language.  */
8195
8196   enum language pretend_language;
8197 };
8198
8199 /* die_reader_func for process_psymtab_comp_unit.  */
8200
8201 static void
8202 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8203                                   const gdb_byte *info_ptr,
8204                                   struct die_info *comp_unit_die,
8205                                   int has_children,
8206                                   void *data)
8207 {
8208   struct dwarf2_cu *cu = reader->cu;
8209   struct objfile *objfile = cu->objfile;
8210   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8211   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8212   CORE_ADDR baseaddr;
8213   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8214   struct partial_symtab *pst;
8215   enum pc_bounds_kind cu_bounds_kind;
8216   const char *filename;
8217   struct process_psymtab_comp_unit_data *info
8218     = (struct process_psymtab_comp_unit_data *) data;
8219
8220   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8221     return;
8222
8223   gdb_assert (! per_cu->is_debug_types);
8224
8225   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8226
8227   cu->list_in_scope = &file_symbols;
8228
8229   /* Allocate a new partial symbol table structure.  */
8230   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8231   if (filename == NULL)
8232     filename = "";
8233
8234   pst = create_partial_symtab (per_cu, filename);
8235
8236   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8237   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8238
8239   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8240
8241   dwarf2_find_base_address (comp_unit_die, cu);
8242
8243   /* Possibly set the default values of LOWPC and HIGHPC from
8244      `DW_AT_ranges'.  */
8245   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8246                                          &best_highpc, cu, pst);
8247   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8248     /* Store the contiguous range if it is not empty; it can be empty for
8249        CUs with no code.  */
8250     addrmap_set_empty (objfile->psymtabs_addrmap,
8251                        gdbarch_adjust_dwarf2_addr (gdbarch,
8252                                                    best_lowpc + baseaddr),
8253                        gdbarch_adjust_dwarf2_addr (gdbarch,
8254                                                    best_highpc + baseaddr) - 1,
8255                        pst);
8256
8257   /* Check if comp unit has_children.
8258      If so, read the rest of the partial symbols from this comp unit.
8259      If not, there's no more debug_info for this comp unit.  */
8260   if (has_children)
8261     {
8262       struct partial_die_info *first_die;
8263       CORE_ADDR lowpc, highpc;
8264
8265       lowpc = ((CORE_ADDR) -1);
8266       highpc = ((CORE_ADDR) 0);
8267
8268       first_die = load_partial_dies (reader, info_ptr, 1);
8269
8270       scan_partial_symbols (first_die, &lowpc, &highpc,
8271                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8272
8273       /* If we didn't find a lowpc, set it to highpc to avoid
8274          complaints from `maint check'.  */
8275       if (lowpc == ((CORE_ADDR) -1))
8276         lowpc = highpc;
8277
8278       /* If the compilation unit didn't have an explicit address range,
8279          then use the information extracted from its child dies.  */
8280       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8281         {
8282           best_lowpc = lowpc;
8283           best_highpc = highpc;
8284         }
8285     }
8286   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8287   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8288
8289   end_psymtab_common (objfile, pst);
8290
8291   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8292     {
8293       int i;
8294       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8295       struct dwarf2_per_cu_data *iter;
8296
8297       /* Fill in 'dependencies' here; we fill in 'users' in a
8298          post-pass.  */
8299       pst->number_of_dependencies = len;
8300       pst->dependencies =
8301         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8302       for (i = 0;
8303            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8304                         i, iter);
8305            ++i)
8306         pst->dependencies[i] = iter->v.psymtab;
8307
8308       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8309     }
8310
8311   /* Get the list of files included in the current compilation unit,
8312      and build a psymtab for each of them.  */
8313   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8314
8315   if (dwarf_read_debug)
8316     {
8317       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8318
8319       fprintf_unfiltered (gdb_stdlog,
8320                           "Psymtab for %s unit @0x%x: %s - %s"
8321                           ", %d global, %d static syms\n",
8322                           per_cu->is_debug_types ? "type" : "comp",
8323                           to_underlying (per_cu->sect_off),
8324                           paddress (gdbarch, pst->textlow),
8325                           paddress (gdbarch, pst->texthigh),
8326                           pst->n_global_syms, pst->n_static_syms);
8327     }
8328 }
8329
8330 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8331    Process compilation unit THIS_CU for a psymtab.  */
8332
8333 static void
8334 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8335                            int want_partial_unit,
8336                            enum language pretend_language)
8337 {
8338   /* If this compilation unit was already read in, free the
8339      cached copy in order to read it in again.  This is
8340      necessary because we skipped some symbols when we first
8341      read in the compilation unit (see load_partial_dies).
8342      This problem could be avoided, but the benefit is unclear.  */
8343   if (this_cu->cu != NULL)
8344     free_one_cached_comp_unit (this_cu);
8345
8346   if (this_cu->is_debug_types)
8347     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8348                              NULL);
8349   else
8350     {
8351       process_psymtab_comp_unit_data info;
8352       info.want_partial_unit = want_partial_unit;
8353       info.pretend_language = pretend_language;
8354       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8355                                process_psymtab_comp_unit_reader, &info);
8356     }
8357
8358   /* Age out any secondary CUs.  */
8359   age_cached_comp_units ();
8360 }
8361
8362 /* Reader function for build_type_psymtabs.  */
8363
8364 static void
8365 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8366                             const gdb_byte *info_ptr,
8367                             struct die_info *type_unit_die,
8368                             int has_children,
8369                             void *data)
8370 {
8371   struct objfile *objfile = dwarf2_per_objfile->objfile;
8372   struct dwarf2_cu *cu = reader->cu;
8373   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8374   struct signatured_type *sig_type;
8375   struct type_unit_group *tu_group;
8376   struct attribute *attr;
8377   struct partial_die_info *first_die;
8378   CORE_ADDR lowpc, highpc;
8379   struct partial_symtab *pst;
8380
8381   gdb_assert (data == NULL);
8382   gdb_assert (per_cu->is_debug_types);
8383   sig_type = (struct signatured_type *) per_cu;
8384
8385   if (! has_children)
8386     return;
8387
8388   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8389   tu_group = get_type_unit_group (cu, attr);
8390
8391   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8392
8393   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8394   cu->list_in_scope = &file_symbols;
8395   pst = create_partial_symtab (per_cu, "");
8396   pst->anonymous = 1;
8397
8398   first_die = load_partial_dies (reader, info_ptr, 1);
8399
8400   lowpc = (CORE_ADDR) -1;
8401   highpc = (CORE_ADDR) 0;
8402   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8403
8404   end_psymtab_common (objfile, pst);
8405 }
8406
8407 /* Struct used to sort TUs by their abbreviation table offset.  */
8408
8409 struct tu_abbrev_offset
8410 {
8411   struct signatured_type *sig_type;
8412   sect_offset abbrev_offset;
8413 };
8414
8415 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8416
8417 static int
8418 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8419 {
8420   const struct tu_abbrev_offset * const *a
8421     = (const struct tu_abbrev_offset * const*) ap;
8422   const struct tu_abbrev_offset * const *b
8423     = (const struct tu_abbrev_offset * const*) bp;
8424   sect_offset aoff = (*a)->abbrev_offset;
8425   sect_offset boff = (*b)->abbrev_offset;
8426
8427   return (aoff > boff) - (aoff < boff);
8428 }
8429
8430 /* Efficiently read all the type units.
8431    This does the bulk of the work for build_type_psymtabs.
8432
8433    The efficiency is because we sort TUs by the abbrev table they use and
8434    only read each abbrev table once.  In one program there are 200K TUs
8435    sharing 8K abbrev tables.
8436
8437    The main purpose of this function is to support building the
8438    dwarf2_per_objfile->type_unit_groups table.
8439    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8440    can collapse the search space by grouping them by stmt_list.
8441    The savings can be significant, in the same program from above the 200K TUs
8442    share 8K stmt_list tables.
8443
8444    FUNC is expected to call get_type_unit_group, which will create the
8445    struct type_unit_group if necessary and add it to
8446    dwarf2_per_objfile->type_unit_groups.  */
8447
8448 static void
8449 build_type_psymtabs_1 (void)
8450 {
8451   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8452   struct cleanup *cleanups;
8453   struct abbrev_table *abbrev_table;
8454   sect_offset abbrev_offset;
8455   struct tu_abbrev_offset *sorted_by_abbrev;
8456   int i;
8457
8458   /* It's up to the caller to not call us multiple times.  */
8459   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8460
8461   if (dwarf2_per_objfile->n_type_units == 0)
8462     return;
8463
8464   /* TUs typically share abbrev tables, and there can be way more TUs than
8465      abbrev tables.  Sort by abbrev table to reduce the number of times we
8466      read each abbrev table in.
8467      Alternatives are to punt or to maintain a cache of abbrev tables.
8468      This is simpler and efficient enough for now.
8469
8470      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8471      symtab to use).  Typically TUs with the same abbrev offset have the same
8472      stmt_list value too so in practice this should work well.
8473
8474      The basic algorithm here is:
8475
8476       sort TUs by abbrev table
8477       for each TU with same abbrev table:
8478         read abbrev table if first user
8479         read TU top level DIE
8480           [IWBN if DWO skeletons had DW_AT_stmt_list]
8481         call FUNC  */
8482
8483   if (dwarf_read_debug)
8484     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8485
8486   /* Sort in a separate table to maintain the order of all_type_units
8487      for .gdb_index: TU indices directly index all_type_units.  */
8488   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8489                               dwarf2_per_objfile->n_type_units);
8490   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8491     {
8492       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8493
8494       sorted_by_abbrev[i].sig_type = sig_type;
8495       sorted_by_abbrev[i].abbrev_offset =
8496         read_abbrev_offset (sig_type->per_cu.section,
8497                             sig_type->per_cu.sect_off);
8498     }
8499   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8500   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8501          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8502
8503   abbrev_offset = (sect_offset) ~(unsigned) 0;
8504   abbrev_table = NULL;
8505   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
8506
8507   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8508     {
8509       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8510
8511       /* Switch to the next abbrev table if necessary.  */
8512       if (abbrev_table == NULL
8513           || tu->abbrev_offset != abbrev_offset)
8514         {
8515           if (abbrev_table != NULL)
8516             {
8517               abbrev_table_free (abbrev_table);
8518               /* Reset to NULL in case abbrev_table_read_table throws
8519                  an error: abbrev_table_free_cleanup will get called.  */
8520               abbrev_table = NULL;
8521             }
8522           abbrev_offset = tu->abbrev_offset;
8523           abbrev_table =
8524             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
8525                                      abbrev_offset);
8526           ++tu_stats->nr_uniq_abbrev_tables;
8527         }
8528
8529       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
8530                                build_type_psymtabs_reader, NULL);
8531     }
8532
8533   do_cleanups (cleanups);
8534 }
8535
8536 /* Print collected type unit statistics.  */
8537
8538 static void
8539 print_tu_stats (void)
8540 {
8541   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8542
8543   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8544   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8545                       dwarf2_per_objfile->n_type_units);
8546   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8547                       tu_stats->nr_uniq_abbrev_tables);
8548   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8549                       tu_stats->nr_symtabs);
8550   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8551                       tu_stats->nr_symtab_sharers);
8552   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8553                       tu_stats->nr_stmt_less_type_units);
8554   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8555                       tu_stats->nr_all_type_units_reallocs);
8556 }
8557
8558 /* Traversal function for build_type_psymtabs.  */
8559
8560 static int
8561 build_type_psymtab_dependencies (void **slot, void *info)
8562 {
8563   struct objfile *objfile = dwarf2_per_objfile->objfile;
8564   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8565   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8566   struct partial_symtab *pst = per_cu->v.psymtab;
8567   int len = VEC_length (sig_type_ptr, tu_group->tus);
8568   struct signatured_type *iter;
8569   int i;
8570
8571   gdb_assert (len > 0);
8572   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8573
8574   pst->number_of_dependencies = len;
8575   pst->dependencies =
8576     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8577   for (i = 0;
8578        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8579        ++i)
8580     {
8581       gdb_assert (iter->per_cu.is_debug_types);
8582       pst->dependencies[i] = iter->per_cu.v.psymtab;
8583       iter->type_unit_group = tu_group;
8584     }
8585
8586   VEC_free (sig_type_ptr, tu_group->tus);
8587
8588   return 1;
8589 }
8590
8591 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8592    Build partial symbol tables for the .debug_types comp-units.  */
8593
8594 static void
8595 build_type_psymtabs (struct objfile *objfile)
8596 {
8597   if (! create_all_type_units (objfile))
8598     return;
8599
8600   build_type_psymtabs_1 ();
8601 }
8602
8603 /* Traversal function for process_skeletonless_type_unit.
8604    Read a TU in a DWO file and build partial symbols for it.  */
8605
8606 static int
8607 process_skeletonless_type_unit (void **slot, void *info)
8608 {
8609   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8610   struct objfile *objfile = (struct objfile *) info;
8611   struct signatured_type find_entry, *entry;
8612
8613   /* If this TU doesn't exist in the global table, add it and read it in.  */
8614
8615   if (dwarf2_per_objfile->signatured_types == NULL)
8616     {
8617       dwarf2_per_objfile->signatured_types
8618         = allocate_signatured_type_table (objfile);
8619     }
8620
8621   find_entry.signature = dwo_unit->signature;
8622   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8623                          INSERT);
8624   /* If we've already seen this type there's nothing to do.  What's happening
8625      is we're doing our own version of comdat-folding here.  */
8626   if (*slot != NULL)
8627     return 1;
8628
8629   /* This does the job that create_all_type_units would have done for
8630      this TU.  */
8631   entry = add_type_unit (dwo_unit->signature, slot);
8632   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
8633   *slot = entry;
8634
8635   /* This does the job that build_type_psymtabs_1 would have done.  */
8636   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8637                            build_type_psymtabs_reader, NULL);
8638
8639   return 1;
8640 }
8641
8642 /* Traversal function for process_skeletonless_type_units.  */
8643
8644 static int
8645 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8646 {
8647   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8648
8649   if (dwo_file->tus != NULL)
8650     {
8651       htab_traverse_noresize (dwo_file->tus,
8652                               process_skeletonless_type_unit, info);
8653     }
8654
8655   return 1;
8656 }
8657
8658 /* Scan all TUs of DWO files, verifying we've processed them.
8659    This is needed in case a TU was emitted without its skeleton.
8660    Note: This can't be done until we know what all the DWO files are.  */
8661
8662 static void
8663 process_skeletonless_type_units (struct objfile *objfile)
8664 {
8665   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8666   if (get_dwp_file () == NULL
8667       && dwarf2_per_objfile->dwo_files != NULL)
8668     {
8669       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8670                               process_dwo_file_for_skeletonless_type_units,
8671                               objfile);
8672     }
8673 }
8674
8675 /* Compute the 'user' field for each psymtab in OBJFILE.  */
8676
8677 static void
8678 set_partial_user (struct objfile *objfile)
8679 {
8680   int i;
8681
8682   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8683     {
8684       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8685       struct partial_symtab *pst = per_cu->v.psymtab;
8686       int j;
8687
8688       if (pst == NULL)
8689         continue;
8690
8691       for (j = 0; j < pst->number_of_dependencies; ++j)
8692         {
8693           /* Set the 'user' field only if it is not already set.  */
8694           if (pst->dependencies[j]->user == NULL)
8695             pst->dependencies[j]->user = pst;
8696         }
8697     }
8698 }
8699
8700 /* Build the partial symbol table by doing a quick pass through the
8701    .debug_info and .debug_abbrev sections.  */
8702
8703 static void
8704 dwarf2_build_psymtabs_hard (struct objfile *objfile)
8705 {
8706   struct cleanup *back_to;
8707   int i;
8708
8709   if (dwarf_read_debug)
8710     {
8711       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8712                           objfile_name (objfile));
8713     }
8714
8715   dwarf2_per_objfile->reading_partial_symbols = 1;
8716
8717   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8718
8719   /* Any cached compilation units will be linked by the per-objfile
8720      read_in_chain.  Make sure to free them when we're done.  */
8721   back_to = make_cleanup (free_cached_comp_units, NULL);
8722
8723   build_type_psymtabs (objfile);
8724
8725   create_all_comp_units (objfile);
8726
8727   /* Create a temporary address map on a temporary obstack.  We later
8728      copy this to the final obstack.  */
8729   auto_obstack temp_obstack;
8730
8731   scoped_restore save_psymtabs_addrmap
8732     = make_scoped_restore (&objfile->psymtabs_addrmap,
8733                            addrmap_create_mutable (&temp_obstack));
8734
8735   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8736     {
8737       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8738
8739       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8740     }
8741
8742   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8743   process_skeletonless_type_units (objfile);
8744
8745   /* Now that all TUs have been processed we can fill in the dependencies.  */
8746   if (dwarf2_per_objfile->type_unit_groups != NULL)
8747     {
8748       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8749                               build_type_psymtab_dependencies, NULL);
8750     }
8751
8752   if (dwarf_read_debug)
8753     print_tu_stats ();
8754
8755   set_partial_user (objfile);
8756
8757   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8758                                                     &objfile->objfile_obstack);
8759   /* At this point we want to keep the address map.  */
8760   save_psymtabs_addrmap.release ();
8761
8762   do_cleanups (back_to);
8763
8764   if (dwarf_read_debug)
8765     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8766                         objfile_name (objfile));
8767 }
8768
8769 /* die_reader_func for load_partial_comp_unit.  */
8770
8771 static void
8772 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8773                                const gdb_byte *info_ptr,
8774                                struct die_info *comp_unit_die,
8775                                int has_children,
8776                                void *data)
8777 {
8778   struct dwarf2_cu *cu = reader->cu;
8779
8780   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8781
8782   /* Check if comp unit has_children.
8783      If so, read the rest of the partial symbols from this comp unit.
8784      If not, there's no more debug_info for this comp unit.  */
8785   if (has_children)
8786     load_partial_dies (reader, info_ptr, 0);
8787 }
8788
8789 /* Load the partial DIEs for a secondary CU into memory.
8790    This is also used when rereading a primary CU with load_all_dies.  */
8791
8792 static void
8793 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8794 {
8795   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8796                            load_partial_comp_unit_reader, NULL);
8797 }
8798
8799 static void
8800 read_comp_units_from_section (struct objfile *objfile,
8801                               struct dwarf2_section_info *section,
8802                               struct dwarf2_section_info *abbrev_section,
8803                               unsigned int is_dwz,
8804                               int *n_allocated,
8805                               int *n_comp_units,
8806                               struct dwarf2_per_cu_data ***all_comp_units)
8807 {
8808   const gdb_byte *info_ptr;
8809
8810   if (dwarf_read_debug)
8811     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8812                         get_section_name (section),
8813                         get_section_file_name (section));
8814
8815   dwarf2_read_section (objfile, section);
8816
8817   info_ptr = section->buffer;
8818
8819   while (info_ptr < section->buffer + section->size)
8820     {
8821       struct dwarf2_per_cu_data *this_cu;
8822
8823       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8824
8825       comp_unit_head cu_header;
8826       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
8827                                      info_ptr, rcuh_kind::COMPILE);
8828
8829       /* Save the compilation unit for later lookup.  */
8830       if (cu_header.unit_type != DW_UT_type)
8831         {
8832           this_cu = XOBNEW (&objfile->objfile_obstack,
8833                             struct dwarf2_per_cu_data);
8834           memset (this_cu, 0, sizeof (*this_cu));
8835         }
8836       else
8837         {
8838           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8839                                   struct signatured_type);
8840           memset (sig_type, 0, sizeof (*sig_type));
8841           sig_type->signature = cu_header.signature;
8842           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8843           this_cu = &sig_type->per_cu;
8844         }
8845       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8846       this_cu->sect_off = sect_off;
8847       this_cu->length = cu_header.length + cu_header.initial_length_size;
8848       this_cu->is_dwz = is_dwz;
8849       this_cu->objfile = objfile;
8850       this_cu->section = section;
8851
8852       if (*n_comp_units == *n_allocated)
8853         {
8854           *n_allocated *= 2;
8855           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8856                                         *all_comp_units, *n_allocated);
8857         }
8858       (*all_comp_units)[*n_comp_units] = this_cu;
8859       ++*n_comp_units;
8860
8861       info_ptr = info_ptr + this_cu->length;
8862     }
8863 }
8864
8865 /* Create a list of all compilation units in OBJFILE.
8866    This is only done for -readnow and building partial symtabs.  */
8867
8868 static void
8869 create_all_comp_units (struct objfile *objfile)
8870 {
8871   int n_allocated;
8872   int n_comp_units;
8873   struct dwarf2_per_cu_data **all_comp_units;
8874   struct dwz_file *dwz;
8875
8876   n_comp_units = 0;
8877   n_allocated = 10;
8878   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
8879
8880   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
8881                                 &dwarf2_per_objfile->abbrev, 0,
8882                                 &n_allocated, &n_comp_units, &all_comp_units);
8883
8884   dwz = dwarf2_get_dwz_file ();
8885   if (dwz != NULL)
8886     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
8887                                   &n_allocated, &n_comp_units,
8888                                   &all_comp_units);
8889
8890   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
8891                                                   struct dwarf2_per_cu_data *,
8892                                                   n_comp_units);
8893   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
8894           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
8895   xfree (all_comp_units);
8896   dwarf2_per_objfile->n_comp_units = n_comp_units;
8897 }
8898
8899 /* Process all loaded DIEs for compilation unit CU, starting at
8900    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8901    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8902    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8903    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8904
8905 static void
8906 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8907                       CORE_ADDR *highpc, int set_addrmap,
8908                       struct dwarf2_cu *cu)
8909 {
8910   struct partial_die_info *pdi;
8911
8912   /* Now, march along the PDI's, descending into ones which have
8913      interesting children but skipping the children of the other ones,
8914      until we reach the end of the compilation unit.  */
8915
8916   pdi = first_die;
8917
8918   while (pdi != NULL)
8919     {
8920       fixup_partial_die (pdi, cu);
8921
8922       /* Anonymous namespaces or modules have no name but have interesting
8923          children, so we need to look at them.  Ditto for anonymous
8924          enums.  */
8925
8926       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8927           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8928           || pdi->tag == DW_TAG_imported_unit)
8929         {
8930           switch (pdi->tag)
8931             {
8932             case DW_TAG_subprogram:
8933               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8934               break;
8935             case DW_TAG_constant:
8936             case DW_TAG_variable:
8937             case DW_TAG_typedef:
8938             case DW_TAG_union_type:
8939               if (!pdi->is_declaration)
8940                 {
8941                   add_partial_symbol (pdi, cu);
8942                 }
8943               break;
8944             case DW_TAG_class_type:
8945             case DW_TAG_interface_type:
8946             case DW_TAG_structure_type:
8947               if (!pdi->is_declaration)
8948                 {
8949                   add_partial_symbol (pdi, cu);
8950                 }
8951               if (cu->language == language_rust && pdi->has_children)
8952                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8953                                       set_addrmap, cu);
8954               break;
8955             case DW_TAG_enumeration_type:
8956               if (!pdi->is_declaration)
8957                 add_partial_enumeration (pdi, cu);
8958               break;
8959             case DW_TAG_base_type:
8960             case DW_TAG_subrange_type:
8961               /* File scope base type definitions are added to the partial
8962                  symbol table.  */
8963               add_partial_symbol (pdi, cu);
8964               break;
8965             case DW_TAG_namespace:
8966               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8967               break;
8968             case DW_TAG_module:
8969               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8970               break;
8971             case DW_TAG_imported_unit:
8972               {
8973                 struct dwarf2_per_cu_data *per_cu;
8974
8975                 /* For now we don't handle imported units in type units.  */
8976                 if (cu->per_cu->is_debug_types)
8977                   {
8978                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8979                              " supported in type units [in module %s]"),
8980                            objfile_name (cu->objfile));
8981                   }
8982
8983                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
8984                                                            pdi->is_dwz,
8985                                                            cu->objfile);
8986
8987                 /* Go read the partial unit, if needed.  */
8988                 if (per_cu->v.psymtab == NULL)
8989                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8990
8991                 VEC_safe_push (dwarf2_per_cu_ptr,
8992                                cu->per_cu->imported_symtabs, per_cu);
8993               }
8994               break;
8995             case DW_TAG_imported_declaration:
8996               add_partial_symbol (pdi, cu);
8997               break;
8998             default:
8999               break;
9000             }
9001         }
9002
9003       /* If the die has a sibling, skip to the sibling.  */
9004
9005       pdi = pdi->die_sibling;
9006     }
9007 }
9008
9009 /* Functions used to compute the fully scoped name of a partial DIE.
9010
9011    Normally, this is simple.  For C++, the parent DIE's fully scoped
9012    name is concatenated with "::" and the partial DIE's name.
9013    Enumerators are an exception; they use the scope of their parent
9014    enumeration type, i.e. the name of the enumeration type is not
9015    prepended to the enumerator.
9016
9017    There are two complexities.  One is DW_AT_specification; in this
9018    case "parent" means the parent of the target of the specification,
9019    instead of the direct parent of the DIE.  The other is compilers
9020    which do not emit DW_TAG_namespace; in this case we try to guess
9021    the fully qualified name of structure types from their members'
9022    linkage names.  This must be done using the DIE's children rather
9023    than the children of any DW_AT_specification target.  We only need
9024    to do this for structures at the top level, i.e. if the target of
9025    any DW_AT_specification (if any; otherwise the DIE itself) does not
9026    have a parent.  */
9027
9028 /* Compute the scope prefix associated with PDI's parent, in
9029    compilation unit CU.  The result will be allocated on CU's
9030    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9031    field.  NULL is returned if no prefix is necessary.  */
9032 static const char *
9033 partial_die_parent_scope (struct partial_die_info *pdi,
9034                           struct dwarf2_cu *cu)
9035 {
9036   const char *grandparent_scope;
9037   struct partial_die_info *parent, *real_pdi;
9038
9039   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9040      then this means the parent of the specification DIE.  */
9041
9042   real_pdi = pdi;
9043   while (real_pdi->has_specification)
9044     real_pdi = find_partial_die (real_pdi->spec_offset,
9045                                  real_pdi->spec_is_dwz, cu);
9046
9047   parent = real_pdi->die_parent;
9048   if (parent == NULL)
9049     return NULL;
9050
9051   if (parent->scope_set)
9052     return parent->scope;
9053
9054   fixup_partial_die (parent, cu);
9055
9056   grandparent_scope = partial_die_parent_scope (parent, cu);
9057
9058   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9059      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9060      Work around this problem here.  */
9061   if (cu->language == language_cplus
9062       && parent->tag == DW_TAG_namespace
9063       && strcmp (parent->name, "::") == 0
9064       && grandparent_scope == NULL)
9065     {
9066       parent->scope = NULL;
9067       parent->scope_set = 1;
9068       return NULL;
9069     }
9070
9071   if (pdi->tag == DW_TAG_enumerator)
9072     /* Enumerators should not get the name of the enumeration as a prefix.  */
9073     parent->scope = grandparent_scope;
9074   else if (parent->tag == DW_TAG_namespace
9075       || parent->tag == DW_TAG_module
9076       || parent->tag == DW_TAG_structure_type
9077       || parent->tag == DW_TAG_class_type
9078       || parent->tag == DW_TAG_interface_type
9079       || parent->tag == DW_TAG_union_type
9080       || parent->tag == DW_TAG_enumeration_type)
9081     {
9082       if (grandparent_scope == NULL)
9083         parent->scope = parent->name;
9084       else
9085         parent->scope = typename_concat (&cu->comp_unit_obstack,
9086                                          grandparent_scope,
9087                                          parent->name, 0, cu);
9088     }
9089   else
9090     {
9091       /* FIXME drow/2004-04-01: What should we be doing with
9092          function-local names?  For partial symbols, we should probably be
9093          ignoring them.  */
9094       complaint (&symfile_complaints,
9095                  _("unhandled containing DIE tag %d for DIE at %d"),
9096                  parent->tag, to_underlying (pdi->sect_off));
9097       parent->scope = grandparent_scope;
9098     }
9099
9100   parent->scope_set = 1;
9101   return parent->scope;
9102 }
9103
9104 /* Return the fully scoped name associated with PDI, from compilation unit
9105    CU.  The result will be allocated with malloc.  */
9106
9107 static char *
9108 partial_die_full_name (struct partial_die_info *pdi,
9109                        struct dwarf2_cu *cu)
9110 {
9111   const char *parent_scope;
9112
9113   /* If this is a template instantiation, we can not work out the
9114      template arguments from partial DIEs.  So, unfortunately, we have
9115      to go through the full DIEs.  At least any work we do building
9116      types here will be reused if full symbols are loaded later.  */
9117   if (pdi->has_template_arguments)
9118     {
9119       fixup_partial_die (pdi, cu);
9120
9121       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9122         {
9123           struct die_info *die;
9124           struct attribute attr;
9125           struct dwarf2_cu *ref_cu = cu;
9126
9127           /* DW_FORM_ref_addr is using section offset.  */
9128           attr.name = (enum dwarf_attribute) 0;
9129           attr.form = DW_FORM_ref_addr;
9130           attr.u.unsnd = to_underlying (pdi->sect_off);
9131           die = follow_die_ref (NULL, &attr, &ref_cu);
9132
9133           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9134         }
9135     }
9136
9137   parent_scope = partial_die_parent_scope (pdi, cu);
9138   if (parent_scope == NULL)
9139     return NULL;
9140   else
9141     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9142 }
9143
9144 static void
9145 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9146 {
9147   struct objfile *objfile = cu->objfile;
9148   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9149   CORE_ADDR addr = 0;
9150   const char *actual_name = NULL;
9151   CORE_ADDR baseaddr;
9152   char *built_actual_name;
9153
9154   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9155
9156   built_actual_name = partial_die_full_name (pdi, cu);
9157   if (built_actual_name != NULL)
9158     actual_name = built_actual_name;
9159
9160   if (actual_name == NULL)
9161     actual_name = pdi->name;
9162
9163   switch (pdi->tag)
9164     {
9165     case DW_TAG_subprogram:
9166       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9167       if (pdi->is_external || cu->language == language_ada)
9168         {
9169           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9170              of the global scope.  But in Ada, we want to be able to access
9171              nested procedures globally.  So all Ada subprograms are stored
9172              in the global scope.  */
9173           add_psymbol_to_list (actual_name, strlen (actual_name),
9174                                built_actual_name != NULL,
9175                                VAR_DOMAIN, LOC_BLOCK,
9176                                &objfile->global_psymbols,
9177                                addr, cu->language, objfile);
9178         }
9179       else
9180         {
9181           add_psymbol_to_list (actual_name, strlen (actual_name),
9182                                built_actual_name != NULL,
9183                                VAR_DOMAIN, LOC_BLOCK,
9184                                &objfile->static_psymbols,
9185                                addr, cu->language, objfile);
9186         }
9187
9188       if (pdi->main_subprogram && actual_name != NULL)
9189         set_objfile_main_name (objfile, actual_name, cu->language);
9190       break;
9191     case DW_TAG_constant:
9192       {
9193         std::vector<partial_symbol *> *list;
9194
9195         if (pdi->is_external)
9196           list = &objfile->global_psymbols;
9197         else
9198           list = &objfile->static_psymbols;
9199         add_psymbol_to_list (actual_name, strlen (actual_name),
9200                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9201                              list, 0, cu->language, objfile);
9202       }
9203       break;
9204     case DW_TAG_variable:
9205       if (pdi->d.locdesc)
9206         addr = decode_locdesc (pdi->d.locdesc, cu);
9207
9208       if (pdi->d.locdesc
9209           && addr == 0
9210           && !dwarf2_per_objfile->has_section_at_zero)
9211         {
9212           /* A global or static variable may also have been stripped
9213              out by the linker if unused, in which case its address
9214              will be nullified; do not add such variables into partial
9215              symbol table then.  */
9216         }
9217       else if (pdi->is_external)
9218         {
9219           /* Global Variable.
9220              Don't enter into the minimal symbol tables as there is
9221              a minimal symbol table entry from the ELF symbols already.
9222              Enter into partial symbol table if it has a location
9223              descriptor or a type.
9224              If the location descriptor is missing, new_symbol will create
9225              a LOC_UNRESOLVED symbol, the address of the variable will then
9226              be determined from the minimal symbol table whenever the variable
9227              is referenced.
9228              The address for the partial symbol table entry is not
9229              used by GDB, but it comes in handy for debugging partial symbol
9230              table building.  */
9231
9232           if (pdi->d.locdesc || pdi->has_type)
9233             add_psymbol_to_list (actual_name, strlen (actual_name),
9234                                  built_actual_name != NULL,
9235                                  VAR_DOMAIN, LOC_STATIC,
9236                                  &objfile->global_psymbols,
9237                                  addr + baseaddr,
9238                                  cu->language, objfile);
9239         }
9240       else
9241         {
9242           int has_loc = pdi->d.locdesc != NULL;
9243
9244           /* Static Variable.  Skip symbols whose value we cannot know (those
9245              without location descriptors or constant values).  */
9246           if (!has_loc && !pdi->has_const_value)
9247             {
9248               xfree (built_actual_name);
9249               return;
9250             }
9251
9252           add_psymbol_to_list (actual_name, strlen (actual_name),
9253                                built_actual_name != NULL,
9254                                VAR_DOMAIN, LOC_STATIC,
9255                                &objfile->static_psymbols,
9256                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9257                                cu->language, objfile);
9258         }
9259       break;
9260     case DW_TAG_typedef:
9261     case DW_TAG_base_type:
9262     case DW_TAG_subrange_type:
9263       add_psymbol_to_list (actual_name, strlen (actual_name),
9264                            built_actual_name != NULL,
9265                            VAR_DOMAIN, LOC_TYPEDEF,
9266                            &objfile->static_psymbols,
9267                            0, cu->language, objfile);
9268       break;
9269     case DW_TAG_imported_declaration:
9270     case DW_TAG_namespace:
9271       add_psymbol_to_list (actual_name, strlen (actual_name),
9272                            built_actual_name != NULL,
9273                            VAR_DOMAIN, LOC_TYPEDEF,
9274                            &objfile->global_psymbols,
9275                            0, cu->language, objfile);
9276       break;
9277     case DW_TAG_module:
9278       add_psymbol_to_list (actual_name, strlen (actual_name),
9279                            built_actual_name != NULL,
9280                            MODULE_DOMAIN, LOC_TYPEDEF,
9281                            &objfile->global_psymbols,
9282                            0, cu->language, objfile);
9283       break;
9284     case DW_TAG_class_type:
9285     case DW_TAG_interface_type:
9286     case DW_TAG_structure_type:
9287     case DW_TAG_union_type:
9288     case DW_TAG_enumeration_type:
9289       /* Skip external references.  The DWARF standard says in the section
9290          about "Structure, Union, and Class Type Entries": "An incomplete
9291          structure, union or class type is represented by a structure,
9292          union or class entry that does not have a byte size attribute
9293          and that has a DW_AT_declaration attribute."  */
9294       if (!pdi->has_byte_size && pdi->is_declaration)
9295         {
9296           xfree (built_actual_name);
9297           return;
9298         }
9299
9300       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9301          static vs. global.  */
9302       add_psymbol_to_list (actual_name, strlen (actual_name),
9303                            built_actual_name != NULL,
9304                            STRUCT_DOMAIN, LOC_TYPEDEF,
9305                            cu->language == language_cplus
9306                            ? &objfile->global_psymbols
9307                            : &objfile->static_psymbols,
9308                            0, cu->language, objfile);
9309
9310       break;
9311     case DW_TAG_enumerator:
9312       add_psymbol_to_list (actual_name, strlen (actual_name),
9313                            built_actual_name != NULL,
9314                            VAR_DOMAIN, LOC_CONST,
9315                            cu->language == language_cplus
9316                            ? &objfile->global_psymbols
9317                            : &objfile->static_psymbols,
9318                            0, cu->language, objfile);
9319       break;
9320     default:
9321       break;
9322     }
9323
9324   xfree (built_actual_name);
9325 }
9326
9327 /* Read a partial die corresponding to a namespace; also, add a symbol
9328    corresponding to that namespace to the symbol table.  NAMESPACE is
9329    the name of the enclosing namespace.  */
9330
9331 static void
9332 add_partial_namespace (struct partial_die_info *pdi,
9333                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9334                        int set_addrmap, struct dwarf2_cu *cu)
9335 {
9336   /* Add a symbol for the namespace.  */
9337
9338   add_partial_symbol (pdi, cu);
9339
9340   /* Now scan partial symbols in that namespace.  */
9341
9342   if (pdi->has_children)
9343     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9344 }
9345
9346 /* Read a partial die corresponding to a Fortran module.  */
9347
9348 static void
9349 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9350                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9351 {
9352   /* Add a symbol for the namespace.  */
9353
9354   add_partial_symbol (pdi, cu);
9355
9356   /* Now scan partial symbols in that module.  */
9357
9358   if (pdi->has_children)
9359     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9360 }
9361
9362 /* Read a partial die corresponding to a subprogram and create a partial
9363    symbol for that subprogram.  When the CU language allows it, this
9364    routine also defines a partial symbol for each nested subprogram
9365    that this subprogram contains.  If SET_ADDRMAP is true, record the
9366    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
9367    and highest PC values found in PDI.
9368
9369    PDI may also be a lexical block, in which case we simply search
9370    recursively for subprograms defined inside that lexical block.
9371    Again, this is only performed when the CU language allows this
9372    type of definitions.  */
9373
9374 static void
9375 add_partial_subprogram (struct partial_die_info *pdi,
9376                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9377                         int set_addrmap, struct dwarf2_cu *cu)
9378 {
9379   if (pdi->tag == DW_TAG_subprogram)
9380     {
9381       if (pdi->has_pc_info)
9382         {
9383           if (pdi->lowpc < *lowpc)
9384             *lowpc = pdi->lowpc;
9385           if (pdi->highpc > *highpc)
9386             *highpc = pdi->highpc;
9387           if (set_addrmap)
9388             {
9389               struct objfile *objfile = cu->objfile;
9390               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9391               CORE_ADDR baseaddr;
9392               CORE_ADDR highpc;
9393               CORE_ADDR lowpc;
9394
9395               baseaddr = ANOFFSET (objfile->section_offsets,
9396                                    SECT_OFF_TEXT (objfile));
9397               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9398                                                   pdi->lowpc + baseaddr);
9399               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9400                                                    pdi->highpc + baseaddr);
9401               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9402                                  cu->per_cu->v.psymtab);
9403             }
9404         }
9405
9406       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9407         {
9408           if (!pdi->is_declaration)
9409             /* Ignore subprogram DIEs that do not have a name, they are
9410                illegal.  Do not emit a complaint at this point, we will
9411                do so when we convert this psymtab into a symtab.  */
9412             if (pdi->name)
9413               add_partial_symbol (pdi, cu);
9414         }
9415     }
9416
9417   if (! pdi->has_children)
9418     return;
9419
9420   if (cu->language == language_ada)
9421     {
9422       pdi = pdi->die_child;
9423       while (pdi != NULL)
9424         {
9425           fixup_partial_die (pdi, cu);
9426           if (pdi->tag == DW_TAG_subprogram
9427               || pdi->tag == DW_TAG_lexical_block)
9428             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9429           pdi = pdi->die_sibling;
9430         }
9431     }
9432 }
9433
9434 /* Read a partial die corresponding to an enumeration type.  */
9435
9436 static void
9437 add_partial_enumeration (struct partial_die_info *enum_pdi,
9438                          struct dwarf2_cu *cu)
9439 {
9440   struct partial_die_info *pdi;
9441
9442   if (enum_pdi->name != NULL)
9443     add_partial_symbol (enum_pdi, cu);
9444
9445   pdi = enum_pdi->die_child;
9446   while (pdi)
9447     {
9448       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9449         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9450       else
9451         add_partial_symbol (pdi, cu);
9452       pdi = pdi->die_sibling;
9453     }
9454 }
9455
9456 /* Return the initial uleb128 in the die at INFO_PTR.  */
9457
9458 static unsigned int
9459 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9460 {
9461   unsigned int bytes_read;
9462
9463   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9464 }
9465
9466 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
9467    Return the corresponding abbrev, or NULL if the number is zero (indicating
9468    an empty DIE).  In either case *BYTES_READ will be set to the length of
9469    the initial number.  */
9470
9471 static struct abbrev_info *
9472 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
9473                  struct dwarf2_cu *cu)
9474 {
9475   bfd *abfd = cu->objfile->obfd;
9476   unsigned int abbrev_number;
9477   struct abbrev_info *abbrev;
9478
9479   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9480
9481   if (abbrev_number == 0)
9482     return NULL;
9483
9484   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
9485   if (!abbrev)
9486     {
9487       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9488                " at offset 0x%x [in module %s]"),
9489              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9490              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9491     }
9492
9493   return abbrev;
9494 }
9495
9496 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9497    Returns a pointer to the end of a series of DIEs, terminated by an empty
9498    DIE.  Any children of the skipped DIEs will also be skipped.  */
9499
9500 static const gdb_byte *
9501 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9502 {
9503   struct dwarf2_cu *cu = reader->cu;
9504   struct abbrev_info *abbrev;
9505   unsigned int bytes_read;
9506
9507   while (1)
9508     {
9509       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
9510       if (abbrev == NULL)
9511         return info_ptr + bytes_read;
9512       else
9513         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9514     }
9515 }
9516
9517 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9518    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9519    abbrev corresponding to that skipped uleb128 should be passed in
9520    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9521    children.  */
9522
9523 static const gdb_byte *
9524 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9525               struct abbrev_info *abbrev)
9526 {
9527   unsigned int bytes_read;
9528   struct attribute attr;
9529   bfd *abfd = reader->abfd;
9530   struct dwarf2_cu *cu = reader->cu;
9531   const gdb_byte *buffer = reader->buffer;
9532   const gdb_byte *buffer_end = reader->buffer_end;
9533   unsigned int form, i;
9534
9535   for (i = 0; i < abbrev->num_attrs; i++)
9536     {
9537       /* The only abbrev we care about is DW_AT_sibling.  */
9538       if (abbrev->attrs[i].name == DW_AT_sibling)
9539         {
9540           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9541           if (attr.form == DW_FORM_ref_addr)
9542             complaint (&symfile_complaints,
9543                        _("ignoring absolute DW_AT_sibling"));
9544           else
9545             {
9546               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9547               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9548
9549               if (sibling_ptr < info_ptr)
9550                 complaint (&symfile_complaints,
9551                            _("DW_AT_sibling points backwards"));
9552               else if (sibling_ptr > reader->buffer_end)
9553                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9554               else
9555                 return sibling_ptr;
9556             }
9557         }
9558
9559       /* If it isn't DW_AT_sibling, skip this attribute.  */
9560       form = abbrev->attrs[i].form;
9561     skip_attribute:
9562       switch (form)
9563         {
9564         case DW_FORM_ref_addr:
9565           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9566              and later it is offset sized.  */
9567           if (cu->header.version == 2)
9568             info_ptr += cu->header.addr_size;
9569           else
9570             info_ptr += cu->header.offset_size;
9571           break;
9572         case DW_FORM_GNU_ref_alt:
9573           info_ptr += cu->header.offset_size;
9574           break;
9575         case DW_FORM_addr:
9576           info_ptr += cu->header.addr_size;
9577           break;
9578         case DW_FORM_data1:
9579         case DW_FORM_ref1:
9580         case DW_FORM_flag:
9581           info_ptr += 1;
9582           break;
9583         case DW_FORM_flag_present:
9584         case DW_FORM_implicit_const:
9585           break;
9586         case DW_FORM_data2:
9587         case DW_FORM_ref2:
9588           info_ptr += 2;
9589           break;
9590         case DW_FORM_data4:
9591         case DW_FORM_ref4:
9592           info_ptr += 4;
9593           break;
9594         case DW_FORM_data8:
9595         case DW_FORM_ref8:
9596         case DW_FORM_ref_sig8:
9597           info_ptr += 8;
9598           break;
9599         case DW_FORM_data16:
9600           info_ptr += 16;
9601           break;
9602         case DW_FORM_string:
9603           read_direct_string (abfd, info_ptr, &bytes_read);
9604           info_ptr += bytes_read;
9605           break;
9606         case DW_FORM_sec_offset:
9607         case DW_FORM_strp:
9608         case DW_FORM_GNU_strp_alt:
9609           info_ptr += cu->header.offset_size;
9610           break;
9611         case DW_FORM_exprloc:
9612         case DW_FORM_block:
9613           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9614           info_ptr += bytes_read;
9615           break;
9616         case DW_FORM_block1:
9617           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9618           break;
9619         case DW_FORM_block2:
9620           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9621           break;
9622         case DW_FORM_block4:
9623           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9624           break;
9625         case DW_FORM_sdata:
9626         case DW_FORM_udata:
9627         case DW_FORM_ref_udata:
9628         case DW_FORM_GNU_addr_index:
9629         case DW_FORM_GNU_str_index:
9630           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9631           break;
9632         case DW_FORM_indirect:
9633           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9634           info_ptr += bytes_read;
9635           /* We need to continue parsing from here, so just go back to
9636              the top.  */
9637           goto skip_attribute;
9638
9639         default:
9640           error (_("Dwarf Error: Cannot handle %s "
9641                    "in DWARF reader [in module %s]"),
9642                  dwarf_form_name (form),
9643                  bfd_get_filename (abfd));
9644         }
9645     }
9646
9647   if (abbrev->has_children)
9648     return skip_children (reader, info_ptr);
9649   else
9650     return info_ptr;
9651 }
9652
9653 /* Locate ORIG_PDI's sibling.
9654    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9655
9656 static const gdb_byte *
9657 locate_pdi_sibling (const struct die_reader_specs *reader,
9658                     struct partial_die_info *orig_pdi,
9659                     const gdb_byte *info_ptr)
9660 {
9661   /* Do we know the sibling already?  */
9662
9663   if (orig_pdi->sibling)
9664     return orig_pdi->sibling;
9665
9666   /* Are there any children to deal with?  */
9667
9668   if (!orig_pdi->has_children)
9669     return info_ptr;
9670
9671   /* Skip the children the long way.  */
9672
9673   return skip_children (reader, info_ptr);
9674 }
9675
9676 /* Expand this partial symbol table into a full symbol table.  SELF is
9677    not NULL.  */
9678
9679 static void
9680 dwarf2_read_symtab (struct partial_symtab *self,
9681                     struct objfile *objfile)
9682 {
9683   if (self->readin)
9684     {
9685       warning (_("bug: psymtab for %s is already read in."),
9686                self->filename);
9687     }
9688   else
9689     {
9690       if (info_verbose)
9691         {
9692           printf_filtered (_("Reading in symbols for %s..."),
9693                            self->filename);
9694           gdb_flush (gdb_stdout);
9695         }
9696
9697       /* Restore our global data.  */
9698       dwarf2_per_objfile
9699         = (struct dwarf2_per_objfile *) objfile_data (objfile,
9700                                                       dwarf2_objfile_data_key);
9701
9702       /* If this psymtab is constructed from a debug-only objfile, the
9703          has_section_at_zero flag will not necessarily be correct.  We
9704          can get the correct value for this flag by looking at the data
9705          associated with the (presumably stripped) associated objfile.  */
9706       if (objfile->separate_debug_objfile_backlink)
9707         {
9708           struct dwarf2_per_objfile *dpo_backlink
9709             = ((struct dwarf2_per_objfile *)
9710                objfile_data (objfile->separate_debug_objfile_backlink,
9711                              dwarf2_objfile_data_key));
9712
9713           dwarf2_per_objfile->has_section_at_zero
9714             = dpo_backlink->has_section_at_zero;
9715         }
9716
9717       dwarf2_per_objfile->reading_partial_symbols = 0;
9718
9719       psymtab_to_symtab_1 (self);
9720
9721       /* Finish up the debug error message.  */
9722       if (info_verbose)
9723         printf_filtered (_("done.\n"));
9724     }
9725
9726   process_cu_includes ();
9727 }
9728 \f
9729 /* Reading in full CUs.  */
9730
9731 /* Add PER_CU to the queue.  */
9732
9733 static void
9734 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9735                  enum language pretend_language)
9736 {
9737   struct dwarf2_queue_item *item;
9738
9739   per_cu->queued = 1;
9740   item = XNEW (struct dwarf2_queue_item);
9741   item->per_cu = per_cu;
9742   item->pretend_language = pretend_language;
9743   item->next = NULL;
9744
9745   if (dwarf2_queue == NULL)
9746     dwarf2_queue = item;
9747   else
9748     dwarf2_queue_tail->next = item;
9749
9750   dwarf2_queue_tail = item;
9751 }
9752
9753 /* If PER_CU is not yet queued, add it to the queue.
9754    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9755    dependency.
9756    The result is non-zero if PER_CU was queued, otherwise the result is zero
9757    meaning either PER_CU is already queued or it is already loaded.
9758
9759    N.B. There is an invariant here that if a CU is queued then it is loaded.
9760    The caller is required to load PER_CU if we return non-zero.  */
9761
9762 static int
9763 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9764                        struct dwarf2_per_cu_data *per_cu,
9765                        enum language pretend_language)
9766 {
9767   /* We may arrive here during partial symbol reading, if we need full
9768      DIEs to process an unusual case (e.g. template arguments).  Do
9769      not queue PER_CU, just tell our caller to load its DIEs.  */
9770   if (dwarf2_per_objfile->reading_partial_symbols)
9771     {
9772       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9773         return 1;
9774       return 0;
9775     }
9776
9777   /* Mark the dependence relation so that we don't flush PER_CU
9778      too early.  */
9779   if (dependent_cu != NULL)
9780     dwarf2_add_dependence (dependent_cu, per_cu);
9781
9782   /* If it's already on the queue, we have nothing to do.  */
9783   if (per_cu->queued)
9784     return 0;
9785
9786   /* If the compilation unit is already loaded, just mark it as
9787      used.  */
9788   if (per_cu->cu != NULL)
9789     {
9790       per_cu->cu->last_used = 0;
9791       return 0;
9792     }
9793
9794   /* Add it to the queue.  */
9795   queue_comp_unit (per_cu, pretend_language);
9796
9797   return 1;
9798 }
9799
9800 /* Process the queue.  */
9801
9802 static void
9803 process_queue (void)
9804 {
9805   struct dwarf2_queue_item *item, *next_item;
9806
9807   if (dwarf_read_debug)
9808     {
9809       fprintf_unfiltered (gdb_stdlog,
9810                           "Expanding one or more symtabs of objfile %s ...\n",
9811                           objfile_name (dwarf2_per_objfile->objfile));
9812     }
9813
9814   /* The queue starts out with one item, but following a DIE reference
9815      may load a new CU, adding it to the end of the queue.  */
9816   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9817     {
9818       if ((dwarf2_per_objfile->using_index
9819            ? !item->per_cu->v.quick->compunit_symtab
9820            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9821           /* Skip dummy CUs.  */
9822           && item->per_cu->cu != NULL)
9823         {
9824           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9825           unsigned int debug_print_threshold;
9826           char buf[100];
9827
9828           if (per_cu->is_debug_types)
9829             {
9830               struct signatured_type *sig_type =
9831                 (struct signatured_type *) per_cu;
9832
9833               sprintf (buf, "TU %s at offset 0x%x",
9834                        hex_string (sig_type->signature),
9835                        to_underlying (per_cu->sect_off));
9836               /* There can be 100s of TUs.
9837                  Only print them in verbose mode.  */
9838               debug_print_threshold = 2;
9839             }
9840           else
9841             {
9842               sprintf (buf, "CU at offset 0x%x",
9843                        to_underlying (per_cu->sect_off));
9844               debug_print_threshold = 1;
9845             }
9846
9847           if (dwarf_read_debug >= debug_print_threshold)
9848             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9849
9850           if (per_cu->is_debug_types)
9851             process_full_type_unit (per_cu, item->pretend_language);
9852           else
9853             process_full_comp_unit (per_cu, item->pretend_language);
9854
9855           if (dwarf_read_debug >= debug_print_threshold)
9856             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9857         }
9858
9859       item->per_cu->queued = 0;
9860       next_item = item->next;
9861       xfree (item);
9862     }
9863
9864   dwarf2_queue_tail = NULL;
9865
9866   if (dwarf_read_debug)
9867     {
9868       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9869                           objfile_name (dwarf2_per_objfile->objfile));
9870     }
9871 }
9872
9873 /* Free all allocated queue entries.  This function only releases anything if
9874    an error was thrown; if the queue was processed then it would have been
9875    freed as we went along.  */
9876
9877 static void
9878 dwarf2_release_queue (void *dummy)
9879 {
9880   struct dwarf2_queue_item *item, *last;
9881
9882   item = dwarf2_queue;
9883   while (item)
9884     {
9885       /* Anything still marked queued is likely to be in an
9886          inconsistent state, so discard it.  */
9887       if (item->per_cu->queued)
9888         {
9889           if (item->per_cu->cu != NULL)
9890             free_one_cached_comp_unit (item->per_cu);
9891           item->per_cu->queued = 0;
9892         }
9893
9894       last = item;
9895       item = item->next;
9896       xfree (last);
9897     }
9898
9899   dwarf2_queue = dwarf2_queue_tail = NULL;
9900 }
9901
9902 /* Read in full symbols for PST, and anything it depends on.  */
9903
9904 static void
9905 psymtab_to_symtab_1 (struct partial_symtab *pst)
9906 {
9907   struct dwarf2_per_cu_data *per_cu;
9908   int i;
9909
9910   if (pst->readin)
9911     return;
9912
9913   for (i = 0; i < pst->number_of_dependencies; i++)
9914     if (!pst->dependencies[i]->readin
9915         && pst->dependencies[i]->user == NULL)
9916       {
9917         /* Inform about additional files that need to be read in.  */
9918         if (info_verbose)
9919           {
9920             /* FIXME: i18n: Need to make this a single string.  */
9921             fputs_filtered (" ", gdb_stdout);
9922             wrap_here ("");
9923             fputs_filtered ("and ", gdb_stdout);
9924             wrap_here ("");
9925             printf_filtered ("%s...", pst->dependencies[i]->filename);
9926             wrap_here ("");     /* Flush output.  */
9927             gdb_flush (gdb_stdout);
9928           }
9929         psymtab_to_symtab_1 (pst->dependencies[i]);
9930       }
9931
9932   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9933
9934   if (per_cu == NULL)
9935     {
9936       /* It's an include file, no symbols to read for it.
9937          Everything is in the parent symtab.  */
9938       pst->readin = 1;
9939       return;
9940     }
9941
9942   dw2_do_instantiate_symtab (per_cu);
9943 }
9944
9945 /* Trivial hash function for die_info: the hash value of a DIE
9946    is its offset in .debug_info for this objfile.  */
9947
9948 static hashval_t
9949 die_hash (const void *item)
9950 {
9951   const struct die_info *die = (const struct die_info *) item;
9952
9953   return to_underlying (die->sect_off);
9954 }
9955
9956 /* Trivial comparison function for die_info structures: two DIEs
9957    are equal if they have the same offset.  */
9958
9959 static int
9960 die_eq (const void *item_lhs, const void *item_rhs)
9961 {
9962   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9963   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9964
9965   return die_lhs->sect_off == die_rhs->sect_off;
9966 }
9967
9968 /* die_reader_func for load_full_comp_unit.
9969    This is identical to read_signatured_type_reader,
9970    but is kept separate for now.  */
9971
9972 static void
9973 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9974                             const gdb_byte *info_ptr,
9975                             struct die_info *comp_unit_die,
9976                             int has_children,
9977                             void *data)
9978 {
9979   struct dwarf2_cu *cu = reader->cu;
9980   enum language *language_ptr = (enum language *) data;
9981
9982   gdb_assert (cu->die_hash == NULL);
9983   cu->die_hash =
9984     htab_create_alloc_ex (cu->header.length / 12,
9985                           die_hash,
9986                           die_eq,
9987                           NULL,
9988                           &cu->comp_unit_obstack,
9989                           hashtab_obstack_allocate,
9990                           dummy_obstack_deallocate);
9991
9992   if (has_children)
9993     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9994                                                   &info_ptr, comp_unit_die);
9995   cu->dies = comp_unit_die;
9996   /* comp_unit_die is not stored in die_hash, no need.  */
9997
9998   /* We try not to read any attributes in this function, because not
9999      all CUs needed for references have been loaded yet, and symbol
10000      table processing isn't initialized.  But we have to set the CU language,
10001      or we won't be able to build types correctly.
10002      Similarly, if we do not read the producer, we can not apply
10003      producer-specific interpretation.  */
10004   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10005 }
10006
10007 /* Load the DIEs associated with PER_CU into memory.  */
10008
10009 static void
10010 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10011                      enum language pretend_language)
10012 {
10013   gdb_assert (! this_cu->is_debug_types);
10014
10015   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10016                            load_full_comp_unit_reader, &pretend_language);
10017 }
10018
10019 /* Add a DIE to the delayed physname list.  */
10020
10021 static void
10022 add_to_method_list (struct type *type, int fnfield_index, int index,
10023                     const char *name, struct die_info *die,
10024                     struct dwarf2_cu *cu)
10025 {
10026   struct delayed_method_info mi;
10027   mi.type = type;
10028   mi.fnfield_index = fnfield_index;
10029   mi.index = index;
10030   mi.name = name;
10031   mi.die = die;
10032   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
10033 }
10034
10035 /* A cleanup for freeing the delayed method list.  */
10036
10037 static void
10038 free_delayed_list (void *ptr)
10039 {
10040   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
10041   if (cu->method_list != NULL)
10042     {
10043       VEC_free (delayed_method_info, cu->method_list);
10044       cu->method_list = NULL;
10045     }
10046 }
10047
10048 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10049    "const" / "volatile".  If so, decrements LEN by the length of the
10050    modifier and return true.  Otherwise return false.  */
10051
10052 template<size_t N>
10053 static bool
10054 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10055 {
10056   size_t mod_len = sizeof (mod) - 1;
10057   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10058     {
10059       len -= mod_len;
10060       return true;
10061     }
10062   return false;
10063 }
10064
10065 /* Compute the physnames of any methods on the CU's method list.
10066
10067    The computation of method physnames is delayed in order to avoid the
10068    (bad) condition that one of the method's formal parameters is of an as yet
10069    incomplete type.  */
10070
10071 static void
10072 compute_delayed_physnames (struct dwarf2_cu *cu)
10073 {
10074   int i;
10075   struct delayed_method_info *mi;
10076
10077   /* Only C++ delays computing physnames.  */
10078   if (VEC_empty (delayed_method_info, cu->method_list))
10079     return;
10080   gdb_assert (cu->language == language_cplus);
10081
10082   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
10083     {
10084       const char *physname;
10085       struct fn_fieldlist *fn_flp
10086         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
10087       physname = dwarf2_physname (mi->name, mi->die, cu);
10088       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
10089         = physname ? physname : "";
10090
10091       /* Since there's no tag to indicate whether a method is a
10092          const/volatile overload, extract that information out of the
10093          demangled name.  */
10094       if (physname != NULL)
10095         {
10096           size_t len = strlen (physname);
10097
10098           while (1)
10099             {
10100               if (physname[len] == ')') /* shortcut */
10101                 break;
10102               else if (check_modifier (physname, len, " const"))
10103                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
10104               else if (check_modifier (physname, len, " volatile"))
10105                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
10106               else
10107                 break;
10108             }
10109         }
10110     }
10111 }
10112
10113 /* Go objects should be embedded in a DW_TAG_module DIE,
10114    and it's not clear if/how imported objects will appear.
10115    To keep Go support simple until that's worked out,
10116    go back through what we've read and create something usable.
10117    We could do this while processing each DIE, and feels kinda cleaner,
10118    but that way is more invasive.
10119    This is to, for example, allow the user to type "p var" or "b main"
10120    without having to specify the package name, and allow lookups
10121    of module.object to work in contexts that use the expression
10122    parser.  */
10123
10124 static void
10125 fixup_go_packaging (struct dwarf2_cu *cu)
10126 {
10127   char *package_name = NULL;
10128   struct pending *list;
10129   int i;
10130
10131   for (list = global_symbols; list != NULL; list = list->next)
10132     {
10133       for (i = 0; i < list->nsyms; ++i)
10134         {
10135           struct symbol *sym = list->symbol[i];
10136
10137           if (SYMBOL_LANGUAGE (sym) == language_go
10138               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10139             {
10140               char *this_package_name = go_symbol_package_name (sym);
10141
10142               if (this_package_name == NULL)
10143                 continue;
10144               if (package_name == NULL)
10145                 package_name = this_package_name;
10146               else
10147                 {
10148                   if (strcmp (package_name, this_package_name) != 0)
10149                     complaint (&symfile_complaints,
10150                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10151                                (symbol_symtab (sym) != NULL
10152                                 ? symtab_to_filename_for_display
10153                                     (symbol_symtab (sym))
10154                                 : objfile_name (cu->objfile)),
10155                                this_package_name, package_name);
10156                   xfree (this_package_name);
10157                 }
10158             }
10159         }
10160     }
10161
10162   if (package_name != NULL)
10163     {
10164       struct objfile *objfile = cu->objfile;
10165       const char *saved_package_name
10166         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10167                                         package_name,
10168                                         strlen (package_name));
10169       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10170                                      saved_package_name);
10171       struct symbol *sym;
10172
10173       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10174
10175       sym = allocate_symbol (objfile);
10176       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10177       SYMBOL_SET_NAMES (sym, saved_package_name,
10178                         strlen (saved_package_name), 0, objfile);
10179       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10180          e.g., "main" finds the "main" module and not C's main().  */
10181       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10182       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10183       SYMBOL_TYPE (sym) = type;
10184
10185       add_symbol_to_list (sym, &global_symbols);
10186
10187       xfree (package_name);
10188     }
10189 }
10190
10191 /* Return the symtab for PER_CU.  This works properly regardless of
10192    whether we're using the index or psymtabs.  */
10193
10194 static struct compunit_symtab *
10195 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10196 {
10197   return (dwarf2_per_objfile->using_index
10198           ? per_cu->v.quick->compunit_symtab
10199           : per_cu->v.psymtab->compunit_symtab);
10200 }
10201
10202 /* A helper function for computing the list of all symbol tables
10203    included by PER_CU.  */
10204
10205 static void
10206 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10207                                 htab_t all_children, htab_t all_type_symtabs,
10208                                 struct dwarf2_per_cu_data *per_cu,
10209                                 struct compunit_symtab *immediate_parent)
10210 {
10211   void **slot;
10212   int ix;
10213   struct compunit_symtab *cust;
10214   struct dwarf2_per_cu_data *iter;
10215
10216   slot = htab_find_slot (all_children, per_cu, INSERT);
10217   if (*slot != NULL)
10218     {
10219       /* This inclusion and its children have been processed.  */
10220       return;
10221     }
10222
10223   *slot = per_cu;
10224   /* Only add a CU if it has a symbol table.  */
10225   cust = get_compunit_symtab (per_cu);
10226   if (cust != NULL)
10227     {
10228       /* If this is a type unit only add its symbol table if we haven't
10229          seen it yet (type unit per_cu's can share symtabs).  */
10230       if (per_cu->is_debug_types)
10231         {
10232           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10233           if (*slot == NULL)
10234             {
10235               *slot = cust;
10236               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10237               if (cust->user == NULL)
10238                 cust->user = immediate_parent;
10239             }
10240         }
10241       else
10242         {
10243           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10244           if (cust->user == NULL)
10245             cust->user = immediate_parent;
10246         }
10247     }
10248
10249   for (ix = 0;
10250        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10251        ++ix)
10252     {
10253       recursively_compute_inclusions (result, all_children,
10254                                       all_type_symtabs, iter, cust);
10255     }
10256 }
10257
10258 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10259    PER_CU.  */
10260
10261 static void
10262 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10263 {
10264   gdb_assert (! per_cu->is_debug_types);
10265
10266   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10267     {
10268       int ix, len;
10269       struct dwarf2_per_cu_data *per_cu_iter;
10270       struct compunit_symtab *compunit_symtab_iter;
10271       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10272       htab_t all_children, all_type_symtabs;
10273       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10274
10275       /* If we don't have a symtab, we can just skip this case.  */
10276       if (cust == NULL)
10277         return;
10278
10279       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10280                                         NULL, xcalloc, xfree);
10281       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10282                                             NULL, xcalloc, xfree);
10283
10284       for (ix = 0;
10285            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10286                         ix, per_cu_iter);
10287            ++ix)
10288         {
10289           recursively_compute_inclusions (&result_symtabs, all_children,
10290                                           all_type_symtabs, per_cu_iter,
10291                                           cust);
10292         }
10293
10294       /* Now we have a transitive closure of all the included symtabs.  */
10295       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10296       cust->includes
10297         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
10298                      struct compunit_symtab *, len + 1);
10299       for (ix = 0;
10300            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10301                         compunit_symtab_iter);
10302            ++ix)
10303         cust->includes[ix] = compunit_symtab_iter;
10304       cust->includes[len] = NULL;
10305
10306       VEC_free (compunit_symtab_ptr, result_symtabs);
10307       htab_delete (all_children);
10308       htab_delete (all_type_symtabs);
10309     }
10310 }
10311
10312 /* Compute the 'includes' field for the symtabs of all the CUs we just
10313    read.  */
10314
10315 static void
10316 process_cu_includes (void)
10317 {
10318   int ix;
10319   struct dwarf2_per_cu_data *iter;
10320
10321   for (ix = 0;
10322        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10323                     ix, iter);
10324        ++ix)
10325     {
10326       if (! iter->is_debug_types)
10327         compute_compunit_symtab_includes (iter);
10328     }
10329
10330   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10331 }
10332
10333 /* Generate full symbol information for PER_CU, whose DIEs have
10334    already been loaded into memory.  */
10335
10336 static void
10337 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10338                         enum language pretend_language)
10339 {
10340   struct dwarf2_cu *cu = per_cu->cu;
10341   struct objfile *objfile = per_cu->objfile;
10342   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10343   CORE_ADDR lowpc, highpc;
10344   struct compunit_symtab *cust;
10345   struct cleanup *delayed_list_cleanup;
10346   CORE_ADDR baseaddr;
10347   struct block *static_block;
10348   CORE_ADDR addr;
10349
10350   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10351
10352   buildsym_init ();
10353   scoped_free_pendings free_pending;
10354   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10355
10356   cu->list_in_scope = &file_symbols;
10357
10358   cu->language = pretend_language;
10359   cu->language_defn = language_def (cu->language);
10360
10361   /* Do line number decoding in read_file_scope () */
10362   process_die (cu->dies, cu);
10363
10364   /* For now fudge the Go package.  */
10365   if (cu->language == language_go)
10366     fixup_go_packaging (cu);
10367
10368   /* Now that we have processed all the DIEs in the CU, all the types 
10369      should be complete, and it should now be safe to compute all of the
10370      physnames.  */
10371   compute_delayed_physnames (cu);
10372   do_cleanups (delayed_list_cleanup);
10373
10374   /* Some compilers don't define a DW_AT_high_pc attribute for the
10375      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10376      it, by scanning the DIE's below the compilation unit.  */
10377   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10378
10379   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10380   static_block = end_symtab_get_static_block (addr, 0, 1);
10381
10382   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10383      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10384      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10385      addrmap to help ensure it has an accurate map of pc values belonging to
10386      this comp unit.  */
10387   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10388
10389   cust = end_symtab_from_static_block (static_block,
10390                                        SECT_OFF_TEXT (objfile), 0);
10391
10392   if (cust != NULL)
10393     {
10394       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10395
10396       /* Set symtab language to language from DW_AT_language.  If the
10397          compilation is from a C file generated by language preprocessors, do
10398          not set the language if it was already deduced by start_subfile.  */
10399       if (!(cu->language == language_c
10400             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10401         COMPUNIT_FILETABS (cust)->language = cu->language;
10402
10403       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10404          produce DW_AT_location with location lists but it can be possibly
10405          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10406          there were bugs in prologue debug info, fixed later in GCC-4.5
10407          by "unwind info for epilogues" patch (which is not directly related).
10408
10409          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10410          needed, it would be wrong due to missing DW_AT_producer there.
10411
10412          Still one can confuse GDB by using non-standard GCC compilation
10413          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10414          */ 
10415       if (cu->has_loclist && gcc_4_minor >= 5)
10416         cust->locations_valid = 1;
10417
10418       if (gcc_4_minor >= 5)
10419         cust->epilogue_unwind_valid = 1;
10420
10421       cust->call_site_htab = cu->call_site_htab;
10422     }
10423
10424   if (dwarf2_per_objfile->using_index)
10425     per_cu->v.quick->compunit_symtab = cust;
10426   else
10427     {
10428       struct partial_symtab *pst = per_cu->v.psymtab;
10429       pst->compunit_symtab = cust;
10430       pst->readin = 1;
10431     }
10432
10433   /* Push it for inclusion processing later.  */
10434   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10435 }
10436
10437 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10438    already been loaded into memory.  */
10439
10440 static void
10441 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10442                         enum language pretend_language)
10443 {
10444   struct dwarf2_cu *cu = per_cu->cu;
10445   struct objfile *objfile = per_cu->objfile;
10446   struct compunit_symtab *cust;
10447   struct cleanup *delayed_list_cleanup;
10448   struct signatured_type *sig_type;
10449
10450   gdb_assert (per_cu->is_debug_types);
10451   sig_type = (struct signatured_type *) per_cu;
10452
10453   buildsym_init ();
10454   scoped_free_pendings free_pending;
10455   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10456
10457   cu->list_in_scope = &file_symbols;
10458
10459   cu->language = pretend_language;
10460   cu->language_defn = language_def (cu->language);
10461
10462   /* The symbol tables are set up in read_type_unit_scope.  */
10463   process_die (cu->dies, cu);
10464
10465   /* For now fudge the Go package.  */
10466   if (cu->language == language_go)
10467     fixup_go_packaging (cu);
10468
10469   /* Now that we have processed all the DIEs in the CU, all the types 
10470      should be complete, and it should now be safe to compute all of the
10471      physnames.  */
10472   compute_delayed_physnames (cu);
10473   do_cleanups (delayed_list_cleanup);
10474
10475   /* TUs share symbol tables.
10476      If this is the first TU to use this symtab, complete the construction
10477      of it with end_expandable_symtab.  Otherwise, complete the addition of
10478      this TU's symbols to the existing symtab.  */
10479   if (sig_type->type_unit_group->compunit_symtab == NULL)
10480     {
10481       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10482       sig_type->type_unit_group->compunit_symtab = cust;
10483
10484       if (cust != NULL)
10485         {
10486           /* Set symtab language to language from DW_AT_language.  If the
10487              compilation is from a C file generated by language preprocessors,
10488              do not set the language if it was already deduced by
10489              start_subfile.  */
10490           if (!(cu->language == language_c
10491                 && COMPUNIT_FILETABS (cust)->language != language_c))
10492             COMPUNIT_FILETABS (cust)->language = cu->language;
10493         }
10494     }
10495   else
10496     {
10497       augment_type_symtab ();
10498       cust = sig_type->type_unit_group->compunit_symtab;
10499     }
10500
10501   if (dwarf2_per_objfile->using_index)
10502     per_cu->v.quick->compunit_symtab = cust;
10503   else
10504     {
10505       struct partial_symtab *pst = per_cu->v.psymtab;
10506       pst->compunit_symtab = cust;
10507       pst->readin = 1;
10508     }
10509 }
10510
10511 /* Process an imported unit DIE.  */
10512
10513 static void
10514 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10515 {
10516   struct attribute *attr;
10517
10518   /* For now we don't handle imported units in type units.  */
10519   if (cu->per_cu->is_debug_types)
10520     {
10521       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10522                " supported in type units [in module %s]"),
10523              objfile_name (cu->objfile));
10524     }
10525
10526   attr = dwarf2_attr (die, DW_AT_import, cu);
10527   if (attr != NULL)
10528     {
10529       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10530       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10531       dwarf2_per_cu_data *per_cu
10532         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
10533
10534       /* If necessary, add it to the queue and load its DIEs.  */
10535       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10536         load_full_comp_unit (per_cu, cu->language);
10537
10538       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10539                      per_cu);
10540     }
10541 }
10542
10543 /* RAII object that represents a process_die scope: i.e.,
10544    starts/finishes processing a DIE.  */
10545 class process_die_scope
10546 {
10547 public:
10548   process_die_scope (die_info *die, dwarf2_cu *cu)
10549     : m_die (die), m_cu (cu)
10550   {
10551     /* We should only be processing DIEs not already in process.  */
10552     gdb_assert (!m_die->in_process);
10553     m_die->in_process = true;
10554   }
10555
10556   ~process_die_scope ()
10557   {
10558     m_die->in_process = false;
10559
10560     /* If we're done processing the DIE for the CU that owns the line
10561        header, we don't need the line header anymore.  */
10562     if (m_cu->line_header_die_owner == m_die)
10563       {
10564         delete m_cu->line_header;
10565         m_cu->line_header = NULL;
10566         m_cu->line_header_die_owner = NULL;
10567       }
10568   }
10569
10570 private:
10571   die_info *m_die;
10572   dwarf2_cu *m_cu;
10573 };
10574
10575 /* Process a die and its children.  */
10576
10577 static void
10578 process_die (struct die_info *die, struct dwarf2_cu *cu)
10579 {
10580   process_die_scope scope (die, cu);
10581
10582   switch (die->tag)
10583     {
10584     case DW_TAG_padding:
10585       break;
10586     case DW_TAG_compile_unit:
10587     case DW_TAG_partial_unit:
10588       read_file_scope (die, cu);
10589       break;
10590     case DW_TAG_type_unit:
10591       read_type_unit_scope (die, cu);
10592       break;
10593     case DW_TAG_subprogram:
10594     case DW_TAG_inlined_subroutine:
10595       read_func_scope (die, cu);
10596       break;
10597     case DW_TAG_lexical_block:
10598     case DW_TAG_try_block:
10599     case DW_TAG_catch_block:
10600       read_lexical_block_scope (die, cu);
10601       break;
10602     case DW_TAG_call_site:
10603     case DW_TAG_GNU_call_site:
10604       read_call_site_scope (die, cu);
10605       break;
10606     case DW_TAG_class_type:
10607     case DW_TAG_interface_type:
10608     case DW_TAG_structure_type:
10609     case DW_TAG_union_type:
10610       process_structure_scope (die, cu);
10611       break;
10612     case DW_TAG_enumeration_type:
10613       process_enumeration_scope (die, cu);
10614       break;
10615
10616     /* These dies have a type, but processing them does not create
10617        a symbol or recurse to process the children.  Therefore we can
10618        read them on-demand through read_type_die.  */
10619     case DW_TAG_subroutine_type:
10620     case DW_TAG_set_type:
10621     case DW_TAG_array_type:
10622     case DW_TAG_pointer_type:
10623     case DW_TAG_ptr_to_member_type:
10624     case DW_TAG_reference_type:
10625     case DW_TAG_rvalue_reference_type:
10626     case DW_TAG_string_type:
10627       break;
10628
10629     case DW_TAG_base_type:
10630     case DW_TAG_subrange_type:
10631     case DW_TAG_typedef:
10632       /* Add a typedef symbol for the type definition, if it has a
10633          DW_AT_name.  */
10634       new_symbol (die, read_type_die (die, cu), cu);
10635       break;
10636     case DW_TAG_common_block:
10637       read_common_block (die, cu);
10638       break;
10639     case DW_TAG_common_inclusion:
10640       break;
10641     case DW_TAG_namespace:
10642       cu->processing_has_namespace_info = 1;
10643       read_namespace (die, cu);
10644       break;
10645     case DW_TAG_module:
10646       cu->processing_has_namespace_info = 1;
10647       read_module (die, cu);
10648       break;
10649     case DW_TAG_imported_declaration:
10650       cu->processing_has_namespace_info = 1;
10651       if (read_namespace_alias (die, cu))
10652         break;
10653       /* The declaration is not a global namespace alias: fall through.  */
10654     case DW_TAG_imported_module:
10655       cu->processing_has_namespace_info = 1;
10656       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10657                                  || cu->language != language_fortran))
10658         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10659                    dwarf_tag_name (die->tag));
10660       read_import_statement (die, cu);
10661       break;
10662
10663     case DW_TAG_imported_unit:
10664       process_imported_unit_die (die, cu);
10665       break;
10666
10667     case DW_TAG_variable:
10668       read_variable (die, cu);
10669       break;
10670
10671     default:
10672       new_symbol (die, NULL, cu);
10673       break;
10674     }
10675 }
10676 \f
10677 /* DWARF name computation.  */
10678
10679 /* A helper function for dwarf2_compute_name which determines whether DIE
10680    needs to have the name of the scope prepended to the name listed in the
10681    die.  */
10682
10683 static int
10684 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10685 {
10686   struct attribute *attr;
10687
10688   switch (die->tag)
10689     {
10690     case DW_TAG_namespace:
10691     case DW_TAG_typedef:
10692     case DW_TAG_class_type:
10693     case DW_TAG_interface_type:
10694     case DW_TAG_structure_type:
10695     case DW_TAG_union_type:
10696     case DW_TAG_enumeration_type:
10697     case DW_TAG_enumerator:
10698     case DW_TAG_subprogram:
10699     case DW_TAG_inlined_subroutine:
10700     case DW_TAG_member:
10701     case DW_TAG_imported_declaration:
10702       return 1;
10703
10704     case DW_TAG_variable:
10705     case DW_TAG_constant:
10706       /* We only need to prefix "globally" visible variables.  These include
10707          any variable marked with DW_AT_external or any variable that
10708          lives in a namespace.  [Variables in anonymous namespaces
10709          require prefixing, but they are not DW_AT_external.]  */
10710
10711       if (dwarf2_attr (die, DW_AT_specification, cu))
10712         {
10713           struct dwarf2_cu *spec_cu = cu;
10714
10715           return die_needs_namespace (die_specification (die, &spec_cu),
10716                                       spec_cu);
10717         }
10718
10719       attr = dwarf2_attr (die, DW_AT_external, cu);
10720       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10721           && die->parent->tag != DW_TAG_module)
10722         return 0;
10723       /* A variable in a lexical block of some kind does not need a
10724          namespace, even though in C++ such variables may be external
10725          and have a mangled name.  */
10726       if (die->parent->tag ==  DW_TAG_lexical_block
10727           || die->parent->tag ==  DW_TAG_try_block
10728           || die->parent->tag ==  DW_TAG_catch_block
10729           || die->parent->tag == DW_TAG_subprogram)
10730         return 0;
10731       return 1;
10732
10733     default:
10734       return 0;
10735     }
10736 }
10737
10738 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10739    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10740    defined for the given DIE.  */
10741
10742 static struct attribute *
10743 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10744 {
10745   struct attribute *attr;
10746
10747   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10748   if (attr == NULL)
10749     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10750
10751   return attr;
10752 }
10753
10754 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10755    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10756    defined for the given DIE.  */
10757
10758 static const char *
10759 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10760 {
10761   const char *linkage_name;
10762
10763   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10764   if (linkage_name == NULL)
10765     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10766
10767   return linkage_name;
10768 }
10769
10770 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10771    compute the physname for the object, which include a method's:
10772    - formal parameters (C++),
10773    - receiver type (Go),
10774
10775    The term "physname" is a bit confusing.
10776    For C++, for example, it is the demangled name.
10777    For Go, for example, it's the mangled name.
10778
10779    For Ada, return the DIE's linkage name rather than the fully qualified
10780    name.  PHYSNAME is ignored..
10781
10782    The result is allocated on the objfile_obstack and canonicalized.  */
10783
10784 static const char *
10785 dwarf2_compute_name (const char *name,
10786                      struct die_info *die, struct dwarf2_cu *cu,
10787                      int physname)
10788 {
10789   struct objfile *objfile = cu->objfile;
10790
10791   if (name == NULL)
10792     name = dwarf2_name (die, cu);
10793
10794   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10795      but otherwise compute it by typename_concat inside GDB.
10796      FIXME: Actually this is not really true, or at least not always true.
10797      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10798      Fortran names because there is no mangling standard.  So new_symbol_full
10799      will set the demangled name to the result of dwarf2_full_name, and it is
10800      the demangled name that GDB uses if it exists.  */
10801   if (cu->language == language_ada
10802       || (cu->language == language_fortran && physname))
10803     {
10804       /* For Ada unit, we prefer the linkage name over the name, as
10805          the former contains the exported name, which the user expects
10806          to be able to reference.  Ideally, we want the user to be able
10807          to reference this entity using either natural or linkage name,
10808          but we haven't started looking at this enhancement yet.  */
10809       const char *linkage_name = dw2_linkage_name (die, cu);
10810
10811       if (linkage_name != NULL)
10812         return linkage_name;
10813     }
10814
10815   /* These are the only languages we know how to qualify names in.  */
10816   if (name != NULL
10817       && (cu->language == language_cplus
10818           || cu->language == language_fortran || cu->language == language_d
10819           || cu->language == language_rust))
10820     {
10821       if (die_needs_namespace (die, cu))
10822         {
10823           const char *prefix;
10824           const char *canonical_name = NULL;
10825
10826           string_file buf;
10827
10828           prefix = determine_prefix (die, cu);
10829           if (*prefix != '\0')
10830             {
10831               char *prefixed_name = typename_concat (NULL, prefix, name,
10832                                                      physname, cu);
10833
10834               buf.puts (prefixed_name);
10835               xfree (prefixed_name);
10836             }
10837           else
10838             buf.puts (name);
10839
10840           /* Template parameters may be specified in the DIE's DW_AT_name, or
10841              as children with DW_TAG_template_type_param or
10842              DW_TAG_value_type_param.  If the latter, add them to the name
10843              here.  If the name already has template parameters, then
10844              skip this step; some versions of GCC emit both, and
10845              it is more efficient to use the pre-computed name.
10846
10847              Something to keep in mind about this process: it is very
10848              unlikely, or in some cases downright impossible, to produce
10849              something that will match the mangled name of a function.
10850              If the definition of the function has the same debug info,
10851              we should be able to match up with it anyway.  But fallbacks
10852              using the minimal symbol, for instance to find a method
10853              implemented in a stripped copy of libstdc++, will not work.
10854              If we do not have debug info for the definition, we will have to
10855              match them up some other way.
10856
10857              When we do name matching there is a related problem with function
10858              templates; two instantiated function templates are allowed to
10859              differ only by their return types, which we do not add here.  */
10860
10861           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10862             {
10863               struct attribute *attr;
10864               struct die_info *child;
10865               int first = 1;
10866
10867               die->building_fullname = 1;
10868
10869               for (child = die->child; child != NULL; child = child->sibling)
10870                 {
10871                   struct type *type;
10872                   LONGEST value;
10873                   const gdb_byte *bytes;
10874                   struct dwarf2_locexpr_baton *baton;
10875                   struct value *v;
10876
10877                   if (child->tag != DW_TAG_template_type_param
10878                       && child->tag != DW_TAG_template_value_param)
10879                     continue;
10880
10881                   if (first)
10882                     {
10883                       buf.puts ("<");
10884                       first = 0;
10885                     }
10886                   else
10887                     buf.puts (", ");
10888
10889                   attr = dwarf2_attr (child, DW_AT_type, cu);
10890                   if (attr == NULL)
10891                     {
10892                       complaint (&symfile_complaints,
10893                                  _("template parameter missing DW_AT_type"));
10894                       buf.puts ("UNKNOWN_TYPE");
10895                       continue;
10896                     }
10897                   type = die_type (child, cu);
10898
10899                   if (child->tag == DW_TAG_template_type_param)
10900                     {
10901                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10902                       continue;
10903                     }
10904
10905                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10906                   if (attr == NULL)
10907                     {
10908                       complaint (&symfile_complaints,
10909                                  _("template parameter missing "
10910                                    "DW_AT_const_value"));
10911                       buf.puts ("UNKNOWN_VALUE");
10912                       continue;
10913                     }
10914
10915                   dwarf2_const_value_attr (attr, type, name,
10916                                            &cu->comp_unit_obstack, cu,
10917                                            &value, &bytes, &baton);
10918
10919                   if (TYPE_NOSIGN (type))
10920                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10921                        changed, this can use value_print instead.  */
10922                     c_printchar (value, type, &buf);
10923                   else
10924                     {
10925                       struct value_print_options opts;
10926
10927                       if (baton != NULL)
10928                         v = dwarf2_evaluate_loc_desc (type, NULL,
10929                                                       baton->data,
10930                                                       baton->size,
10931                                                       baton->per_cu);
10932                       else if (bytes != NULL)
10933                         {
10934                           v = allocate_value (type);
10935                           memcpy (value_contents_writeable (v), bytes,
10936                                   TYPE_LENGTH (type));
10937                         }
10938                       else
10939                         v = value_from_longest (type, value);
10940
10941                       /* Specify decimal so that we do not depend on
10942                          the radix.  */
10943                       get_formatted_print_options (&opts, 'd');
10944                       opts.raw = 1;
10945                       value_print (v, &buf, &opts);
10946                       release_value (v);
10947                       value_free (v);
10948                     }
10949                 }
10950
10951               die->building_fullname = 0;
10952
10953               if (!first)
10954                 {
10955                   /* Close the argument list, with a space if necessary
10956                      (nested templates).  */
10957                   if (!buf.empty () && buf.string ().back () == '>')
10958                     buf.puts (" >");
10959                   else
10960                     buf.puts (">");
10961                 }
10962             }
10963
10964           /* For C++ methods, append formal parameter type
10965              information, if PHYSNAME.  */
10966
10967           if (physname && die->tag == DW_TAG_subprogram
10968               && cu->language == language_cplus)
10969             {
10970               struct type *type = read_type_die (die, cu);
10971
10972               c_type_print_args (type, &buf, 1, cu->language,
10973                                  &type_print_raw_options);
10974
10975               if (cu->language == language_cplus)
10976                 {
10977                   /* Assume that an artificial first parameter is
10978                      "this", but do not crash if it is not.  RealView
10979                      marks unnamed (and thus unused) parameters as
10980                      artificial; there is no way to differentiate
10981                      the two cases.  */
10982                   if (TYPE_NFIELDS (type) > 0
10983                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10984                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10985                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10986                                                                         0))))
10987                     buf.puts (" const");
10988                 }
10989             }
10990
10991           const std::string &intermediate_name = buf.string ();
10992
10993           if (cu->language == language_cplus)
10994             canonical_name
10995               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10996                                           &objfile->per_bfd->storage_obstack);
10997
10998           /* If we only computed INTERMEDIATE_NAME, or if
10999              INTERMEDIATE_NAME is already canonical, then we need to
11000              copy it to the appropriate obstack.  */
11001           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11002             name = ((const char *)
11003                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11004                                    intermediate_name.c_str (),
11005                                    intermediate_name.length ()));
11006           else
11007             name = canonical_name;
11008         }
11009     }
11010
11011   return name;
11012 }
11013
11014 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11015    If scope qualifiers are appropriate they will be added.  The result
11016    will be allocated on the storage_obstack, or NULL if the DIE does
11017    not have a name.  NAME may either be from a previous call to
11018    dwarf2_name or NULL.
11019
11020    The output string will be canonicalized (if C++).  */
11021
11022 static const char *
11023 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11024 {
11025   return dwarf2_compute_name (name, die, cu, 0);
11026 }
11027
11028 /* Construct a physname for the given DIE in CU.  NAME may either be
11029    from a previous call to dwarf2_name or NULL.  The result will be
11030    allocated on the objfile_objstack or NULL if the DIE does not have a
11031    name.
11032
11033    The output string will be canonicalized (if C++).  */
11034
11035 static const char *
11036 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11037 {
11038   struct objfile *objfile = cu->objfile;
11039   const char *retval, *mangled = NULL, *canon = NULL;
11040   int need_copy = 1;
11041
11042   /* In this case dwarf2_compute_name is just a shortcut not building anything
11043      on its own.  */
11044   if (!die_needs_namespace (die, cu))
11045     return dwarf2_compute_name (name, die, cu, 1);
11046
11047   mangled = dw2_linkage_name (die, cu);
11048
11049   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11050      See https://github.com/rust-lang/rust/issues/32925.  */
11051   if (cu->language == language_rust && mangled != NULL
11052       && strchr (mangled, '{') != NULL)
11053     mangled = NULL;
11054
11055   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11056      has computed.  */
11057   gdb::unique_xmalloc_ptr<char> demangled;
11058   if (mangled != NULL)
11059     {
11060       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11061          type.  It is easier for GDB users to search for such functions as
11062          `name(params)' than `long name(params)'.  In such case the minimal
11063          symbol names do not match the full symbol names but for template
11064          functions there is never a need to look up their definition from their
11065          declaration so the only disadvantage remains the minimal symbol
11066          variant `long name(params)' does not have the proper inferior type.
11067          */
11068
11069       if (cu->language == language_go)
11070         {
11071           /* This is a lie, but we already lie to the caller new_symbol_full.
11072              new_symbol_full assumes we return the mangled name.
11073              This just undoes that lie until things are cleaned up.  */
11074         }
11075       else
11076         {
11077           demangled.reset (gdb_demangle (mangled,
11078                                          (DMGL_PARAMS | DMGL_ANSI
11079                                           | DMGL_RET_DROP)));
11080         }
11081       if (demangled)
11082         canon = demangled.get ();
11083       else
11084         {
11085           canon = mangled;
11086           need_copy = 0;
11087         }
11088     }
11089
11090   if (canon == NULL || check_physname)
11091     {
11092       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11093
11094       if (canon != NULL && strcmp (physname, canon) != 0)
11095         {
11096           /* It may not mean a bug in GDB.  The compiler could also
11097              compute DW_AT_linkage_name incorrectly.  But in such case
11098              GDB would need to be bug-to-bug compatible.  */
11099
11100           complaint (&symfile_complaints,
11101                      _("Computed physname <%s> does not match demangled <%s> "
11102                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11103                      physname, canon, mangled, to_underlying (die->sect_off),
11104                      objfile_name (objfile));
11105
11106           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11107              is available here - over computed PHYSNAME.  It is safer
11108              against both buggy GDB and buggy compilers.  */
11109
11110           retval = canon;
11111         }
11112       else
11113         {
11114           retval = physname;
11115           need_copy = 0;
11116         }
11117     }
11118   else
11119     retval = canon;
11120
11121   if (need_copy)
11122     retval = ((const char *)
11123               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11124                              retval, strlen (retval)));
11125
11126   return retval;
11127 }
11128
11129 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11130    a new symbol for it.
11131
11132    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11133
11134 static int
11135 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11136 {
11137   struct attribute *attr;
11138
11139   /* If the die does not have a name, this is not a namespace
11140      alias.  */
11141   attr = dwarf2_attr (die, DW_AT_name, cu);
11142   if (attr != NULL)
11143     {
11144       int num;
11145       struct die_info *d = die;
11146       struct dwarf2_cu *imported_cu = cu;
11147
11148       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11149          keep inspecting DIEs until we hit the underlying import.  */
11150 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11151       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11152         {
11153           attr = dwarf2_attr (d, DW_AT_import, cu);
11154           if (attr == NULL)
11155             break;
11156
11157           d = follow_die_ref (d, attr, &imported_cu);
11158           if (d->tag != DW_TAG_imported_declaration)
11159             break;
11160         }
11161
11162       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11163         {
11164           complaint (&symfile_complaints,
11165                      _("DIE at 0x%x has too many recursively imported "
11166                        "declarations"), to_underlying (d->sect_off));
11167           return 0;
11168         }
11169
11170       if (attr != NULL)
11171         {
11172           struct type *type;
11173           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11174
11175           type = get_die_type_at_offset (sect_off, cu->per_cu);
11176           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11177             {
11178               /* This declaration is a global namespace alias.  Add
11179                  a symbol for it whose type is the aliased namespace.  */
11180               new_symbol (die, type, cu);
11181               return 1;
11182             }
11183         }
11184     }
11185
11186   return 0;
11187 }
11188
11189 /* Return the using directives repository (global or local?) to use in the
11190    current context for LANGUAGE.
11191
11192    For Ada, imported declarations can materialize renamings, which *may* be
11193    global.  However it is impossible (for now?) in DWARF to distinguish
11194    "external" imported declarations and "static" ones.  As all imported
11195    declarations seem to be static in all other languages, make them all CU-wide
11196    global only in Ada.  */
11197
11198 static struct using_direct **
11199 using_directives (enum language language)
11200 {
11201   if (language == language_ada && context_stack_depth == 0)
11202     return &global_using_directives;
11203   else
11204     return &local_using_directives;
11205 }
11206
11207 /* Read the import statement specified by the given die and record it.  */
11208
11209 static void
11210 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11211 {
11212   struct objfile *objfile = cu->objfile;
11213   struct attribute *import_attr;
11214   struct die_info *imported_die, *child_die;
11215   struct dwarf2_cu *imported_cu;
11216   const char *imported_name;
11217   const char *imported_name_prefix;
11218   const char *canonical_name;
11219   const char *import_alias;
11220   const char *imported_declaration = NULL;
11221   const char *import_prefix;
11222   std::vector<const char *> excludes;
11223
11224   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11225   if (import_attr == NULL)
11226     {
11227       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11228                  dwarf_tag_name (die->tag));
11229       return;
11230     }
11231
11232   imported_cu = cu;
11233   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11234   imported_name = dwarf2_name (imported_die, imported_cu);
11235   if (imported_name == NULL)
11236     {
11237       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11238
11239         The import in the following code:
11240         namespace A
11241           {
11242             typedef int B;
11243           }
11244
11245         int main ()
11246           {
11247             using A::B;
11248             B b;
11249             return b;
11250           }
11251
11252         ...
11253          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11254             <52>   DW_AT_decl_file   : 1
11255             <53>   DW_AT_decl_line   : 6
11256             <54>   DW_AT_import      : <0x75>
11257          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11258             <59>   DW_AT_name        : B
11259             <5b>   DW_AT_decl_file   : 1
11260             <5c>   DW_AT_decl_line   : 2
11261             <5d>   DW_AT_type        : <0x6e>
11262         ...
11263          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11264             <76>   DW_AT_byte_size   : 4
11265             <77>   DW_AT_encoding    : 5        (signed)
11266
11267         imports the wrong die ( 0x75 instead of 0x58 ).
11268         This case will be ignored until the gcc bug is fixed.  */
11269       return;
11270     }
11271
11272   /* Figure out the local name after import.  */
11273   import_alias = dwarf2_name (die, cu);
11274
11275   /* Figure out where the statement is being imported to.  */
11276   import_prefix = determine_prefix (die, cu);
11277
11278   /* Figure out what the scope of the imported die is and prepend it
11279      to the name of the imported die.  */
11280   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11281
11282   if (imported_die->tag != DW_TAG_namespace
11283       && imported_die->tag != DW_TAG_module)
11284     {
11285       imported_declaration = imported_name;
11286       canonical_name = imported_name_prefix;
11287     }
11288   else if (strlen (imported_name_prefix) > 0)
11289     canonical_name = obconcat (&objfile->objfile_obstack,
11290                                imported_name_prefix,
11291                                (cu->language == language_d ? "." : "::"),
11292                                imported_name, (char *) NULL);
11293   else
11294     canonical_name = imported_name;
11295
11296   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11297     for (child_die = die->child; child_die && child_die->tag;
11298          child_die = sibling_die (child_die))
11299       {
11300         /* DWARF-4: A Fortran use statement with a “rename list” may be
11301            represented by an imported module entry with an import attribute
11302            referring to the module and owned entries corresponding to those
11303            entities that are renamed as part of being imported.  */
11304
11305         if (child_die->tag != DW_TAG_imported_declaration)
11306           {
11307             complaint (&symfile_complaints,
11308                        _("child DW_TAG_imported_declaration expected "
11309                          "- DIE at 0x%x [in module %s]"),
11310                        to_underlying (child_die->sect_off), objfile_name (objfile));
11311             continue;
11312           }
11313
11314         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11315         if (import_attr == NULL)
11316           {
11317             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11318                        dwarf_tag_name (child_die->tag));
11319             continue;
11320           }
11321
11322         imported_cu = cu;
11323         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11324                                               &imported_cu);
11325         imported_name = dwarf2_name (imported_die, imported_cu);
11326         if (imported_name == NULL)
11327           {
11328             complaint (&symfile_complaints,
11329                        _("child DW_TAG_imported_declaration has unknown "
11330                          "imported name - DIE at 0x%x [in module %s]"),
11331                        to_underlying (child_die->sect_off), objfile_name (objfile));
11332             continue;
11333           }
11334
11335         excludes.push_back (imported_name);
11336
11337         process_die (child_die, cu);
11338       }
11339
11340   add_using_directive (using_directives (cu->language),
11341                        import_prefix,
11342                        canonical_name,
11343                        import_alias,
11344                        imported_declaration,
11345                        excludes,
11346                        0,
11347                        &objfile->objfile_obstack);
11348 }
11349
11350 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11351    types, but gives them a size of zero.  Starting with version 14,
11352    ICC is compatible with GCC.  */
11353
11354 static int
11355 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11356 {
11357   if (!cu->checked_producer)
11358     check_producer (cu);
11359
11360   return cu->producer_is_icc_lt_14;
11361 }
11362
11363 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11364    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11365    this, it was first present in GCC release 4.3.0.  */
11366
11367 static int
11368 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11369 {
11370   if (!cu->checked_producer)
11371     check_producer (cu);
11372
11373   return cu->producer_is_gcc_lt_4_3;
11374 }
11375
11376 static file_and_directory
11377 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11378 {
11379   file_and_directory res;
11380
11381   /* Find the filename.  Do not use dwarf2_name here, since the filename
11382      is not a source language identifier.  */
11383   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11384   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11385
11386   if (res.comp_dir == NULL
11387       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11388       && IS_ABSOLUTE_PATH (res.name))
11389     {
11390       res.comp_dir_storage = ldirname (res.name);
11391       if (!res.comp_dir_storage.empty ())
11392         res.comp_dir = res.comp_dir_storage.c_str ();
11393     }
11394   if (res.comp_dir != NULL)
11395     {
11396       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11397          directory, get rid of it.  */
11398       const char *cp = strchr (res.comp_dir, ':');
11399
11400       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11401         res.comp_dir = cp + 1;
11402     }
11403
11404   if (res.name == NULL)
11405     res.name = "<unknown>";
11406
11407   return res;
11408 }
11409
11410 /* Handle DW_AT_stmt_list for a compilation unit.
11411    DIE is the DW_TAG_compile_unit die for CU.
11412    COMP_DIR is the compilation directory.  LOWPC is passed to
11413    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11414
11415 static void
11416 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11417                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11418 {
11419   struct objfile *objfile = dwarf2_per_objfile->objfile;
11420   struct attribute *attr;
11421   struct line_header line_header_local;
11422   hashval_t line_header_local_hash;
11423   void **slot;
11424   int decode_mapping;
11425
11426   gdb_assert (! cu->per_cu->is_debug_types);
11427
11428   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11429   if (attr == NULL)
11430     return;
11431
11432   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11433
11434   /* The line header hash table is only created if needed (it exists to
11435      prevent redundant reading of the line table for partial_units).
11436      If we're given a partial_unit, we'll need it.  If we're given a
11437      compile_unit, then use the line header hash table if it's already
11438      created, but don't create one just yet.  */
11439
11440   if (dwarf2_per_objfile->line_header_hash == NULL
11441       && die->tag == DW_TAG_partial_unit)
11442     {
11443       dwarf2_per_objfile->line_header_hash
11444         = htab_create_alloc_ex (127, line_header_hash_voidp,
11445                                 line_header_eq_voidp,
11446                                 free_line_header_voidp,
11447                                 &objfile->objfile_obstack,
11448                                 hashtab_obstack_allocate,
11449                                 dummy_obstack_deallocate);
11450     }
11451
11452   line_header_local.sect_off = line_offset;
11453   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11454   line_header_local_hash = line_header_hash (&line_header_local);
11455   if (dwarf2_per_objfile->line_header_hash != NULL)
11456     {
11457       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11458                                        &line_header_local,
11459                                        line_header_local_hash, NO_INSERT);
11460
11461       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11462          is not present in *SLOT (since if there is something in *SLOT then
11463          it will be for a partial_unit).  */
11464       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11465         {
11466           gdb_assert (*slot != NULL);
11467           cu->line_header = (struct line_header *) *slot;
11468           return;
11469         }
11470     }
11471
11472   /* dwarf_decode_line_header does not yet provide sufficient information.
11473      We always have to call also dwarf_decode_lines for it.  */
11474   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11475   if (lh == NULL)
11476     return;
11477
11478   cu->line_header = lh.release ();
11479   cu->line_header_die_owner = die;
11480
11481   if (dwarf2_per_objfile->line_header_hash == NULL)
11482     slot = NULL;
11483   else
11484     {
11485       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11486                                        &line_header_local,
11487                                        line_header_local_hash, INSERT);
11488       gdb_assert (slot != NULL);
11489     }
11490   if (slot != NULL && *slot == NULL)
11491     {
11492       /* This newly decoded line number information unit will be owned
11493          by line_header_hash hash table.  */
11494       *slot = cu->line_header;
11495       cu->line_header_die_owner = NULL;
11496     }
11497   else
11498     {
11499       /* We cannot free any current entry in (*slot) as that struct line_header
11500          may be already used by multiple CUs.  Create only temporary decoded
11501          line_header for this CU - it may happen at most once for each line
11502          number information unit.  And if we're not using line_header_hash
11503          then this is what we want as well.  */
11504       gdb_assert (die->tag != DW_TAG_partial_unit);
11505     }
11506   decode_mapping = (die->tag != DW_TAG_partial_unit);
11507   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11508                       decode_mapping);
11509
11510 }
11511
11512 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11513
11514 static void
11515 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11516 {
11517   struct objfile *objfile = dwarf2_per_objfile->objfile;
11518   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11519   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11520   CORE_ADDR highpc = ((CORE_ADDR) 0);
11521   struct attribute *attr;
11522   struct die_info *child_die;
11523   CORE_ADDR baseaddr;
11524
11525   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11526
11527   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11528
11529   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11530      from finish_block.  */
11531   if (lowpc == ((CORE_ADDR) -1))
11532     lowpc = highpc;
11533   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11534
11535   file_and_directory fnd = find_file_and_directory (die, cu);
11536
11537   prepare_one_comp_unit (cu, die, cu->language);
11538
11539   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11540      standardised yet.  As a workaround for the language detection we fall
11541      back to the DW_AT_producer string.  */
11542   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11543     cu->language = language_opencl;
11544
11545   /* Similar hack for Go.  */
11546   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11547     set_cu_language (DW_LANG_Go, cu);
11548
11549   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11550
11551   /* Decode line number information if present.  We do this before
11552      processing child DIEs, so that the line header table is available
11553      for DW_AT_decl_file.  */
11554   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11555
11556   /* Process all dies in compilation unit.  */
11557   if (die->child != NULL)
11558     {
11559       child_die = die->child;
11560       while (child_die && child_die->tag)
11561         {
11562           process_die (child_die, cu);
11563           child_die = sibling_die (child_die);
11564         }
11565     }
11566
11567   /* Decode macro information, if present.  Dwarf 2 macro information
11568      refers to information in the line number info statement program
11569      header, so we can only read it if we've read the header
11570      successfully.  */
11571   attr = dwarf2_attr (die, DW_AT_macros, cu);
11572   if (attr == NULL)
11573     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11574   if (attr && cu->line_header)
11575     {
11576       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11577         complaint (&symfile_complaints,
11578                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11579
11580       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11581     }
11582   else
11583     {
11584       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11585       if (attr && cu->line_header)
11586         {
11587           unsigned int macro_offset = DW_UNSND (attr);
11588
11589           dwarf_decode_macros (cu, macro_offset, 0);
11590         }
11591     }
11592 }
11593
11594 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11595    Create the set of symtabs used by this TU, or if this TU is sharing
11596    symtabs with another TU and the symtabs have already been created
11597    then restore those symtabs in the line header.
11598    We don't need the pc/line-number mapping for type units.  */
11599
11600 static void
11601 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11602 {
11603   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11604   struct type_unit_group *tu_group;
11605   int first_time;
11606   struct attribute *attr;
11607   unsigned int i;
11608   struct signatured_type *sig_type;
11609
11610   gdb_assert (per_cu->is_debug_types);
11611   sig_type = (struct signatured_type *) per_cu;
11612
11613   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11614
11615   /* If we're using .gdb_index (includes -readnow) then
11616      per_cu->type_unit_group may not have been set up yet.  */
11617   if (sig_type->type_unit_group == NULL)
11618     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11619   tu_group = sig_type->type_unit_group;
11620
11621   /* If we've already processed this stmt_list there's no real need to
11622      do it again, we could fake it and just recreate the part we need
11623      (file name,index -> symtab mapping).  If data shows this optimization
11624      is useful we can do it then.  */
11625   first_time = tu_group->compunit_symtab == NULL;
11626
11627   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11628      debug info.  */
11629   line_header_up lh;
11630   if (attr != NULL)
11631     {
11632       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11633       lh = dwarf_decode_line_header (line_offset, cu);
11634     }
11635   if (lh == NULL)
11636     {
11637       if (first_time)
11638         dwarf2_start_symtab (cu, "", NULL, 0);
11639       else
11640         {
11641           gdb_assert (tu_group->symtabs == NULL);
11642           restart_symtab (tu_group->compunit_symtab, "", 0);
11643         }
11644       return;
11645     }
11646
11647   cu->line_header = lh.release ();
11648   cu->line_header_die_owner = die;
11649
11650   if (first_time)
11651     {
11652       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11653
11654       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11655          still initializing it, and our caller (a few levels up)
11656          process_full_type_unit still needs to know if this is the first
11657          time.  */
11658
11659       tu_group->num_symtabs = cu->line_header->file_names.size ();
11660       tu_group->symtabs = XNEWVEC (struct symtab *,
11661                                    cu->line_header->file_names.size ());
11662
11663       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11664         {
11665           file_entry &fe = cu->line_header->file_names[i];
11666
11667           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11668
11669           if (current_subfile->symtab == NULL)
11670             {
11671               /* NOTE: start_subfile will recognize when it's been
11672                  passed a file it has already seen.  So we can't
11673                  assume there's a simple mapping from
11674                  cu->line_header->file_names to subfiles, plus
11675                  cu->line_header->file_names may contain dups.  */
11676               current_subfile->symtab
11677                 = allocate_symtab (cust, current_subfile->name);
11678             }
11679
11680           fe.symtab = current_subfile->symtab;
11681           tu_group->symtabs[i] = fe.symtab;
11682         }
11683     }
11684   else
11685     {
11686       restart_symtab (tu_group->compunit_symtab, "", 0);
11687
11688       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11689         {
11690           file_entry &fe = cu->line_header->file_names[i];
11691
11692           fe.symtab = tu_group->symtabs[i];
11693         }
11694     }
11695
11696   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11697      so they don't have a "real" (so to speak) symtab anyway.
11698      There is later code that will assign the main symtab to all symbols
11699      that don't have one.  We need to handle the case of a symbol with a
11700      missing symtab (DW_AT_decl_file) anyway.  */
11701 }
11702
11703 /* Process DW_TAG_type_unit.
11704    For TUs we want to skip the first top level sibling if it's not the
11705    actual type being defined by this TU.  In this case the first top
11706    level sibling is there to provide context only.  */
11707
11708 static void
11709 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11710 {
11711   struct die_info *child_die;
11712
11713   prepare_one_comp_unit (cu, die, language_minimal);
11714
11715   /* Initialize (or reinitialize) the machinery for building symtabs.
11716      We do this before processing child DIEs, so that the line header table
11717      is available for DW_AT_decl_file.  */
11718   setup_type_unit_groups (die, cu);
11719
11720   if (die->child != NULL)
11721     {
11722       child_die = die->child;
11723       while (child_die && child_die->tag)
11724         {
11725           process_die (child_die, cu);
11726           child_die = sibling_die (child_die);
11727         }
11728     }
11729 }
11730 \f
11731 /* DWO/DWP files.
11732
11733    http://gcc.gnu.org/wiki/DebugFission
11734    http://gcc.gnu.org/wiki/DebugFissionDWP
11735
11736    To simplify handling of both DWO files ("object" files with the DWARF info)
11737    and DWP files (a file with the DWOs packaged up into one file), we treat
11738    DWP files as having a collection of virtual DWO files.  */
11739
11740 static hashval_t
11741 hash_dwo_file (const void *item)
11742 {
11743   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11744   hashval_t hash;
11745
11746   hash = htab_hash_string (dwo_file->dwo_name);
11747   if (dwo_file->comp_dir != NULL)
11748     hash += htab_hash_string (dwo_file->comp_dir);
11749   return hash;
11750 }
11751
11752 static int
11753 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11754 {
11755   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11756   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11757
11758   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11759     return 0;
11760   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11761     return lhs->comp_dir == rhs->comp_dir;
11762   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11763 }
11764
11765 /* Allocate a hash table for DWO files.  */
11766
11767 static htab_t
11768 allocate_dwo_file_hash_table (void)
11769 {
11770   struct objfile *objfile = dwarf2_per_objfile->objfile;
11771
11772   return htab_create_alloc_ex (41,
11773                                hash_dwo_file,
11774                                eq_dwo_file,
11775                                NULL,
11776                                &objfile->objfile_obstack,
11777                                hashtab_obstack_allocate,
11778                                dummy_obstack_deallocate);
11779 }
11780
11781 /* Lookup DWO file DWO_NAME.  */
11782
11783 static void **
11784 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
11785 {
11786   struct dwo_file find_entry;
11787   void **slot;
11788
11789   if (dwarf2_per_objfile->dwo_files == NULL)
11790     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
11791
11792   memset (&find_entry, 0, sizeof (find_entry));
11793   find_entry.dwo_name = dwo_name;
11794   find_entry.comp_dir = comp_dir;
11795   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11796
11797   return slot;
11798 }
11799
11800 static hashval_t
11801 hash_dwo_unit (const void *item)
11802 {
11803   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11804
11805   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11806   return dwo_unit->signature;
11807 }
11808
11809 static int
11810 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11811 {
11812   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11813   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11814
11815   /* The signature is assumed to be unique within the DWO file.
11816      So while object file CU dwo_id's always have the value zero,
11817      that's OK, assuming each object file DWO file has only one CU,
11818      and that's the rule for now.  */
11819   return lhs->signature == rhs->signature;
11820 }
11821
11822 /* Allocate a hash table for DWO CUs,TUs.
11823    There is one of these tables for each of CUs,TUs for each DWO file.  */
11824
11825 static htab_t
11826 allocate_dwo_unit_table (struct objfile *objfile)
11827 {
11828   /* Start out with a pretty small number.
11829      Generally DWO files contain only one CU and maybe some TUs.  */
11830   return htab_create_alloc_ex (3,
11831                                hash_dwo_unit,
11832                                eq_dwo_unit,
11833                                NULL,
11834                                &objfile->objfile_obstack,
11835                                hashtab_obstack_allocate,
11836                                dummy_obstack_deallocate);
11837 }
11838
11839 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11840
11841 struct create_dwo_cu_data
11842 {
11843   struct dwo_file *dwo_file;
11844   struct dwo_unit dwo_unit;
11845 };
11846
11847 /* die_reader_func for create_dwo_cu.  */
11848
11849 static void
11850 create_dwo_cu_reader (const struct die_reader_specs *reader,
11851                       const gdb_byte *info_ptr,
11852                       struct die_info *comp_unit_die,
11853                       int has_children,
11854                       void *datap)
11855 {
11856   struct dwarf2_cu *cu = reader->cu;
11857   sect_offset sect_off = cu->per_cu->sect_off;
11858   struct dwarf2_section_info *section = cu->per_cu->section;
11859   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11860   struct dwo_file *dwo_file = data->dwo_file;
11861   struct dwo_unit *dwo_unit = &data->dwo_unit;
11862   struct attribute *attr;
11863
11864   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11865   if (attr == NULL)
11866     {
11867       complaint (&symfile_complaints,
11868                  _("Dwarf Error: debug entry at offset 0x%x is missing"
11869                    " its dwo_id [in module %s]"),
11870                  to_underlying (sect_off), dwo_file->dwo_name);
11871       return;
11872     }
11873
11874   dwo_unit->dwo_file = dwo_file;
11875   dwo_unit->signature = DW_UNSND (attr);
11876   dwo_unit->section = section;
11877   dwo_unit->sect_off = sect_off;
11878   dwo_unit->length = cu->per_cu->length;
11879
11880   if (dwarf_read_debug)
11881     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
11882                         to_underlying (sect_off),
11883                         hex_string (dwo_unit->signature));
11884 }
11885
11886 /* Create the dwo_units for the CUs in a DWO_FILE.
11887    Note: This function processes DWO files only, not DWP files.  */
11888
11889 static void
11890 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
11891                        htab_t &cus_htab)
11892 {
11893   struct objfile *objfile = dwarf2_per_objfile->objfile;
11894   const gdb_byte *info_ptr, *end_ptr;
11895
11896   dwarf2_read_section (objfile, &section);
11897   info_ptr = section.buffer;
11898
11899   if (info_ptr == NULL)
11900     return;
11901
11902   if (dwarf_read_debug)
11903     {
11904       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11905                           get_section_name (&section),
11906                           get_section_file_name (&section));
11907     }
11908
11909   end_ptr = info_ptr + section.size;
11910   while (info_ptr < end_ptr)
11911     {
11912       struct dwarf2_per_cu_data per_cu;
11913       struct create_dwo_cu_data create_dwo_cu_data;
11914       struct dwo_unit *dwo_unit;
11915       void **slot;
11916       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11917
11918       memset (&create_dwo_cu_data.dwo_unit, 0,
11919               sizeof (create_dwo_cu_data.dwo_unit));
11920       memset (&per_cu, 0, sizeof (per_cu));
11921       per_cu.objfile = objfile;
11922       per_cu.is_debug_types = 0;
11923       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11924       per_cu.section = &section;
11925       create_dwo_cu_data.dwo_file = &dwo_file;
11926
11927       init_cutu_and_read_dies_no_follow (
11928           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11929       info_ptr += per_cu.length;
11930
11931       // If the unit could not be parsed, skip it.
11932       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11933         continue;
11934
11935       if (cus_htab == NULL)
11936         cus_htab = allocate_dwo_unit_table (objfile);
11937
11938       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11939       *dwo_unit = create_dwo_cu_data.dwo_unit;
11940       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11941       gdb_assert (slot != NULL);
11942       if (*slot != NULL)
11943         {
11944           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11945           sect_offset dup_sect_off = dup_cu->sect_off;
11946
11947           complaint (&symfile_complaints,
11948                      _("debug cu entry at offset 0x%x is duplicate to"
11949                        " the entry at offset 0x%x, signature %s"),
11950                      to_underlying (sect_off), to_underlying (dup_sect_off),
11951                      hex_string (dwo_unit->signature));
11952         }
11953       *slot = (void *)dwo_unit;
11954     }
11955 }
11956
11957 /* DWP file .debug_{cu,tu}_index section format:
11958    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11959
11960    DWP Version 1:
11961
11962    Both index sections have the same format, and serve to map a 64-bit
11963    signature to a set of section numbers.  Each section begins with a header,
11964    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11965    indexes, and a pool of 32-bit section numbers.  The index sections will be
11966    aligned at 8-byte boundaries in the file.
11967
11968    The index section header consists of:
11969
11970     V, 32 bit version number
11971     -, 32 bits unused
11972     N, 32 bit number of compilation units or type units in the index
11973     M, 32 bit number of slots in the hash table
11974
11975    Numbers are recorded using the byte order of the application binary.
11976
11977    The hash table begins at offset 16 in the section, and consists of an array
11978    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11979    order of the application binary).  Unused slots in the hash table are 0.
11980    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11981
11982    The parallel table begins immediately after the hash table
11983    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11984    array of 32-bit indexes (using the byte order of the application binary),
11985    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11986    table contains a 32-bit index into the pool of section numbers.  For unused
11987    hash table slots, the corresponding entry in the parallel table will be 0.
11988
11989    The pool of section numbers begins immediately following the hash table
11990    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11991    section numbers consists of an array of 32-bit words (using the byte order
11992    of the application binary).  Each item in the array is indexed starting
11993    from 0.  The hash table entry provides the index of the first section
11994    number in the set.  Additional section numbers in the set follow, and the
11995    set is terminated by a 0 entry (section number 0 is not used in ELF).
11996
11997    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11998    section must be the first entry in the set, and the .debug_abbrev.dwo must
11999    be the second entry. Other members of the set may follow in any order.
12000
12001    ---
12002
12003    DWP Version 2:
12004
12005    DWP Version 2 combines all the .debug_info, etc. sections into one,
12006    and the entries in the index tables are now offsets into these sections.
12007    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12008    section.
12009
12010    Index Section Contents:
12011     Header
12012     Hash Table of Signatures   dwp_hash_table.hash_table
12013     Parallel Table of Indices  dwp_hash_table.unit_table
12014     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12015     Table of Section Sizes     dwp_hash_table.v2.sizes
12016
12017    The index section header consists of:
12018
12019     V, 32 bit version number
12020     L, 32 bit number of columns in the table of section offsets
12021     N, 32 bit number of compilation units or type units in the index
12022     M, 32 bit number of slots in the hash table
12023
12024    Numbers are recorded using the byte order of the application binary.
12025
12026    The hash table has the same format as version 1.
12027    The parallel table of indices has the same format as version 1,
12028    except that the entries are origin-1 indices into the table of sections
12029    offsets and the table of section sizes.
12030
12031    The table of offsets begins immediately following the parallel table
12032    (at offset 16 + 12 * M from the beginning of the section).  The table is
12033    a two-dimensional array of 32-bit words (using the byte order of the
12034    application binary), with L columns and N+1 rows, in row-major order.
12035    Each row in the array is indexed starting from 0.  The first row provides
12036    a key to the remaining rows: each column in this row provides an identifier
12037    for a debug section, and the offsets in the same column of subsequent rows
12038    refer to that section.  The section identifiers are:
12039
12040     DW_SECT_INFO         1  .debug_info.dwo
12041     DW_SECT_TYPES        2  .debug_types.dwo
12042     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12043     DW_SECT_LINE         4  .debug_line.dwo
12044     DW_SECT_LOC          5  .debug_loc.dwo
12045     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12046     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12047     DW_SECT_MACRO        8  .debug_macro.dwo
12048
12049    The offsets provided by the CU and TU index sections are the base offsets
12050    for the contributions made by each CU or TU to the corresponding section
12051    in the package file.  Each CU and TU header contains an abbrev_offset
12052    field, used to find the abbreviations table for that CU or TU within the
12053    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12054    be interpreted as relative to the base offset given in the index section.
12055    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12056    should be interpreted as relative to the base offset for .debug_line.dwo,
12057    and offsets into other debug sections obtained from DWARF attributes should
12058    also be interpreted as relative to the corresponding base offset.
12059
12060    The table of sizes begins immediately following the table of offsets.
12061    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12062    with L columns and N rows, in row-major order.  Each row in the array is
12063    indexed starting from 1 (row 0 is shared by the two tables).
12064
12065    ---
12066
12067    Hash table lookup is handled the same in version 1 and 2:
12068
12069    We assume that N and M will not exceed 2^32 - 1.
12070    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12071
12072    Given a 64-bit compilation unit signature or a type signature S, an entry
12073    in the hash table is located as follows:
12074
12075    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12076       the low-order k bits all set to 1.
12077
12078    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12079
12080    3) If the hash table entry at index H matches the signature, use that
12081       entry.  If the hash table entry at index H is unused (all zeroes),
12082       terminate the search: the signature is not present in the table.
12083
12084    4) Let H = (H + H') modulo M. Repeat at Step 3.
12085
12086    Because M > N and H' and M are relatively prime, the search is guaranteed
12087    to stop at an unused slot or find the match.  */
12088
12089 /* Create a hash table to map DWO IDs to their CU/TU entry in
12090    .debug_{info,types}.dwo in DWP_FILE.
12091    Returns NULL if there isn't one.
12092    Note: This function processes DWP files only, not DWO files.  */
12093
12094 static struct dwp_hash_table *
12095 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
12096 {
12097   struct objfile *objfile = dwarf2_per_objfile->objfile;
12098   bfd *dbfd = dwp_file->dbfd;
12099   const gdb_byte *index_ptr, *index_end;
12100   struct dwarf2_section_info *index;
12101   uint32_t version, nr_columns, nr_units, nr_slots;
12102   struct dwp_hash_table *htab;
12103
12104   if (is_debug_types)
12105     index = &dwp_file->sections.tu_index;
12106   else
12107     index = &dwp_file->sections.cu_index;
12108
12109   if (dwarf2_section_empty_p (index))
12110     return NULL;
12111   dwarf2_read_section (objfile, index);
12112
12113   index_ptr = index->buffer;
12114   index_end = index_ptr + index->size;
12115
12116   version = read_4_bytes (dbfd, index_ptr);
12117   index_ptr += 4;
12118   if (version == 2)
12119     nr_columns = read_4_bytes (dbfd, index_ptr);
12120   else
12121     nr_columns = 0;
12122   index_ptr += 4;
12123   nr_units = read_4_bytes (dbfd, index_ptr);
12124   index_ptr += 4;
12125   nr_slots = read_4_bytes (dbfd, index_ptr);
12126   index_ptr += 4;
12127
12128   if (version != 1 && version != 2)
12129     {
12130       error (_("Dwarf Error: unsupported DWP file version (%s)"
12131                " [in module %s]"),
12132              pulongest (version), dwp_file->name);
12133     }
12134   if (nr_slots != (nr_slots & -nr_slots))
12135     {
12136       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12137                " is not power of 2 [in module %s]"),
12138              pulongest (nr_slots), dwp_file->name);
12139     }
12140
12141   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12142   htab->version = version;
12143   htab->nr_columns = nr_columns;
12144   htab->nr_units = nr_units;
12145   htab->nr_slots = nr_slots;
12146   htab->hash_table = index_ptr;
12147   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12148
12149   /* Exit early if the table is empty.  */
12150   if (nr_slots == 0 || nr_units == 0
12151       || (version == 2 && nr_columns == 0))
12152     {
12153       /* All must be zero.  */
12154       if (nr_slots != 0 || nr_units != 0
12155           || (version == 2 && nr_columns != 0))
12156         {
12157           complaint (&symfile_complaints,
12158                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12159                        " all zero [in modules %s]"),
12160                      dwp_file->name);
12161         }
12162       return htab;
12163     }
12164
12165   if (version == 1)
12166     {
12167       htab->section_pool.v1.indices =
12168         htab->unit_table + sizeof (uint32_t) * nr_slots;
12169       /* It's harder to decide whether the section is too small in v1.
12170          V1 is deprecated anyway so we punt.  */
12171     }
12172   else
12173     {
12174       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12175       int *ids = htab->section_pool.v2.section_ids;
12176       /* Reverse map for error checking.  */
12177       int ids_seen[DW_SECT_MAX + 1];
12178       int i;
12179
12180       if (nr_columns < 2)
12181         {
12182           error (_("Dwarf Error: bad DWP hash table, too few columns"
12183                    " in section table [in module %s]"),
12184                  dwp_file->name);
12185         }
12186       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12187         {
12188           error (_("Dwarf Error: bad DWP hash table, too many columns"
12189                    " in section table [in module %s]"),
12190                  dwp_file->name);
12191         }
12192       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12193       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12194       for (i = 0; i < nr_columns; ++i)
12195         {
12196           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12197
12198           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12199             {
12200               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12201                        " in section table [in module %s]"),
12202                      id, dwp_file->name);
12203             }
12204           if (ids_seen[id] != -1)
12205             {
12206               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12207                        " id %d in section table [in module %s]"),
12208                      id, dwp_file->name);
12209             }
12210           ids_seen[id] = i;
12211           ids[i] = id;
12212         }
12213       /* Must have exactly one info or types section.  */
12214       if (((ids_seen[DW_SECT_INFO] != -1)
12215            + (ids_seen[DW_SECT_TYPES] != -1))
12216           != 1)
12217         {
12218           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12219                    " DWO info/types section [in module %s]"),
12220                  dwp_file->name);
12221         }
12222       /* Must have an abbrev section.  */
12223       if (ids_seen[DW_SECT_ABBREV] == -1)
12224         {
12225           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12226                    " section [in module %s]"),
12227                  dwp_file->name);
12228         }
12229       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12230       htab->section_pool.v2.sizes =
12231         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12232                                          * nr_units * nr_columns);
12233       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12234                                           * nr_units * nr_columns))
12235           > index_end)
12236         {
12237           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12238                    " [in module %s]"),
12239                  dwp_file->name);
12240         }
12241     }
12242
12243   return htab;
12244 }
12245
12246 /* Update SECTIONS with the data from SECTP.
12247
12248    This function is like the other "locate" section routines that are
12249    passed to bfd_map_over_sections, but in this context the sections to
12250    read comes from the DWP V1 hash table, not the full ELF section table.
12251
12252    The result is non-zero for success, or zero if an error was found.  */
12253
12254 static int
12255 locate_v1_virtual_dwo_sections (asection *sectp,
12256                                 struct virtual_v1_dwo_sections *sections)
12257 {
12258   const struct dwop_section_names *names = &dwop_section_names;
12259
12260   if (section_is_p (sectp->name, &names->abbrev_dwo))
12261     {
12262       /* There can be only one.  */
12263       if (sections->abbrev.s.section != NULL)
12264         return 0;
12265       sections->abbrev.s.section = sectp;
12266       sections->abbrev.size = bfd_get_section_size (sectp);
12267     }
12268   else if (section_is_p (sectp->name, &names->info_dwo)
12269            || section_is_p (sectp->name, &names->types_dwo))
12270     {
12271       /* There can be only one.  */
12272       if (sections->info_or_types.s.section != NULL)
12273         return 0;
12274       sections->info_or_types.s.section = sectp;
12275       sections->info_or_types.size = bfd_get_section_size (sectp);
12276     }
12277   else if (section_is_p (sectp->name, &names->line_dwo))
12278     {
12279       /* There can be only one.  */
12280       if (sections->line.s.section != NULL)
12281         return 0;
12282       sections->line.s.section = sectp;
12283       sections->line.size = bfd_get_section_size (sectp);
12284     }
12285   else if (section_is_p (sectp->name, &names->loc_dwo))
12286     {
12287       /* There can be only one.  */
12288       if (sections->loc.s.section != NULL)
12289         return 0;
12290       sections->loc.s.section = sectp;
12291       sections->loc.size = bfd_get_section_size (sectp);
12292     }
12293   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12294     {
12295       /* There can be only one.  */
12296       if (sections->macinfo.s.section != NULL)
12297         return 0;
12298       sections->macinfo.s.section = sectp;
12299       sections->macinfo.size = bfd_get_section_size (sectp);
12300     }
12301   else if (section_is_p (sectp->name, &names->macro_dwo))
12302     {
12303       /* There can be only one.  */
12304       if (sections->macro.s.section != NULL)
12305         return 0;
12306       sections->macro.s.section = sectp;
12307       sections->macro.size = bfd_get_section_size (sectp);
12308     }
12309   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12310     {
12311       /* There can be only one.  */
12312       if (sections->str_offsets.s.section != NULL)
12313         return 0;
12314       sections->str_offsets.s.section = sectp;
12315       sections->str_offsets.size = bfd_get_section_size (sectp);
12316     }
12317   else
12318     {
12319       /* No other kind of section is valid.  */
12320       return 0;
12321     }
12322
12323   return 1;
12324 }
12325
12326 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12327    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12328    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12329    This is for DWP version 1 files.  */
12330
12331 static struct dwo_unit *
12332 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
12333                            uint32_t unit_index,
12334                            const char *comp_dir,
12335                            ULONGEST signature, int is_debug_types)
12336 {
12337   struct objfile *objfile = dwarf2_per_objfile->objfile;
12338   const struct dwp_hash_table *dwp_htab =
12339     is_debug_types ? dwp_file->tus : dwp_file->cus;
12340   bfd *dbfd = dwp_file->dbfd;
12341   const char *kind = is_debug_types ? "TU" : "CU";
12342   struct dwo_file *dwo_file;
12343   struct dwo_unit *dwo_unit;
12344   struct virtual_v1_dwo_sections sections;
12345   void **dwo_file_slot;
12346   int i;
12347
12348   gdb_assert (dwp_file->version == 1);
12349
12350   if (dwarf_read_debug)
12351     {
12352       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12353                           kind,
12354                           pulongest (unit_index), hex_string (signature),
12355                           dwp_file->name);
12356     }
12357
12358   /* Fetch the sections of this DWO unit.
12359      Put a limit on the number of sections we look for so that bad data
12360      doesn't cause us to loop forever.  */
12361
12362 #define MAX_NR_V1_DWO_SECTIONS \
12363   (1 /* .debug_info or .debug_types */ \
12364    + 1 /* .debug_abbrev */ \
12365    + 1 /* .debug_line */ \
12366    + 1 /* .debug_loc */ \
12367    + 1 /* .debug_str_offsets */ \
12368    + 1 /* .debug_macro or .debug_macinfo */ \
12369    + 1 /* trailing zero */)
12370
12371   memset (&sections, 0, sizeof (sections));
12372
12373   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12374     {
12375       asection *sectp;
12376       uint32_t section_nr =
12377         read_4_bytes (dbfd,
12378                       dwp_htab->section_pool.v1.indices
12379                       + (unit_index + i) * sizeof (uint32_t));
12380
12381       if (section_nr == 0)
12382         break;
12383       if (section_nr >= dwp_file->num_sections)
12384         {
12385           error (_("Dwarf Error: bad DWP hash table, section number too large"
12386                    " [in module %s]"),
12387                  dwp_file->name);
12388         }
12389
12390       sectp = dwp_file->elf_sections[section_nr];
12391       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12392         {
12393           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12394                    " [in module %s]"),
12395                  dwp_file->name);
12396         }
12397     }
12398
12399   if (i < 2
12400       || dwarf2_section_empty_p (&sections.info_or_types)
12401       || dwarf2_section_empty_p (&sections.abbrev))
12402     {
12403       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12404                " [in module %s]"),
12405              dwp_file->name);
12406     }
12407   if (i == MAX_NR_V1_DWO_SECTIONS)
12408     {
12409       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12410                " [in module %s]"),
12411              dwp_file->name);
12412     }
12413
12414   /* It's easier for the rest of the code if we fake a struct dwo_file and
12415      have dwo_unit "live" in that.  At least for now.
12416
12417      The DWP file can be made up of a random collection of CUs and TUs.
12418      However, for each CU + set of TUs that came from the same original DWO
12419      file, we can combine them back into a virtual DWO file to save space
12420      (fewer struct dwo_file objects to allocate).  Remember that for really
12421      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12422
12423   std::string virtual_dwo_name =
12424     string_printf ("virtual-dwo/%d-%d-%d-%d",
12425                    get_section_id (&sections.abbrev),
12426                    get_section_id (&sections.line),
12427                    get_section_id (&sections.loc),
12428                    get_section_id (&sections.str_offsets));
12429   /* Can we use an existing virtual DWO file?  */
12430   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12431   /* Create one if necessary.  */
12432   if (*dwo_file_slot == NULL)
12433     {
12434       if (dwarf_read_debug)
12435         {
12436           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12437                               virtual_dwo_name.c_str ());
12438         }
12439       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12440       dwo_file->dwo_name
12441         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12442                                         virtual_dwo_name.c_str (),
12443                                         virtual_dwo_name.size ());
12444       dwo_file->comp_dir = comp_dir;
12445       dwo_file->sections.abbrev = sections.abbrev;
12446       dwo_file->sections.line = sections.line;
12447       dwo_file->sections.loc = sections.loc;
12448       dwo_file->sections.macinfo = sections.macinfo;
12449       dwo_file->sections.macro = sections.macro;
12450       dwo_file->sections.str_offsets = sections.str_offsets;
12451       /* The "str" section is global to the entire DWP file.  */
12452       dwo_file->sections.str = dwp_file->sections.str;
12453       /* The info or types section is assigned below to dwo_unit,
12454          there's no need to record it in dwo_file.
12455          Also, we can't simply record type sections in dwo_file because
12456          we record a pointer into the vector in dwo_unit.  As we collect more
12457          types we'll grow the vector and eventually have to reallocate space
12458          for it, invalidating all copies of pointers into the previous
12459          contents.  */
12460       *dwo_file_slot = dwo_file;
12461     }
12462   else
12463     {
12464       if (dwarf_read_debug)
12465         {
12466           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12467                               virtual_dwo_name.c_str ());
12468         }
12469       dwo_file = (struct dwo_file *) *dwo_file_slot;
12470     }
12471
12472   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12473   dwo_unit->dwo_file = dwo_file;
12474   dwo_unit->signature = signature;
12475   dwo_unit->section =
12476     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12477   *dwo_unit->section = sections.info_or_types;
12478   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12479
12480   return dwo_unit;
12481 }
12482
12483 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12484    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12485    piece within that section used by a TU/CU, return a virtual section
12486    of just that piece.  */
12487
12488 static struct dwarf2_section_info
12489 create_dwp_v2_section (struct dwarf2_section_info *section,
12490                        bfd_size_type offset, bfd_size_type size)
12491 {
12492   struct dwarf2_section_info result;
12493   asection *sectp;
12494
12495   gdb_assert (section != NULL);
12496   gdb_assert (!section->is_virtual);
12497
12498   memset (&result, 0, sizeof (result));
12499   result.s.containing_section = section;
12500   result.is_virtual = 1;
12501
12502   if (size == 0)
12503     return result;
12504
12505   sectp = get_section_bfd_section (section);
12506
12507   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12508      bounds of the real section.  This is a pretty-rare event, so just
12509      flag an error (easier) instead of a warning and trying to cope.  */
12510   if (sectp == NULL
12511       || offset + size > bfd_get_section_size (sectp))
12512     {
12513       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12514                " in section %s [in module %s]"),
12515              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12516              objfile_name (dwarf2_per_objfile->objfile));
12517     }
12518
12519   result.virtual_offset = offset;
12520   result.size = size;
12521   return result;
12522 }
12523
12524 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12525    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12526    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12527    This is for DWP version 2 files.  */
12528
12529 static struct dwo_unit *
12530 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
12531                            uint32_t unit_index,
12532                            const char *comp_dir,
12533                            ULONGEST signature, int is_debug_types)
12534 {
12535   struct objfile *objfile = dwarf2_per_objfile->objfile;
12536   const struct dwp_hash_table *dwp_htab =
12537     is_debug_types ? dwp_file->tus : dwp_file->cus;
12538   bfd *dbfd = dwp_file->dbfd;
12539   const char *kind = is_debug_types ? "TU" : "CU";
12540   struct dwo_file *dwo_file;
12541   struct dwo_unit *dwo_unit;
12542   struct virtual_v2_dwo_sections sections;
12543   void **dwo_file_slot;
12544   int i;
12545
12546   gdb_assert (dwp_file->version == 2);
12547
12548   if (dwarf_read_debug)
12549     {
12550       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12551                           kind,
12552                           pulongest (unit_index), hex_string (signature),
12553                           dwp_file->name);
12554     }
12555
12556   /* Fetch the section offsets of this DWO unit.  */
12557
12558   memset (&sections, 0, sizeof (sections));
12559
12560   for (i = 0; i < dwp_htab->nr_columns; ++i)
12561     {
12562       uint32_t offset = read_4_bytes (dbfd,
12563                                       dwp_htab->section_pool.v2.offsets
12564                                       + (((unit_index - 1) * dwp_htab->nr_columns
12565                                           + i)
12566                                          * sizeof (uint32_t)));
12567       uint32_t size = read_4_bytes (dbfd,
12568                                     dwp_htab->section_pool.v2.sizes
12569                                     + (((unit_index - 1) * dwp_htab->nr_columns
12570                                         + i)
12571                                        * sizeof (uint32_t)));
12572
12573       switch (dwp_htab->section_pool.v2.section_ids[i])
12574         {
12575         case DW_SECT_INFO:
12576         case DW_SECT_TYPES:
12577           sections.info_or_types_offset = offset;
12578           sections.info_or_types_size = size;
12579           break;
12580         case DW_SECT_ABBREV:
12581           sections.abbrev_offset = offset;
12582           sections.abbrev_size = size;
12583           break;
12584         case DW_SECT_LINE:
12585           sections.line_offset = offset;
12586           sections.line_size = size;
12587           break;
12588         case DW_SECT_LOC:
12589           sections.loc_offset = offset;
12590           sections.loc_size = size;
12591           break;
12592         case DW_SECT_STR_OFFSETS:
12593           sections.str_offsets_offset = offset;
12594           sections.str_offsets_size = size;
12595           break;
12596         case DW_SECT_MACINFO:
12597           sections.macinfo_offset = offset;
12598           sections.macinfo_size = size;
12599           break;
12600         case DW_SECT_MACRO:
12601           sections.macro_offset = offset;
12602           sections.macro_size = size;
12603           break;
12604         }
12605     }
12606
12607   /* It's easier for the rest of the code if we fake a struct dwo_file and
12608      have dwo_unit "live" in that.  At least for now.
12609
12610      The DWP file can be made up of a random collection of CUs and TUs.
12611      However, for each CU + set of TUs that came from the same original DWO
12612      file, we can combine them back into a virtual DWO file to save space
12613      (fewer struct dwo_file objects to allocate).  Remember that for really
12614      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12615
12616   std::string virtual_dwo_name =
12617     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12618                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12619                    (long) (sections.line_size ? sections.line_offset : 0),
12620                    (long) (sections.loc_size ? sections.loc_offset : 0),
12621                    (long) (sections.str_offsets_size
12622                            ? sections.str_offsets_offset : 0));
12623   /* Can we use an existing virtual DWO file?  */
12624   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12625   /* Create one if necessary.  */
12626   if (*dwo_file_slot == NULL)
12627     {
12628       if (dwarf_read_debug)
12629         {
12630           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12631                               virtual_dwo_name.c_str ());
12632         }
12633       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12634       dwo_file->dwo_name
12635         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12636                                         virtual_dwo_name.c_str (),
12637                                         virtual_dwo_name.size ());
12638       dwo_file->comp_dir = comp_dir;
12639       dwo_file->sections.abbrev =
12640         create_dwp_v2_section (&dwp_file->sections.abbrev,
12641                                sections.abbrev_offset, sections.abbrev_size);
12642       dwo_file->sections.line =
12643         create_dwp_v2_section (&dwp_file->sections.line,
12644                                sections.line_offset, sections.line_size);
12645       dwo_file->sections.loc =
12646         create_dwp_v2_section (&dwp_file->sections.loc,
12647                                sections.loc_offset, sections.loc_size);
12648       dwo_file->sections.macinfo =
12649         create_dwp_v2_section (&dwp_file->sections.macinfo,
12650                                sections.macinfo_offset, sections.macinfo_size);
12651       dwo_file->sections.macro =
12652         create_dwp_v2_section (&dwp_file->sections.macro,
12653                                sections.macro_offset, sections.macro_size);
12654       dwo_file->sections.str_offsets =
12655         create_dwp_v2_section (&dwp_file->sections.str_offsets,
12656                                sections.str_offsets_offset,
12657                                sections.str_offsets_size);
12658       /* The "str" section is global to the entire DWP file.  */
12659       dwo_file->sections.str = dwp_file->sections.str;
12660       /* The info or types section is assigned below to dwo_unit,
12661          there's no need to record it in dwo_file.
12662          Also, we can't simply record type sections in dwo_file because
12663          we record a pointer into the vector in dwo_unit.  As we collect more
12664          types we'll grow the vector and eventually have to reallocate space
12665          for it, invalidating all copies of pointers into the previous
12666          contents.  */
12667       *dwo_file_slot = dwo_file;
12668     }
12669   else
12670     {
12671       if (dwarf_read_debug)
12672         {
12673           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12674                               virtual_dwo_name.c_str ());
12675         }
12676       dwo_file = (struct dwo_file *) *dwo_file_slot;
12677     }
12678
12679   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12680   dwo_unit->dwo_file = dwo_file;
12681   dwo_unit->signature = signature;
12682   dwo_unit->section =
12683     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12684   *dwo_unit->section = create_dwp_v2_section (is_debug_types
12685                                               ? &dwp_file->sections.types
12686                                               : &dwp_file->sections.info,
12687                                               sections.info_or_types_offset,
12688                                               sections.info_or_types_size);
12689   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12690
12691   return dwo_unit;
12692 }
12693
12694 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12695    Returns NULL if the signature isn't found.  */
12696
12697 static struct dwo_unit *
12698 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
12699                         ULONGEST signature, int is_debug_types)
12700 {
12701   const struct dwp_hash_table *dwp_htab =
12702     is_debug_types ? dwp_file->tus : dwp_file->cus;
12703   bfd *dbfd = dwp_file->dbfd;
12704   uint32_t mask = dwp_htab->nr_slots - 1;
12705   uint32_t hash = signature & mask;
12706   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12707   unsigned int i;
12708   void **slot;
12709   struct dwo_unit find_dwo_cu;
12710
12711   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12712   find_dwo_cu.signature = signature;
12713   slot = htab_find_slot (is_debug_types
12714                          ? dwp_file->loaded_tus
12715                          : dwp_file->loaded_cus,
12716                          &find_dwo_cu, INSERT);
12717
12718   if (*slot != NULL)
12719     return (struct dwo_unit *) *slot;
12720
12721   /* Use a for loop so that we don't loop forever on bad debug info.  */
12722   for (i = 0; i < dwp_htab->nr_slots; ++i)
12723     {
12724       ULONGEST signature_in_table;
12725
12726       signature_in_table =
12727         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12728       if (signature_in_table == signature)
12729         {
12730           uint32_t unit_index =
12731             read_4_bytes (dbfd,
12732                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12733
12734           if (dwp_file->version == 1)
12735             {
12736               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
12737                                                  comp_dir, signature,
12738                                                  is_debug_types);
12739             }
12740           else
12741             {
12742               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
12743                                                  comp_dir, signature,
12744                                                  is_debug_types);
12745             }
12746           return (struct dwo_unit *) *slot;
12747         }
12748       if (signature_in_table == 0)
12749         return NULL;
12750       hash = (hash + hash2) & mask;
12751     }
12752
12753   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12754            " [in module %s]"),
12755          dwp_file->name);
12756 }
12757
12758 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12759    Open the file specified by FILE_NAME and hand it off to BFD for
12760    preliminary analysis.  Return a newly initialized bfd *, which
12761    includes a canonicalized copy of FILE_NAME.
12762    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12763    SEARCH_CWD is true if the current directory is to be searched.
12764    It will be searched before debug-file-directory.
12765    If successful, the file is added to the bfd include table of the
12766    objfile's bfd (see gdb_bfd_record_inclusion).
12767    If unable to find/open the file, return NULL.
12768    NOTE: This function is derived from symfile_bfd_open.  */
12769
12770 static gdb_bfd_ref_ptr
12771 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
12772 {
12773   int desc, flags;
12774   char *absolute_name;
12775   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12776      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12777      to debug_file_directory.  */
12778   char *search_path;
12779   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12780
12781   if (search_cwd)
12782     {
12783       if (*debug_file_directory != '\0')
12784         search_path = concat (".", dirname_separator_string,
12785                               debug_file_directory, (char *) NULL);
12786       else
12787         search_path = xstrdup (".");
12788     }
12789   else
12790     search_path = xstrdup (debug_file_directory);
12791
12792   flags = OPF_RETURN_REALPATH;
12793   if (is_dwp)
12794     flags |= OPF_SEARCH_IN_PATH;
12795   desc = openp (search_path, flags, file_name,
12796                 O_RDONLY | O_BINARY, &absolute_name);
12797   xfree (search_path);
12798   if (desc < 0)
12799     return NULL;
12800
12801   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12802   xfree (absolute_name);
12803   if (sym_bfd == NULL)
12804     return NULL;
12805   bfd_set_cacheable (sym_bfd.get (), 1);
12806
12807   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12808     return NULL;
12809
12810   /* Success.  Record the bfd as having been included by the objfile's bfd.
12811      This is important because things like demangled_names_hash lives in the
12812      objfile's per_bfd space and may have references to things like symbol
12813      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12814   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12815
12816   return sym_bfd;
12817 }
12818
12819 /* Try to open DWO file FILE_NAME.
12820    COMP_DIR is the DW_AT_comp_dir attribute.
12821    The result is the bfd handle of the file.
12822    If there is a problem finding or opening the file, return NULL.
12823    Upon success, the canonicalized path of the file is stored in the bfd,
12824    same as symfile_bfd_open.  */
12825
12826 static gdb_bfd_ref_ptr
12827 open_dwo_file (const char *file_name, const char *comp_dir)
12828 {
12829   if (IS_ABSOLUTE_PATH (file_name))
12830     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
12831
12832   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12833
12834   if (comp_dir != NULL)
12835     {
12836       char *path_to_try = concat (comp_dir, SLASH_STRING,
12837                                   file_name, (char *) NULL);
12838
12839       /* NOTE: If comp_dir is a relative path, this will also try the
12840          search path, which seems useful.  */
12841       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
12842                                                 1 /*search_cwd*/));
12843       xfree (path_to_try);
12844       if (abfd != NULL)
12845         return abfd;
12846     }
12847
12848   /* That didn't work, try debug-file-directory, which, despite its name,
12849      is a list of paths.  */
12850
12851   if (*debug_file_directory == '\0')
12852     return NULL;
12853
12854   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
12855 }
12856
12857 /* This function is mapped across the sections and remembers the offset and
12858    size of each of the DWO debugging sections we are interested in.  */
12859
12860 static void
12861 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12862 {
12863   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12864   const struct dwop_section_names *names = &dwop_section_names;
12865
12866   if (section_is_p (sectp->name, &names->abbrev_dwo))
12867     {
12868       dwo_sections->abbrev.s.section = sectp;
12869       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12870     }
12871   else if (section_is_p (sectp->name, &names->info_dwo))
12872     {
12873       dwo_sections->info.s.section = sectp;
12874       dwo_sections->info.size = bfd_get_section_size (sectp);
12875     }
12876   else if (section_is_p (sectp->name, &names->line_dwo))
12877     {
12878       dwo_sections->line.s.section = sectp;
12879       dwo_sections->line.size = bfd_get_section_size (sectp);
12880     }
12881   else if (section_is_p (sectp->name, &names->loc_dwo))
12882     {
12883       dwo_sections->loc.s.section = sectp;
12884       dwo_sections->loc.size = bfd_get_section_size (sectp);
12885     }
12886   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12887     {
12888       dwo_sections->macinfo.s.section = sectp;
12889       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12890     }
12891   else if (section_is_p (sectp->name, &names->macro_dwo))
12892     {
12893       dwo_sections->macro.s.section = sectp;
12894       dwo_sections->macro.size = bfd_get_section_size (sectp);
12895     }
12896   else if (section_is_p (sectp->name, &names->str_dwo))
12897     {
12898       dwo_sections->str.s.section = sectp;
12899       dwo_sections->str.size = bfd_get_section_size (sectp);
12900     }
12901   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12902     {
12903       dwo_sections->str_offsets.s.section = sectp;
12904       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12905     }
12906   else if (section_is_p (sectp->name, &names->types_dwo))
12907     {
12908       struct dwarf2_section_info type_section;
12909
12910       memset (&type_section, 0, sizeof (type_section));
12911       type_section.s.section = sectp;
12912       type_section.size = bfd_get_section_size (sectp);
12913       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12914                      &type_section);
12915     }
12916 }
12917
12918 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12919    by PER_CU.  This is for the non-DWP case.
12920    The result is NULL if DWO_NAME can't be found.  */
12921
12922 static struct dwo_file *
12923 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12924                         const char *dwo_name, const char *comp_dir)
12925 {
12926   struct objfile *objfile = dwarf2_per_objfile->objfile;
12927   struct dwo_file *dwo_file;
12928   struct cleanup *cleanups;
12929
12930   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
12931   if (dbfd == NULL)
12932     {
12933       if (dwarf_read_debug)
12934         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12935       return NULL;
12936     }
12937   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12938   dwo_file->dwo_name = dwo_name;
12939   dwo_file->comp_dir = comp_dir;
12940   dwo_file->dbfd = dbfd.release ();
12941
12942   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
12943
12944   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12945                          &dwo_file->sections);
12946
12947   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
12948
12949   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
12950                                  dwo_file->tus);
12951
12952   discard_cleanups (cleanups);
12953
12954   if (dwarf_read_debug)
12955     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12956
12957   return dwo_file;
12958 }
12959
12960 /* This function is mapped across the sections and remembers the offset and
12961    size of each of the DWP debugging sections common to version 1 and 2 that
12962    we are interested in.  */
12963
12964 static void
12965 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12966                                    void *dwp_file_ptr)
12967 {
12968   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12969   const struct dwop_section_names *names = &dwop_section_names;
12970   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12971
12972   /* Record the ELF section number for later lookup: this is what the
12973      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12974   gdb_assert (elf_section_nr < dwp_file->num_sections);
12975   dwp_file->elf_sections[elf_section_nr] = sectp;
12976
12977   /* Look for specific sections that we need.  */
12978   if (section_is_p (sectp->name, &names->str_dwo))
12979     {
12980       dwp_file->sections.str.s.section = sectp;
12981       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12982     }
12983   else if (section_is_p (sectp->name, &names->cu_index))
12984     {
12985       dwp_file->sections.cu_index.s.section = sectp;
12986       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12987     }
12988   else if (section_is_p (sectp->name, &names->tu_index))
12989     {
12990       dwp_file->sections.tu_index.s.section = sectp;
12991       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12992     }
12993 }
12994
12995 /* This function is mapped across the sections and remembers the offset and
12996    size of each of the DWP version 2 debugging sections that we are interested
12997    in.  This is split into a separate function because we don't know if we
12998    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12999
13000 static void
13001 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13002 {
13003   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13004   const struct dwop_section_names *names = &dwop_section_names;
13005   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13006
13007   /* Record the ELF section number for later lookup: this is what the
13008      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13009   gdb_assert (elf_section_nr < dwp_file->num_sections);
13010   dwp_file->elf_sections[elf_section_nr] = sectp;
13011
13012   /* Look for specific sections that we need.  */
13013   if (section_is_p (sectp->name, &names->abbrev_dwo))
13014     {
13015       dwp_file->sections.abbrev.s.section = sectp;
13016       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13017     }
13018   else if (section_is_p (sectp->name, &names->info_dwo))
13019     {
13020       dwp_file->sections.info.s.section = sectp;
13021       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13022     }
13023   else if (section_is_p (sectp->name, &names->line_dwo))
13024     {
13025       dwp_file->sections.line.s.section = sectp;
13026       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13027     }
13028   else if (section_is_p (sectp->name, &names->loc_dwo))
13029     {
13030       dwp_file->sections.loc.s.section = sectp;
13031       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13032     }
13033   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13034     {
13035       dwp_file->sections.macinfo.s.section = sectp;
13036       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13037     }
13038   else if (section_is_p (sectp->name, &names->macro_dwo))
13039     {
13040       dwp_file->sections.macro.s.section = sectp;
13041       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13042     }
13043   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13044     {
13045       dwp_file->sections.str_offsets.s.section = sectp;
13046       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13047     }
13048   else if (section_is_p (sectp->name, &names->types_dwo))
13049     {
13050       dwp_file->sections.types.s.section = sectp;
13051       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13052     }
13053 }
13054
13055 /* Hash function for dwp_file loaded CUs/TUs.  */
13056
13057 static hashval_t
13058 hash_dwp_loaded_cutus (const void *item)
13059 {
13060   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13061
13062   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13063   return dwo_unit->signature;
13064 }
13065
13066 /* Equality function for dwp_file loaded CUs/TUs.  */
13067
13068 static int
13069 eq_dwp_loaded_cutus (const void *a, const void *b)
13070 {
13071   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13072   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13073
13074   return dua->signature == dub->signature;
13075 }
13076
13077 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13078
13079 static htab_t
13080 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13081 {
13082   return htab_create_alloc_ex (3,
13083                                hash_dwp_loaded_cutus,
13084                                eq_dwp_loaded_cutus,
13085                                NULL,
13086                                &objfile->objfile_obstack,
13087                                hashtab_obstack_allocate,
13088                                dummy_obstack_deallocate);
13089 }
13090
13091 /* Try to open DWP file FILE_NAME.
13092    The result is the bfd handle of the file.
13093    If there is a problem finding or opening the file, return NULL.
13094    Upon success, the canonicalized path of the file is stored in the bfd,
13095    same as symfile_bfd_open.  */
13096
13097 static gdb_bfd_ref_ptr
13098 open_dwp_file (const char *file_name)
13099 {
13100   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
13101                                             1 /*search_cwd*/));
13102   if (abfd != NULL)
13103     return abfd;
13104
13105   /* Work around upstream bug 15652.
13106      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13107      [Whether that's a "bug" is debatable, but it is getting in our way.]
13108      We have no real idea where the dwp file is, because gdb's realpath-ing
13109      of the executable's path may have discarded the needed info.
13110      [IWBN if the dwp file name was recorded in the executable, akin to
13111      .gnu_debuglink, but that doesn't exist yet.]
13112      Strip the directory from FILE_NAME and search again.  */
13113   if (*debug_file_directory != '\0')
13114     {
13115       /* Don't implicitly search the current directory here.
13116          If the user wants to search "." to handle this case,
13117          it must be added to debug-file-directory.  */
13118       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
13119                                  0 /*search_cwd*/);
13120     }
13121
13122   return NULL;
13123 }
13124
13125 /* Initialize the use of the DWP file for the current objfile.
13126    By convention the name of the DWP file is ${objfile}.dwp.
13127    The result is NULL if it can't be found.  */
13128
13129 static struct dwp_file *
13130 open_and_init_dwp_file (void)
13131 {
13132   struct objfile *objfile = dwarf2_per_objfile->objfile;
13133   struct dwp_file *dwp_file;
13134
13135   /* Try to find first .dwp for the binary file before any symbolic links
13136      resolving.  */
13137
13138   /* If the objfile is a debug file, find the name of the real binary
13139      file and get the name of dwp file from there.  */
13140   std::string dwp_name;
13141   if (objfile->separate_debug_objfile_backlink != NULL)
13142     {
13143       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13144       const char *backlink_basename = lbasename (backlink->original_name);
13145
13146       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13147     }
13148   else
13149     dwp_name = objfile->original_name;
13150
13151   dwp_name += ".dwp";
13152
13153   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
13154   if (dbfd == NULL
13155       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13156     {
13157       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13158       dwp_name = objfile_name (objfile);
13159       dwp_name += ".dwp";
13160       dbfd = open_dwp_file (dwp_name.c_str ());
13161     }
13162
13163   if (dbfd == NULL)
13164     {
13165       if (dwarf_read_debug)
13166         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13167       return NULL;
13168     }
13169   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13170   dwp_file->name = bfd_get_filename (dbfd.get ());
13171   dwp_file->dbfd = dbfd.release ();
13172
13173   /* +1: section 0 is unused */
13174   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13175   dwp_file->elf_sections =
13176     OBSTACK_CALLOC (&objfile->objfile_obstack,
13177                     dwp_file->num_sections, asection *);
13178
13179   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13180                          dwp_file);
13181
13182   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
13183
13184   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
13185
13186   /* The DWP file version is stored in the hash table.  Oh well.  */
13187   if (dwp_file->cus && dwp_file->tus
13188       && dwp_file->cus->version != dwp_file->tus->version)
13189     {
13190       /* Technically speaking, we should try to limp along, but this is
13191          pretty bizarre.  We use pulongest here because that's the established
13192          portability solution (e.g, we cannot use %u for uint32_t).  */
13193       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13194                " TU version %s [in DWP file %s]"),
13195              pulongest (dwp_file->cus->version),
13196              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13197     }
13198
13199   if (dwp_file->cus)
13200     dwp_file->version = dwp_file->cus->version;
13201   else if (dwp_file->tus)
13202     dwp_file->version = dwp_file->tus->version;
13203   else
13204     dwp_file->version = 2;
13205
13206   if (dwp_file->version == 2)
13207     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13208                            dwp_file);
13209
13210   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13211   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13212
13213   if (dwarf_read_debug)
13214     {
13215       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13216       fprintf_unfiltered (gdb_stdlog,
13217                           "    %s CUs, %s TUs\n",
13218                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13219                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13220     }
13221
13222   return dwp_file;
13223 }
13224
13225 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13226
13227 static struct dwp_file *
13228 get_dwp_file (void)
13229 {
13230   if (! dwarf2_per_objfile->dwp_checked)
13231     {
13232       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
13233       dwarf2_per_objfile->dwp_checked = 1;
13234     }
13235   return dwarf2_per_objfile->dwp_file;
13236 }
13237
13238 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13239    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13240    or in the DWP file for the objfile, referenced by THIS_UNIT.
13241    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13242    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13243
13244    This is called, for example, when wanting to read a variable with a
13245    complex location.  Therefore we don't want to do file i/o for every call.
13246    Therefore we don't want to look for a DWO file on every call.
13247    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13248    then we check if we've already seen DWO_NAME, and only THEN do we check
13249    for a DWO file.
13250
13251    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13252    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13253
13254 static struct dwo_unit *
13255 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13256                  const char *dwo_name, const char *comp_dir,
13257                  ULONGEST signature, int is_debug_types)
13258 {
13259   struct objfile *objfile = dwarf2_per_objfile->objfile;
13260   const char *kind = is_debug_types ? "TU" : "CU";
13261   void **dwo_file_slot;
13262   struct dwo_file *dwo_file;
13263   struct dwp_file *dwp_file;
13264
13265   /* First see if there's a DWP file.
13266      If we have a DWP file but didn't find the DWO inside it, don't
13267      look for the original DWO file.  It makes gdb behave differently
13268      depending on whether one is debugging in the build tree.  */
13269
13270   dwp_file = get_dwp_file ();
13271   if (dwp_file != NULL)
13272     {
13273       const struct dwp_hash_table *dwp_htab =
13274         is_debug_types ? dwp_file->tus : dwp_file->cus;
13275
13276       if (dwp_htab != NULL)
13277         {
13278           struct dwo_unit *dwo_cutu =
13279             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
13280                                     signature, is_debug_types);
13281
13282           if (dwo_cutu != NULL)
13283             {
13284               if (dwarf_read_debug)
13285                 {
13286                   fprintf_unfiltered (gdb_stdlog,
13287                                       "Virtual DWO %s %s found: @%s\n",
13288                                       kind, hex_string (signature),
13289                                       host_address_to_string (dwo_cutu));
13290                 }
13291               return dwo_cutu;
13292             }
13293         }
13294     }
13295   else
13296     {
13297       /* No DWP file, look for the DWO file.  */
13298
13299       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
13300       if (*dwo_file_slot == NULL)
13301         {
13302           /* Read in the file and build a table of the CUs/TUs it contains.  */
13303           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13304         }
13305       /* NOTE: This will be NULL if unable to open the file.  */
13306       dwo_file = (struct dwo_file *) *dwo_file_slot;
13307
13308       if (dwo_file != NULL)
13309         {
13310           struct dwo_unit *dwo_cutu = NULL;
13311
13312           if (is_debug_types && dwo_file->tus)
13313             {
13314               struct dwo_unit find_dwo_cutu;
13315
13316               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13317               find_dwo_cutu.signature = signature;
13318               dwo_cutu
13319                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13320             }
13321           else if (!is_debug_types && dwo_file->cus)
13322             {
13323               struct dwo_unit find_dwo_cutu;
13324
13325               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13326               find_dwo_cutu.signature = signature;
13327               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13328                                                        &find_dwo_cutu);
13329             }
13330
13331           if (dwo_cutu != NULL)
13332             {
13333               if (dwarf_read_debug)
13334                 {
13335                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13336                                       kind, dwo_name, hex_string (signature),
13337                                       host_address_to_string (dwo_cutu));
13338                 }
13339               return dwo_cutu;
13340             }
13341         }
13342     }
13343
13344   /* We didn't find it.  This could mean a dwo_id mismatch, or
13345      someone deleted the DWO/DWP file, or the search path isn't set up
13346      correctly to find the file.  */
13347
13348   if (dwarf_read_debug)
13349     {
13350       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13351                           kind, dwo_name, hex_string (signature));
13352     }
13353
13354   /* This is a warning and not a complaint because it can be caused by
13355      pilot error (e.g., user accidentally deleting the DWO).  */
13356   {
13357     /* Print the name of the DWP file if we looked there, helps the user
13358        better diagnose the problem.  */
13359     std::string dwp_text;
13360
13361     if (dwp_file != NULL)
13362       dwp_text = string_printf (" [in DWP file %s]",
13363                                 lbasename (dwp_file->name));
13364
13365     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13366                " [in module %s]"),
13367              kind, dwo_name, hex_string (signature),
13368              dwp_text.c_str (),
13369              this_unit->is_debug_types ? "TU" : "CU",
13370              to_underlying (this_unit->sect_off), objfile_name (objfile));
13371   }
13372   return NULL;
13373 }
13374
13375 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13376    See lookup_dwo_cutu_unit for details.  */
13377
13378 static struct dwo_unit *
13379 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13380                       const char *dwo_name, const char *comp_dir,
13381                       ULONGEST signature)
13382 {
13383   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13384 }
13385
13386 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13387    See lookup_dwo_cutu_unit for details.  */
13388
13389 static struct dwo_unit *
13390 lookup_dwo_type_unit (struct signatured_type *this_tu,
13391                       const char *dwo_name, const char *comp_dir)
13392 {
13393   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13394 }
13395
13396 /* Traversal function for queue_and_load_all_dwo_tus.  */
13397
13398 static int
13399 queue_and_load_dwo_tu (void **slot, void *info)
13400 {
13401   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13402   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13403   ULONGEST signature = dwo_unit->signature;
13404   struct signatured_type *sig_type =
13405     lookup_dwo_signatured_type (per_cu->cu, signature);
13406
13407   if (sig_type != NULL)
13408     {
13409       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13410
13411       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13412          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13413          while processing PER_CU.  */
13414       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13415         load_full_type_unit (sig_cu);
13416       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13417     }
13418
13419   return 1;
13420 }
13421
13422 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13423    The DWO may have the only definition of the type, though it may not be
13424    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13425    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13426
13427 static void
13428 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13429 {
13430   struct dwo_unit *dwo_unit;
13431   struct dwo_file *dwo_file;
13432
13433   gdb_assert (!per_cu->is_debug_types);
13434   gdb_assert (get_dwp_file () == NULL);
13435   gdb_assert (per_cu->cu != NULL);
13436
13437   dwo_unit = per_cu->cu->dwo_unit;
13438   gdb_assert (dwo_unit != NULL);
13439
13440   dwo_file = dwo_unit->dwo_file;
13441   if (dwo_file->tus != NULL)
13442     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13443 }
13444
13445 /* Free all resources associated with DWO_FILE.
13446    Close the DWO file and munmap the sections.
13447    All memory should be on the objfile obstack.  */
13448
13449 static void
13450 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13451 {
13452
13453   /* Note: dbfd is NULL for virtual DWO files.  */
13454   gdb_bfd_unref (dwo_file->dbfd);
13455
13456   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13457 }
13458
13459 /* Wrapper for free_dwo_file for use in cleanups.  */
13460
13461 static void
13462 free_dwo_file_cleanup (void *arg)
13463 {
13464   struct dwo_file *dwo_file = (struct dwo_file *) arg;
13465   struct objfile *objfile = dwarf2_per_objfile->objfile;
13466
13467   free_dwo_file (dwo_file, objfile);
13468 }
13469
13470 /* Traversal function for free_dwo_files.  */
13471
13472 static int
13473 free_dwo_file_from_slot (void **slot, void *info)
13474 {
13475   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13476   struct objfile *objfile = (struct objfile *) info;
13477
13478   free_dwo_file (dwo_file, objfile);
13479
13480   return 1;
13481 }
13482
13483 /* Free all resources associated with DWO_FILES.  */
13484
13485 static void
13486 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13487 {
13488   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13489 }
13490 \f
13491 /* Read in various DIEs.  */
13492
13493 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13494    Inherit only the children of the DW_AT_abstract_origin DIE not being
13495    already referenced by DW_AT_abstract_origin from the children of the
13496    current DIE.  */
13497
13498 static void
13499 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13500 {
13501   struct die_info *child_die;
13502   sect_offset *offsetp;
13503   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13504   struct die_info *origin_die;
13505   /* Iterator of the ORIGIN_DIE children.  */
13506   struct die_info *origin_child_die;
13507   struct attribute *attr;
13508   struct dwarf2_cu *origin_cu;
13509   struct pending **origin_previous_list_in_scope;
13510
13511   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13512   if (!attr)
13513     return;
13514
13515   /* Note that following die references may follow to a die in a
13516      different cu.  */
13517
13518   origin_cu = cu;
13519   origin_die = follow_die_ref (die, attr, &origin_cu);
13520
13521   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13522      symbols in.  */
13523   origin_previous_list_in_scope = origin_cu->list_in_scope;
13524   origin_cu->list_in_scope = cu->list_in_scope;
13525
13526   if (die->tag != origin_die->tag
13527       && !(die->tag == DW_TAG_inlined_subroutine
13528            && origin_die->tag == DW_TAG_subprogram))
13529     complaint (&symfile_complaints,
13530                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13531                to_underlying (die->sect_off),
13532                to_underlying (origin_die->sect_off));
13533
13534   std::vector<sect_offset> offsets;
13535
13536   for (child_die = die->child;
13537        child_die && child_die->tag;
13538        child_die = sibling_die (child_die))
13539     {
13540       struct die_info *child_origin_die;
13541       struct dwarf2_cu *child_origin_cu;
13542
13543       /* We are trying to process concrete instance entries:
13544          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13545          it's not relevant to our analysis here. i.e. detecting DIEs that are
13546          present in the abstract instance but not referenced in the concrete
13547          one.  */
13548       if (child_die->tag == DW_TAG_call_site
13549           || child_die->tag == DW_TAG_GNU_call_site)
13550         continue;
13551
13552       /* For each CHILD_DIE, find the corresponding child of
13553          ORIGIN_DIE.  If there is more than one layer of
13554          DW_AT_abstract_origin, follow them all; there shouldn't be,
13555          but GCC versions at least through 4.4 generate this (GCC PR
13556          40573).  */
13557       child_origin_die = child_die;
13558       child_origin_cu = cu;
13559       while (1)
13560         {
13561           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13562                               child_origin_cu);
13563           if (attr == NULL)
13564             break;
13565           child_origin_die = follow_die_ref (child_origin_die, attr,
13566                                              &child_origin_cu);
13567         }
13568
13569       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13570          counterpart may exist.  */
13571       if (child_origin_die != child_die)
13572         {
13573           if (child_die->tag != child_origin_die->tag
13574               && !(child_die->tag == DW_TAG_inlined_subroutine
13575                    && child_origin_die->tag == DW_TAG_subprogram))
13576             complaint (&symfile_complaints,
13577                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13578                          "different tags"),
13579                        to_underlying (child_die->sect_off),
13580                        to_underlying (child_origin_die->sect_off));
13581           if (child_origin_die->parent != origin_die)
13582             complaint (&symfile_complaints,
13583                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13584                          "different parents"),
13585                        to_underlying (child_die->sect_off),
13586                        to_underlying (child_origin_die->sect_off));
13587           else
13588             offsets.push_back (child_origin_die->sect_off);
13589         }
13590     }
13591   std::sort (offsets.begin (), offsets.end ());
13592   sect_offset *offsets_end = offsets.data () + offsets.size ();
13593   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13594     if (offsetp[-1] == *offsetp)
13595       complaint (&symfile_complaints,
13596                  _("Multiple children of DIE 0x%x refer "
13597                    "to DIE 0x%x as their abstract origin"),
13598                  to_underlying (die->sect_off), to_underlying (*offsetp));
13599
13600   offsetp = offsets.data ();
13601   origin_child_die = origin_die->child;
13602   while (origin_child_die && origin_child_die->tag)
13603     {
13604       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13605       while (offsetp < offsets_end
13606              && *offsetp < origin_child_die->sect_off)
13607         offsetp++;
13608       if (offsetp >= offsets_end
13609           || *offsetp > origin_child_die->sect_off)
13610         {
13611           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13612              Check whether we're already processing ORIGIN_CHILD_DIE.
13613              This can happen with mutually referenced abstract_origins.
13614              PR 16581.  */
13615           if (!origin_child_die->in_process)
13616             process_die (origin_child_die, origin_cu);
13617         }
13618       origin_child_die = sibling_die (origin_child_die);
13619     }
13620   origin_cu->list_in_scope = origin_previous_list_in_scope;
13621 }
13622
13623 static void
13624 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13625 {
13626   struct objfile *objfile = cu->objfile;
13627   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13628   struct context_stack *newobj;
13629   CORE_ADDR lowpc;
13630   CORE_ADDR highpc;
13631   struct die_info *child_die;
13632   struct attribute *attr, *call_line, *call_file;
13633   const char *name;
13634   CORE_ADDR baseaddr;
13635   struct block *block;
13636   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13637   std::vector<struct symbol *> template_args;
13638   struct template_symbol *templ_func = NULL;
13639
13640   if (inlined_func)
13641     {
13642       /* If we do not have call site information, we can't show the
13643          caller of this inlined function.  That's too confusing, so
13644          only use the scope for local variables.  */
13645       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13646       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13647       if (call_line == NULL || call_file == NULL)
13648         {
13649           read_lexical_block_scope (die, cu);
13650           return;
13651         }
13652     }
13653
13654   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13655
13656   name = dwarf2_name (die, cu);
13657
13658   /* Ignore functions with missing or empty names.  These are actually
13659      illegal according to the DWARF standard.  */
13660   if (name == NULL)
13661     {
13662       complaint (&symfile_complaints,
13663                  _("missing name for subprogram DIE at %d"),
13664                  to_underlying (die->sect_off));
13665       return;
13666     }
13667
13668   /* Ignore functions with missing or invalid low and high pc attributes.  */
13669   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13670       <= PC_BOUNDS_INVALID)
13671     {
13672       attr = dwarf2_attr (die, DW_AT_external, cu);
13673       if (!attr || !DW_UNSND (attr))
13674         complaint (&symfile_complaints,
13675                    _("cannot get low and high bounds "
13676                      "for subprogram DIE at %d"),
13677                    to_underlying (die->sect_off));
13678       return;
13679     }
13680
13681   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13682   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13683
13684   /* If we have any template arguments, then we must allocate a
13685      different sort of symbol.  */
13686   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13687     {
13688       if (child_die->tag == DW_TAG_template_type_param
13689           || child_die->tag == DW_TAG_template_value_param)
13690         {
13691           templ_func = allocate_template_symbol (objfile);
13692           templ_func->subclass = SYMBOL_TEMPLATE;
13693           break;
13694         }
13695     }
13696
13697   newobj = push_context (0, lowpc);
13698   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
13699                                (struct symbol *) templ_func);
13700
13701   /* If there is a location expression for DW_AT_frame_base, record
13702      it.  */
13703   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13704   if (attr)
13705     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13706
13707   /* If there is a location for the static link, record it.  */
13708   newobj->static_link = NULL;
13709   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13710   if (attr)
13711     {
13712       newobj->static_link
13713         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13714       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13715     }
13716
13717   cu->list_in_scope = &local_symbols;
13718
13719   if (die->child != NULL)
13720     {
13721       child_die = die->child;
13722       while (child_die && child_die->tag)
13723         {
13724           if (child_die->tag == DW_TAG_template_type_param
13725               || child_die->tag == DW_TAG_template_value_param)
13726             {
13727               struct symbol *arg = new_symbol (child_die, NULL, cu);
13728
13729               if (arg != NULL)
13730                 template_args.push_back (arg);
13731             }
13732           else
13733             process_die (child_die, cu);
13734           child_die = sibling_die (child_die);
13735         }
13736     }
13737
13738   inherit_abstract_dies (die, cu);
13739
13740   /* If we have a DW_AT_specification, we might need to import using
13741      directives from the context of the specification DIE.  See the
13742      comment in determine_prefix.  */
13743   if (cu->language == language_cplus
13744       && dwarf2_attr (die, DW_AT_specification, cu))
13745     {
13746       struct dwarf2_cu *spec_cu = cu;
13747       struct die_info *spec_die = die_specification (die, &spec_cu);
13748
13749       while (spec_die)
13750         {
13751           child_die = spec_die->child;
13752           while (child_die && child_die->tag)
13753             {
13754               if (child_die->tag == DW_TAG_imported_module)
13755                 process_die (child_die, spec_cu);
13756               child_die = sibling_die (child_die);
13757             }
13758
13759           /* In some cases, GCC generates specification DIEs that
13760              themselves contain DW_AT_specification attributes.  */
13761           spec_die = die_specification (spec_die, &spec_cu);
13762         }
13763     }
13764
13765   newobj = pop_context ();
13766   /* Make a block for the local symbols within.  */
13767   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13768                         newobj->static_link, lowpc, highpc);
13769
13770   /* For C++, set the block's scope.  */
13771   if ((cu->language == language_cplus
13772        || cu->language == language_fortran
13773        || cu->language == language_d
13774        || cu->language == language_rust)
13775       && cu->processing_has_namespace_info)
13776     block_set_scope (block, determine_prefix (die, cu),
13777                      &objfile->objfile_obstack);
13778
13779   /* If we have address ranges, record them.  */
13780   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13781
13782   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13783
13784   /* Attach template arguments to function.  */
13785   if (!template_args.empty ())
13786     {
13787       gdb_assert (templ_func != NULL);
13788
13789       templ_func->n_template_arguments = template_args.size ();
13790       templ_func->template_arguments
13791         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13792                      templ_func->n_template_arguments);
13793       memcpy (templ_func->template_arguments,
13794               template_args.data (),
13795               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13796     }
13797
13798   /* In C++, we can have functions nested inside functions (e.g., when
13799      a function declares a class that has methods).  This means that
13800      when we finish processing a function scope, we may need to go
13801      back to building a containing block's symbol lists.  */
13802   local_symbols = newobj->locals;
13803   local_using_directives = newobj->local_using_directives;
13804
13805   /* If we've finished processing a top-level function, subsequent
13806      symbols go in the file symbol list.  */
13807   if (outermost_context_p ())
13808     cu->list_in_scope = &file_symbols;
13809 }
13810
13811 /* Process all the DIES contained within a lexical block scope.  Start
13812    a new scope, process the dies, and then close the scope.  */
13813
13814 static void
13815 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13816 {
13817   struct objfile *objfile = cu->objfile;
13818   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13819   struct context_stack *newobj;
13820   CORE_ADDR lowpc, highpc;
13821   struct die_info *child_die;
13822   CORE_ADDR baseaddr;
13823
13824   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13825
13826   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13827   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13828      as multiple lexical blocks?  Handling children in a sane way would
13829      be nasty.  Might be easier to properly extend generic blocks to
13830      describe ranges.  */
13831   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13832     {
13833     case PC_BOUNDS_NOT_PRESENT:
13834       /* DW_TAG_lexical_block has no attributes, process its children as if
13835          there was no wrapping by that DW_TAG_lexical_block.
13836          GCC does no longer produces such DWARF since GCC r224161.  */
13837       for (child_die = die->child;
13838            child_die != NULL && child_die->tag;
13839            child_die = sibling_die (child_die))
13840         process_die (child_die, cu);
13841       return;
13842     case PC_BOUNDS_INVALID:
13843       return;
13844     }
13845   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13846   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13847
13848   push_context (0, lowpc);
13849   if (die->child != NULL)
13850     {
13851       child_die = die->child;
13852       while (child_die && child_die->tag)
13853         {
13854           process_die (child_die, cu);
13855           child_die = sibling_die (child_die);
13856         }
13857     }
13858   inherit_abstract_dies (die, cu);
13859   newobj = pop_context ();
13860
13861   if (local_symbols != NULL || local_using_directives != NULL)
13862     {
13863       struct block *block
13864         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13865                         newobj->start_addr, highpc);
13866
13867       /* Note that recording ranges after traversing children, as we
13868          do here, means that recording a parent's ranges entails
13869          walking across all its children's ranges as they appear in
13870          the address map, which is quadratic behavior.
13871
13872          It would be nicer to record the parent's ranges before
13873          traversing its children, simply overriding whatever you find
13874          there.  But since we don't even decide whether to create a
13875          block until after we've traversed its children, that's hard
13876          to do.  */
13877       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13878     }
13879   local_symbols = newobj->locals;
13880   local_using_directives = newobj->local_using_directives;
13881 }
13882
13883 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13884
13885 static void
13886 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13887 {
13888   struct objfile *objfile = cu->objfile;
13889   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13890   CORE_ADDR pc, baseaddr;
13891   struct attribute *attr;
13892   struct call_site *call_site, call_site_local;
13893   void **slot;
13894   int nparams;
13895   struct die_info *child_die;
13896
13897   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13898
13899   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13900   if (attr == NULL)
13901     {
13902       /* This was a pre-DWARF-5 GNU extension alias
13903          for DW_AT_call_return_pc.  */
13904       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13905     }
13906   if (!attr)
13907     {
13908       complaint (&symfile_complaints,
13909                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
13910                    "DIE 0x%x [in module %s]"),
13911                  to_underlying (die->sect_off), objfile_name (objfile));
13912       return;
13913     }
13914   pc = attr_value_as_address (attr) + baseaddr;
13915   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13916
13917   if (cu->call_site_htab == NULL)
13918     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13919                                                NULL, &objfile->objfile_obstack,
13920                                                hashtab_obstack_allocate, NULL);
13921   call_site_local.pc = pc;
13922   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13923   if (*slot != NULL)
13924     {
13925       complaint (&symfile_complaints,
13926                  _("Duplicate PC %s for DW_TAG_call_site "
13927                    "DIE 0x%x [in module %s]"),
13928                  paddress (gdbarch, pc), to_underlying (die->sect_off),
13929                  objfile_name (objfile));
13930       return;
13931     }
13932
13933   /* Count parameters at the caller.  */
13934
13935   nparams = 0;
13936   for (child_die = die->child; child_die && child_die->tag;
13937        child_die = sibling_die (child_die))
13938     {
13939       if (child_die->tag != DW_TAG_call_site_parameter
13940           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13941         {
13942           complaint (&symfile_complaints,
13943                      _("Tag %d is not DW_TAG_call_site_parameter in "
13944                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13945                      child_die->tag, to_underlying (child_die->sect_off),
13946                      objfile_name (objfile));
13947           continue;
13948         }
13949
13950       nparams++;
13951     }
13952
13953   call_site
13954     = ((struct call_site *)
13955        obstack_alloc (&objfile->objfile_obstack,
13956                       sizeof (*call_site)
13957                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13958   *slot = call_site;
13959   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13960   call_site->pc = pc;
13961
13962   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13963       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13964     {
13965       struct die_info *func_die;
13966
13967       /* Skip also over DW_TAG_inlined_subroutine.  */
13968       for (func_die = die->parent;
13969            func_die && func_die->tag != DW_TAG_subprogram
13970            && func_die->tag != DW_TAG_subroutine_type;
13971            func_die = func_die->parent);
13972
13973       /* DW_AT_call_all_calls is a superset
13974          of DW_AT_call_all_tail_calls.  */
13975       if (func_die
13976           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13977           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13978           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13979           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13980         {
13981           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13982              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13983              both the initial caller containing the real return address PC and
13984              the final callee containing the current PC of a chain of tail
13985              calls do not need to have the tail call list complete.  But any
13986              function candidate for a virtual tail call frame searched via
13987              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13988              determined unambiguously.  */
13989         }
13990       else
13991         {
13992           struct type *func_type = NULL;
13993
13994           if (func_die)
13995             func_type = get_die_type (func_die, cu);
13996           if (func_type != NULL)
13997             {
13998               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13999
14000               /* Enlist this call site to the function.  */
14001               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14002               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14003             }
14004           else
14005             complaint (&symfile_complaints,
14006                        _("Cannot find function owning DW_TAG_call_site "
14007                          "DIE 0x%x [in module %s]"),
14008                        to_underlying (die->sect_off), objfile_name (objfile));
14009         }
14010     }
14011
14012   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14013   if (attr == NULL)
14014     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14015   if (attr == NULL)
14016     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14017   if (attr == NULL)
14018     {
14019       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14020       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14021     }
14022   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14023   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14024     /* Keep NULL DWARF_BLOCK.  */;
14025   else if (attr_form_is_block (attr))
14026     {
14027       struct dwarf2_locexpr_baton *dlbaton;
14028
14029       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14030       dlbaton->data = DW_BLOCK (attr)->data;
14031       dlbaton->size = DW_BLOCK (attr)->size;
14032       dlbaton->per_cu = cu->per_cu;
14033
14034       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14035     }
14036   else if (attr_form_is_ref (attr))
14037     {
14038       struct dwarf2_cu *target_cu = cu;
14039       struct die_info *target_die;
14040
14041       target_die = follow_die_ref (die, attr, &target_cu);
14042       gdb_assert (target_cu->objfile == objfile);
14043       if (die_is_declaration (target_die, target_cu))
14044         {
14045           const char *target_physname;
14046
14047           /* Prefer the mangled name; otherwise compute the demangled one.  */
14048           target_physname = dw2_linkage_name (target_die, target_cu);
14049           if (target_physname == NULL)
14050             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14051           if (target_physname == NULL)
14052             complaint (&symfile_complaints,
14053                        _("DW_AT_call_target target DIE has invalid "
14054                          "physname, for referencing DIE 0x%x [in module %s]"),
14055                        to_underlying (die->sect_off), objfile_name (objfile));
14056           else
14057             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14058         }
14059       else
14060         {
14061           CORE_ADDR lowpc;
14062
14063           /* DW_AT_entry_pc should be preferred.  */
14064           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14065               <= PC_BOUNDS_INVALID)
14066             complaint (&symfile_complaints,
14067                        _("DW_AT_call_target target DIE has invalid "
14068                          "low pc, for referencing DIE 0x%x [in module %s]"),
14069                        to_underlying (die->sect_off), objfile_name (objfile));
14070           else
14071             {
14072               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14073               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14074             }
14075         }
14076     }
14077   else
14078     complaint (&symfile_complaints,
14079                _("DW_TAG_call_site DW_AT_call_target is neither "
14080                  "block nor reference, for DIE 0x%x [in module %s]"),
14081                to_underlying (die->sect_off), objfile_name (objfile));
14082
14083   call_site->per_cu = cu->per_cu;
14084
14085   for (child_die = die->child;
14086        child_die && child_die->tag;
14087        child_die = sibling_die (child_die))
14088     {
14089       struct call_site_parameter *parameter;
14090       struct attribute *loc, *origin;
14091
14092       if (child_die->tag != DW_TAG_call_site_parameter
14093           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14094         {
14095           /* Already printed the complaint above.  */
14096           continue;
14097         }
14098
14099       gdb_assert (call_site->parameter_count < nparams);
14100       parameter = &call_site->parameter[call_site->parameter_count];
14101
14102       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14103          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14104          register is contained in DW_AT_call_value.  */
14105
14106       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14107       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14108       if (origin == NULL)
14109         {
14110           /* This was a pre-DWARF-5 GNU extension alias
14111              for DW_AT_call_parameter.  */
14112           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14113         }
14114       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14115         {
14116           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14117
14118           sect_offset sect_off
14119             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14120           if (!offset_in_cu_p (&cu->header, sect_off))
14121             {
14122               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14123                  binding can be done only inside one CU.  Such referenced DIE
14124                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14125               complaint (&symfile_complaints,
14126                          _("DW_AT_call_parameter offset is not in CU for "
14127                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14128                          to_underlying (child_die->sect_off),
14129                          objfile_name (objfile));
14130               continue;
14131             }
14132           parameter->u.param_cu_off
14133             = (cu_offset) (sect_off - cu->header.sect_off);
14134         }
14135       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14136         {
14137           complaint (&symfile_complaints,
14138                      _("No DW_FORM_block* DW_AT_location for "
14139                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14140                      to_underlying (child_die->sect_off), objfile_name (objfile));
14141           continue;
14142         }
14143       else
14144         {
14145           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14146             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14147           if (parameter->u.dwarf_reg != -1)
14148             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14149           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14150                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14151                                              &parameter->u.fb_offset))
14152             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14153           else
14154             {
14155               complaint (&symfile_complaints,
14156                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14157                            "for DW_FORM_block* DW_AT_location is supported for "
14158                            "DW_TAG_call_site child DIE 0x%x "
14159                            "[in module %s]"),
14160                          to_underlying (child_die->sect_off),
14161                          objfile_name (objfile));
14162               continue;
14163             }
14164         }
14165
14166       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14167       if (attr == NULL)
14168         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14169       if (!attr_form_is_block (attr))
14170         {
14171           complaint (&symfile_complaints,
14172                      _("No DW_FORM_block* DW_AT_call_value for "
14173                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14174                      to_underlying (child_die->sect_off),
14175                      objfile_name (objfile));
14176           continue;
14177         }
14178       parameter->value = DW_BLOCK (attr)->data;
14179       parameter->value_size = DW_BLOCK (attr)->size;
14180
14181       /* Parameters are not pre-cleared by memset above.  */
14182       parameter->data_value = NULL;
14183       parameter->data_value_size = 0;
14184       call_site->parameter_count++;
14185
14186       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14187       if (attr == NULL)
14188         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14189       if (attr)
14190         {
14191           if (!attr_form_is_block (attr))
14192             complaint (&symfile_complaints,
14193                        _("No DW_FORM_block* DW_AT_call_data_value for "
14194                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14195                        to_underlying (child_die->sect_off),
14196                        objfile_name (objfile));
14197           else
14198             {
14199               parameter->data_value = DW_BLOCK (attr)->data;
14200               parameter->data_value_size = DW_BLOCK (attr)->size;
14201             }
14202         }
14203     }
14204 }
14205
14206 /* Helper function for read_variable.  If DIE represents a virtual
14207    table, then return the type of the concrete object that is
14208    associated with the virtual table.  Otherwise, return NULL.  */
14209
14210 static struct type *
14211 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14212 {
14213   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14214   if (attr == NULL)
14215     return NULL;
14216
14217   /* Find the type DIE.  */
14218   struct die_info *type_die = NULL;
14219   struct dwarf2_cu *type_cu = cu;
14220
14221   if (attr_form_is_ref (attr))
14222     type_die = follow_die_ref (die, attr, &type_cu);
14223   if (type_die == NULL)
14224     return NULL;
14225
14226   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14227     return NULL;
14228   return die_containing_type (type_die, type_cu);
14229 }
14230
14231 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14232
14233 static void
14234 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14235 {
14236   struct rust_vtable_symbol *storage = NULL;
14237
14238   if (cu->language == language_rust)
14239     {
14240       struct type *containing_type = rust_containing_type (die, cu);
14241
14242       if (containing_type != NULL)
14243         {
14244           struct objfile *objfile = cu->objfile;
14245
14246           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14247                                     struct rust_vtable_symbol);
14248           initialize_objfile_symbol (storage);
14249           storage->concrete_type = containing_type;
14250           storage->subclass = SYMBOL_RUST_VTABLE;
14251         }
14252     }
14253
14254   new_symbol_full (die, NULL, cu, storage);
14255 }
14256
14257 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14258    reading .debug_rnglists.
14259    Callback's type should be:
14260     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14261    Return true if the attributes are present and valid, otherwise,
14262    return false.  */
14263
14264 template <typename Callback>
14265 static bool
14266 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14267                          Callback &&callback)
14268 {
14269   struct objfile *objfile = cu->objfile;
14270   bfd *obfd = objfile->obfd;
14271   /* Base address selection entry.  */
14272   CORE_ADDR base;
14273   int found_base;
14274   const gdb_byte *buffer;
14275   CORE_ADDR baseaddr;
14276   bool overflow = false;
14277
14278   found_base = cu->base_known;
14279   base = cu->base_address;
14280
14281   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14282   if (offset >= dwarf2_per_objfile->rnglists.size)
14283     {
14284       complaint (&symfile_complaints,
14285                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14286                  offset);
14287       return false;
14288     }
14289   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14290
14291   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14292
14293   while (1)
14294     {
14295       /* Initialize it due to a false compiler warning.  */
14296       CORE_ADDR range_beginning = 0, range_end = 0;
14297       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14298                                  + dwarf2_per_objfile->rnglists.size);
14299       unsigned int bytes_read;
14300
14301       if (buffer == buf_end)
14302         {
14303           overflow = true;
14304           break;
14305         }
14306       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14307       switch (rlet)
14308         {
14309         case DW_RLE_end_of_list:
14310           break;
14311         case DW_RLE_base_address:
14312           if (buffer + cu->header.addr_size > buf_end)
14313             {
14314               overflow = true;
14315               break;
14316             }
14317           base = read_address (obfd, buffer, cu, &bytes_read);
14318           found_base = 1;
14319           buffer += bytes_read;
14320           break;
14321         case DW_RLE_start_length:
14322           if (buffer + cu->header.addr_size > buf_end)
14323             {
14324               overflow = true;
14325               break;
14326             }
14327           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14328           buffer += bytes_read;
14329           range_end = (range_beginning
14330                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14331           buffer += bytes_read;
14332           if (buffer > buf_end)
14333             {
14334               overflow = true;
14335               break;
14336             }
14337           break;
14338         case DW_RLE_offset_pair:
14339           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14340           buffer += bytes_read;
14341           if (buffer > buf_end)
14342             {
14343               overflow = true;
14344               break;
14345             }
14346           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14347           buffer += bytes_read;
14348           if (buffer > buf_end)
14349             {
14350               overflow = true;
14351               break;
14352             }
14353           break;
14354         case DW_RLE_start_end:
14355           if (buffer + 2 * cu->header.addr_size > buf_end)
14356             {
14357               overflow = true;
14358               break;
14359             }
14360           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14361           buffer += bytes_read;
14362           range_end = read_address (obfd, buffer, cu, &bytes_read);
14363           buffer += bytes_read;
14364           break;
14365         default:
14366           complaint (&symfile_complaints,
14367                      _("Invalid .debug_rnglists data (no base address)"));
14368           return false;
14369         }
14370       if (rlet == DW_RLE_end_of_list || overflow)
14371         break;
14372       if (rlet == DW_RLE_base_address)
14373         continue;
14374
14375       if (!found_base)
14376         {
14377           /* We have no valid base address for the ranges
14378              data.  */
14379           complaint (&symfile_complaints,
14380                      _("Invalid .debug_rnglists data (no base address)"));
14381           return false;
14382         }
14383
14384       if (range_beginning > range_end)
14385         {
14386           /* Inverted range entries are invalid.  */
14387           complaint (&symfile_complaints,
14388                      _("Invalid .debug_rnglists data (inverted range)"));
14389           return false;
14390         }
14391
14392       /* Empty range entries have no effect.  */
14393       if (range_beginning == range_end)
14394         continue;
14395
14396       range_beginning += base;
14397       range_end += base;
14398
14399       /* A not-uncommon case of bad debug info.
14400          Don't pollute the addrmap with bad data.  */
14401       if (range_beginning + baseaddr == 0
14402           && !dwarf2_per_objfile->has_section_at_zero)
14403         {
14404           complaint (&symfile_complaints,
14405                      _(".debug_rnglists entry has start address of zero"
14406                        " [in module %s]"), objfile_name (objfile));
14407           continue;
14408         }
14409
14410       callback (range_beginning, range_end);
14411     }
14412
14413   if (overflow)
14414     {
14415       complaint (&symfile_complaints,
14416                  _("Offset %d is not terminated "
14417                    "for DW_AT_ranges attribute"),
14418                  offset);
14419       return false;
14420     }
14421
14422   return true;
14423 }
14424
14425 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14426    Callback's type should be:
14427     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14428    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14429
14430 template <typename Callback>
14431 static int
14432 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14433                        Callback &&callback)
14434 {
14435   struct objfile *objfile = cu->objfile;
14436   struct comp_unit_head *cu_header = &cu->header;
14437   bfd *obfd = objfile->obfd;
14438   unsigned int addr_size = cu_header->addr_size;
14439   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14440   /* Base address selection entry.  */
14441   CORE_ADDR base;
14442   int found_base;
14443   unsigned int dummy;
14444   const gdb_byte *buffer;
14445   CORE_ADDR baseaddr;
14446
14447   if (cu_header->version >= 5)
14448     return dwarf2_rnglists_process (offset, cu, callback);
14449
14450   found_base = cu->base_known;
14451   base = cu->base_address;
14452
14453   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14454   if (offset >= dwarf2_per_objfile->ranges.size)
14455     {
14456       complaint (&symfile_complaints,
14457                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14458                  offset);
14459       return 0;
14460     }
14461   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14462
14463   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14464
14465   while (1)
14466     {
14467       CORE_ADDR range_beginning, range_end;
14468
14469       range_beginning = read_address (obfd, buffer, cu, &dummy);
14470       buffer += addr_size;
14471       range_end = read_address (obfd, buffer, cu, &dummy);
14472       buffer += addr_size;
14473       offset += 2 * addr_size;
14474
14475       /* An end of list marker is a pair of zero addresses.  */
14476       if (range_beginning == 0 && range_end == 0)
14477         /* Found the end of list entry.  */
14478         break;
14479
14480       /* Each base address selection entry is a pair of 2 values.
14481          The first is the largest possible address, the second is
14482          the base address.  Check for a base address here.  */
14483       if ((range_beginning & mask) == mask)
14484         {
14485           /* If we found the largest possible address, then we already
14486              have the base address in range_end.  */
14487           base = range_end;
14488           found_base = 1;
14489           continue;
14490         }
14491
14492       if (!found_base)
14493         {
14494           /* We have no valid base address for the ranges
14495              data.  */
14496           complaint (&symfile_complaints,
14497                      _("Invalid .debug_ranges data (no base address)"));
14498           return 0;
14499         }
14500
14501       if (range_beginning > range_end)
14502         {
14503           /* Inverted range entries are invalid.  */
14504           complaint (&symfile_complaints,
14505                      _("Invalid .debug_ranges data (inverted range)"));
14506           return 0;
14507         }
14508
14509       /* Empty range entries have no effect.  */
14510       if (range_beginning == range_end)
14511         continue;
14512
14513       range_beginning += base;
14514       range_end += base;
14515
14516       /* A not-uncommon case of bad debug info.
14517          Don't pollute the addrmap with bad data.  */
14518       if (range_beginning + baseaddr == 0
14519           && !dwarf2_per_objfile->has_section_at_zero)
14520         {
14521           complaint (&symfile_complaints,
14522                      _(".debug_ranges entry has start address of zero"
14523                        " [in module %s]"), objfile_name (objfile));
14524           continue;
14525         }
14526
14527       callback (range_beginning, range_end);
14528     }
14529
14530   return 1;
14531 }
14532
14533 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14534    Return 1 if the attributes are present and valid, otherwise, return 0.
14535    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14536
14537 static int
14538 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14539                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14540                     struct partial_symtab *ranges_pst)
14541 {
14542   struct objfile *objfile = cu->objfile;
14543   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14544   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14545                                        SECT_OFF_TEXT (objfile));
14546   int low_set = 0;
14547   CORE_ADDR low = 0;
14548   CORE_ADDR high = 0;
14549   int retval;
14550
14551   retval = dwarf2_ranges_process (offset, cu,
14552     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14553     {
14554       if (ranges_pst != NULL)
14555         {
14556           CORE_ADDR lowpc;
14557           CORE_ADDR highpc;
14558
14559           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14560                                               range_beginning + baseaddr);
14561           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14562                                                range_end + baseaddr);
14563           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14564                              ranges_pst);
14565         }
14566
14567       /* FIXME: This is recording everything as a low-high
14568          segment of consecutive addresses.  We should have a
14569          data structure for discontiguous block ranges
14570          instead.  */
14571       if (! low_set)
14572         {
14573           low = range_beginning;
14574           high = range_end;
14575           low_set = 1;
14576         }
14577       else
14578         {
14579           if (range_beginning < low)
14580             low = range_beginning;
14581           if (range_end > high)
14582             high = range_end;
14583         }
14584     });
14585   if (!retval)
14586     return 0;
14587
14588   if (! low_set)
14589     /* If the first entry is an end-of-list marker, the range
14590        describes an empty scope, i.e. no instructions.  */
14591     return 0;
14592
14593   if (low_return)
14594     *low_return = low;
14595   if (high_return)
14596     *high_return = high;
14597   return 1;
14598 }
14599
14600 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14601    definition for the return value.  *LOWPC and *HIGHPC are set iff
14602    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14603
14604 static enum pc_bounds_kind
14605 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14606                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14607                       struct partial_symtab *pst)
14608 {
14609   struct attribute *attr;
14610   struct attribute *attr_high;
14611   CORE_ADDR low = 0;
14612   CORE_ADDR high = 0;
14613   enum pc_bounds_kind ret;
14614
14615   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14616   if (attr_high)
14617     {
14618       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14619       if (attr)
14620         {
14621           low = attr_value_as_address (attr);
14622           high = attr_value_as_address (attr_high);
14623           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14624             high += low;
14625         }
14626       else
14627         /* Found high w/o low attribute.  */
14628         return PC_BOUNDS_INVALID;
14629
14630       /* Found consecutive range of addresses.  */
14631       ret = PC_BOUNDS_HIGH_LOW;
14632     }
14633   else
14634     {
14635       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14636       if (attr != NULL)
14637         {
14638           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14639              We take advantage of the fact that DW_AT_ranges does not appear
14640              in DW_TAG_compile_unit of DWO files.  */
14641           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14642           unsigned int ranges_offset = (DW_UNSND (attr)
14643                                         + (need_ranges_base
14644                                            ? cu->ranges_base
14645                                            : 0));
14646
14647           /* Value of the DW_AT_ranges attribute is the offset in the
14648              .debug_ranges section.  */
14649           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14650             return PC_BOUNDS_INVALID;
14651           /* Found discontinuous range of addresses.  */
14652           ret = PC_BOUNDS_RANGES;
14653         }
14654       else
14655         return PC_BOUNDS_NOT_PRESENT;
14656     }
14657
14658   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14659   if (high <= low)
14660     return PC_BOUNDS_INVALID;
14661
14662   /* When using the GNU linker, .gnu.linkonce. sections are used to
14663      eliminate duplicate copies of functions and vtables and such.
14664      The linker will arbitrarily choose one and discard the others.
14665      The AT_*_pc values for such functions refer to local labels in
14666      these sections.  If the section from that file was discarded, the
14667      labels are not in the output, so the relocs get a value of 0.
14668      If this is a discarded function, mark the pc bounds as invalid,
14669      so that GDB will ignore it.  */
14670   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14671     return PC_BOUNDS_INVALID;
14672
14673   *lowpc = low;
14674   if (highpc)
14675     *highpc = high;
14676   return ret;
14677 }
14678
14679 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14680    its low and high PC addresses.  Do nothing if these addresses could not
14681    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14682    and HIGHPC to the high address if greater than HIGHPC.  */
14683
14684 static void
14685 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14686                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14687                                  struct dwarf2_cu *cu)
14688 {
14689   CORE_ADDR low, high;
14690   struct die_info *child = die->child;
14691
14692   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14693     {
14694       *lowpc = std::min (*lowpc, low);
14695       *highpc = std::max (*highpc, high);
14696     }
14697
14698   /* If the language does not allow nested subprograms (either inside
14699      subprograms or lexical blocks), we're done.  */
14700   if (cu->language != language_ada)
14701     return;
14702
14703   /* Check all the children of the given DIE.  If it contains nested
14704      subprograms, then check their pc bounds.  Likewise, we need to
14705      check lexical blocks as well, as they may also contain subprogram
14706      definitions.  */
14707   while (child && child->tag)
14708     {
14709       if (child->tag == DW_TAG_subprogram
14710           || child->tag == DW_TAG_lexical_block)
14711         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14712       child = sibling_die (child);
14713     }
14714 }
14715
14716 /* Get the low and high pc's represented by the scope DIE, and store
14717    them in *LOWPC and *HIGHPC.  If the correct values can't be
14718    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14719
14720 static void
14721 get_scope_pc_bounds (struct die_info *die,
14722                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14723                      struct dwarf2_cu *cu)
14724 {
14725   CORE_ADDR best_low = (CORE_ADDR) -1;
14726   CORE_ADDR best_high = (CORE_ADDR) 0;
14727   CORE_ADDR current_low, current_high;
14728
14729   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14730       >= PC_BOUNDS_RANGES)
14731     {
14732       best_low = current_low;
14733       best_high = current_high;
14734     }
14735   else
14736     {
14737       struct die_info *child = die->child;
14738
14739       while (child && child->tag)
14740         {
14741           switch (child->tag) {
14742           case DW_TAG_subprogram:
14743             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14744             break;
14745           case DW_TAG_namespace:
14746           case DW_TAG_module:
14747             /* FIXME: carlton/2004-01-16: Should we do this for
14748                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14749                that current GCC's always emit the DIEs corresponding
14750                to definitions of methods of classes as children of a
14751                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14752                the DIEs giving the declarations, which could be
14753                anywhere).  But I don't see any reason why the
14754                standards says that they have to be there.  */
14755             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14756
14757             if (current_low != ((CORE_ADDR) -1))
14758               {
14759                 best_low = std::min (best_low, current_low);
14760                 best_high = std::max (best_high, current_high);
14761               }
14762             break;
14763           default:
14764             /* Ignore.  */
14765             break;
14766           }
14767
14768           child = sibling_die (child);
14769         }
14770     }
14771
14772   *lowpc = best_low;
14773   *highpc = best_high;
14774 }
14775
14776 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14777    in DIE.  */
14778
14779 static void
14780 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14781                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14782 {
14783   struct objfile *objfile = cu->objfile;
14784   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14785   struct attribute *attr;
14786   struct attribute *attr_high;
14787
14788   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14789   if (attr_high)
14790     {
14791       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14792       if (attr)
14793         {
14794           CORE_ADDR low = attr_value_as_address (attr);
14795           CORE_ADDR high = attr_value_as_address (attr_high);
14796
14797           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14798             high += low;
14799
14800           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14801           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14802           record_block_range (block, low, high - 1);
14803         }
14804     }
14805
14806   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14807   if (attr)
14808     {
14809       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14810          We take advantage of the fact that DW_AT_ranges does not appear
14811          in DW_TAG_compile_unit of DWO files.  */
14812       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14813
14814       /* The value of the DW_AT_ranges attribute is the offset of the
14815          address range list in the .debug_ranges section.  */
14816       unsigned long offset = (DW_UNSND (attr)
14817                               + (need_ranges_base ? cu->ranges_base : 0));
14818       const gdb_byte *buffer;
14819
14820       /* For some target architectures, but not others, the
14821          read_address function sign-extends the addresses it returns.
14822          To recognize base address selection entries, we need a
14823          mask.  */
14824       unsigned int addr_size = cu->header.addr_size;
14825       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14826
14827       /* The base address, to which the next pair is relative.  Note
14828          that this 'base' is a DWARF concept: most entries in a range
14829          list are relative, to reduce the number of relocs against the
14830          debugging information.  This is separate from this function's
14831          'baseaddr' argument, which GDB uses to relocate debugging
14832          information from a shared library based on the address at
14833          which the library was loaded.  */
14834       CORE_ADDR base = cu->base_address;
14835       int base_known = cu->base_known;
14836
14837       dwarf2_ranges_process (offset, cu,
14838         [&] (CORE_ADDR start, CORE_ADDR end)
14839         {
14840           start += baseaddr;
14841           end += baseaddr;
14842           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14843           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14844           record_block_range (block, start, end - 1);
14845         });
14846     }
14847 }
14848
14849 /* Check whether the producer field indicates either of GCC < 4.6, or the
14850    Intel C/C++ compiler, and cache the result in CU.  */
14851
14852 static void
14853 check_producer (struct dwarf2_cu *cu)
14854 {
14855   int major, minor;
14856
14857   if (cu->producer == NULL)
14858     {
14859       /* For unknown compilers expect their behavior is DWARF version
14860          compliant.
14861
14862          GCC started to support .debug_types sections by -gdwarf-4 since
14863          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14864          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14865          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14866          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14867     }
14868   else if (producer_is_gcc (cu->producer, &major, &minor))
14869     {
14870       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14871       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14872     }
14873   else if (producer_is_icc (cu->producer, &major, &minor))
14874     cu->producer_is_icc_lt_14 = major < 14;
14875   else
14876     {
14877       /* For other non-GCC compilers, expect their behavior is DWARF version
14878          compliant.  */
14879     }
14880
14881   cu->checked_producer = 1;
14882 }
14883
14884 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14885    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14886    during 4.6.0 experimental.  */
14887
14888 static int
14889 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14890 {
14891   if (!cu->checked_producer)
14892     check_producer (cu);
14893
14894   return cu->producer_is_gxx_lt_4_6;
14895 }
14896
14897 /* Return the default accessibility type if it is not overriden by
14898    DW_AT_accessibility.  */
14899
14900 static enum dwarf_access_attribute
14901 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14902 {
14903   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14904     {
14905       /* The default DWARF 2 accessibility for members is public, the default
14906          accessibility for inheritance is private.  */
14907
14908       if (die->tag != DW_TAG_inheritance)
14909         return DW_ACCESS_public;
14910       else
14911         return DW_ACCESS_private;
14912     }
14913   else
14914     {
14915       /* DWARF 3+ defines the default accessibility a different way.  The same
14916          rules apply now for DW_TAG_inheritance as for the members and it only
14917          depends on the container kind.  */
14918
14919       if (die->parent->tag == DW_TAG_class_type)
14920         return DW_ACCESS_private;
14921       else
14922         return DW_ACCESS_public;
14923     }
14924 }
14925
14926 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14927    offset.  If the attribute was not found return 0, otherwise return
14928    1.  If it was found but could not properly be handled, set *OFFSET
14929    to 0.  */
14930
14931 static int
14932 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14933                              LONGEST *offset)
14934 {
14935   struct attribute *attr;
14936
14937   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14938   if (attr != NULL)
14939     {
14940       *offset = 0;
14941
14942       /* Note that we do not check for a section offset first here.
14943          This is because DW_AT_data_member_location is new in DWARF 4,
14944          so if we see it, we can assume that a constant form is really
14945          a constant and not a section offset.  */
14946       if (attr_form_is_constant (attr))
14947         *offset = dwarf2_get_attr_constant_value (attr, 0);
14948       else if (attr_form_is_section_offset (attr))
14949         dwarf2_complex_location_expr_complaint ();
14950       else if (attr_form_is_block (attr))
14951         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14952       else
14953         dwarf2_complex_location_expr_complaint ();
14954
14955       return 1;
14956     }
14957
14958   return 0;
14959 }
14960
14961 /* Add an aggregate field to the field list.  */
14962
14963 static void
14964 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14965                   struct dwarf2_cu *cu)
14966 {
14967   struct objfile *objfile = cu->objfile;
14968   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14969   struct nextfield *new_field;
14970   struct attribute *attr;
14971   struct field *fp;
14972   const char *fieldname = "";
14973
14974   /* Allocate a new field list entry and link it in.  */
14975   new_field = XNEW (struct nextfield);
14976   make_cleanup (xfree, new_field);
14977   memset (new_field, 0, sizeof (struct nextfield));
14978
14979   if (die->tag == DW_TAG_inheritance)
14980     {
14981       new_field->next = fip->baseclasses;
14982       fip->baseclasses = new_field;
14983     }
14984   else
14985     {
14986       new_field->next = fip->fields;
14987       fip->fields = new_field;
14988     }
14989   fip->nfields++;
14990
14991   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14992   if (attr)
14993     new_field->accessibility = DW_UNSND (attr);
14994   else
14995     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14996   if (new_field->accessibility != DW_ACCESS_public)
14997     fip->non_public_fields = 1;
14998
14999   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15000   if (attr)
15001     new_field->virtuality = DW_UNSND (attr);
15002   else
15003     new_field->virtuality = DW_VIRTUALITY_none;
15004
15005   fp = &new_field->field;
15006
15007   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15008     {
15009       LONGEST offset;
15010
15011       /* Data member other than a C++ static data member.  */
15012
15013       /* Get type of field.  */
15014       fp->type = die_type (die, cu);
15015
15016       SET_FIELD_BITPOS (*fp, 0);
15017
15018       /* Get bit size of field (zero if none).  */
15019       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15020       if (attr)
15021         {
15022           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15023         }
15024       else
15025         {
15026           FIELD_BITSIZE (*fp) = 0;
15027         }
15028
15029       /* Get bit offset of field.  */
15030       if (handle_data_member_location (die, cu, &offset))
15031         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15032       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15033       if (attr)
15034         {
15035           if (gdbarch_bits_big_endian (gdbarch))
15036             {
15037               /* For big endian bits, the DW_AT_bit_offset gives the
15038                  additional bit offset from the MSB of the containing
15039                  anonymous object to the MSB of the field.  We don't
15040                  have to do anything special since we don't need to
15041                  know the size of the anonymous object.  */
15042               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15043             }
15044           else
15045             {
15046               /* For little endian bits, compute the bit offset to the
15047                  MSB of the anonymous object, subtract off the number of
15048                  bits from the MSB of the field to the MSB of the
15049                  object, and then subtract off the number of bits of
15050                  the field itself.  The result is the bit offset of
15051                  the LSB of the field.  */
15052               int anonymous_size;
15053               int bit_offset = DW_UNSND (attr);
15054
15055               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15056               if (attr)
15057                 {
15058                   /* The size of the anonymous object containing
15059                      the bit field is explicit, so use the
15060                      indicated size (in bytes).  */
15061                   anonymous_size = DW_UNSND (attr);
15062                 }
15063               else
15064                 {
15065                   /* The size of the anonymous object containing
15066                      the bit field must be inferred from the type
15067                      attribute of the data member containing the
15068                      bit field.  */
15069                   anonymous_size = TYPE_LENGTH (fp->type);
15070                 }
15071               SET_FIELD_BITPOS (*fp,
15072                                 (FIELD_BITPOS (*fp)
15073                                  + anonymous_size * bits_per_byte
15074                                  - bit_offset - FIELD_BITSIZE (*fp)));
15075             }
15076         }
15077       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15078       if (attr != NULL)
15079         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15080                                 + dwarf2_get_attr_constant_value (attr, 0)));
15081
15082       /* Get name of field.  */
15083       fieldname = dwarf2_name (die, cu);
15084       if (fieldname == NULL)
15085         fieldname = "";
15086
15087       /* The name is already allocated along with this objfile, so we don't
15088          need to duplicate it for the type.  */
15089       fp->name = fieldname;
15090
15091       /* Change accessibility for artificial fields (e.g. virtual table
15092          pointer or virtual base class pointer) to private.  */
15093       if (dwarf2_attr (die, DW_AT_artificial, cu))
15094         {
15095           FIELD_ARTIFICIAL (*fp) = 1;
15096           new_field->accessibility = DW_ACCESS_private;
15097           fip->non_public_fields = 1;
15098         }
15099     }
15100   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15101     {
15102       /* C++ static member.  */
15103
15104       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15105          is a declaration, but all versions of G++ as of this writing
15106          (so through at least 3.2.1) incorrectly generate
15107          DW_TAG_variable tags.  */
15108
15109       const char *physname;
15110
15111       /* Get name of field.  */
15112       fieldname = dwarf2_name (die, cu);
15113       if (fieldname == NULL)
15114         return;
15115
15116       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15117       if (attr
15118           /* Only create a symbol if this is an external value.
15119              new_symbol checks this and puts the value in the global symbol
15120              table, which we want.  If it is not external, new_symbol
15121              will try to put the value in cu->list_in_scope which is wrong.  */
15122           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15123         {
15124           /* A static const member, not much different than an enum as far as
15125              we're concerned, except that we can support more types.  */
15126           new_symbol (die, NULL, cu);
15127         }
15128
15129       /* Get physical name.  */
15130       physname = dwarf2_physname (fieldname, die, cu);
15131
15132       /* The name is already allocated along with this objfile, so we don't
15133          need to duplicate it for the type.  */
15134       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15135       FIELD_TYPE (*fp) = die_type (die, cu);
15136       FIELD_NAME (*fp) = fieldname;
15137     }
15138   else if (die->tag == DW_TAG_inheritance)
15139     {
15140       LONGEST offset;
15141
15142       /* C++ base class field.  */
15143       if (handle_data_member_location (die, cu, &offset))
15144         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15145       FIELD_BITSIZE (*fp) = 0;
15146       FIELD_TYPE (*fp) = die_type (die, cu);
15147       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15148       fip->nbaseclasses++;
15149     }
15150 }
15151
15152 /* Can the type given by DIE define another type?  */
15153
15154 static bool
15155 type_can_define_types (const struct die_info *die)
15156 {
15157   switch (die->tag)
15158     {
15159     case DW_TAG_typedef:
15160     case DW_TAG_class_type:
15161     case DW_TAG_structure_type:
15162     case DW_TAG_union_type:
15163     case DW_TAG_enumeration_type:
15164       return true;
15165
15166     default:
15167       return false;
15168     }
15169 }
15170
15171 /* Add a type definition defined in the scope of the FIP's class.  */
15172
15173 static void
15174 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15175                       struct dwarf2_cu *cu)
15176 {
15177   struct decl_field_list *new_field;
15178   struct decl_field *fp;
15179
15180   /* Allocate a new field list entry and link it in.  */
15181   new_field = XCNEW (struct decl_field_list);
15182   make_cleanup (xfree, new_field);
15183
15184   gdb_assert (type_can_define_types (die));
15185
15186   fp = &new_field->field;
15187
15188   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15189   fp->name = dwarf2_name (die, cu);
15190   fp->type = read_type_die (die, cu);
15191
15192   /* Save accessibility.  */
15193   enum dwarf_access_attribute accessibility;
15194   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15195   if (attr != NULL)
15196     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15197   else
15198     accessibility = dwarf2_default_access_attribute (die, cu);
15199   switch (accessibility)
15200     {
15201     case DW_ACCESS_public:
15202       /* The assumed value if neither private nor protected.  */
15203       break;
15204     case DW_ACCESS_private:
15205       fp->is_private = 1;
15206       break;
15207     case DW_ACCESS_protected:
15208       fp->is_protected = 1;
15209       break;
15210     default:
15211       complaint (&symfile_complaints,
15212                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15213     }
15214
15215   if (die->tag == DW_TAG_typedef)
15216     {
15217       new_field->next = fip->typedef_field_list;
15218       fip->typedef_field_list = new_field;
15219       fip->typedef_field_list_count++;
15220     }
15221   else
15222     {
15223       new_field->next = fip->nested_types_list;
15224       fip->nested_types_list = new_field;
15225       fip->nested_types_list_count++;
15226     }
15227 }
15228
15229 /* Create the vector of fields, and attach it to the type.  */
15230
15231 static void
15232 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15233                               struct dwarf2_cu *cu)
15234 {
15235   int nfields = fip->nfields;
15236
15237   /* Record the field count, allocate space for the array of fields,
15238      and create blank accessibility bitfields if necessary.  */
15239   TYPE_NFIELDS (type) = nfields;
15240   TYPE_FIELDS (type) = (struct field *)
15241     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15242   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15243
15244   if (fip->non_public_fields && cu->language != language_ada)
15245     {
15246       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15247
15248       TYPE_FIELD_PRIVATE_BITS (type) =
15249         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15250       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15251
15252       TYPE_FIELD_PROTECTED_BITS (type) =
15253         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15254       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15255
15256       TYPE_FIELD_IGNORE_BITS (type) =
15257         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15258       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15259     }
15260
15261   /* If the type has baseclasses, allocate and clear a bit vector for
15262      TYPE_FIELD_VIRTUAL_BITS.  */
15263   if (fip->nbaseclasses && cu->language != language_ada)
15264     {
15265       int num_bytes = B_BYTES (fip->nbaseclasses);
15266       unsigned char *pointer;
15267
15268       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15269       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15270       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15271       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15272       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15273     }
15274
15275   /* Copy the saved-up fields into the field vector.  Start from the head of
15276      the list, adding to the tail of the field array, so that they end up in
15277      the same order in the array in which they were added to the list.  */
15278   while (nfields-- > 0)
15279     {
15280       struct nextfield *fieldp;
15281
15282       if (fip->fields)
15283         {
15284           fieldp = fip->fields;
15285           fip->fields = fieldp->next;
15286         }
15287       else
15288         {
15289           fieldp = fip->baseclasses;
15290           fip->baseclasses = fieldp->next;
15291         }
15292
15293       TYPE_FIELD (type, nfields) = fieldp->field;
15294       switch (fieldp->accessibility)
15295         {
15296         case DW_ACCESS_private:
15297           if (cu->language != language_ada)
15298             SET_TYPE_FIELD_PRIVATE (type, nfields);
15299           break;
15300
15301         case DW_ACCESS_protected:
15302           if (cu->language != language_ada)
15303             SET_TYPE_FIELD_PROTECTED (type, nfields);
15304           break;
15305
15306         case DW_ACCESS_public:
15307           break;
15308
15309         default:
15310           /* Unknown accessibility.  Complain and treat it as public.  */
15311           {
15312             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15313                        fieldp->accessibility);
15314           }
15315           break;
15316         }
15317       if (nfields < fip->nbaseclasses)
15318         {
15319           switch (fieldp->virtuality)
15320             {
15321             case DW_VIRTUALITY_virtual:
15322             case DW_VIRTUALITY_pure_virtual:
15323               if (cu->language == language_ada)
15324                 error (_("unexpected virtuality in component of Ada type"));
15325               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15326               break;
15327             }
15328         }
15329     }
15330 }
15331
15332 /* Return true if this member function is a constructor, false
15333    otherwise.  */
15334
15335 static int
15336 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15337 {
15338   const char *fieldname;
15339   const char *type_name;
15340   int len;
15341
15342   if (die->parent == NULL)
15343     return 0;
15344
15345   if (die->parent->tag != DW_TAG_structure_type
15346       && die->parent->tag != DW_TAG_union_type
15347       && die->parent->tag != DW_TAG_class_type)
15348     return 0;
15349
15350   fieldname = dwarf2_name (die, cu);
15351   type_name = dwarf2_name (die->parent, cu);
15352   if (fieldname == NULL || type_name == NULL)
15353     return 0;
15354
15355   len = strlen (fieldname);
15356   return (strncmp (fieldname, type_name, len) == 0
15357           && (type_name[len] == '\0' || type_name[len] == '<'));
15358 }
15359
15360 /* Add a member function to the proper fieldlist.  */
15361
15362 static void
15363 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15364                       struct type *type, struct dwarf2_cu *cu)
15365 {
15366   struct objfile *objfile = cu->objfile;
15367   struct attribute *attr;
15368   struct fnfieldlist *flp;
15369   int i;
15370   struct fn_field *fnp;
15371   const char *fieldname;
15372   struct nextfnfield *new_fnfield;
15373   struct type *this_type;
15374   enum dwarf_access_attribute accessibility;
15375
15376   if (cu->language == language_ada)
15377     error (_("unexpected member function in Ada type"));
15378
15379   /* Get name of member function.  */
15380   fieldname = dwarf2_name (die, cu);
15381   if (fieldname == NULL)
15382     return;
15383
15384   /* Look up member function name in fieldlist.  */
15385   for (i = 0; i < fip->nfnfields; i++)
15386     {
15387       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15388         break;
15389     }
15390
15391   /* Create new list element if necessary.  */
15392   if (i < fip->nfnfields)
15393     flp = &fip->fnfieldlists[i];
15394   else
15395     {
15396       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15397         {
15398           fip->fnfieldlists = (struct fnfieldlist *)
15399             xrealloc (fip->fnfieldlists,
15400                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15401                       * sizeof (struct fnfieldlist));
15402           if (fip->nfnfields == 0)
15403             make_cleanup (free_current_contents, &fip->fnfieldlists);
15404         }
15405       flp = &fip->fnfieldlists[fip->nfnfields];
15406       flp->name = fieldname;
15407       flp->length = 0;
15408       flp->head = NULL;
15409       i = fip->nfnfields++;
15410     }
15411
15412   /* Create a new member function field and chain it to the field list
15413      entry.  */
15414   new_fnfield = XNEW (struct nextfnfield);
15415   make_cleanup (xfree, new_fnfield);
15416   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15417   new_fnfield->next = flp->head;
15418   flp->head = new_fnfield;
15419   flp->length++;
15420
15421   /* Fill in the member function field info.  */
15422   fnp = &new_fnfield->fnfield;
15423
15424   /* Delay processing of the physname until later.  */
15425   if (cu->language == language_cplus)
15426     {
15427       add_to_method_list (type, i, flp->length - 1, fieldname,
15428                           die, cu);
15429     }
15430   else
15431     {
15432       const char *physname = dwarf2_physname (fieldname, die, cu);
15433       fnp->physname = physname ? physname : "";
15434     }
15435
15436   fnp->type = alloc_type (objfile);
15437   this_type = read_type_die (die, cu);
15438   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15439     {
15440       int nparams = TYPE_NFIELDS (this_type);
15441
15442       /* TYPE is the domain of this method, and THIS_TYPE is the type
15443            of the method itself (TYPE_CODE_METHOD).  */
15444       smash_to_method_type (fnp->type, type,
15445                             TYPE_TARGET_TYPE (this_type),
15446                             TYPE_FIELDS (this_type),
15447                             TYPE_NFIELDS (this_type),
15448                             TYPE_VARARGS (this_type));
15449
15450       /* Handle static member functions.
15451          Dwarf2 has no clean way to discern C++ static and non-static
15452          member functions.  G++ helps GDB by marking the first
15453          parameter for non-static member functions (which is the this
15454          pointer) as artificial.  We obtain this information from
15455          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15456       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15457         fnp->voffset = VOFFSET_STATIC;
15458     }
15459   else
15460     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15461                dwarf2_full_name (fieldname, die, cu));
15462
15463   /* Get fcontext from DW_AT_containing_type if present.  */
15464   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15465     fnp->fcontext = die_containing_type (die, cu);
15466
15467   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15468      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15469
15470   /* Get accessibility.  */
15471   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15472   if (attr)
15473     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15474   else
15475     accessibility = dwarf2_default_access_attribute (die, cu);
15476   switch (accessibility)
15477     {
15478     case DW_ACCESS_private:
15479       fnp->is_private = 1;
15480       break;
15481     case DW_ACCESS_protected:
15482       fnp->is_protected = 1;
15483       break;
15484     }
15485
15486   /* Check for artificial methods.  */
15487   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15488   if (attr && DW_UNSND (attr) != 0)
15489     fnp->is_artificial = 1;
15490
15491   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15492
15493   /* Get index in virtual function table if it is a virtual member
15494      function.  For older versions of GCC, this is an offset in the
15495      appropriate virtual table, as specified by DW_AT_containing_type.
15496      For everyone else, it is an expression to be evaluated relative
15497      to the object address.  */
15498
15499   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15500   if (attr)
15501     {
15502       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15503         {
15504           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15505             {
15506               /* Old-style GCC.  */
15507               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15508             }
15509           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15510                    || (DW_BLOCK (attr)->size > 1
15511                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15512                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15513             {
15514               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15515               if ((fnp->voffset % cu->header.addr_size) != 0)
15516                 dwarf2_complex_location_expr_complaint ();
15517               else
15518                 fnp->voffset /= cu->header.addr_size;
15519               fnp->voffset += 2;
15520             }
15521           else
15522             dwarf2_complex_location_expr_complaint ();
15523
15524           if (!fnp->fcontext)
15525             {
15526               /* If there is no `this' field and no DW_AT_containing_type,
15527                  we cannot actually find a base class context for the
15528                  vtable!  */
15529               if (TYPE_NFIELDS (this_type) == 0
15530                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15531                 {
15532                   complaint (&symfile_complaints,
15533                              _("cannot determine context for virtual member "
15534                                "function \"%s\" (offset %d)"),
15535                              fieldname, to_underlying (die->sect_off));
15536                 }
15537               else
15538                 {
15539                   fnp->fcontext
15540                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15541                 }
15542             }
15543         }
15544       else if (attr_form_is_section_offset (attr))
15545         {
15546           dwarf2_complex_location_expr_complaint ();
15547         }
15548       else
15549         {
15550           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15551                                                  fieldname);
15552         }
15553     }
15554   else
15555     {
15556       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15557       if (attr && DW_UNSND (attr))
15558         {
15559           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15560           complaint (&symfile_complaints,
15561                      _("Member function \"%s\" (offset %d) is virtual "
15562                        "but the vtable offset is not specified"),
15563                      fieldname, to_underlying (die->sect_off));
15564           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15565           TYPE_CPLUS_DYNAMIC (type) = 1;
15566         }
15567     }
15568 }
15569
15570 /* Create the vector of member function fields, and attach it to the type.  */
15571
15572 static void
15573 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15574                                  struct dwarf2_cu *cu)
15575 {
15576   struct fnfieldlist *flp;
15577   int i;
15578
15579   if (cu->language == language_ada)
15580     error (_("unexpected member functions in Ada type"));
15581
15582   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15583   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15584     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15585
15586   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15587     {
15588       struct nextfnfield *nfp = flp->head;
15589       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15590       int k;
15591
15592       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15593       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15594       fn_flp->fn_fields = (struct fn_field *)
15595         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15596       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15597         fn_flp->fn_fields[k] = nfp->fnfield;
15598     }
15599
15600   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15601 }
15602
15603 /* Returns non-zero if NAME is the name of a vtable member in CU's
15604    language, zero otherwise.  */
15605 static int
15606 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15607 {
15608   static const char vptr[] = "_vptr";
15609
15610   /* Look for the C++ form of the vtable.  */
15611   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15612     return 1;
15613
15614   return 0;
15615 }
15616
15617 /* GCC outputs unnamed structures that are really pointers to member
15618    functions, with the ABI-specified layout.  If TYPE describes
15619    such a structure, smash it into a member function type.
15620
15621    GCC shouldn't do this; it should just output pointer to member DIEs.
15622    This is GCC PR debug/28767.  */
15623
15624 static void
15625 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15626 {
15627   struct type *pfn_type, *self_type, *new_type;
15628
15629   /* Check for a structure with no name and two children.  */
15630   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15631     return;
15632
15633   /* Check for __pfn and __delta members.  */
15634   if (TYPE_FIELD_NAME (type, 0) == NULL
15635       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15636       || TYPE_FIELD_NAME (type, 1) == NULL
15637       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15638     return;
15639
15640   /* Find the type of the method.  */
15641   pfn_type = TYPE_FIELD_TYPE (type, 0);
15642   if (pfn_type == NULL
15643       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15644       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15645     return;
15646
15647   /* Look for the "this" argument.  */
15648   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15649   if (TYPE_NFIELDS (pfn_type) == 0
15650       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15651       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15652     return;
15653
15654   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15655   new_type = alloc_type (objfile);
15656   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15657                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15658                         TYPE_VARARGS (pfn_type));
15659   smash_to_methodptr_type (type, new_type);
15660 }
15661
15662
15663 /* Called when we find the DIE that starts a structure or union scope
15664    (definition) to create a type for the structure or union.  Fill in
15665    the type's name and general properties; the members will not be
15666    processed until process_structure_scope.  A symbol table entry for
15667    the type will also not be done until process_structure_scope (assuming
15668    the type has a name).
15669
15670    NOTE: we need to call these functions regardless of whether or not the
15671    DIE has a DW_AT_name attribute, since it might be an anonymous
15672    structure or union.  This gets the type entered into our set of
15673    user defined types.  */
15674
15675 static struct type *
15676 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15677 {
15678   struct objfile *objfile = cu->objfile;
15679   struct type *type;
15680   struct attribute *attr;
15681   const char *name;
15682
15683   /* If the definition of this type lives in .debug_types, read that type.
15684      Don't follow DW_AT_specification though, that will take us back up
15685      the chain and we want to go down.  */
15686   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15687   if (attr)
15688     {
15689       type = get_DW_AT_signature_type (die, attr, cu);
15690
15691       /* The type's CU may not be the same as CU.
15692          Ensure TYPE is recorded with CU in die_type_hash.  */
15693       return set_die_type (die, type, cu);
15694     }
15695
15696   type = alloc_type (objfile);
15697   INIT_CPLUS_SPECIFIC (type);
15698
15699   name = dwarf2_name (die, cu);
15700   if (name != NULL)
15701     {
15702       if (cu->language == language_cplus
15703           || cu->language == language_d
15704           || cu->language == language_rust)
15705         {
15706           const char *full_name = dwarf2_full_name (name, die, cu);
15707
15708           /* dwarf2_full_name might have already finished building the DIE's
15709              type.  If so, there is no need to continue.  */
15710           if (get_die_type (die, cu) != NULL)
15711             return get_die_type (die, cu);
15712
15713           TYPE_TAG_NAME (type) = full_name;
15714           if (die->tag == DW_TAG_structure_type
15715               || die->tag == DW_TAG_class_type)
15716             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15717         }
15718       else
15719         {
15720           /* The name is already allocated along with this objfile, so
15721              we don't need to duplicate it for the type.  */
15722           TYPE_TAG_NAME (type) = name;
15723           if (die->tag == DW_TAG_class_type)
15724             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15725         }
15726     }
15727
15728   if (die->tag == DW_TAG_structure_type)
15729     {
15730       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15731     }
15732   else if (die->tag == DW_TAG_union_type)
15733     {
15734       TYPE_CODE (type) = TYPE_CODE_UNION;
15735     }
15736   else
15737     {
15738       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15739     }
15740
15741   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15742     TYPE_DECLARED_CLASS (type) = 1;
15743
15744   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15745   if (attr)
15746     {
15747       if (attr_form_is_constant (attr))
15748         TYPE_LENGTH (type) = DW_UNSND (attr);
15749       else
15750         {
15751           /* For the moment, dynamic type sizes are not supported
15752              by GDB's struct type.  The actual size is determined
15753              on-demand when resolving the type of a given object,
15754              so set the type's length to zero for now.  Otherwise,
15755              we record an expression as the length, and that expression
15756              could lead to a very large value, which could eventually
15757              lead to us trying to allocate that much memory when creating
15758              a value of that type.  */
15759           TYPE_LENGTH (type) = 0;
15760         }
15761     }
15762   else
15763     {
15764       TYPE_LENGTH (type) = 0;
15765     }
15766
15767   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15768     {
15769       /* ICC<14 does not output the required DW_AT_declaration on
15770          incomplete types, but gives them a size of zero.  */
15771       TYPE_STUB (type) = 1;
15772     }
15773   else
15774     TYPE_STUB_SUPPORTED (type) = 1;
15775
15776   if (die_is_declaration (die, cu))
15777     TYPE_STUB (type) = 1;
15778   else if (attr == NULL && die->child == NULL
15779            && producer_is_realview (cu->producer))
15780     /* RealView does not output the required DW_AT_declaration
15781        on incomplete types.  */
15782     TYPE_STUB (type) = 1;
15783
15784   /* We need to add the type field to the die immediately so we don't
15785      infinitely recurse when dealing with pointers to the structure
15786      type within the structure itself.  */
15787   set_die_type (die, type, cu);
15788
15789   /* set_die_type should be already done.  */
15790   set_descriptive_type (type, die, cu);
15791
15792   return type;
15793 }
15794
15795 /* Finish creating a structure or union type, including filling in
15796    its members and creating a symbol for it.  */
15797
15798 static void
15799 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15800 {
15801   struct objfile *objfile = cu->objfile;
15802   struct die_info *child_die;
15803   struct type *type;
15804
15805   type = get_die_type (die, cu);
15806   if (type == NULL)
15807     type = read_structure_type (die, cu);
15808
15809   if (die->child != NULL && ! die_is_declaration (die, cu))
15810     {
15811       struct field_info fi;
15812       std::vector<struct symbol *> template_args;
15813       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15814
15815       memset (&fi, 0, sizeof (struct field_info));
15816
15817       child_die = die->child;
15818
15819       while (child_die && child_die->tag)
15820         {
15821           if (child_die->tag == DW_TAG_member
15822               || child_die->tag == DW_TAG_variable)
15823             {
15824               /* NOTE: carlton/2002-11-05: A C++ static data member
15825                  should be a DW_TAG_member that is a declaration, but
15826                  all versions of G++ as of this writing (so through at
15827                  least 3.2.1) incorrectly generate DW_TAG_variable
15828                  tags for them instead.  */
15829               dwarf2_add_field (&fi, child_die, cu);
15830             }
15831           else if (child_die->tag == DW_TAG_subprogram)
15832             {
15833               /* Rust doesn't have member functions in the C++ sense.
15834                  However, it does emit ordinary functions as children
15835                  of a struct DIE.  */
15836               if (cu->language == language_rust)
15837                 read_func_scope (child_die, cu);
15838               else
15839                 {
15840                   /* C++ member function.  */
15841                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15842                 }
15843             }
15844           else if (child_die->tag == DW_TAG_inheritance)
15845             {
15846               /* C++ base class field.  */
15847               dwarf2_add_field (&fi, child_die, cu);
15848             }
15849           else if (type_can_define_types (child_die))
15850             dwarf2_add_type_defn (&fi, child_die, cu);
15851           else if (child_die->tag == DW_TAG_template_type_param
15852                    || child_die->tag == DW_TAG_template_value_param)
15853             {
15854               struct symbol *arg = new_symbol (child_die, NULL, cu);
15855
15856               if (arg != NULL)
15857                 template_args.push_back (arg);
15858             }
15859
15860           child_die = sibling_die (child_die);
15861         }
15862
15863       /* Attach template arguments to type.  */
15864       if (!template_args.empty ())
15865         {
15866           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15867           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15868           TYPE_TEMPLATE_ARGUMENTS (type)
15869             = XOBNEWVEC (&objfile->objfile_obstack,
15870                          struct symbol *,
15871                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15872           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15873                   template_args.data (),
15874                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15875                    * sizeof (struct symbol *)));
15876         }
15877
15878       /* Attach fields and member functions to the type.  */
15879       if (fi.nfields)
15880         dwarf2_attach_fields_to_type (&fi, type, cu);
15881       if (fi.nfnfields)
15882         {
15883           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15884
15885           /* Get the type which refers to the base class (possibly this
15886              class itself) which contains the vtable pointer for the current
15887              class from the DW_AT_containing_type attribute.  This use of
15888              DW_AT_containing_type is a GNU extension.  */
15889
15890           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15891             {
15892               struct type *t = die_containing_type (die, cu);
15893
15894               set_type_vptr_basetype (type, t);
15895               if (type == t)
15896                 {
15897                   int i;
15898
15899                   /* Our own class provides vtbl ptr.  */
15900                   for (i = TYPE_NFIELDS (t) - 1;
15901                        i >= TYPE_N_BASECLASSES (t);
15902                        --i)
15903                     {
15904                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15905
15906                       if (is_vtable_name (fieldname, cu))
15907                         {
15908                           set_type_vptr_fieldno (type, i);
15909                           break;
15910                         }
15911                     }
15912
15913                   /* Complain if virtual function table field not found.  */
15914                   if (i < TYPE_N_BASECLASSES (t))
15915                     complaint (&symfile_complaints,
15916                                _("virtual function table pointer "
15917                                  "not found when defining class '%s'"),
15918                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
15919                                "");
15920                 }
15921               else
15922                 {
15923                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15924                 }
15925             }
15926           else if (cu->producer
15927                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15928             {
15929               /* The IBM XLC compiler does not provide direct indication
15930                  of the containing type, but the vtable pointer is
15931                  always named __vfp.  */
15932
15933               int i;
15934
15935               for (i = TYPE_NFIELDS (type) - 1;
15936                    i >= TYPE_N_BASECLASSES (type);
15937                    --i)
15938                 {
15939                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15940                     {
15941                       set_type_vptr_fieldno (type, i);
15942                       set_type_vptr_basetype (type, type);
15943                       break;
15944                     }
15945                 }
15946             }
15947         }
15948
15949       /* Copy fi.typedef_field_list linked list elements content into the
15950          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15951       if (fi.typedef_field_list)
15952         {
15953           int i = fi.typedef_field_list_count;
15954
15955           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15956           TYPE_TYPEDEF_FIELD_ARRAY (type)
15957             = ((struct decl_field *)
15958                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
15959           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
15960
15961           /* Reverse the list order to keep the debug info elements order.  */
15962           while (--i >= 0)
15963             {
15964               struct decl_field *dest, *src;
15965
15966               dest = &TYPE_TYPEDEF_FIELD (type, i);
15967               src = &fi.typedef_field_list->field;
15968               fi.typedef_field_list = fi.typedef_field_list->next;
15969               *dest = *src;
15970             }
15971         }
15972
15973       /* Copy fi.nested_types_list linked list elements content into the
15974          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15975       if (fi.nested_types_list != NULL && cu->language != language_ada)
15976         {
15977           int i = fi.nested_types_list_count;
15978
15979           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15980           TYPE_NESTED_TYPES_ARRAY (type)
15981             = ((struct decl_field *)
15982                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
15983           TYPE_NESTED_TYPES_COUNT (type) = i;
15984
15985           /* Reverse the list order to keep the debug info elements order.  */
15986           while (--i >= 0)
15987             {
15988               struct decl_field *dest, *src;
15989
15990               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
15991               src = &fi.nested_types_list->field;
15992               fi.nested_types_list = fi.nested_types_list->next;
15993               *dest = *src;
15994             }
15995         }
15996
15997       do_cleanups (back_to);
15998     }
15999
16000   quirk_gcc_member_function_pointer (type, objfile);
16001
16002   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16003      snapshots) has been known to create a die giving a declaration
16004      for a class that has, as a child, a die giving a definition for a
16005      nested class.  So we have to process our children even if the
16006      current die is a declaration.  Normally, of course, a declaration
16007      won't have any children at all.  */
16008
16009   child_die = die->child;
16010
16011   while (child_die != NULL && child_die->tag)
16012     {
16013       if (child_die->tag == DW_TAG_member
16014           || child_die->tag == DW_TAG_variable
16015           || child_die->tag == DW_TAG_inheritance
16016           || child_die->tag == DW_TAG_template_value_param
16017           || child_die->tag == DW_TAG_template_type_param)
16018         {
16019           /* Do nothing.  */
16020         }
16021       else
16022         process_die (child_die, cu);
16023
16024       child_die = sibling_die (child_die);
16025     }
16026
16027   /* Do not consider external references.  According to the DWARF standard,
16028      these DIEs are identified by the fact that they have no byte_size
16029      attribute, and a declaration attribute.  */
16030   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16031       || !die_is_declaration (die, cu))
16032     new_symbol (die, type, cu);
16033 }
16034
16035 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16036    update TYPE using some information only available in DIE's children.  */
16037
16038 static void
16039 update_enumeration_type_from_children (struct die_info *die,
16040                                        struct type *type,
16041                                        struct dwarf2_cu *cu)
16042 {
16043   struct die_info *child_die;
16044   int unsigned_enum = 1;
16045   int flag_enum = 1;
16046   ULONGEST mask = 0;
16047
16048   auto_obstack obstack;
16049
16050   for (child_die = die->child;
16051        child_die != NULL && child_die->tag;
16052        child_die = sibling_die (child_die))
16053     {
16054       struct attribute *attr;
16055       LONGEST value;
16056       const gdb_byte *bytes;
16057       struct dwarf2_locexpr_baton *baton;
16058       const char *name;
16059
16060       if (child_die->tag != DW_TAG_enumerator)
16061         continue;
16062
16063       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16064       if (attr == NULL)
16065         continue;
16066
16067       name = dwarf2_name (child_die, cu);
16068       if (name == NULL)
16069         name = "<anonymous enumerator>";
16070
16071       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16072                                &value, &bytes, &baton);
16073       if (value < 0)
16074         {
16075           unsigned_enum = 0;
16076           flag_enum = 0;
16077         }
16078       else if ((mask & value) != 0)
16079         flag_enum = 0;
16080       else
16081         mask |= value;
16082
16083       /* If we already know that the enum type is neither unsigned, nor
16084          a flag type, no need to look at the rest of the enumerates.  */
16085       if (!unsigned_enum && !flag_enum)
16086         break;
16087     }
16088
16089   if (unsigned_enum)
16090     TYPE_UNSIGNED (type) = 1;
16091   if (flag_enum)
16092     TYPE_FLAG_ENUM (type) = 1;
16093 }
16094
16095 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16096    complete the type's fields yet, or create any symbols.  */
16097
16098 static struct type *
16099 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16100 {
16101   struct objfile *objfile = cu->objfile;
16102   struct type *type;
16103   struct attribute *attr;
16104   const char *name;
16105
16106   /* If the definition of this type lives in .debug_types, read that type.
16107      Don't follow DW_AT_specification though, that will take us back up
16108      the chain and we want to go down.  */
16109   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16110   if (attr)
16111     {
16112       type = get_DW_AT_signature_type (die, attr, cu);
16113
16114       /* The type's CU may not be the same as CU.
16115          Ensure TYPE is recorded with CU in die_type_hash.  */
16116       return set_die_type (die, type, cu);
16117     }
16118
16119   type = alloc_type (objfile);
16120
16121   TYPE_CODE (type) = TYPE_CODE_ENUM;
16122   name = dwarf2_full_name (NULL, die, cu);
16123   if (name != NULL)
16124     TYPE_TAG_NAME (type) = name;
16125
16126   attr = dwarf2_attr (die, DW_AT_type, cu);
16127   if (attr != NULL)
16128     {
16129       struct type *underlying_type = die_type (die, cu);
16130
16131       TYPE_TARGET_TYPE (type) = underlying_type;
16132     }
16133
16134   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16135   if (attr)
16136     {
16137       TYPE_LENGTH (type) = DW_UNSND (attr);
16138     }
16139   else
16140     {
16141       TYPE_LENGTH (type) = 0;
16142     }
16143
16144   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16145      declared as private in the package spec, and then defined only
16146      inside the package body.  Such types are known as Taft Amendment
16147      Types.  When another package uses such a type, an incomplete DIE
16148      may be generated by the compiler.  */
16149   if (die_is_declaration (die, cu))
16150     TYPE_STUB (type) = 1;
16151
16152   /* Finish the creation of this type by using the enum's children.
16153      We must call this even when the underlying type has been provided
16154      so that we can determine if we're looking at a "flag" enum.  */
16155   update_enumeration_type_from_children (die, type, cu);
16156
16157   /* If this type has an underlying type that is not a stub, then we
16158      may use its attributes.  We always use the "unsigned" attribute
16159      in this situation, because ordinarily we guess whether the type
16160      is unsigned -- but the guess can be wrong and the underlying type
16161      can tell us the reality.  However, we defer to a local size
16162      attribute if one exists, because this lets the compiler override
16163      the underlying type if needed.  */
16164   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16165     {
16166       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16167       if (TYPE_LENGTH (type) == 0)
16168         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16169     }
16170
16171   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16172
16173   return set_die_type (die, type, cu);
16174 }
16175
16176 /* Given a pointer to a die which begins an enumeration, process all
16177    the dies that define the members of the enumeration, and create the
16178    symbol for the enumeration type.
16179
16180    NOTE: We reverse the order of the element list.  */
16181
16182 static void
16183 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16184 {
16185   struct type *this_type;
16186
16187   this_type = get_die_type (die, cu);
16188   if (this_type == NULL)
16189     this_type = read_enumeration_type (die, cu);
16190
16191   if (die->child != NULL)
16192     {
16193       struct die_info *child_die;
16194       struct symbol *sym;
16195       struct field *fields = NULL;
16196       int num_fields = 0;
16197       const char *name;
16198
16199       child_die = die->child;
16200       while (child_die && child_die->tag)
16201         {
16202           if (child_die->tag != DW_TAG_enumerator)
16203             {
16204               process_die (child_die, cu);
16205             }
16206           else
16207             {
16208               name = dwarf2_name (child_die, cu);
16209               if (name)
16210                 {
16211                   sym = new_symbol (child_die, this_type, cu);
16212
16213                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16214                     {
16215                       fields = (struct field *)
16216                         xrealloc (fields,
16217                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16218                                   * sizeof (struct field));
16219                     }
16220
16221                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16222                   FIELD_TYPE (fields[num_fields]) = NULL;
16223                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16224                   FIELD_BITSIZE (fields[num_fields]) = 0;
16225
16226                   num_fields++;
16227                 }
16228             }
16229
16230           child_die = sibling_die (child_die);
16231         }
16232
16233       if (num_fields)
16234         {
16235           TYPE_NFIELDS (this_type) = num_fields;
16236           TYPE_FIELDS (this_type) = (struct field *)
16237             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16238           memcpy (TYPE_FIELDS (this_type), fields,
16239                   sizeof (struct field) * num_fields);
16240           xfree (fields);
16241         }
16242     }
16243
16244   /* If we are reading an enum from a .debug_types unit, and the enum
16245      is a declaration, and the enum is not the signatured type in the
16246      unit, then we do not want to add a symbol for it.  Adding a
16247      symbol would in some cases obscure the true definition of the
16248      enum, giving users an incomplete type when the definition is
16249      actually available.  Note that we do not want to do this for all
16250      enums which are just declarations, because C++0x allows forward
16251      enum declarations.  */
16252   if (cu->per_cu->is_debug_types
16253       && die_is_declaration (die, cu))
16254     {
16255       struct signatured_type *sig_type;
16256
16257       sig_type = (struct signatured_type *) cu->per_cu;
16258       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16259       if (sig_type->type_offset_in_section != die->sect_off)
16260         return;
16261     }
16262
16263   new_symbol (die, this_type, cu);
16264 }
16265
16266 /* Extract all information from a DW_TAG_array_type DIE and put it in
16267    the DIE's type field.  For now, this only handles one dimensional
16268    arrays.  */
16269
16270 static struct type *
16271 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16272 {
16273   struct objfile *objfile = cu->objfile;
16274   struct die_info *child_die;
16275   struct type *type;
16276   struct type *element_type, *range_type, *index_type;
16277   struct attribute *attr;
16278   const char *name;
16279   unsigned int bit_stride = 0;
16280
16281   element_type = die_type (die, cu);
16282
16283   /* The die_type call above may have already set the type for this DIE.  */
16284   type = get_die_type (die, cu);
16285   if (type)
16286     return type;
16287
16288   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16289   if (attr != NULL)
16290     bit_stride = DW_UNSND (attr) * 8;
16291
16292   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16293   if (attr != NULL)
16294     bit_stride = DW_UNSND (attr);
16295
16296   /* Irix 6.2 native cc creates array types without children for
16297      arrays with unspecified length.  */
16298   if (die->child == NULL)
16299     {
16300       index_type = objfile_type (objfile)->builtin_int;
16301       range_type = create_static_range_type (NULL, index_type, 0, -1);
16302       type = create_array_type_with_stride (NULL, element_type, range_type,
16303                                             bit_stride);
16304       return set_die_type (die, type, cu);
16305     }
16306
16307   std::vector<struct type *> range_types;
16308   child_die = die->child;
16309   while (child_die && child_die->tag)
16310     {
16311       if (child_die->tag == DW_TAG_subrange_type)
16312         {
16313           struct type *child_type = read_type_die (child_die, cu);
16314
16315           if (child_type != NULL)
16316             {
16317               /* The range type was succesfully read.  Save it for the
16318                  array type creation.  */
16319               range_types.push_back (child_type);
16320             }
16321         }
16322       child_die = sibling_die (child_die);
16323     }
16324
16325   /* Dwarf2 dimensions are output from left to right, create the
16326      necessary array types in backwards order.  */
16327
16328   type = element_type;
16329
16330   if (read_array_order (die, cu) == DW_ORD_col_major)
16331     {
16332       int i = 0;
16333
16334       while (i < range_types.size ())
16335         type = create_array_type_with_stride (NULL, type, range_types[i++],
16336                                               bit_stride);
16337     }
16338   else
16339     {
16340       size_t ndim = range_types.size ();
16341       while (ndim-- > 0)
16342         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16343                                               bit_stride);
16344     }
16345
16346   /* Understand Dwarf2 support for vector types (like they occur on
16347      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16348      array type.  This is not part of the Dwarf2/3 standard yet, but a
16349      custom vendor extension.  The main difference between a regular
16350      array and the vector variant is that vectors are passed by value
16351      to functions.  */
16352   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16353   if (attr)
16354     make_vector_type (type);
16355
16356   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16357      implementation may choose to implement triple vectors using this
16358      attribute.  */
16359   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16360   if (attr)
16361     {
16362       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16363         TYPE_LENGTH (type) = DW_UNSND (attr);
16364       else
16365         complaint (&symfile_complaints,
16366                    _("DW_AT_byte_size for array type smaller "
16367                      "than the total size of elements"));
16368     }
16369
16370   name = dwarf2_name (die, cu);
16371   if (name)
16372     TYPE_NAME (type) = name;
16373
16374   /* Install the type in the die.  */
16375   set_die_type (die, type, cu);
16376
16377   /* set_die_type should be already done.  */
16378   set_descriptive_type (type, die, cu);
16379
16380   return type;
16381 }
16382
16383 static enum dwarf_array_dim_ordering
16384 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16385 {
16386   struct attribute *attr;
16387
16388   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16389
16390   if (attr)
16391     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16392
16393   /* GNU F77 is a special case, as at 08/2004 array type info is the
16394      opposite order to the dwarf2 specification, but data is still
16395      laid out as per normal fortran.
16396
16397      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16398      version checking.  */
16399
16400   if (cu->language == language_fortran
16401       && cu->producer && strstr (cu->producer, "GNU F77"))
16402     {
16403       return DW_ORD_row_major;
16404     }
16405
16406   switch (cu->language_defn->la_array_ordering)
16407     {
16408     case array_column_major:
16409       return DW_ORD_col_major;
16410     case array_row_major:
16411     default:
16412       return DW_ORD_row_major;
16413     };
16414 }
16415
16416 /* Extract all information from a DW_TAG_set_type DIE and put it in
16417    the DIE's type field.  */
16418
16419 static struct type *
16420 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16421 {
16422   struct type *domain_type, *set_type;
16423   struct attribute *attr;
16424
16425   domain_type = die_type (die, cu);
16426
16427   /* The die_type call above may have already set the type for this DIE.  */
16428   set_type = get_die_type (die, cu);
16429   if (set_type)
16430     return set_type;
16431
16432   set_type = create_set_type (NULL, domain_type);
16433
16434   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16435   if (attr)
16436     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16437
16438   return set_die_type (die, set_type, cu);
16439 }
16440
16441 /* A helper for read_common_block that creates a locexpr baton.
16442    SYM is the symbol which we are marking as computed.
16443    COMMON_DIE is the DIE for the common block.
16444    COMMON_LOC is the location expression attribute for the common
16445    block itself.
16446    MEMBER_LOC is the location expression attribute for the particular
16447    member of the common block that we are processing.
16448    CU is the CU from which the above come.  */
16449
16450 static void
16451 mark_common_block_symbol_computed (struct symbol *sym,
16452                                    struct die_info *common_die,
16453                                    struct attribute *common_loc,
16454                                    struct attribute *member_loc,
16455                                    struct dwarf2_cu *cu)
16456 {
16457   struct objfile *objfile = dwarf2_per_objfile->objfile;
16458   struct dwarf2_locexpr_baton *baton;
16459   gdb_byte *ptr;
16460   unsigned int cu_off;
16461   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16462   LONGEST offset = 0;
16463
16464   gdb_assert (common_loc && member_loc);
16465   gdb_assert (attr_form_is_block (common_loc));
16466   gdb_assert (attr_form_is_block (member_loc)
16467               || attr_form_is_constant (member_loc));
16468
16469   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16470   baton->per_cu = cu->per_cu;
16471   gdb_assert (baton->per_cu);
16472
16473   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16474
16475   if (attr_form_is_constant (member_loc))
16476     {
16477       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16478       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16479     }
16480   else
16481     baton->size += DW_BLOCK (member_loc)->size;
16482
16483   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16484   baton->data = ptr;
16485
16486   *ptr++ = DW_OP_call4;
16487   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16488   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16489   ptr += 4;
16490
16491   if (attr_form_is_constant (member_loc))
16492     {
16493       *ptr++ = DW_OP_addr;
16494       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16495       ptr += cu->header.addr_size;
16496     }
16497   else
16498     {
16499       /* We have to copy the data here, because DW_OP_call4 will only
16500          use a DW_AT_location attribute.  */
16501       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16502       ptr += DW_BLOCK (member_loc)->size;
16503     }
16504
16505   *ptr++ = DW_OP_plus;
16506   gdb_assert (ptr - baton->data == baton->size);
16507
16508   SYMBOL_LOCATION_BATON (sym) = baton;
16509   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16510 }
16511
16512 /* Create appropriate locally-scoped variables for all the
16513    DW_TAG_common_block entries.  Also create a struct common_block
16514    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16515    is used to sepate the common blocks name namespace from regular
16516    variable names.  */
16517
16518 static void
16519 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16520 {
16521   struct attribute *attr;
16522
16523   attr = dwarf2_attr (die, DW_AT_location, cu);
16524   if (attr)
16525     {
16526       /* Support the .debug_loc offsets.  */
16527       if (attr_form_is_block (attr))
16528         {
16529           /* Ok.  */
16530         }
16531       else if (attr_form_is_section_offset (attr))
16532         {
16533           dwarf2_complex_location_expr_complaint ();
16534           attr = NULL;
16535         }
16536       else
16537         {
16538           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16539                                                  "common block member");
16540           attr = NULL;
16541         }
16542     }
16543
16544   if (die->child != NULL)
16545     {
16546       struct objfile *objfile = cu->objfile;
16547       struct die_info *child_die;
16548       size_t n_entries = 0, size;
16549       struct common_block *common_block;
16550       struct symbol *sym;
16551
16552       for (child_die = die->child;
16553            child_die && child_die->tag;
16554            child_die = sibling_die (child_die))
16555         ++n_entries;
16556
16557       size = (sizeof (struct common_block)
16558               + (n_entries - 1) * sizeof (struct symbol *));
16559       common_block
16560         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16561                                                  size);
16562       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16563       common_block->n_entries = 0;
16564
16565       for (child_die = die->child;
16566            child_die && child_die->tag;
16567            child_die = sibling_die (child_die))
16568         {
16569           /* Create the symbol in the DW_TAG_common_block block in the current
16570              symbol scope.  */
16571           sym = new_symbol (child_die, NULL, cu);
16572           if (sym != NULL)
16573             {
16574               struct attribute *member_loc;
16575
16576               common_block->contents[common_block->n_entries++] = sym;
16577
16578               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16579                                         cu);
16580               if (member_loc)
16581                 {
16582                   /* GDB has handled this for a long time, but it is
16583                      not specified by DWARF.  It seems to have been
16584                      emitted by gfortran at least as recently as:
16585                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16586                   complaint (&symfile_complaints,
16587                              _("Variable in common block has "
16588                                "DW_AT_data_member_location "
16589                                "- DIE at 0x%x [in module %s]"),
16590                              to_underlying (child_die->sect_off),
16591                              objfile_name (cu->objfile));
16592
16593                   if (attr_form_is_section_offset (member_loc))
16594                     dwarf2_complex_location_expr_complaint ();
16595                   else if (attr_form_is_constant (member_loc)
16596                            || attr_form_is_block (member_loc))
16597                     {
16598                       if (attr)
16599                         mark_common_block_symbol_computed (sym, die, attr,
16600                                                            member_loc, cu);
16601                     }
16602                   else
16603                     dwarf2_complex_location_expr_complaint ();
16604                 }
16605             }
16606         }
16607
16608       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16609       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16610     }
16611 }
16612
16613 /* Create a type for a C++ namespace.  */
16614
16615 static struct type *
16616 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16617 {
16618   struct objfile *objfile = cu->objfile;
16619   const char *previous_prefix, *name;
16620   int is_anonymous;
16621   struct type *type;
16622
16623   /* For extensions, reuse the type of the original namespace.  */
16624   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16625     {
16626       struct die_info *ext_die;
16627       struct dwarf2_cu *ext_cu = cu;
16628
16629       ext_die = dwarf2_extension (die, &ext_cu);
16630       type = read_type_die (ext_die, ext_cu);
16631
16632       /* EXT_CU may not be the same as CU.
16633          Ensure TYPE is recorded with CU in die_type_hash.  */
16634       return set_die_type (die, type, cu);
16635     }
16636
16637   name = namespace_name (die, &is_anonymous, cu);
16638
16639   /* Now build the name of the current namespace.  */
16640
16641   previous_prefix = determine_prefix (die, cu);
16642   if (previous_prefix[0] != '\0')
16643     name = typename_concat (&objfile->objfile_obstack,
16644                             previous_prefix, name, 0, cu);
16645
16646   /* Create the type.  */
16647   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16648   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16649
16650   return set_die_type (die, type, cu);
16651 }
16652
16653 /* Read a namespace scope.  */
16654
16655 static void
16656 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16657 {
16658   struct objfile *objfile = cu->objfile;
16659   int is_anonymous;
16660
16661   /* Add a symbol associated to this if we haven't seen the namespace
16662      before.  Also, add a using directive if it's an anonymous
16663      namespace.  */
16664
16665   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16666     {
16667       struct type *type;
16668
16669       type = read_type_die (die, cu);
16670       new_symbol (die, type, cu);
16671
16672       namespace_name (die, &is_anonymous, cu);
16673       if (is_anonymous)
16674         {
16675           const char *previous_prefix = determine_prefix (die, cu);
16676
16677           std::vector<const char *> excludes;
16678           add_using_directive (using_directives (cu->language),
16679                                previous_prefix, TYPE_NAME (type), NULL,
16680                                NULL, excludes, 0, &objfile->objfile_obstack);
16681         }
16682     }
16683
16684   if (die->child != NULL)
16685     {
16686       struct die_info *child_die = die->child;
16687
16688       while (child_die && child_die->tag)
16689         {
16690           process_die (child_die, cu);
16691           child_die = sibling_die (child_die);
16692         }
16693     }
16694 }
16695
16696 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16697    imported module.  Still we need that type as local Fortran "use ... only"
16698    declaration imports depend on the created type in determine_prefix.  */
16699
16700 static struct type *
16701 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16702 {
16703   struct objfile *objfile = cu->objfile;
16704   const char *module_name;
16705   struct type *type;
16706
16707   module_name = dwarf2_name (die, cu);
16708   if (!module_name)
16709     complaint (&symfile_complaints,
16710                _("DW_TAG_module has no name, offset 0x%x"),
16711                to_underlying (die->sect_off));
16712   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16713
16714   /* determine_prefix uses TYPE_TAG_NAME.  */
16715   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16716
16717   return set_die_type (die, type, cu);
16718 }
16719
16720 /* Read a Fortran module.  */
16721
16722 static void
16723 read_module (struct die_info *die, struct dwarf2_cu *cu)
16724 {
16725   struct die_info *child_die = die->child;
16726   struct type *type;
16727
16728   type = read_type_die (die, cu);
16729   new_symbol (die, type, cu);
16730
16731   while (child_die && child_die->tag)
16732     {
16733       process_die (child_die, cu);
16734       child_die = sibling_die (child_die);
16735     }
16736 }
16737
16738 /* Return the name of the namespace represented by DIE.  Set
16739    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16740    namespace.  */
16741
16742 static const char *
16743 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16744 {
16745   struct die_info *current_die;
16746   const char *name = NULL;
16747
16748   /* Loop through the extensions until we find a name.  */
16749
16750   for (current_die = die;
16751        current_die != NULL;
16752        current_die = dwarf2_extension (die, &cu))
16753     {
16754       /* We don't use dwarf2_name here so that we can detect the absence
16755          of a name -> anonymous namespace.  */
16756       name = dwarf2_string_attr (die, DW_AT_name, cu);
16757
16758       if (name != NULL)
16759         break;
16760     }
16761
16762   /* Is it an anonymous namespace?  */
16763
16764   *is_anonymous = (name == NULL);
16765   if (*is_anonymous)
16766     name = CP_ANONYMOUS_NAMESPACE_STR;
16767
16768   return name;
16769 }
16770
16771 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16772    the user defined type vector.  */
16773
16774 static struct type *
16775 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16776 {
16777   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
16778   struct comp_unit_head *cu_header = &cu->header;
16779   struct type *type;
16780   struct attribute *attr_byte_size;
16781   struct attribute *attr_address_class;
16782   int byte_size, addr_class;
16783   struct type *target_type;
16784
16785   target_type = die_type (die, cu);
16786
16787   /* The die_type call above may have already set the type for this DIE.  */
16788   type = get_die_type (die, cu);
16789   if (type)
16790     return type;
16791
16792   type = lookup_pointer_type (target_type);
16793
16794   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16795   if (attr_byte_size)
16796     byte_size = DW_UNSND (attr_byte_size);
16797   else
16798     byte_size = cu_header->addr_size;
16799
16800   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16801   if (attr_address_class)
16802     addr_class = DW_UNSND (attr_address_class);
16803   else
16804     addr_class = DW_ADDR_none;
16805
16806   /* If the pointer size or address class is different than the
16807      default, create a type variant marked as such and set the
16808      length accordingly.  */
16809   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16810     {
16811       if (gdbarch_address_class_type_flags_p (gdbarch))
16812         {
16813           int type_flags;
16814
16815           type_flags = gdbarch_address_class_type_flags
16816                          (gdbarch, byte_size, addr_class);
16817           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16818                       == 0);
16819           type = make_type_with_address_space (type, type_flags);
16820         }
16821       else if (TYPE_LENGTH (type) != byte_size)
16822         {
16823           complaint (&symfile_complaints,
16824                      _("invalid pointer size %d"), byte_size);
16825         }
16826       else
16827         {
16828           /* Should we also complain about unhandled address classes?  */
16829         }
16830     }
16831
16832   TYPE_LENGTH (type) = byte_size;
16833   return set_die_type (die, type, cu);
16834 }
16835
16836 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16837    the user defined type vector.  */
16838
16839 static struct type *
16840 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16841 {
16842   struct type *type;
16843   struct type *to_type;
16844   struct type *domain;
16845
16846   to_type = die_type (die, cu);
16847   domain = die_containing_type (die, cu);
16848
16849   /* The calls above may have already set the type for this DIE.  */
16850   type = get_die_type (die, cu);
16851   if (type)
16852     return type;
16853
16854   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16855     type = lookup_methodptr_type (to_type);
16856   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16857     {
16858       struct type *new_type = alloc_type (cu->objfile);
16859
16860       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16861                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16862                             TYPE_VARARGS (to_type));
16863       type = lookup_methodptr_type (new_type);
16864     }
16865   else
16866     type = lookup_memberptr_type (to_type, domain);
16867
16868   return set_die_type (die, type, cu);
16869 }
16870
16871 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16872    the user defined type vector.  */
16873
16874 static struct type *
16875 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16876                           enum type_code refcode)
16877 {
16878   struct comp_unit_head *cu_header = &cu->header;
16879   struct type *type, *target_type;
16880   struct attribute *attr;
16881
16882   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16883
16884   target_type = die_type (die, cu);
16885
16886   /* The die_type call above may have already set the type for this DIE.  */
16887   type = get_die_type (die, cu);
16888   if (type)
16889     return type;
16890
16891   type = lookup_reference_type (target_type, refcode);
16892   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16893   if (attr)
16894     {
16895       TYPE_LENGTH (type) = DW_UNSND (attr);
16896     }
16897   else
16898     {
16899       TYPE_LENGTH (type) = cu_header->addr_size;
16900     }
16901   return set_die_type (die, type, cu);
16902 }
16903
16904 /* Add the given cv-qualifiers to the element type of the array.  GCC
16905    outputs DWARF type qualifiers that apply to an array, not the
16906    element type.  But GDB relies on the array element type to carry
16907    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16908    specification.  */
16909
16910 static struct type *
16911 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16912                    struct type *base_type, int cnst, int voltl)
16913 {
16914   struct type *el_type, *inner_array;
16915
16916   base_type = copy_type (base_type);
16917   inner_array = base_type;
16918
16919   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16920     {
16921       TYPE_TARGET_TYPE (inner_array) =
16922         copy_type (TYPE_TARGET_TYPE (inner_array));
16923       inner_array = TYPE_TARGET_TYPE (inner_array);
16924     }
16925
16926   el_type = TYPE_TARGET_TYPE (inner_array);
16927   cnst |= TYPE_CONST (el_type);
16928   voltl |= TYPE_VOLATILE (el_type);
16929   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16930
16931   return set_die_type (die, base_type, cu);
16932 }
16933
16934 static struct type *
16935 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16936 {
16937   struct type *base_type, *cv_type;
16938
16939   base_type = die_type (die, cu);
16940
16941   /* The die_type call above may have already set the type for this DIE.  */
16942   cv_type = get_die_type (die, cu);
16943   if (cv_type)
16944     return cv_type;
16945
16946   /* In case the const qualifier is applied to an array type, the element type
16947      is so qualified, not the array type (section 6.7.3 of C99).  */
16948   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16949     return add_array_cv_type (die, cu, base_type, 1, 0);
16950
16951   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16952   return set_die_type (die, cv_type, cu);
16953 }
16954
16955 static struct type *
16956 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16957 {
16958   struct type *base_type, *cv_type;
16959
16960   base_type = die_type (die, cu);
16961
16962   /* The die_type call above may have already set the type for this DIE.  */
16963   cv_type = get_die_type (die, cu);
16964   if (cv_type)
16965     return cv_type;
16966
16967   /* In case the volatile qualifier is applied to an array type, the
16968      element type is so qualified, not the array type (section 6.7.3
16969      of C99).  */
16970   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16971     return add_array_cv_type (die, cu, base_type, 0, 1);
16972
16973   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
16974   return set_die_type (die, cv_type, cu);
16975 }
16976
16977 /* Handle DW_TAG_restrict_type.  */
16978
16979 static struct type *
16980 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
16981 {
16982   struct type *base_type, *cv_type;
16983
16984   base_type = die_type (die, cu);
16985
16986   /* The die_type call above may have already set the type for this DIE.  */
16987   cv_type = get_die_type (die, cu);
16988   if (cv_type)
16989     return cv_type;
16990
16991   cv_type = make_restrict_type (base_type);
16992   return set_die_type (die, cv_type, cu);
16993 }
16994
16995 /* Handle DW_TAG_atomic_type.  */
16996
16997 static struct type *
16998 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
16999 {
17000   struct type *base_type, *cv_type;
17001
17002   base_type = die_type (die, cu);
17003
17004   /* The die_type call above may have already set the type for this DIE.  */
17005   cv_type = get_die_type (die, cu);
17006   if (cv_type)
17007     return cv_type;
17008
17009   cv_type = make_atomic_type (base_type);
17010   return set_die_type (die, cv_type, cu);
17011 }
17012
17013 /* Extract all information from a DW_TAG_string_type DIE and add to
17014    the user defined type vector.  It isn't really a user defined type,
17015    but it behaves like one, with other DIE's using an AT_user_def_type
17016    attribute to reference it.  */
17017
17018 static struct type *
17019 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17020 {
17021   struct objfile *objfile = cu->objfile;
17022   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17023   struct type *type, *range_type, *index_type, *char_type;
17024   struct attribute *attr;
17025   unsigned int length;
17026
17027   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17028   if (attr)
17029     {
17030       length = DW_UNSND (attr);
17031     }
17032   else
17033     {
17034       /* Check for the DW_AT_byte_size attribute.  */
17035       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17036       if (attr)
17037         {
17038           length = DW_UNSND (attr);
17039         }
17040       else
17041         {
17042           length = 1;
17043         }
17044     }
17045
17046   index_type = objfile_type (objfile)->builtin_int;
17047   range_type = create_static_range_type (NULL, index_type, 1, length);
17048   char_type = language_string_char_type (cu->language_defn, gdbarch);
17049   type = create_string_type (NULL, char_type, range_type);
17050
17051   return set_die_type (die, type, cu);
17052 }
17053
17054 /* Assuming that DIE corresponds to a function, returns nonzero
17055    if the function is prototyped.  */
17056
17057 static int
17058 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17059 {
17060   struct attribute *attr;
17061
17062   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17063   if (attr && (DW_UNSND (attr) != 0))
17064     return 1;
17065
17066   /* The DWARF standard implies that the DW_AT_prototyped attribute
17067      is only meaninful for C, but the concept also extends to other
17068      languages that allow unprototyped functions (Eg: Objective C).
17069      For all other languages, assume that functions are always
17070      prototyped.  */
17071   if (cu->language != language_c
17072       && cu->language != language_objc
17073       && cu->language != language_opencl)
17074     return 1;
17075
17076   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17077      prototyped and unprototyped functions; default to prototyped,
17078      since that is more common in modern code (and RealView warns
17079      about unprototyped functions).  */
17080   if (producer_is_realview (cu->producer))
17081     return 1;
17082
17083   return 0;
17084 }
17085
17086 /* Handle DIES due to C code like:
17087
17088    struct foo
17089    {
17090    int (*funcp)(int a, long l);
17091    int b;
17092    };
17093
17094    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17095
17096 static struct type *
17097 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17098 {
17099   struct objfile *objfile = cu->objfile;
17100   struct type *type;            /* Type that this function returns.  */
17101   struct type *ftype;           /* Function that returns above type.  */
17102   struct attribute *attr;
17103
17104   type = die_type (die, cu);
17105
17106   /* The die_type call above may have already set the type for this DIE.  */
17107   ftype = get_die_type (die, cu);
17108   if (ftype)
17109     return ftype;
17110
17111   ftype = lookup_function_type (type);
17112
17113   if (prototyped_function_p (die, cu))
17114     TYPE_PROTOTYPED (ftype) = 1;
17115
17116   /* Store the calling convention in the type if it's available in
17117      the subroutine die.  Otherwise set the calling convention to
17118      the default value DW_CC_normal.  */
17119   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17120   if (attr)
17121     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17122   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17123     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17124   else
17125     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17126
17127   /* Record whether the function returns normally to its caller or not
17128      if the DWARF producer set that information.  */
17129   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17130   if (attr && (DW_UNSND (attr) != 0))
17131     TYPE_NO_RETURN (ftype) = 1;
17132
17133   /* We need to add the subroutine type to the die immediately so
17134      we don't infinitely recurse when dealing with parameters
17135      declared as the same subroutine type.  */
17136   set_die_type (die, ftype, cu);
17137
17138   if (die->child != NULL)
17139     {
17140       struct type *void_type = objfile_type (objfile)->builtin_void;
17141       struct die_info *child_die;
17142       int nparams, iparams;
17143
17144       /* Count the number of parameters.
17145          FIXME: GDB currently ignores vararg functions, but knows about
17146          vararg member functions.  */
17147       nparams = 0;
17148       child_die = die->child;
17149       while (child_die && child_die->tag)
17150         {
17151           if (child_die->tag == DW_TAG_formal_parameter)
17152             nparams++;
17153           else if (child_die->tag == DW_TAG_unspecified_parameters)
17154             TYPE_VARARGS (ftype) = 1;
17155           child_die = sibling_die (child_die);
17156         }
17157
17158       /* Allocate storage for parameters and fill them in.  */
17159       TYPE_NFIELDS (ftype) = nparams;
17160       TYPE_FIELDS (ftype) = (struct field *)
17161         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17162
17163       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17164          even if we error out during the parameters reading below.  */
17165       for (iparams = 0; iparams < nparams; iparams++)
17166         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17167
17168       iparams = 0;
17169       child_die = die->child;
17170       while (child_die && child_die->tag)
17171         {
17172           if (child_die->tag == DW_TAG_formal_parameter)
17173             {
17174               struct type *arg_type;
17175
17176               /* DWARF version 2 has no clean way to discern C++
17177                  static and non-static member functions.  G++ helps
17178                  GDB by marking the first parameter for non-static
17179                  member functions (which is the this pointer) as
17180                  artificial.  We pass this information to
17181                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17182
17183                  DWARF version 3 added DW_AT_object_pointer, which GCC
17184                  4.5 does not yet generate.  */
17185               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17186               if (attr)
17187                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17188               else
17189                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17190               arg_type = die_type (child_die, cu);
17191
17192               /* RealView does not mark THIS as const, which the testsuite
17193                  expects.  GCC marks THIS as const in method definitions,
17194                  but not in the class specifications (GCC PR 43053).  */
17195               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17196                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17197                 {
17198                   int is_this = 0;
17199                   struct dwarf2_cu *arg_cu = cu;
17200                   const char *name = dwarf2_name (child_die, cu);
17201
17202                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17203                   if (attr)
17204                     {
17205                       /* If the compiler emits this, use it.  */
17206                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17207                         is_this = 1;
17208                     }
17209                   else if (name && strcmp (name, "this") == 0)
17210                     /* Function definitions will have the argument names.  */
17211                     is_this = 1;
17212                   else if (name == NULL && iparams == 0)
17213                     /* Declarations may not have the names, so like
17214                        elsewhere in GDB, assume an artificial first
17215                        argument is "this".  */
17216                     is_this = 1;
17217
17218                   if (is_this)
17219                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17220                                              arg_type, 0);
17221                 }
17222
17223               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17224               iparams++;
17225             }
17226           child_die = sibling_die (child_die);
17227         }
17228     }
17229
17230   return ftype;
17231 }
17232
17233 static struct type *
17234 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17235 {
17236   struct objfile *objfile = cu->objfile;
17237   const char *name = NULL;
17238   struct type *this_type, *target_type;
17239
17240   name = dwarf2_full_name (NULL, die, cu);
17241   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17242   TYPE_TARGET_STUB (this_type) = 1;
17243   set_die_type (die, this_type, cu);
17244   target_type = die_type (die, cu);
17245   if (target_type != this_type)
17246     TYPE_TARGET_TYPE (this_type) = target_type;
17247   else
17248     {
17249       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17250          spec and cause infinite loops in GDB.  */
17251       complaint (&symfile_complaints,
17252                  _("Self-referential DW_TAG_typedef "
17253                    "- DIE at 0x%x [in module %s]"),
17254                  to_underlying (die->sect_off), objfile_name (objfile));
17255       TYPE_TARGET_TYPE (this_type) = NULL;
17256     }
17257   return this_type;
17258 }
17259
17260 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17261    (which may be different from NAME) to the architecture back-end to allow
17262    it to guess the correct format if necessary.  */
17263
17264 static struct type *
17265 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17266                         const char *name_hint)
17267 {
17268   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17269   const struct floatformat **format;
17270   struct type *type;
17271
17272   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17273   if (format)
17274     type = init_float_type (objfile, bits, name, format);
17275   else
17276     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17277
17278   return type;
17279 }
17280
17281 /* Find a representation of a given base type and install
17282    it in the TYPE field of the die.  */
17283
17284 static struct type *
17285 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17286 {
17287   struct objfile *objfile = cu->objfile;
17288   struct type *type;
17289   struct attribute *attr;
17290   int encoding = 0, bits = 0;
17291   const char *name;
17292
17293   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17294   if (attr)
17295     {
17296       encoding = DW_UNSND (attr);
17297     }
17298   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17299   if (attr)
17300     {
17301       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17302     }
17303   name = dwarf2_name (die, cu);
17304   if (!name)
17305     {
17306       complaint (&symfile_complaints,
17307                  _("DW_AT_name missing from DW_TAG_base_type"));
17308     }
17309
17310   switch (encoding)
17311     {
17312       case DW_ATE_address:
17313         /* Turn DW_ATE_address into a void * pointer.  */
17314         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17315         type = init_pointer_type (objfile, bits, name, type);
17316         break;
17317       case DW_ATE_boolean:
17318         type = init_boolean_type (objfile, bits, 1, name);
17319         break;
17320       case DW_ATE_complex_float:
17321         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17322         type = init_complex_type (objfile, name, type);
17323         break;
17324       case DW_ATE_decimal_float:
17325         type = init_decfloat_type (objfile, bits, name);
17326         break;
17327       case DW_ATE_float:
17328         type = dwarf2_init_float_type (objfile, bits, name, name);
17329         break;
17330       case DW_ATE_signed:
17331         type = init_integer_type (objfile, bits, 0, name);
17332         break;
17333       case DW_ATE_unsigned:
17334         if (cu->language == language_fortran
17335             && name
17336             && startswith (name, "character("))
17337           type = init_character_type (objfile, bits, 1, name);
17338         else
17339           type = init_integer_type (objfile, bits, 1, name);
17340         break;
17341       case DW_ATE_signed_char:
17342         if (cu->language == language_ada || cu->language == language_m2
17343             || cu->language == language_pascal
17344             || cu->language == language_fortran)
17345           type = init_character_type (objfile, bits, 0, name);
17346         else
17347           type = init_integer_type (objfile, bits, 0, name);
17348         break;
17349       case DW_ATE_unsigned_char:
17350         if (cu->language == language_ada || cu->language == language_m2
17351             || cu->language == language_pascal
17352             || cu->language == language_fortran
17353             || cu->language == language_rust)
17354           type = init_character_type (objfile, bits, 1, name);
17355         else
17356           type = init_integer_type (objfile, bits, 1, name);
17357         break;
17358       case DW_ATE_UTF:
17359         {
17360           gdbarch *arch = get_objfile_arch (objfile);
17361
17362           if (bits == 16)
17363             type = builtin_type (arch)->builtin_char16;
17364           else if (bits == 32)
17365             type = builtin_type (arch)->builtin_char32;
17366           else
17367             {
17368               complaint (&symfile_complaints,
17369                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17370                          bits);
17371               type = init_integer_type (objfile, bits, 1, name);
17372             }
17373           return set_die_type (die, type, cu);
17374         }
17375         break;
17376
17377       default:
17378         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17379                    dwarf_type_encoding_name (encoding));
17380         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17381         break;
17382     }
17383
17384   if (name && strcmp (name, "char") == 0)
17385     TYPE_NOSIGN (type) = 1;
17386
17387   return set_die_type (die, type, cu);
17388 }
17389
17390 /* Parse dwarf attribute if it's a block, reference or constant and put the
17391    resulting value of the attribute into struct bound_prop.
17392    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17393
17394 static int
17395 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17396                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17397 {
17398   struct dwarf2_property_baton *baton;
17399   struct obstack *obstack = &cu->objfile->objfile_obstack;
17400
17401   if (attr == NULL || prop == NULL)
17402     return 0;
17403
17404   if (attr_form_is_block (attr))
17405     {
17406       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17407       baton->referenced_type = NULL;
17408       baton->locexpr.per_cu = cu->per_cu;
17409       baton->locexpr.size = DW_BLOCK (attr)->size;
17410       baton->locexpr.data = DW_BLOCK (attr)->data;
17411       prop->data.baton = baton;
17412       prop->kind = PROP_LOCEXPR;
17413       gdb_assert (prop->data.baton != NULL);
17414     }
17415   else if (attr_form_is_ref (attr))
17416     {
17417       struct dwarf2_cu *target_cu = cu;
17418       struct die_info *target_die;
17419       struct attribute *target_attr;
17420
17421       target_die = follow_die_ref (die, attr, &target_cu);
17422       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17423       if (target_attr == NULL)
17424         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17425                                    target_cu);
17426       if (target_attr == NULL)
17427         return 0;
17428
17429       switch (target_attr->name)
17430         {
17431           case DW_AT_location:
17432             if (attr_form_is_section_offset (target_attr))
17433               {
17434                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17435                 baton->referenced_type = die_type (target_die, target_cu);
17436                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17437                 prop->data.baton = baton;
17438                 prop->kind = PROP_LOCLIST;
17439                 gdb_assert (prop->data.baton != NULL);
17440               }
17441             else if (attr_form_is_block (target_attr))
17442               {
17443                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17444                 baton->referenced_type = die_type (target_die, target_cu);
17445                 baton->locexpr.per_cu = cu->per_cu;
17446                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17447                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17448                 prop->data.baton = baton;
17449                 prop->kind = PROP_LOCEXPR;
17450                 gdb_assert (prop->data.baton != NULL);
17451               }
17452             else
17453               {
17454                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17455                                                        "dynamic property");
17456                 return 0;
17457               }
17458             break;
17459           case DW_AT_data_member_location:
17460             {
17461               LONGEST offset;
17462
17463               if (!handle_data_member_location (target_die, target_cu,
17464                                                 &offset))
17465                 return 0;
17466
17467               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17468               baton->referenced_type = read_type_die (target_die->parent,
17469                                                       target_cu);
17470               baton->offset_info.offset = offset;
17471               baton->offset_info.type = die_type (target_die, target_cu);
17472               prop->data.baton = baton;
17473               prop->kind = PROP_ADDR_OFFSET;
17474               break;
17475             }
17476         }
17477     }
17478   else if (attr_form_is_constant (attr))
17479     {
17480       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17481       prop->kind = PROP_CONST;
17482     }
17483   else
17484     {
17485       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17486                                              dwarf2_name (die, cu));
17487       return 0;
17488     }
17489
17490   return 1;
17491 }
17492
17493 /* Read the given DW_AT_subrange DIE.  */
17494
17495 static struct type *
17496 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17497 {
17498   struct type *base_type, *orig_base_type;
17499   struct type *range_type;
17500   struct attribute *attr;
17501   struct dynamic_prop low, high;
17502   int low_default_is_valid;
17503   int high_bound_is_count = 0;
17504   const char *name;
17505   LONGEST negative_mask;
17506
17507   orig_base_type = die_type (die, cu);
17508   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17509      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17510      creating the range type, but we use the result of check_typedef
17511      when examining properties of the type.  */
17512   base_type = check_typedef (orig_base_type);
17513
17514   /* The die_type call above may have already set the type for this DIE.  */
17515   range_type = get_die_type (die, cu);
17516   if (range_type)
17517     return range_type;
17518
17519   low.kind = PROP_CONST;
17520   high.kind = PROP_CONST;
17521   high.data.const_val = 0;
17522
17523   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17524      omitting DW_AT_lower_bound.  */
17525   switch (cu->language)
17526     {
17527     case language_c:
17528     case language_cplus:
17529       low.data.const_val = 0;
17530       low_default_is_valid = 1;
17531       break;
17532     case language_fortran:
17533       low.data.const_val = 1;
17534       low_default_is_valid = 1;
17535       break;
17536     case language_d:
17537     case language_objc:
17538     case language_rust:
17539       low.data.const_val = 0;
17540       low_default_is_valid = (cu->header.version >= 4);
17541       break;
17542     case language_ada:
17543     case language_m2:
17544     case language_pascal:
17545       low.data.const_val = 1;
17546       low_default_is_valid = (cu->header.version >= 4);
17547       break;
17548     default:
17549       low.data.const_val = 0;
17550       low_default_is_valid = 0;
17551       break;
17552     }
17553
17554   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17555   if (attr)
17556     attr_to_dynamic_prop (attr, die, cu, &low);
17557   else if (!low_default_is_valid)
17558     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17559                                       "- DIE at 0x%x [in module %s]"),
17560                to_underlying (die->sect_off), objfile_name (cu->objfile));
17561
17562   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17563   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17564     {
17565       attr = dwarf2_attr (die, DW_AT_count, cu);
17566       if (attr_to_dynamic_prop (attr, die, cu, &high))
17567         {
17568           /* If bounds are constant do the final calculation here.  */
17569           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17570             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17571           else
17572             high_bound_is_count = 1;
17573         }
17574     }
17575
17576   /* Dwarf-2 specifications explicitly allows to create subrange types
17577      without specifying a base type.
17578      In that case, the base type must be set to the type of
17579      the lower bound, upper bound or count, in that order, if any of these
17580      three attributes references an object that has a type.
17581      If no base type is found, the Dwarf-2 specifications say that
17582      a signed integer type of size equal to the size of an address should
17583      be used.
17584      For the following C code: `extern char gdb_int [];'
17585      GCC produces an empty range DIE.
17586      FIXME: muller/2010-05-28: Possible references to object for low bound,
17587      high bound or count are not yet handled by this code.  */
17588   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17589     {
17590       struct objfile *objfile = cu->objfile;
17591       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17592       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17593       struct type *int_type = objfile_type (objfile)->builtin_int;
17594
17595       /* Test "int", "long int", and "long long int" objfile types,
17596          and select the first one having a size above or equal to the
17597          architecture address size.  */
17598       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17599         base_type = int_type;
17600       else
17601         {
17602           int_type = objfile_type (objfile)->builtin_long;
17603           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17604             base_type = int_type;
17605           else
17606             {
17607               int_type = objfile_type (objfile)->builtin_long_long;
17608               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17609                 base_type = int_type;
17610             }
17611         }
17612     }
17613
17614   /* Normally, the DWARF producers are expected to use a signed
17615      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17616      But this is unfortunately not always the case, as witnessed
17617      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17618      is used instead.  To work around that ambiguity, we treat
17619      the bounds as signed, and thus sign-extend their values, when
17620      the base type is signed.  */
17621   negative_mask =
17622     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17623   if (low.kind == PROP_CONST
17624       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17625     low.data.const_val |= negative_mask;
17626   if (high.kind == PROP_CONST
17627       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17628     high.data.const_val |= negative_mask;
17629
17630   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17631
17632   if (high_bound_is_count)
17633     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17634
17635   /* Ada expects an empty array on no boundary attributes.  */
17636   if (attr == NULL && cu->language != language_ada)
17637     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17638
17639   name = dwarf2_name (die, cu);
17640   if (name)
17641     TYPE_NAME (range_type) = name;
17642
17643   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17644   if (attr)
17645     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17646
17647   set_die_type (die, range_type, cu);
17648
17649   /* set_die_type should be already done.  */
17650   set_descriptive_type (range_type, die, cu);
17651
17652   return range_type;
17653 }
17654
17655 static struct type *
17656 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17657 {
17658   struct type *type;
17659
17660   /* For now, we only support the C meaning of an unspecified type: void.  */
17661
17662   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
17663   TYPE_NAME (type) = dwarf2_name (die, cu);
17664
17665   return set_die_type (die, type, cu);
17666 }
17667
17668 /* Read a single die and all its descendents.  Set the die's sibling
17669    field to NULL; set other fields in the die correctly, and set all
17670    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17671    location of the info_ptr after reading all of those dies.  PARENT
17672    is the parent of the die in question.  */
17673
17674 static struct die_info *
17675 read_die_and_children (const struct die_reader_specs *reader,
17676                        const gdb_byte *info_ptr,
17677                        const gdb_byte **new_info_ptr,
17678                        struct die_info *parent)
17679 {
17680   struct die_info *die;
17681   const gdb_byte *cur_ptr;
17682   int has_children;
17683
17684   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17685   if (die == NULL)
17686     {
17687       *new_info_ptr = cur_ptr;
17688       return NULL;
17689     }
17690   store_in_ref_table (die, reader->cu);
17691
17692   if (has_children)
17693     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17694   else
17695     {
17696       die->child = NULL;
17697       *new_info_ptr = cur_ptr;
17698     }
17699
17700   die->sibling = NULL;
17701   die->parent = parent;
17702   return die;
17703 }
17704
17705 /* Read a die, all of its descendents, and all of its siblings; set
17706    all of the fields of all of the dies correctly.  Arguments are as
17707    in read_die_and_children.  */
17708
17709 static struct die_info *
17710 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17711                          const gdb_byte *info_ptr,
17712                          const gdb_byte **new_info_ptr,
17713                          struct die_info *parent)
17714 {
17715   struct die_info *first_die, *last_sibling;
17716   const gdb_byte *cur_ptr;
17717
17718   cur_ptr = info_ptr;
17719   first_die = last_sibling = NULL;
17720
17721   while (1)
17722     {
17723       struct die_info *die
17724         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17725
17726       if (die == NULL)
17727         {
17728           *new_info_ptr = cur_ptr;
17729           return first_die;
17730         }
17731
17732       if (!first_die)
17733         first_die = die;
17734       else
17735         last_sibling->sibling = die;
17736
17737       last_sibling = die;
17738     }
17739 }
17740
17741 /* Read a die, all of its descendents, and all of its siblings; set
17742    all of the fields of all of the dies correctly.  Arguments are as
17743    in read_die_and_children.
17744    This the main entry point for reading a DIE and all its children.  */
17745
17746 static struct die_info *
17747 read_die_and_siblings (const struct die_reader_specs *reader,
17748                        const gdb_byte *info_ptr,
17749                        const gdb_byte **new_info_ptr,
17750                        struct die_info *parent)
17751 {
17752   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17753                                                   new_info_ptr, parent);
17754
17755   if (dwarf_die_debug)
17756     {
17757       fprintf_unfiltered (gdb_stdlog,
17758                           "Read die from %s@0x%x of %s:\n",
17759                           get_section_name (reader->die_section),
17760                           (unsigned) (info_ptr - reader->die_section->buffer),
17761                           bfd_get_filename (reader->abfd));
17762       dump_die (die, dwarf_die_debug);
17763     }
17764
17765   return die;
17766 }
17767
17768 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17769    attributes.
17770    The caller is responsible for filling in the extra attributes
17771    and updating (*DIEP)->num_attrs.
17772    Set DIEP to point to a newly allocated die with its information,
17773    except for its child, sibling, and parent fields.
17774    Set HAS_CHILDREN to tell whether the die has children or not.  */
17775
17776 static const gdb_byte *
17777 read_full_die_1 (const struct die_reader_specs *reader,
17778                  struct die_info **diep, const gdb_byte *info_ptr,
17779                  int *has_children, int num_extra_attrs)
17780 {
17781   unsigned int abbrev_number, bytes_read, i;
17782   struct abbrev_info *abbrev;
17783   struct die_info *die;
17784   struct dwarf2_cu *cu = reader->cu;
17785   bfd *abfd = reader->abfd;
17786
17787   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17788   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17789   info_ptr += bytes_read;
17790   if (!abbrev_number)
17791     {
17792       *diep = NULL;
17793       *has_children = 0;
17794       return info_ptr;
17795     }
17796
17797   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
17798   if (!abbrev)
17799     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17800            abbrev_number,
17801            bfd_get_filename (abfd));
17802
17803   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17804   die->sect_off = sect_off;
17805   die->tag = abbrev->tag;
17806   die->abbrev = abbrev_number;
17807
17808   /* Make the result usable.
17809      The caller needs to update num_attrs after adding the extra
17810      attributes.  */
17811   die->num_attrs = abbrev->num_attrs;
17812
17813   for (i = 0; i < abbrev->num_attrs; ++i)
17814     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17815                                info_ptr);
17816
17817   *diep = die;
17818   *has_children = abbrev->has_children;
17819   return info_ptr;
17820 }
17821
17822 /* Read a die and all its attributes.
17823    Set DIEP to point to a newly allocated die with its information,
17824    except for its child, sibling, and parent fields.
17825    Set HAS_CHILDREN to tell whether the die has children or not.  */
17826
17827 static const gdb_byte *
17828 read_full_die (const struct die_reader_specs *reader,
17829                struct die_info **diep, const gdb_byte *info_ptr,
17830                int *has_children)
17831 {
17832   const gdb_byte *result;
17833
17834   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17835
17836   if (dwarf_die_debug)
17837     {
17838       fprintf_unfiltered (gdb_stdlog,
17839                           "Read die from %s@0x%x of %s:\n",
17840                           get_section_name (reader->die_section),
17841                           (unsigned) (info_ptr - reader->die_section->buffer),
17842                           bfd_get_filename (reader->abfd));
17843       dump_die (*diep, dwarf_die_debug);
17844     }
17845
17846   return result;
17847 }
17848 \f
17849 /* Abbreviation tables.
17850
17851    In DWARF version 2, the description of the debugging information is
17852    stored in a separate .debug_abbrev section.  Before we read any
17853    dies from a section we read in all abbreviations and install them
17854    in a hash table.  */
17855
17856 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17857
17858 static struct abbrev_info *
17859 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
17860 {
17861   struct abbrev_info *abbrev;
17862
17863   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
17864   memset (abbrev, 0, sizeof (struct abbrev_info));
17865
17866   return abbrev;
17867 }
17868
17869 /* Add an abbreviation to the table.  */
17870
17871 static void
17872 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
17873                          unsigned int abbrev_number,
17874                          struct abbrev_info *abbrev)
17875 {
17876   unsigned int hash_number;
17877
17878   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17879   abbrev->next = abbrev_table->abbrevs[hash_number];
17880   abbrev_table->abbrevs[hash_number] = abbrev;
17881 }
17882
17883 /* Look up an abbrev in the table.
17884    Returns NULL if the abbrev is not found.  */
17885
17886 static struct abbrev_info *
17887 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
17888                             unsigned int abbrev_number)
17889 {
17890   unsigned int hash_number;
17891   struct abbrev_info *abbrev;
17892
17893   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17894   abbrev = abbrev_table->abbrevs[hash_number];
17895
17896   while (abbrev)
17897     {
17898       if (abbrev->number == abbrev_number)
17899         return abbrev;
17900       abbrev = abbrev->next;
17901     }
17902   return NULL;
17903 }
17904
17905 /* Read in an abbrev table.  */
17906
17907 static struct abbrev_table *
17908 abbrev_table_read_table (struct dwarf2_section_info *section,
17909                          sect_offset sect_off)
17910 {
17911   struct objfile *objfile = dwarf2_per_objfile->objfile;
17912   bfd *abfd = get_section_bfd_owner (section);
17913   struct abbrev_table *abbrev_table;
17914   const gdb_byte *abbrev_ptr;
17915   struct abbrev_info *cur_abbrev;
17916   unsigned int abbrev_number, bytes_read, abbrev_name;
17917   unsigned int abbrev_form;
17918   struct attr_abbrev *cur_attrs;
17919   unsigned int allocated_attrs;
17920
17921   abbrev_table = XNEW (struct abbrev_table);
17922   abbrev_table->sect_off = sect_off;
17923   obstack_init (&abbrev_table->abbrev_obstack);
17924   abbrev_table->abbrevs =
17925     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
17926                ABBREV_HASH_SIZE);
17927   memset (abbrev_table->abbrevs, 0,
17928           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
17929
17930   dwarf2_read_section (objfile, section);
17931   abbrev_ptr = section->buffer + to_underlying (sect_off);
17932   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17933   abbrev_ptr += bytes_read;
17934
17935   allocated_attrs = ATTR_ALLOC_CHUNK;
17936   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
17937
17938   /* Loop until we reach an abbrev number of 0.  */
17939   while (abbrev_number)
17940     {
17941       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
17942
17943       /* read in abbrev header */
17944       cur_abbrev->number = abbrev_number;
17945       cur_abbrev->tag
17946         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17947       abbrev_ptr += bytes_read;
17948       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
17949       abbrev_ptr += 1;
17950
17951       /* now read in declarations */
17952       for (;;)
17953         {
17954           LONGEST implicit_const;
17955
17956           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17957           abbrev_ptr += bytes_read;
17958           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17959           abbrev_ptr += bytes_read;
17960           if (abbrev_form == DW_FORM_implicit_const)
17961             {
17962               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
17963                                                    &bytes_read);
17964               abbrev_ptr += bytes_read;
17965             }
17966           else
17967             {
17968               /* Initialize it due to a false compiler warning.  */
17969               implicit_const = -1;
17970             }
17971
17972           if (abbrev_name == 0)
17973             break;
17974
17975           if (cur_abbrev->num_attrs == allocated_attrs)
17976             {
17977               allocated_attrs += ATTR_ALLOC_CHUNK;
17978               cur_attrs
17979                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
17980             }
17981
17982           cur_attrs[cur_abbrev->num_attrs].name
17983             = (enum dwarf_attribute) abbrev_name;
17984           cur_attrs[cur_abbrev->num_attrs].form
17985             = (enum dwarf_form) abbrev_form;
17986           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
17987           ++cur_abbrev->num_attrs;
17988         }
17989
17990       cur_abbrev->attrs =
17991         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
17992                    cur_abbrev->num_attrs);
17993       memcpy (cur_abbrev->attrs, cur_attrs,
17994               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
17995
17996       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
17997
17998       /* Get next abbreviation.
17999          Under Irix6 the abbreviations for a compilation unit are not
18000          always properly terminated with an abbrev number of 0.
18001          Exit loop if we encounter an abbreviation which we have
18002          already read (which means we are about to read the abbreviations
18003          for the next compile unit) or if the end of the abbreviation
18004          table is reached.  */
18005       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18006         break;
18007       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18008       abbrev_ptr += bytes_read;
18009       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
18010         break;
18011     }
18012
18013   xfree (cur_attrs);
18014   return abbrev_table;
18015 }
18016
18017 /* Free the resources held by ABBREV_TABLE.  */
18018
18019 static void
18020 abbrev_table_free (struct abbrev_table *abbrev_table)
18021 {
18022   obstack_free (&abbrev_table->abbrev_obstack, NULL);
18023   xfree (abbrev_table);
18024 }
18025
18026 /* Same as abbrev_table_free but as a cleanup.
18027    We pass in a pointer to the pointer to the table so that we can
18028    set the pointer to NULL when we're done.  It also simplifies
18029    build_type_psymtabs_1.  */
18030
18031 static void
18032 abbrev_table_free_cleanup (void *table_ptr)
18033 {
18034   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
18035
18036   if (*abbrev_table_ptr != NULL)
18037     abbrev_table_free (*abbrev_table_ptr);
18038   *abbrev_table_ptr = NULL;
18039 }
18040
18041 /* Read the abbrev table for CU from ABBREV_SECTION.  */
18042
18043 static void
18044 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
18045                      struct dwarf2_section_info *abbrev_section)
18046 {
18047   cu->abbrev_table =
18048     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
18049 }
18050
18051 /* Release the memory used by the abbrev table for a compilation unit.  */
18052
18053 static void
18054 dwarf2_free_abbrev_table (void *ptr_to_cu)
18055 {
18056   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
18057
18058   if (cu->abbrev_table != NULL)
18059     abbrev_table_free (cu->abbrev_table);
18060   /* Set this to NULL so that we SEGV if we try to read it later,
18061      and also because free_comp_unit verifies this is NULL.  */
18062   cu->abbrev_table = NULL;
18063 }
18064 \f
18065 /* Returns nonzero if TAG represents a type that we might generate a partial
18066    symbol for.  */
18067
18068 static int
18069 is_type_tag_for_partial (int tag)
18070 {
18071   switch (tag)
18072     {
18073 #if 0
18074     /* Some types that would be reasonable to generate partial symbols for,
18075        that we don't at present.  */
18076     case DW_TAG_array_type:
18077     case DW_TAG_file_type:
18078     case DW_TAG_ptr_to_member_type:
18079     case DW_TAG_set_type:
18080     case DW_TAG_string_type:
18081     case DW_TAG_subroutine_type:
18082 #endif
18083     case DW_TAG_base_type:
18084     case DW_TAG_class_type:
18085     case DW_TAG_interface_type:
18086     case DW_TAG_enumeration_type:
18087     case DW_TAG_structure_type:
18088     case DW_TAG_subrange_type:
18089     case DW_TAG_typedef:
18090     case DW_TAG_union_type:
18091       return 1;
18092     default:
18093       return 0;
18094     }
18095 }
18096
18097 /* Load all DIEs that are interesting for partial symbols into memory.  */
18098
18099 static struct partial_die_info *
18100 load_partial_dies (const struct die_reader_specs *reader,
18101                    const gdb_byte *info_ptr, int building_psymtab)
18102 {
18103   struct dwarf2_cu *cu = reader->cu;
18104   struct objfile *objfile = cu->objfile;
18105   struct partial_die_info *part_die;
18106   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18107   struct abbrev_info *abbrev;
18108   unsigned int bytes_read;
18109   unsigned int load_all = 0;
18110   int nesting_level = 1;
18111
18112   parent_die = NULL;
18113   last_die = NULL;
18114
18115   gdb_assert (cu->per_cu != NULL);
18116   if (cu->per_cu->load_all_dies)
18117     load_all = 1;
18118
18119   cu->partial_dies
18120     = htab_create_alloc_ex (cu->header.length / 12,
18121                             partial_die_hash,
18122                             partial_die_eq,
18123                             NULL,
18124                             &cu->comp_unit_obstack,
18125                             hashtab_obstack_allocate,
18126                             dummy_obstack_deallocate);
18127
18128   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18129
18130   while (1)
18131     {
18132       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
18133
18134       /* A NULL abbrev means the end of a series of children.  */
18135       if (abbrev == NULL)
18136         {
18137           if (--nesting_level == 0)
18138             {
18139               /* PART_DIE was probably the last thing allocated on the
18140                  comp_unit_obstack, so we could call obstack_free
18141                  here.  We don't do that because the waste is small,
18142                  and will be cleaned up when we're done with this
18143                  compilation unit.  This way, we're also more robust
18144                  against other users of the comp_unit_obstack.  */
18145               return first_die;
18146             }
18147           info_ptr += bytes_read;
18148           last_die = parent_die;
18149           parent_die = parent_die->die_parent;
18150           continue;
18151         }
18152
18153       /* Check for template arguments.  We never save these; if
18154          they're seen, we just mark the parent, and go on our way.  */
18155       if (parent_die != NULL
18156           && cu->language == language_cplus
18157           && (abbrev->tag == DW_TAG_template_type_param
18158               || abbrev->tag == DW_TAG_template_value_param))
18159         {
18160           parent_die->has_template_arguments = 1;
18161
18162           if (!load_all)
18163             {
18164               /* We don't need a partial DIE for the template argument.  */
18165               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18166               continue;
18167             }
18168         }
18169
18170       /* We only recurse into c++ subprograms looking for template arguments.
18171          Skip their other children.  */
18172       if (!load_all
18173           && cu->language == language_cplus
18174           && parent_die != NULL
18175           && parent_die->tag == DW_TAG_subprogram)
18176         {
18177           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18178           continue;
18179         }
18180
18181       /* Check whether this DIE is interesting enough to save.  Normally
18182          we would not be interested in members here, but there may be
18183          later variables referencing them via DW_AT_specification (for
18184          static members).  */
18185       if (!load_all
18186           && !is_type_tag_for_partial (abbrev->tag)
18187           && abbrev->tag != DW_TAG_constant
18188           && abbrev->tag != DW_TAG_enumerator
18189           && abbrev->tag != DW_TAG_subprogram
18190           && abbrev->tag != DW_TAG_lexical_block
18191           && abbrev->tag != DW_TAG_variable
18192           && abbrev->tag != DW_TAG_namespace
18193           && abbrev->tag != DW_TAG_module
18194           && abbrev->tag != DW_TAG_member
18195           && abbrev->tag != DW_TAG_imported_unit
18196           && abbrev->tag != DW_TAG_imported_declaration)
18197         {
18198           /* Otherwise we skip to the next sibling, if any.  */
18199           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18200           continue;
18201         }
18202
18203       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18204                                    info_ptr);
18205
18206       /* This two-pass algorithm for processing partial symbols has a
18207          high cost in cache pressure.  Thus, handle some simple cases
18208          here which cover the majority of C partial symbols.  DIEs
18209          which neither have specification tags in them, nor could have
18210          specification tags elsewhere pointing at them, can simply be
18211          processed and discarded.
18212
18213          This segment is also optional; scan_partial_symbols and
18214          add_partial_symbol will handle these DIEs if we chain
18215          them in normally.  When compilers which do not emit large
18216          quantities of duplicate debug information are more common,
18217          this code can probably be removed.  */
18218
18219       /* Any complete simple types at the top level (pretty much all
18220          of them, for a language without namespaces), can be processed
18221          directly.  */
18222       if (parent_die == NULL
18223           && part_die->has_specification == 0
18224           && part_die->is_declaration == 0
18225           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18226               || part_die->tag == DW_TAG_base_type
18227               || part_die->tag == DW_TAG_subrange_type))
18228         {
18229           if (building_psymtab && part_die->name != NULL)
18230             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18231                                  VAR_DOMAIN, LOC_TYPEDEF,
18232                                  &objfile->static_psymbols,
18233                                  0, cu->language, objfile);
18234           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18235           continue;
18236         }
18237
18238       /* The exception for DW_TAG_typedef with has_children above is
18239          a workaround of GCC PR debug/47510.  In the case of this complaint
18240          type_name_no_tag_or_error will error on such types later.
18241
18242          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18243          it could not find the child DIEs referenced later, this is checked
18244          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18245
18246       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18247         complaint (&symfile_complaints,
18248                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18249                      "- DIE at 0x%x [in module %s]"),
18250                    to_underlying (part_die->sect_off), objfile_name (objfile));
18251
18252       /* If we're at the second level, and we're an enumerator, and
18253          our parent has no specification (meaning possibly lives in a
18254          namespace elsewhere), then we can add the partial symbol now
18255          instead of queueing it.  */
18256       if (part_die->tag == DW_TAG_enumerator
18257           && parent_die != NULL
18258           && parent_die->die_parent == NULL
18259           && parent_die->tag == DW_TAG_enumeration_type
18260           && parent_die->has_specification == 0)
18261         {
18262           if (part_die->name == NULL)
18263             complaint (&symfile_complaints,
18264                        _("malformed enumerator DIE ignored"));
18265           else if (building_psymtab)
18266             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18267                                  VAR_DOMAIN, LOC_CONST,
18268                                  cu->language == language_cplus
18269                                  ? &objfile->global_psymbols
18270                                  : &objfile->static_psymbols,
18271                                  0, cu->language, objfile);
18272
18273           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18274           continue;
18275         }
18276
18277       /* We'll save this DIE so link it in.  */
18278       part_die->die_parent = parent_die;
18279       part_die->die_sibling = NULL;
18280       part_die->die_child = NULL;
18281
18282       if (last_die && last_die == parent_die)
18283         last_die->die_child = part_die;
18284       else if (last_die)
18285         last_die->die_sibling = part_die;
18286
18287       last_die = part_die;
18288
18289       if (first_die == NULL)
18290         first_die = part_die;
18291
18292       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18293          find interesting need to be in the hash table, because we
18294          also have the parent/sibling/child chains; only those that we
18295          might refer to by offset later during partial symbol reading.
18296
18297          For now this means things that might have be the target of a
18298          DW_AT_specification, DW_AT_abstract_origin, or
18299          DW_AT_extension.  DW_AT_extension will refer only to
18300          namespaces; DW_AT_abstract_origin refers to functions (and
18301          many things under the function DIE, but we do not recurse
18302          into function DIEs during partial symbol reading) and
18303          possibly variables as well; DW_AT_specification refers to
18304          declarations.  Declarations ought to have the DW_AT_declaration
18305          flag.  It happens that GCC forgets to put it in sometimes, but
18306          only for functions, not for types.
18307
18308          Adding more things than necessary to the hash table is harmless
18309          except for the performance cost.  Adding too few will result in
18310          wasted time in find_partial_die, when we reread the compilation
18311          unit with load_all_dies set.  */
18312
18313       if (load_all
18314           || abbrev->tag == DW_TAG_constant
18315           || abbrev->tag == DW_TAG_subprogram
18316           || abbrev->tag == DW_TAG_variable
18317           || abbrev->tag == DW_TAG_namespace
18318           || part_die->is_declaration)
18319         {
18320           void **slot;
18321
18322           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18323                                            to_underlying (part_die->sect_off),
18324                                            INSERT);
18325           *slot = part_die;
18326         }
18327
18328       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18329
18330       /* For some DIEs we want to follow their children (if any).  For C
18331          we have no reason to follow the children of structures; for other
18332          languages we have to, so that we can get at method physnames
18333          to infer fully qualified class names, for DW_AT_specification,
18334          and for C++ template arguments.  For C++, we also look one level
18335          inside functions to find template arguments (if the name of the
18336          function does not already contain the template arguments).
18337
18338          For Ada, we need to scan the children of subprograms and lexical
18339          blocks as well because Ada allows the definition of nested
18340          entities that could be interesting for the debugger, such as
18341          nested subprograms for instance.  */
18342       if (last_die->has_children
18343           && (load_all
18344               || last_die->tag == DW_TAG_namespace
18345               || last_die->tag == DW_TAG_module
18346               || last_die->tag == DW_TAG_enumeration_type
18347               || (cu->language == language_cplus
18348                   && last_die->tag == DW_TAG_subprogram
18349                   && (last_die->name == NULL
18350                       || strchr (last_die->name, '<') == NULL))
18351               || (cu->language != language_c
18352                   && (last_die->tag == DW_TAG_class_type
18353                       || last_die->tag == DW_TAG_interface_type
18354                       || last_die->tag == DW_TAG_structure_type
18355                       || last_die->tag == DW_TAG_union_type))
18356               || (cu->language == language_ada
18357                   && (last_die->tag == DW_TAG_subprogram
18358                       || last_die->tag == DW_TAG_lexical_block))))
18359         {
18360           nesting_level++;
18361           parent_die = last_die;
18362           continue;
18363         }
18364
18365       /* Otherwise we skip to the next sibling, if any.  */
18366       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18367
18368       /* Back to the top, do it again.  */
18369     }
18370 }
18371
18372 /* Read a minimal amount of information into the minimal die structure.  */
18373
18374 static const gdb_byte *
18375 read_partial_die (const struct die_reader_specs *reader,
18376                   struct partial_die_info *part_die,
18377                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18378                   const gdb_byte *info_ptr)
18379 {
18380   struct dwarf2_cu *cu = reader->cu;
18381   struct objfile *objfile = cu->objfile;
18382   const gdb_byte *buffer = reader->buffer;
18383   unsigned int i;
18384   struct attribute attr;
18385   int has_low_pc_attr = 0;
18386   int has_high_pc_attr = 0;
18387   int high_pc_relative = 0;
18388
18389   memset (part_die, 0, sizeof (struct partial_die_info));
18390
18391   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18392
18393   info_ptr += abbrev_len;
18394
18395   if (abbrev == NULL)
18396     return info_ptr;
18397
18398   part_die->tag = abbrev->tag;
18399   part_die->has_children = abbrev->has_children;
18400
18401   for (i = 0; i < abbrev->num_attrs; ++i)
18402     {
18403       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18404
18405       /* Store the data if it is of an attribute we want to keep in a
18406          partial symbol table.  */
18407       switch (attr.name)
18408         {
18409         case DW_AT_name:
18410           switch (part_die->tag)
18411             {
18412             case DW_TAG_compile_unit:
18413             case DW_TAG_partial_unit:
18414             case DW_TAG_type_unit:
18415               /* Compilation units have a DW_AT_name that is a filename, not
18416                  a source language identifier.  */
18417             case DW_TAG_enumeration_type:
18418             case DW_TAG_enumerator:
18419               /* These tags always have simple identifiers already; no need
18420                  to canonicalize them.  */
18421               part_die->name = DW_STRING (&attr);
18422               break;
18423             default:
18424               part_die->name
18425                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18426                                             &objfile->per_bfd->storage_obstack);
18427               break;
18428             }
18429           break;
18430         case DW_AT_linkage_name:
18431         case DW_AT_MIPS_linkage_name:
18432           /* Note that both forms of linkage name might appear.  We
18433              assume they will be the same, and we only store the last
18434              one we see.  */
18435           if (cu->language == language_ada)
18436             part_die->name = DW_STRING (&attr);
18437           part_die->linkage_name = DW_STRING (&attr);
18438           break;
18439         case DW_AT_low_pc:
18440           has_low_pc_attr = 1;
18441           part_die->lowpc = attr_value_as_address (&attr);
18442           break;
18443         case DW_AT_high_pc:
18444           has_high_pc_attr = 1;
18445           part_die->highpc = attr_value_as_address (&attr);
18446           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18447                 high_pc_relative = 1;
18448           break;
18449         case DW_AT_location:
18450           /* Support the .debug_loc offsets.  */
18451           if (attr_form_is_block (&attr))
18452             {
18453                part_die->d.locdesc = DW_BLOCK (&attr);
18454             }
18455           else if (attr_form_is_section_offset (&attr))
18456             {
18457               dwarf2_complex_location_expr_complaint ();
18458             }
18459           else
18460             {
18461               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18462                                                      "partial symbol information");
18463             }
18464           break;
18465         case DW_AT_external:
18466           part_die->is_external = DW_UNSND (&attr);
18467           break;
18468         case DW_AT_declaration:
18469           part_die->is_declaration = DW_UNSND (&attr);
18470           break;
18471         case DW_AT_type:
18472           part_die->has_type = 1;
18473           break;
18474         case DW_AT_abstract_origin:
18475         case DW_AT_specification:
18476         case DW_AT_extension:
18477           part_die->has_specification = 1;
18478           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18479           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18480                                    || cu->per_cu->is_dwz);
18481           break;
18482         case DW_AT_sibling:
18483           /* Ignore absolute siblings, they might point outside of
18484              the current compile unit.  */
18485           if (attr.form == DW_FORM_ref_addr)
18486             complaint (&symfile_complaints,
18487                        _("ignoring absolute DW_AT_sibling"));
18488           else
18489             {
18490               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18491               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18492
18493               if (sibling_ptr < info_ptr)
18494                 complaint (&symfile_complaints,
18495                            _("DW_AT_sibling points backwards"));
18496               else if (sibling_ptr > reader->buffer_end)
18497                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18498               else
18499                 part_die->sibling = sibling_ptr;
18500             }
18501           break;
18502         case DW_AT_byte_size:
18503           part_die->has_byte_size = 1;
18504           break;
18505         case DW_AT_const_value:
18506           part_die->has_const_value = 1;
18507           break;
18508         case DW_AT_calling_convention:
18509           /* DWARF doesn't provide a way to identify a program's source-level
18510              entry point.  DW_AT_calling_convention attributes are only meant
18511              to describe functions' calling conventions.
18512
18513              However, because it's a necessary piece of information in
18514              Fortran, and before DWARF 4 DW_CC_program was the only
18515              piece of debugging information whose definition refers to
18516              a 'main program' at all, several compilers marked Fortran
18517              main programs with DW_CC_program --- even when those
18518              functions use the standard calling conventions.
18519
18520              Although DWARF now specifies a way to provide this
18521              information, we support this practice for backward
18522              compatibility.  */
18523           if (DW_UNSND (&attr) == DW_CC_program
18524               && cu->language == language_fortran)
18525             part_die->main_subprogram = 1;
18526           break;
18527         case DW_AT_inline:
18528           if (DW_UNSND (&attr) == DW_INL_inlined
18529               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18530             part_die->may_be_inlined = 1;
18531           break;
18532
18533         case DW_AT_import:
18534           if (part_die->tag == DW_TAG_imported_unit)
18535             {
18536               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18537               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18538                                   || cu->per_cu->is_dwz);
18539             }
18540           break;
18541
18542         case DW_AT_main_subprogram:
18543           part_die->main_subprogram = DW_UNSND (&attr);
18544           break;
18545
18546         default:
18547           break;
18548         }
18549     }
18550
18551   if (high_pc_relative)
18552     part_die->highpc += part_die->lowpc;
18553
18554   if (has_low_pc_attr && has_high_pc_attr)
18555     {
18556       /* When using the GNU linker, .gnu.linkonce. sections are used to
18557          eliminate duplicate copies of functions and vtables and such.
18558          The linker will arbitrarily choose one and discard the others.
18559          The AT_*_pc values for such functions refer to local labels in
18560          these sections.  If the section from that file was discarded, the
18561          labels are not in the output, so the relocs get a value of 0.
18562          If this is a discarded function, mark the pc bounds as invalid,
18563          so that GDB will ignore it.  */
18564       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18565         {
18566           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18567
18568           complaint (&symfile_complaints,
18569                      _("DW_AT_low_pc %s is zero "
18570                        "for DIE at 0x%x [in module %s]"),
18571                      paddress (gdbarch, part_die->lowpc),
18572                      to_underlying (part_die->sect_off), objfile_name (objfile));
18573         }
18574       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18575       else if (part_die->lowpc >= part_die->highpc)
18576         {
18577           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18578
18579           complaint (&symfile_complaints,
18580                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18581                        "for DIE at 0x%x [in module %s]"),
18582                      paddress (gdbarch, part_die->lowpc),
18583                      paddress (gdbarch, part_die->highpc),
18584                      to_underlying (part_die->sect_off),
18585                      objfile_name (objfile));
18586         }
18587       else
18588         part_die->has_pc_info = 1;
18589     }
18590
18591   return info_ptr;
18592 }
18593
18594 /* Find a cached partial DIE at OFFSET in CU.  */
18595
18596 static struct partial_die_info *
18597 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18598 {
18599   struct partial_die_info *lookup_die = NULL;
18600   struct partial_die_info part_die;
18601
18602   part_die.sect_off = sect_off;
18603   lookup_die = ((struct partial_die_info *)
18604                 htab_find_with_hash (cu->partial_dies, &part_die,
18605                                      to_underlying (sect_off)));
18606
18607   return lookup_die;
18608 }
18609
18610 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18611    except in the case of .debug_types DIEs which do not reference
18612    outside their CU (they do however referencing other types via
18613    DW_FORM_ref_sig8).  */
18614
18615 static struct partial_die_info *
18616 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18617 {
18618   struct objfile *objfile = cu->objfile;
18619   struct dwarf2_per_cu_data *per_cu = NULL;
18620   struct partial_die_info *pd = NULL;
18621
18622   if (offset_in_dwz == cu->per_cu->is_dwz
18623       && offset_in_cu_p (&cu->header, sect_off))
18624     {
18625       pd = find_partial_die_in_comp_unit (sect_off, cu);
18626       if (pd != NULL)
18627         return pd;
18628       /* We missed recording what we needed.
18629          Load all dies and try again.  */
18630       per_cu = cu->per_cu;
18631     }
18632   else
18633     {
18634       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18635       if (cu->per_cu->is_debug_types)
18636         {
18637           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18638                    " external reference to offset 0x%x [in module %s].\n"),
18639                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18640                  bfd_get_filename (objfile->obfd));
18641         }
18642       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18643                                                  objfile);
18644
18645       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18646         load_partial_comp_unit (per_cu);
18647
18648       per_cu->cu->last_used = 0;
18649       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18650     }
18651
18652   /* If we didn't find it, and not all dies have been loaded,
18653      load them all and try again.  */
18654
18655   if (pd == NULL && per_cu->load_all_dies == 0)
18656     {
18657       per_cu->load_all_dies = 1;
18658
18659       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18660          THIS_CU->cu may already be in use.  So we can't just free it and
18661          replace its DIEs with the ones we read in.  Instead, we leave those
18662          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18663          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18664          set.  */
18665       load_partial_comp_unit (per_cu);
18666
18667       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18668     }
18669
18670   if (pd == NULL)
18671     internal_error (__FILE__, __LINE__,
18672                     _("could not find partial DIE 0x%x "
18673                       "in cache [from module %s]\n"),
18674                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18675   return pd;
18676 }
18677
18678 /* See if we can figure out if the class lives in a namespace.  We do
18679    this by looking for a member function; its demangled name will
18680    contain namespace info, if there is any.  */
18681
18682 static void
18683 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18684                                   struct dwarf2_cu *cu)
18685 {
18686   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18687      what template types look like, because the demangler
18688      frequently doesn't give the same name as the debug info.  We
18689      could fix this by only using the demangled name to get the
18690      prefix (but see comment in read_structure_type).  */
18691
18692   struct partial_die_info *real_pdi;
18693   struct partial_die_info *child_pdi;
18694
18695   /* If this DIE (this DIE's specification, if any) has a parent, then
18696      we should not do this.  We'll prepend the parent's fully qualified
18697      name when we create the partial symbol.  */
18698
18699   real_pdi = struct_pdi;
18700   while (real_pdi->has_specification)
18701     real_pdi = find_partial_die (real_pdi->spec_offset,
18702                                  real_pdi->spec_is_dwz, cu);
18703
18704   if (real_pdi->die_parent != NULL)
18705     return;
18706
18707   for (child_pdi = struct_pdi->die_child;
18708        child_pdi != NULL;
18709        child_pdi = child_pdi->die_sibling)
18710     {
18711       if (child_pdi->tag == DW_TAG_subprogram
18712           && child_pdi->linkage_name != NULL)
18713         {
18714           char *actual_class_name
18715             = language_class_name_from_physname (cu->language_defn,
18716                                                  child_pdi->linkage_name);
18717           if (actual_class_name != NULL)
18718             {
18719               struct_pdi->name
18720                 = ((const char *)
18721                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18722                                   actual_class_name,
18723                                   strlen (actual_class_name)));
18724               xfree (actual_class_name);
18725             }
18726           break;
18727         }
18728     }
18729 }
18730
18731 /* Adjust PART_DIE before generating a symbol for it.  This function
18732    may set the is_external flag or change the DIE's name.  */
18733
18734 static void
18735 fixup_partial_die (struct partial_die_info *part_die,
18736                    struct dwarf2_cu *cu)
18737 {
18738   /* Once we've fixed up a die, there's no point in doing so again.
18739      This also avoids a memory leak if we were to call
18740      guess_partial_die_structure_name multiple times.  */
18741   if (part_die->fixup_called)
18742     return;
18743
18744   /* If we found a reference attribute and the DIE has no name, try
18745      to find a name in the referred to DIE.  */
18746
18747   if (part_die->name == NULL && part_die->has_specification)
18748     {
18749       struct partial_die_info *spec_die;
18750
18751       spec_die = find_partial_die (part_die->spec_offset,
18752                                    part_die->spec_is_dwz, cu);
18753
18754       fixup_partial_die (spec_die, cu);
18755
18756       if (spec_die->name)
18757         {
18758           part_die->name = spec_die->name;
18759
18760           /* Copy DW_AT_external attribute if it is set.  */
18761           if (spec_die->is_external)
18762             part_die->is_external = spec_die->is_external;
18763         }
18764     }
18765
18766   /* Set default names for some unnamed DIEs.  */
18767
18768   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18769     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18770
18771   /* If there is no parent die to provide a namespace, and there are
18772      children, see if we can determine the namespace from their linkage
18773      name.  */
18774   if (cu->language == language_cplus
18775       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18776       && part_die->die_parent == NULL
18777       && part_die->has_children
18778       && (part_die->tag == DW_TAG_class_type
18779           || part_die->tag == DW_TAG_structure_type
18780           || part_die->tag == DW_TAG_union_type))
18781     guess_partial_die_structure_name (part_die, cu);
18782
18783   /* GCC might emit a nameless struct or union that has a linkage
18784      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18785   if (part_die->name == NULL
18786       && (part_die->tag == DW_TAG_class_type
18787           || part_die->tag == DW_TAG_interface_type
18788           || part_die->tag == DW_TAG_structure_type
18789           || part_die->tag == DW_TAG_union_type)
18790       && part_die->linkage_name != NULL)
18791     {
18792       char *demangled;
18793
18794       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18795       if (demangled)
18796         {
18797           const char *base;
18798
18799           /* Strip any leading namespaces/classes, keep only the base name.
18800              DW_AT_name for named DIEs does not contain the prefixes.  */
18801           base = strrchr (demangled, ':');
18802           if (base && base > demangled && base[-1] == ':')
18803             base++;
18804           else
18805             base = demangled;
18806
18807           part_die->name
18808             = ((const char *)
18809                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18810                               base, strlen (base)));
18811           xfree (demangled);
18812         }
18813     }
18814
18815   part_die->fixup_called = 1;
18816 }
18817
18818 /* Read an attribute value described by an attribute form.  */
18819
18820 static const gdb_byte *
18821 read_attribute_value (const struct die_reader_specs *reader,
18822                       struct attribute *attr, unsigned form,
18823                       LONGEST implicit_const, const gdb_byte *info_ptr)
18824 {
18825   struct dwarf2_cu *cu = reader->cu;
18826   struct objfile *objfile = cu->objfile;
18827   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18828   bfd *abfd = reader->abfd;
18829   struct comp_unit_head *cu_header = &cu->header;
18830   unsigned int bytes_read;
18831   struct dwarf_block *blk;
18832
18833   attr->form = (enum dwarf_form) form;
18834   switch (form)
18835     {
18836     case DW_FORM_ref_addr:
18837       if (cu->header.version == 2)
18838         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18839       else
18840         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18841                                        &cu->header, &bytes_read);
18842       info_ptr += bytes_read;
18843       break;
18844     case DW_FORM_GNU_ref_alt:
18845       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18846       info_ptr += bytes_read;
18847       break;
18848     case DW_FORM_addr:
18849       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18850       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18851       info_ptr += bytes_read;
18852       break;
18853     case DW_FORM_block2:
18854       blk = dwarf_alloc_block (cu);
18855       blk->size = read_2_bytes (abfd, info_ptr);
18856       info_ptr += 2;
18857       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18858       info_ptr += blk->size;
18859       DW_BLOCK (attr) = blk;
18860       break;
18861     case DW_FORM_block4:
18862       blk = dwarf_alloc_block (cu);
18863       blk->size = read_4_bytes (abfd, info_ptr);
18864       info_ptr += 4;
18865       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18866       info_ptr += blk->size;
18867       DW_BLOCK (attr) = blk;
18868       break;
18869     case DW_FORM_data2:
18870       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18871       info_ptr += 2;
18872       break;
18873     case DW_FORM_data4:
18874       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18875       info_ptr += 4;
18876       break;
18877     case DW_FORM_data8:
18878       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18879       info_ptr += 8;
18880       break;
18881     case DW_FORM_data16:
18882       blk = dwarf_alloc_block (cu);
18883       blk->size = 16;
18884       blk->data = read_n_bytes (abfd, info_ptr, 16);
18885       info_ptr += 16;
18886       DW_BLOCK (attr) = blk;
18887       break;
18888     case DW_FORM_sec_offset:
18889       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18890       info_ptr += bytes_read;
18891       break;
18892     case DW_FORM_string:
18893       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18894       DW_STRING_IS_CANONICAL (attr) = 0;
18895       info_ptr += bytes_read;
18896       break;
18897     case DW_FORM_strp:
18898       if (!cu->per_cu->is_dwz)
18899         {
18900           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
18901                                                    &bytes_read);
18902           DW_STRING_IS_CANONICAL (attr) = 0;
18903           info_ptr += bytes_read;
18904           break;
18905         }
18906       /* FALLTHROUGH */
18907     case DW_FORM_line_strp:
18908       if (!cu->per_cu->is_dwz)
18909         {
18910           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
18911                                                         cu_header, &bytes_read);
18912           DW_STRING_IS_CANONICAL (attr) = 0;
18913           info_ptr += bytes_read;
18914           break;
18915         }
18916       /* FALLTHROUGH */
18917     case DW_FORM_GNU_strp_alt:
18918       {
18919         struct dwz_file *dwz = dwarf2_get_dwz_file ();
18920         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18921                                           &bytes_read);
18922
18923         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
18924         DW_STRING_IS_CANONICAL (attr) = 0;
18925         info_ptr += bytes_read;
18926       }
18927       break;
18928     case DW_FORM_exprloc:
18929     case DW_FORM_block:
18930       blk = dwarf_alloc_block (cu);
18931       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18932       info_ptr += bytes_read;
18933       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18934       info_ptr += blk->size;
18935       DW_BLOCK (attr) = blk;
18936       break;
18937     case DW_FORM_block1:
18938       blk = dwarf_alloc_block (cu);
18939       blk->size = read_1_byte (abfd, info_ptr);
18940       info_ptr += 1;
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_data1:
18946       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18947       info_ptr += 1;
18948       break;
18949     case DW_FORM_flag:
18950       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18951       info_ptr += 1;
18952       break;
18953     case DW_FORM_flag_present:
18954       DW_UNSND (attr) = 1;
18955       break;
18956     case DW_FORM_sdata:
18957       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18958       info_ptr += bytes_read;
18959       break;
18960     case DW_FORM_udata:
18961       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18962       info_ptr += bytes_read;
18963       break;
18964     case DW_FORM_ref1:
18965       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18966                          + read_1_byte (abfd, info_ptr));
18967       info_ptr += 1;
18968       break;
18969     case DW_FORM_ref2:
18970       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18971                          + read_2_bytes (abfd, info_ptr));
18972       info_ptr += 2;
18973       break;
18974     case DW_FORM_ref4:
18975       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18976                          + read_4_bytes (abfd, info_ptr));
18977       info_ptr += 4;
18978       break;
18979     case DW_FORM_ref8:
18980       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18981                          + read_8_bytes (abfd, info_ptr));
18982       info_ptr += 8;
18983       break;
18984     case DW_FORM_ref_sig8:
18985       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18986       info_ptr += 8;
18987       break;
18988     case DW_FORM_ref_udata:
18989       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18990                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
18991       info_ptr += bytes_read;
18992       break;
18993     case DW_FORM_indirect:
18994       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18995       info_ptr += bytes_read;
18996       if (form == DW_FORM_implicit_const)
18997         {
18998           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18999           info_ptr += bytes_read;
19000         }
19001       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19002                                        info_ptr);
19003       break;
19004     case DW_FORM_implicit_const:
19005       DW_SND (attr) = implicit_const;
19006       break;
19007     case DW_FORM_GNU_addr_index:
19008       if (reader->dwo_file == NULL)
19009         {
19010           /* For now flag a hard error.
19011              Later we can turn this into a complaint.  */
19012           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19013                  dwarf_form_name (form),
19014                  bfd_get_filename (abfd));
19015         }
19016       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19017       info_ptr += bytes_read;
19018       break;
19019     case DW_FORM_GNU_str_index:
19020       if (reader->dwo_file == NULL)
19021         {
19022           /* For now flag a hard error.
19023              Later we can turn this into a complaint if warranted.  */
19024           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19025                  dwarf_form_name (form),
19026                  bfd_get_filename (abfd));
19027         }
19028       {
19029         ULONGEST str_index =
19030           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19031
19032         DW_STRING (attr) = read_str_index (reader, str_index);
19033         DW_STRING_IS_CANONICAL (attr) = 0;
19034         info_ptr += bytes_read;
19035       }
19036       break;
19037     default:
19038       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19039              dwarf_form_name (form),
19040              bfd_get_filename (abfd));
19041     }
19042
19043   /* Super hack.  */
19044   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19045     attr->form = DW_FORM_GNU_ref_alt;
19046
19047   /* We have seen instances where the compiler tried to emit a byte
19048      size attribute of -1 which ended up being encoded as an unsigned
19049      0xffffffff.  Although 0xffffffff is technically a valid size value,
19050      an object of this size seems pretty unlikely so we can relatively
19051      safely treat these cases as if the size attribute was invalid and
19052      treat them as zero by default.  */
19053   if (attr->name == DW_AT_byte_size
19054       && form == DW_FORM_data4
19055       && DW_UNSND (attr) >= 0xffffffff)
19056     {
19057       complaint
19058         (&symfile_complaints,
19059          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19060          hex_string (DW_UNSND (attr)));
19061       DW_UNSND (attr) = 0;
19062     }
19063
19064   return info_ptr;
19065 }
19066
19067 /* Read an attribute described by an abbreviated attribute.  */
19068
19069 static const gdb_byte *
19070 read_attribute (const struct die_reader_specs *reader,
19071                 struct attribute *attr, struct attr_abbrev *abbrev,
19072                 const gdb_byte *info_ptr)
19073 {
19074   attr->name = abbrev->name;
19075   return read_attribute_value (reader, attr, abbrev->form,
19076                                abbrev->implicit_const, info_ptr);
19077 }
19078
19079 /* Read dwarf information from a buffer.  */
19080
19081 static unsigned int
19082 read_1_byte (bfd *abfd, const gdb_byte *buf)
19083 {
19084   return bfd_get_8 (abfd, buf);
19085 }
19086
19087 static int
19088 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19089 {
19090   return bfd_get_signed_8 (abfd, buf);
19091 }
19092
19093 static unsigned int
19094 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19095 {
19096   return bfd_get_16 (abfd, buf);
19097 }
19098
19099 static int
19100 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19101 {
19102   return bfd_get_signed_16 (abfd, buf);
19103 }
19104
19105 static unsigned int
19106 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19107 {
19108   return bfd_get_32 (abfd, buf);
19109 }
19110
19111 static int
19112 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19113 {
19114   return bfd_get_signed_32 (abfd, buf);
19115 }
19116
19117 static ULONGEST
19118 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19119 {
19120   return bfd_get_64 (abfd, buf);
19121 }
19122
19123 static CORE_ADDR
19124 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19125               unsigned int *bytes_read)
19126 {
19127   struct comp_unit_head *cu_header = &cu->header;
19128   CORE_ADDR retval = 0;
19129
19130   if (cu_header->signed_addr_p)
19131     {
19132       switch (cu_header->addr_size)
19133         {
19134         case 2:
19135           retval = bfd_get_signed_16 (abfd, buf);
19136           break;
19137         case 4:
19138           retval = bfd_get_signed_32 (abfd, buf);
19139           break;
19140         case 8:
19141           retval = bfd_get_signed_64 (abfd, buf);
19142           break;
19143         default:
19144           internal_error (__FILE__, __LINE__,
19145                           _("read_address: bad switch, signed [in module %s]"),
19146                           bfd_get_filename (abfd));
19147         }
19148     }
19149   else
19150     {
19151       switch (cu_header->addr_size)
19152         {
19153         case 2:
19154           retval = bfd_get_16 (abfd, buf);
19155           break;
19156         case 4:
19157           retval = bfd_get_32 (abfd, buf);
19158           break;
19159         case 8:
19160           retval = bfd_get_64 (abfd, buf);
19161           break;
19162         default:
19163           internal_error (__FILE__, __LINE__,
19164                           _("read_address: bad switch, "
19165                             "unsigned [in module %s]"),
19166                           bfd_get_filename (abfd));
19167         }
19168     }
19169
19170   *bytes_read = cu_header->addr_size;
19171   return retval;
19172 }
19173
19174 /* Read the initial length from a section.  The (draft) DWARF 3
19175    specification allows the initial length to take up either 4 bytes
19176    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19177    bytes describe the length and all offsets will be 8 bytes in length
19178    instead of 4.
19179
19180    An older, non-standard 64-bit format is also handled by this
19181    function.  The older format in question stores the initial length
19182    as an 8-byte quantity without an escape value.  Lengths greater
19183    than 2^32 aren't very common which means that the initial 4 bytes
19184    is almost always zero.  Since a length value of zero doesn't make
19185    sense for the 32-bit format, this initial zero can be considered to
19186    be an escape value which indicates the presence of the older 64-bit
19187    format.  As written, the code can't detect (old format) lengths
19188    greater than 4GB.  If it becomes necessary to handle lengths
19189    somewhat larger than 4GB, we could allow other small values (such
19190    as the non-sensical values of 1, 2, and 3) to also be used as
19191    escape values indicating the presence of the old format.
19192
19193    The value returned via bytes_read should be used to increment the
19194    relevant pointer after calling read_initial_length().
19195
19196    [ Note:  read_initial_length() and read_offset() are based on the
19197      document entitled "DWARF Debugging Information Format", revision
19198      3, draft 8, dated November 19, 2001.  This document was obtained
19199      from:
19200
19201         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19202
19203      This document is only a draft and is subject to change.  (So beware.)
19204
19205      Details regarding the older, non-standard 64-bit format were
19206      determined empirically by examining 64-bit ELF files produced by
19207      the SGI toolchain on an IRIX 6.5 machine.
19208
19209      - Kevin, July 16, 2002
19210    ] */
19211
19212 static LONGEST
19213 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19214 {
19215   LONGEST length = bfd_get_32 (abfd, buf);
19216
19217   if (length == 0xffffffff)
19218     {
19219       length = bfd_get_64 (abfd, buf + 4);
19220       *bytes_read = 12;
19221     }
19222   else if (length == 0)
19223     {
19224       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19225       length = bfd_get_64 (abfd, buf);
19226       *bytes_read = 8;
19227     }
19228   else
19229     {
19230       *bytes_read = 4;
19231     }
19232
19233   return length;
19234 }
19235
19236 /* Cover function for read_initial_length.
19237    Returns the length of the object at BUF, and stores the size of the
19238    initial length in *BYTES_READ and stores the size that offsets will be in
19239    *OFFSET_SIZE.
19240    If the initial length size is not equivalent to that specified in
19241    CU_HEADER then issue a complaint.
19242    This is useful when reading non-comp-unit headers.  */
19243
19244 static LONGEST
19245 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19246                                         const struct comp_unit_head *cu_header,
19247                                         unsigned int *bytes_read,
19248                                         unsigned int *offset_size)
19249 {
19250   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19251
19252   gdb_assert (cu_header->initial_length_size == 4
19253               || cu_header->initial_length_size == 8
19254               || cu_header->initial_length_size == 12);
19255
19256   if (cu_header->initial_length_size != *bytes_read)
19257     complaint (&symfile_complaints,
19258                _("intermixed 32-bit and 64-bit DWARF sections"));
19259
19260   *offset_size = (*bytes_read == 4) ? 4 : 8;
19261   return length;
19262 }
19263
19264 /* Read an offset from the data stream.  The size of the offset is
19265    given by cu_header->offset_size.  */
19266
19267 static LONGEST
19268 read_offset (bfd *abfd, const gdb_byte *buf,
19269              const struct comp_unit_head *cu_header,
19270              unsigned int *bytes_read)
19271 {
19272   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19273
19274   *bytes_read = cu_header->offset_size;
19275   return offset;
19276 }
19277
19278 /* Read an offset from the data stream.  */
19279
19280 static LONGEST
19281 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19282 {
19283   LONGEST retval = 0;
19284
19285   switch (offset_size)
19286     {
19287     case 4:
19288       retval = bfd_get_32 (abfd, buf);
19289       break;
19290     case 8:
19291       retval = bfd_get_64 (abfd, buf);
19292       break;
19293     default:
19294       internal_error (__FILE__, __LINE__,
19295                       _("read_offset_1: bad switch [in module %s]"),
19296                       bfd_get_filename (abfd));
19297     }
19298
19299   return retval;
19300 }
19301
19302 static const gdb_byte *
19303 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19304 {
19305   /* If the size of a host char is 8 bits, we can return a pointer
19306      to the buffer, otherwise we have to copy the data to a buffer
19307      allocated on the temporary obstack.  */
19308   gdb_assert (HOST_CHAR_BIT == 8);
19309   return buf;
19310 }
19311
19312 static const char *
19313 read_direct_string (bfd *abfd, const gdb_byte *buf,
19314                     unsigned int *bytes_read_ptr)
19315 {
19316   /* If the size of a host char is 8 bits, we can return a pointer
19317      to the string, otherwise we have to copy the string to a buffer
19318      allocated on the temporary obstack.  */
19319   gdb_assert (HOST_CHAR_BIT == 8);
19320   if (*buf == '\0')
19321     {
19322       *bytes_read_ptr = 1;
19323       return NULL;
19324     }
19325   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19326   return (const char *) buf;
19327 }
19328
19329 /* Return pointer to string at section SECT offset STR_OFFSET with error
19330    reporting strings FORM_NAME and SECT_NAME.  */
19331
19332 static const char *
19333 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
19334                                      struct dwarf2_section_info *sect,
19335                                      const char *form_name,
19336                                      const char *sect_name)
19337 {
19338   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
19339   if (sect->buffer == NULL)
19340     error (_("%s used without %s section [in module %s]"),
19341            form_name, sect_name, bfd_get_filename (abfd));
19342   if (str_offset >= sect->size)
19343     error (_("%s pointing outside of %s section [in module %s]"),
19344            form_name, sect_name, bfd_get_filename (abfd));
19345   gdb_assert (HOST_CHAR_BIT == 8);
19346   if (sect->buffer[str_offset] == '\0')
19347     return NULL;
19348   return (const char *) (sect->buffer + str_offset);
19349 }
19350
19351 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19352
19353 static const char *
19354 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
19355 {
19356   return read_indirect_string_at_offset_from (abfd, str_offset,
19357                                               &dwarf2_per_objfile->str,
19358                                               "DW_FORM_strp", ".debug_str");
19359 }
19360
19361 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19362
19363 static const char *
19364 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
19365 {
19366   return read_indirect_string_at_offset_from (abfd, str_offset,
19367                                               &dwarf2_per_objfile->line_str,
19368                                               "DW_FORM_line_strp",
19369                                               ".debug_line_str");
19370 }
19371
19372 /* Read a string at offset STR_OFFSET in the .debug_str section from
19373    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19374    the string consists of a single NUL byte, return NULL; otherwise
19375    return a pointer to the string.  */
19376
19377 static const char *
19378 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
19379 {
19380   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
19381
19382   if (dwz->str.buffer == NULL)
19383     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19384              "section [in module %s]"),
19385            bfd_get_filename (dwz->dwz_bfd));
19386   if (str_offset >= dwz->str.size)
19387     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19388              ".debug_str section [in module %s]"),
19389            bfd_get_filename (dwz->dwz_bfd));
19390   gdb_assert (HOST_CHAR_BIT == 8);
19391   if (dwz->str.buffer[str_offset] == '\0')
19392     return NULL;
19393   return (const char *) (dwz->str.buffer + str_offset);
19394 }
19395
19396 /* Return pointer to string at .debug_str offset as read from BUF.
19397    BUF is assumed to be in a compilation unit described by CU_HEADER.
19398    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19399
19400 static const char *
19401 read_indirect_string (bfd *abfd, const gdb_byte *buf,
19402                       const struct comp_unit_head *cu_header,
19403                       unsigned int *bytes_read_ptr)
19404 {
19405   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19406
19407   return read_indirect_string_at_offset (abfd, str_offset);
19408 }
19409
19410 /* Return pointer to string at .debug_line_str offset as read from BUF.
19411    BUF is assumed to be in a compilation unit described by CU_HEADER.
19412    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19413
19414 static const char *
19415 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
19416                            const struct comp_unit_head *cu_header,
19417                            unsigned int *bytes_read_ptr)
19418 {
19419   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19420
19421   return read_indirect_line_string_at_offset (abfd, str_offset);
19422 }
19423
19424 ULONGEST
19425 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19426                           unsigned int *bytes_read_ptr)
19427 {
19428   ULONGEST result;
19429   unsigned int num_read;
19430   int shift;
19431   unsigned char byte;
19432
19433   result = 0;
19434   shift = 0;
19435   num_read = 0;
19436   while (1)
19437     {
19438       byte = bfd_get_8 (abfd, buf);
19439       buf++;
19440       num_read++;
19441       result |= ((ULONGEST) (byte & 127) << shift);
19442       if ((byte & 128) == 0)
19443         {
19444           break;
19445         }
19446       shift += 7;
19447     }
19448   *bytes_read_ptr = num_read;
19449   return result;
19450 }
19451
19452 static LONGEST
19453 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19454                     unsigned int *bytes_read_ptr)
19455 {
19456   LONGEST result;
19457   int shift, num_read;
19458   unsigned char byte;
19459
19460   result = 0;
19461   shift = 0;
19462   num_read = 0;
19463   while (1)
19464     {
19465       byte = bfd_get_8 (abfd, buf);
19466       buf++;
19467       num_read++;
19468       result |= ((LONGEST) (byte & 127) << shift);
19469       shift += 7;
19470       if ((byte & 128) == 0)
19471         {
19472           break;
19473         }
19474     }
19475   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19476     result |= -(((LONGEST) 1) << shift);
19477   *bytes_read_ptr = num_read;
19478   return result;
19479 }
19480
19481 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19482    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19483    ADDR_SIZE is the size of addresses from the CU header.  */
19484
19485 static CORE_ADDR
19486 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
19487 {
19488   struct objfile *objfile = dwarf2_per_objfile->objfile;
19489   bfd *abfd = objfile->obfd;
19490   const gdb_byte *info_ptr;
19491
19492   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19493   if (dwarf2_per_objfile->addr.buffer == NULL)
19494     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19495            objfile_name (objfile));
19496   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19497     error (_("DW_FORM_addr_index pointing outside of "
19498              ".debug_addr section [in module %s]"),
19499            objfile_name (objfile));
19500   info_ptr = (dwarf2_per_objfile->addr.buffer
19501               + addr_base + addr_index * addr_size);
19502   if (addr_size == 4)
19503     return bfd_get_32 (abfd, info_ptr);
19504   else
19505     return bfd_get_64 (abfd, info_ptr);
19506 }
19507
19508 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19509
19510 static CORE_ADDR
19511 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19512 {
19513   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
19514 }
19515
19516 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19517
19518 static CORE_ADDR
19519 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19520                              unsigned int *bytes_read)
19521 {
19522   bfd *abfd = cu->objfile->obfd;
19523   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19524
19525   return read_addr_index (cu, addr_index);
19526 }
19527
19528 /* Data structure to pass results from dwarf2_read_addr_index_reader
19529    back to dwarf2_read_addr_index.  */
19530
19531 struct dwarf2_read_addr_index_data
19532 {
19533   ULONGEST addr_base;
19534   int addr_size;
19535 };
19536
19537 /* die_reader_func for dwarf2_read_addr_index.  */
19538
19539 static void
19540 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19541                                const gdb_byte *info_ptr,
19542                                struct die_info *comp_unit_die,
19543                                int has_children,
19544                                void *data)
19545 {
19546   struct dwarf2_cu *cu = reader->cu;
19547   struct dwarf2_read_addr_index_data *aidata =
19548     (struct dwarf2_read_addr_index_data *) data;
19549
19550   aidata->addr_base = cu->addr_base;
19551   aidata->addr_size = cu->header.addr_size;
19552 }
19553
19554 /* Given an index in .debug_addr, fetch the value.
19555    NOTE: This can be called during dwarf expression evaluation,
19556    long after the debug information has been read, and thus per_cu->cu
19557    may no longer exist.  */
19558
19559 CORE_ADDR
19560 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19561                         unsigned int addr_index)
19562 {
19563   struct objfile *objfile = per_cu->objfile;
19564   struct dwarf2_cu *cu = per_cu->cu;
19565   ULONGEST addr_base;
19566   int addr_size;
19567
19568   /* This is intended to be called from outside this file.  */
19569   dw2_setup (objfile);
19570
19571   /* We need addr_base and addr_size.
19572      If we don't have PER_CU->cu, we have to get it.
19573      Nasty, but the alternative is storing the needed info in PER_CU,
19574      which at this point doesn't seem justified: it's not clear how frequently
19575      it would get used and it would increase the size of every PER_CU.
19576      Entry points like dwarf2_per_cu_addr_size do a similar thing
19577      so we're not in uncharted territory here.
19578      Alas we need to be a bit more complicated as addr_base is contained
19579      in the DIE.
19580
19581      We don't need to read the entire CU(/TU).
19582      We just need the header and top level die.
19583
19584      IWBN to use the aging mechanism to let us lazily later discard the CU.
19585      For now we skip this optimization.  */
19586
19587   if (cu != NULL)
19588     {
19589       addr_base = cu->addr_base;
19590       addr_size = cu->header.addr_size;
19591     }
19592   else
19593     {
19594       struct dwarf2_read_addr_index_data aidata;
19595
19596       /* Note: We can't use init_cutu_and_read_dies_simple here,
19597          we need addr_base.  */
19598       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19599                                dwarf2_read_addr_index_reader, &aidata);
19600       addr_base = aidata.addr_base;
19601       addr_size = aidata.addr_size;
19602     }
19603
19604   return read_addr_index_1 (addr_index, addr_base, addr_size);
19605 }
19606
19607 /* Given a DW_FORM_GNU_str_index, fetch the string.
19608    This is only used by the Fission support.  */
19609
19610 static const char *
19611 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19612 {
19613   struct objfile *objfile = dwarf2_per_objfile->objfile;
19614   const char *objf_name = objfile_name (objfile);
19615   bfd *abfd = objfile->obfd;
19616   struct dwarf2_cu *cu = reader->cu;
19617   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19618   struct dwarf2_section_info *str_offsets_section =
19619     &reader->dwo_file->sections.str_offsets;
19620   const gdb_byte *info_ptr;
19621   ULONGEST str_offset;
19622   static const char form_name[] = "DW_FORM_GNU_str_index";
19623
19624   dwarf2_read_section (objfile, str_section);
19625   dwarf2_read_section (objfile, str_offsets_section);
19626   if (str_section->buffer == NULL)
19627     error (_("%s used without .debug_str.dwo section"
19628              " in CU at offset 0x%x [in module %s]"),
19629            form_name, to_underlying (cu->header.sect_off), objf_name);
19630   if (str_offsets_section->buffer == NULL)
19631     error (_("%s used without .debug_str_offsets.dwo section"
19632              " in CU at offset 0x%x [in module %s]"),
19633            form_name, to_underlying (cu->header.sect_off), objf_name);
19634   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19635     error (_("%s pointing outside of .debug_str_offsets.dwo"
19636              " section in CU at offset 0x%x [in module %s]"),
19637            form_name, to_underlying (cu->header.sect_off), objf_name);
19638   info_ptr = (str_offsets_section->buffer
19639               + str_index * cu->header.offset_size);
19640   if (cu->header.offset_size == 4)
19641     str_offset = bfd_get_32 (abfd, info_ptr);
19642   else
19643     str_offset = bfd_get_64 (abfd, info_ptr);
19644   if (str_offset >= str_section->size)
19645     error (_("Offset from %s pointing outside of"
19646              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19647            form_name, to_underlying (cu->header.sect_off), objf_name);
19648   return (const char *) (str_section->buffer + str_offset);
19649 }
19650
19651 /* Return the length of an LEB128 number in BUF.  */
19652
19653 static int
19654 leb128_size (const gdb_byte *buf)
19655 {
19656   const gdb_byte *begin = buf;
19657   gdb_byte byte;
19658
19659   while (1)
19660     {
19661       byte = *buf++;
19662       if ((byte & 128) == 0)
19663         return buf - begin;
19664     }
19665 }
19666
19667 static void
19668 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19669 {
19670   switch (lang)
19671     {
19672     case DW_LANG_C89:
19673     case DW_LANG_C99:
19674     case DW_LANG_C11:
19675     case DW_LANG_C:
19676     case DW_LANG_UPC:
19677       cu->language = language_c;
19678       break;
19679     case DW_LANG_Java:
19680     case DW_LANG_C_plus_plus:
19681     case DW_LANG_C_plus_plus_11:
19682     case DW_LANG_C_plus_plus_14:
19683       cu->language = language_cplus;
19684       break;
19685     case DW_LANG_D:
19686       cu->language = language_d;
19687       break;
19688     case DW_LANG_Fortran77:
19689     case DW_LANG_Fortran90:
19690     case DW_LANG_Fortran95:
19691     case DW_LANG_Fortran03:
19692     case DW_LANG_Fortran08:
19693       cu->language = language_fortran;
19694       break;
19695     case DW_LANG_Go:
19696       cu->language = language_go;
19697       break;
19698     case DW_LANG_Mips_Assembler:
19699       cu->language = language_asm;
19700       break;
19701     case DW_LANG_Ada83:
19702     case DW_LANG_Ada95:
19703       cu->language = language_ada;
19704       break;
19705     case DW_LANG_Modula2:
19706       cu->language = language_m2;
19707       break;
19708     case DW_LANG_Pascal83:
19709       cu->language = language_pascal;
19710       break;
19711     case DW_LANG_ObjC:
19712       cu->language = language_objc;
19713       break;
19714     case DW_LANG_Rust:
19715     case DW_LANG_Rust_old:
19716       cu->language = language_rust;
19717       break;
19718     case DW_LANG_Cobol74:
19719     case DW_LANG_Cobol85:
19720     default:
19721       cu->language = language_minimal;
19722       break;
19723     }
19724   cu->language_defn = language_def (cu->language);
19725 }
19726
19727 /* Return the named attribute or NULL if not there.  */
19728
19729 static struct attribute *
19730 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19731 {
19732   for (;;)
19733     {
19734       unsigned int i;
19735       struct attribute *spec = NULL;
19736
19737       for (i = 0; i < die->num_attrs; ++i)
19738         {
19739           if (die->attrs[i].name == name)
19740             return &die->attrs[i];
19741           if (die->attrs[i].name == DW_AT_specification
19742               || die->attrs[i].name == DW_AT_abstract_origin)
19743             spec = &die->attrs[i];
19744         }
19745
19746       if (!spec)
19747         break;
19748
19749       die = follow_die_ref (die, spec, &cu);
19750     }
19751
19752   return NULL;
19753 }
19754
19755 /* Return the named attribute or NULL if not there,
19756    but do not follow DW_AT_specification, etc.
19757    This is for use in contexts where we're reading .debug_types dies.
19758    Following DW_AT_specification, DW_AT_abstract_origin will take us
19759    back up the chain, and we want to go down.  */
19760
19761 static struct attribute *
19762 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19763 {
19764   unsigned int i;
19765
19766   for (i = 0; i < die->num_attrs; ++i)
19767     if (die->attrs[i].name == name)
19768       return &die->attrs[i];
19769
19770   return NULL;
19771 }
19772
19773 /* Return the string associated with a string-typed attribute, or NULL if it
19774    is either not found or is of an incorrect type.  */
19775
19776 static const char *
19777 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19778 {
19779   struct attribute *attr;
19780   const char *str = NULL;
19781
19782   attr = dwarf2_attr (die, name, cu);
19783
19784   if (attr != NULL)
19785     {
19786       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19787           || attr->form == DW_FORM_string
19788           || attr->form == DW_FORM_GNU_str_index
19789           || attr->form == DW_FORM_GNU_strp_alt)
19790         str = DW_STRING (attr);
19791       else
19792         complaint (&symfile_complaints,
19793                    _("string type expected for attribute %s for "
19794                      "DIE at 0x%x in module %s"),
19795                    dwarf_attr_name (name), to_underlying (die->sect_off),
19796                    objfile_name (cu->objfile));
19797     }
19798
19799   return str;
19800 }
19801
19802 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19803    and holds a non-zero value.  This function should only be used for
19804    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19805
19806 static int
19807 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19808 {
19809   struct attribute *attr = dwarf2_attr (die, name, cu);
19810
19811   return (attr && DW_UNSND (attr));
19812 }
19813
19814 static int
19815 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19816 {
19817   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19818      which value is non-zero.  However, we have to be careful with
19819      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19820      (via dwarf2_flag_true_p) follows this attribute.  So we may
19821      end up accidently finding a declaration attribute that belongs
19822      to a different DIE referenced by the specification attribute,
19823      even though the given DIE does not have a declaration attribute.  */
19824   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19825           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19826 }
19827
19828 /* Return the die giving the specification for DIE, if there is
19829    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19830    containing the return value on output.  If there is no
19831    specification, but there is an abstract origin, that is
19832    returned.  */
19833
19834 static struct die_info *
19835 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19836 {
19837   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19838                                              *spec_cu);
19839
19840   if (spec_attr == NULL)
19841     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19842
19843   if (spec_attr == NULL)
19844     return NULL;
19845   else
19846     return follow_die_ref (die, spec_attr, spec_cu);
19847 }
19848
19849 /* Stub for free_line_header to match void * callback types.  */
19850
19851 static void
19852 free_line_header_voidp (void *arg)
19853 {
19854   struct line_header *lh = (struct line_header *) arg;
19855
19856   delete lh;
19857 }
19858
19859 void
19860 line_header::add_include_dir (const char *include_dir)
19861 {
19862   if (dwarf_line_debug >= 2)
19863     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19864                         include_dirs.size () + 1, include_dir);
19865
19866   include_dirs.push_back (include_dir);
19867 }
19868
19869 void
19870 line_header::add_file_name (const char *name,
19871                             dir_index d_index,
19872                             unsigned int mod_time,
19873                             unsigned int length)
19874 {
19875   if (dwarf_line_debug >= 2)
19876     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19877                         (unsigned) file_names.size () + 1, name);
19878
19879   file_names.emplace_back (name, d_index, mod_time, length);
19880 }
19881
19882 /* A convenience function to find the proper .debug_line section for a CU.  */
19883
19884 static struct dwarf2_section_info *
19885 get_debug_line_section (struct dwarf2_cu *cu)
19886 {
19887   struct dwarf2_section_info *section;
19888
19889   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19890      DWO file.  */
19891   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19892     section = &cu->dwo_unit->dwo_file->sections.line;
19893   else if (cu->per_cu->is_dwz)
19894     {
19895       struct dwz_file *dwz = dwarf2_get_dwz_file ();
19896
19897       section = &dwz->line;
19898     }
19899   else
19900     section = &dwarf2_per_objfile->line;
19901
19902   return section;
19903 }
19904
19905 /* Read directory or file name entry format, starting with byte of
19906    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19907    entries count and the entries themselves in the described entry
19908    format.  */
19909
19910 static void
19911 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
19912                         struct line_header *lh,
19913                         const struct comp_unit_head *cu_header,
19914                         void (*callback) (struct line_header *lh,
19915                                           const char *name,
19916                                           dir_index d_index,
19917                                           unsigned int mod_time,
19918                                           unsigned int length))
19919 {
19920   gdb_byte format_count, formati;
19921   ULONGEST data_count, datai;
19922   const gdb_byte *buf = *bufp;
19923   const gdb_byte *format_header_data;
19924   unsigned int bytes_read;
19925
19926   format_count = read_1_byte (abfd, buf);
19927   buf += 1;
19928   format_header_data = buf;
19929   for (formati = 0; formati < format_count; formati++)
19930     {
19931       read_unsigned_leb128 (abfd, buf, &bytes_read);
19932       buf += bytes_read;
19933       read_unsigned_leb128 (abfd, buf, &bytes_read);
19934       buf += bytes_read;
19935     }
19936
19937   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19938   buf += bytes_read;
19939   for (datai = 0; datai < data_count; datai++)
19940     {
19941       const gdb_byte *format = format_header_data;
19942       struct file_entry fe;
19943
19944       for (formati = 0; formati < format_count; formati++)
19945         {
19946           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19947           format += bytes_read;
19948
19949           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19950           format += bytes_read;
19951
19952           gdb::optional<const char *> string;
19953           gdb::optional<unsigned int> uint;
19954
19955           switch (form)
19956             {
19957             case DW_FORM_string:
19958               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19959               buf += bytes_read;
19960               break;
19961
19962             case DW_FORM_line_strp:
19963               string.emplace (read_indirect_line_string (abfd, buf,
19964                                                          cu_header,
19965                                                          &bytes_read));
19966               buf += bytes_read;
19967               break;
19968
19969             case DW_FORM_data1:
19970               uint.emplace (read_1_byte (abfd, buf));
19971               buf += 1;
19972               break;
19973
19974             case DW_FORM_data2:
19975               uint.emplace (read_2_bytes (abfd, buf));
19976               buf += 2;
19977               break;
19978
19979             case DW_FORM_data4:
19980               uint.emplace (read_4_bytes (abfd, buf));
19981               buf += 4;
19982               break;
19983
19984             case DW_FORM_data8:
19985               uint.emplace (read_8_bytes (abfd, buf));
19986               buf += 8;
19987               break;
19988
19989             case DW_FORM_udata:
19990               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
19991               buf += bytes_read;
19992               break;
19993
19994             case DW_FORM_block:
19995               /* It is valid only for DW_LNCT_timestamp which is ignored by
19996                  current GDB.  */
19997               break;
19998             }
19999
20000           switch (content_type)
20001             {
20002             case DW_LNCT_path:
20003               if (string.has_value ())
20004                 fe.name = *string;
20005               break;
20006             case DW_LNCT_directory_index:
20007               if (uint.has_value ())
20008                 fe.d_index = (dir_index) *uint;
20009               break;
20010             case DW_LNCT_timestamp:
20011               if (uint.has_value ())
20012                 fe.mod_time = *uint;
20013               break;
20014             case DW_LNCT_size:
20015               if (uint.has_value ())
20016                 fe.length = *uint;
20017               break;
20018             case DW_LNCT_MD5:
20019               break;
20020             default:
20021               complaint (&symfile_complaints,
20022                          _("Unknown format content type %s"),
20023                          pulongest (content_type));
20024             }
20025         }
20026
20027       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20028     }
20029
20030   *bufp = buf;
20031 }
20032
20033 /* Read the statement program header starting at OFFSET in
20034    .debug_line, or .debug_line.dwo.  Return a pointer
20035    to a struct line_header, allocated using xmalloc.
20036    Returns NULL if there is a problem reading the header, e.g., if it
20037    has a version we don't understand.
20038
20039    NOTE: the strings in the include directory and file name tables of
20040    the returned object point into the dwarf line section buffer,
20041    and must not be freed.  */
20042
20043 static line_header_up
20044 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20045 {
20046   const gdb_byte *line_ptr;
20047   unsigned int bytes_read, offset_size;
20048   int i;
20049   const char *cur_dir, *cur_file;
20050   struct dwarf2_section_info *section;
20051   bfd *abfd;
20052
20053   section = get_debug_line_section (cu);
20054   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20055   if (section->buffer == NULL)
20056     {
20057       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20058         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20059       else
20060         complaint (&symfile_complaints, _("missing .debug_line section"));
20061       return 0;
20062     }
20063
20064   /* We can't do this until we know the section is non-empty.
20065      Only then do we know we have such a section.  */
20066   abfd = get_section_bfd_owner (section);
20067
20068   /* Make sure that at least there's room for the total_length field.
20069      That could be 12 bytes long, but we're just going to fudge that.  */
20070   if (to_underlying (sect_off) + 4 >= section->size)
20071     {
20072       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20073       return 0;
20074     }
20075
20076   line_header_up lh (new line_header ());
20077
20078   lh->sect_off = sect_off;
20079   lh->offset_in_dwz = cu->per_cu->is_dwz;
20080
20081   line_ptr = section->buffer + to_underlying (sect_off);
20082
20083   /* Read in the header.  */
20084   lh->total_length =
20085     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20086                                             &bytes_read, &offset_size);
20087   line_ptr += bytes_read;
20088   if (line_ptr + lh->total_length > (section->buffer + section->size))
20089     {
20090       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20091       return 0;
20092     }
20093   lh->statement_program_end = line_ptr + lh->total_length;
20094   lh->version = read_2_bytes (abfd, line_ptr);
20095   line_ptr += 2;
20096   if (lh->version > 5)
20097     {
20098       /* This is a version we don't understand.  The format could have
20099          changed in ways we don't handle properly so just punt.  */
20100       complaint (&symfile_complaints,
20101                  _("unsupported version in .debug_line section"));
20102       return NULL;
20103     }
20104   if (lh->version >= 5)
20105     {
20106       gdb_byte segment_selector_size;
20107
20108       /* Skip address size.  */
20109       read_1_byte (abfd, line_ptr);
20110       line_ptr += 1;
20111
20112       segment_selector_size = read_1_byte (abfd, line_ptr);
20113       line_ptr += 1;
20114       if (segment_selector_size != 0)
20115         {
20116           complaint (&symfile_complaints,
20117                      _("unsupported segment selector size %u "
20118                        "in .debug_line section"),
20119                      segment_selector_size);
20120           return NULL;
20121         }
20122     }
20123   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20124   line_ptr += offset_size;
20125   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20126   line_ptr += 1;
20127   if (lh->version >= 4)
20128     {
20129       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20130       line_ptr += 1;
20131     }
20132   else
20133     lh->maximum_ops_per_instruction = 1;
20134
20135   if (lh->maximum_ops_per_instruction == 0)
20136     {
20137       lh->maximum_ops_per_instruction = 1;
20138       complaint (&symfile_complaints,
20139                  _("invalid maximum_ops_per_instruction "
20140                    "in `.debug_line' section"));
20141     }
20142
20143   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20144   line_ptr += 1;
20145   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20146   line_ptr += 1;
20147   lh->line_range = read_1_byte (abfd, line_ptr);
20148   line_ptr += 1;
20149   lh->opcode_base = read_1_byte (abfd, line_ptr);
20150   line_ptr += 1;
20151   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20152
20153   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20154   for (i = 1; i < lh->opcode_base; ++i)
20155     {
20156       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20157       line_ptr += 1;
20158     }
20159
20160   if (lh->version >= 5)
20161     {
20162       /* Read directory table.  */
20163       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20164                               [] (struct line_header *lh, const char *name,
20165                                   dir_index d_index, unsigned int mod_time,
20166                                   unsigned int length)
20167         {
20168           lh->add_include_dir (name);
20169         });
20170
20171       /* Read file name table.  */
20172       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20173                               [] (struct line_header *lh, const char *name,
20174                                   dir_index d_index, unsigned int mod_time,
20175                                   unsigned int length)
20176         {
20177           lh->add_file_name (name, d_index, mod_time, length);
20178         });
20179     }
20180   else
20181     {
20182       /* Read directory table.  */
20183       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20184         {
20185           line_ptr += bytes_read;
20186           lh->add_include_dir (cur_dir);
20187         }
20188       line_ptr += bytes_read;
20189
20190       /* Read file name table.  */
20191       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20192         {
20193           unsigned int mod_time, length;
20194           dir_index d_index;
20195
20196           line_ptr += bytes_read;
20197           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20198           line_ptr += bytes_read;
20199           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20200           line_ptr += bytes_read;
20201           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20202           line_ptr += bytes_read;
20203
20204           lh->add_file_name (cur_file, d_index, mod_time, length);
20205         }
20206       line_ptr += bytes_read;
20207     }
20208   lh->statement_program_start = line_ptr;
20209
20210   if (line_ptr > (section->buffer + section->size))
20211     complaint (&symfile_complaints,
20212                _("line number info header doesn't "
20213                  "fit in `.debug_line' section"));
20214
20215   return lh;
20216 }
20217
20218 /* Subroutine of dwarf_decode_lines to simplify it.
20219    Return the file name of the psymtab for included file FILE_INDEX
20220    in line header LH of PST.
20221    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20222    If space for the result is malloc'd, it will be freed by a cleanup.
20223    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
20224
20225    The function creates dangling cleanup registration.  */
20226
20227 static const char *
20228 psymtab_include_file_name (const struct line_header *lh, int file_index,
20229                            const struct partial_symtab *pst,
20230                            const char *comp_dir)
20231 {
20232   const file_entry &fe = lh->file_names[file_index];
20233   const char *include_name = fe.name;
20234   const char *include_name_to_compare = include_name;
20235   const char *pst_filename;
20236   char *copied_name = NULL;
20237   int file_is_pst;
20238
20239   const char *dir_name = fe.include_dir (lh);
20240
20241   if (!IS_ABSOLUTE_PATH (include_name)
20242       && (dir_name != NULL || comp_dir != NULL))
20243     {
20244       /* Avoid creating a duplicate psymtab for PST.
20245          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20246          Before we do the comparison, however, we need to account
20247          for DIR_NAME and COMP_DIR.
20248          First prepend dir_name (if non-NULL).  If we still don't
20249          have an absolute path prepend comp_dir (if non-NULL).
20250          However, the directory we record in the include-file's
20251          psymtab does not contain COMP_DIR (to match the
20252          corresponding symtab(s)).
20253
20254          Example:
20255
20256          bash$ cd /tmp
20257          bash$ gcc -g ./hello.c
20258          include_name = "hello.c"
20259          dir_name = "."
20260          DW_AT_comp_dir = comp_dir = "/tmp"
20261          DW_AT_name = "./hello.c"
20262
20263       */
20264
20265       if (dir_name != NULL)
20266         {
20267           char *tem = concat (dir_name, SLASH_STRING,
20268                               include_name, (char *)NULL);
20269
20270           make_cleanup (xfree, tem);
20271           include_name = tem;
20272           include_name_to_compare = include_name;
20273         }
20274       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20275         {
20276           char *tem = concat (comp_dir, SLASH_STRING,
20277                               include_name, (char *)NULL);
20278
20279           make_cleanup (xfree, tem);
20280           include_name_to_compare = tem;
20281         }
20282     }
20283
20284   pst_filename = pst->filename;
20285   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20286     {
20287       copied_name = concat (pst->dirname, SLASH_STRING,
20288                             pst_filename, (char *)NULL);
20289       pst_filename = copied_name;
20290     }
20291
20292   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20293
20294   if (copied_name != NULL)
20295     xfree (copied_name);
20296
20297   if (file_is_pst)
20298     return NULL;
20299   return include_name;
20300 }
20301
20302 /* State machine to track the state of the line number program.  */
20303
20304 class lnp_state_machine
20305 {
20306 public:
20307   /* Initialize a machine state for the start of a line number
20308      program.  */
20309   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20310
20311   file_entry *current_file ()
20312   {
20313     /* lh->file_names is 0-based, but the file name numbers in the
20314        statement program are 1-based.  */
20315     return m_line_header->file_name_at (m_file);
20316   }
20317
20318   /* Record the line in the state machine.  END_SEQUENCE is true if
20319      we're processing the end of a sequence.  */
20320   void record_line (bool end_sequence);
20321
20322   /* Check address and if invalid nop-out the rest of the lines in this
20323      sequence.  */
20324   void check_line_address (struct dwarf2_cu *cu,
20325                            const gdb_byte *line_ptr,
20326                            CORE_ADDR lowpc, CORE_ADDR address);
20327
20328   void handle_set_discriminator (unsigned int discriminator)
20329   {
20330     m_discriminator = discriminator;
20331     m_line_has_non_zero_discriminator |= discriminator != 0;
20332   }
20333
20334   /* Handle DW_LNE_set_address.  */
20335   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20336   {
20337     m_op_index = 0;
20338     address += baseaddr;
20339     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20340   }
20341
20342   /* Handle DW_LNS_advance_pc.  */
20343   void handle_advance_pc (CORE_ADDR adjust);
20344
20345   /* Handle a special opcode.  */
20346   void handle_special_opcode (unsigned char op_code);
20347
20348   /* Handle DW_LNS_advance_line.  */
20349   void handle_advance_line (int line_delta)
20350   {
20351     advance_line (line_delta);
20352   }
20353
20354   /* Handle DW_LNS_set_file.  */
20355   void handle_set_file (file_name_index file);
20356
20357   /* Handle DW_LNS_negate_stmt.  */
20358   void handle_negate_stmt ()
20359   {
20360     m_is_stmt = !m_is_stmt;
20361   }
20362
20363   /* Handle DW_LNS_const_add_pc.  */
20364   void handle_const_add_pc ();
20365
20366   /* Handle DW_LNS_fixed_advance_pc.  */
20367   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20368   {
20369     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20370     m_op_index = 0;
20371   }
20372
20373   /* Handle DW_LNS_copy.  */
20374   void handle_copy ()
20375   {
20376     record_line (false);
20377     m_discriminator = 0;
20378   }
20379
20380   /* Handle DW_LNE_end_sequence.  */
20381   void handle_end_sequence ()
20382   {
20383     m_record_line_callback = ::record_line;
20384   }
20385
20386 private:
20387   /* Advance the line by LINE_DELTA.  */
20388   void advance_line (int line_delta)
20389   {
20390     m_line += line_delta;
20391
20392     if (line_delta != 0)
20393       m_line_has_non_zero_discriminator = m_discriminator != 0;
20394   }
20395
20396   gdbarch *m_gdbarch;
20397
20398   /* True if we're recording lines.
20399      Otherwise we're building partial symtabs and are just interested in
20400      finding include files mentioned by the line number program.  */
20401   bool m_record_lines_p;
20402
20403   /* The line number header.  */
20404   line_header *m_line_header;
20405
20406   /* These are part of the standard DWARF line number state machine,
20407      and initialized according to the DWARF spec.  */
20408
20409   unsigned char m_op_index = 0;
20410   /* The line table index (1-based) of the current file.  */
20411   file_name_index m_file = (file_name_index) 1;
20412   unsigned int m_line = 1;
20413
20414   /* These are initialized in the constructor.  */
20415
20416   CORE_ADDR m_address;
20417   bool m_is_stmt;
20418   unsigned int m_discriminator;
20419
20420   /* Additional bits of state we need to track.  */
20421
20422   /* The last file that we called dwarf2_start_subfile for.
20423      This is only used for TLLs.  */
20424   unsigned int m_last_file = 0;
20425   /* The last file a line number was recorded for.  */
20426   struct subfile *m_last_subfile = NULL;
20427
20428   /* The function to call to record a line.  */
20429   record_line_ftype *m_record_line_callback = NULL;
20430
20431   /* The last line number that was recorded, used to coalesce
20432      consecutive entries for the same line.  This can happen, for
20433      example, when discriminators are present.  PR 17276.  */
20434   unsigned int m_last_line = 0;
20435   bool m_line_has_non_zero_discriminator = false;
20436 };
20437
20438 void
20439 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20440 {
20441   CORE_ADDR addr_adj = (((m_op_index + adjust)
20442                          / m_line_header->maximum_ops_per_instruction)
20443                         * m_line_header->minimum_instruction_length);
20444   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20445   m_op_index = ((m_op_index + adjust)
20446                 % m_line_header->maximum_ops_per_instruction);
20447 }
20448
20449 void
20450 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20451 {
20452   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20453   CORE_ADDR addr_adj = (((m_op_index
20454                           + (adj_opcode / m_line_header->line_range))
20455                          / m_line_header->maximum_ops_per_instruction)
20456                         * m_line_header->minimum_instruction_length);
20457   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20458   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20459                 % m_line_header->maximum_ops_per_instruction);
20460
20461   int line_delta = (m_line_header->line_base
20462                     + (adj_opcode % m_line_header->line_range));
20463   advance_line (line_delta);
20464   record_line (false);
20465   m_discriminator = 0;
20466 }
20467
20468 void
20469 lnp_state_machine::handle_set_file (file_name_index file)
20470 {
20471   m_file = file;
20472
20473   const file_entry *fe = current_file ();
20474   if (fe == NULL)
20475     dwarf2_debug_line_missing_file_complaint ();
20476   else if (m_record_lines_p)
20477     {
20478       const char *dir = fe->include_dir (m_line_header);
20479
20480       m_last_subfile = current_subfile;
20481       m_line_has_non_zero_discriminator = m_discriminator != 0;
20482       dwarf2_start_subfile (fe->name, dir);
20483     }
20484 }
20485
20486 void
20487 lnp_state_machine::handle_const_add_pc ()
20488 {
20489   CORE_ADDR adjust
20490     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20491
20492   CORE_ADDR addr_adj
20493     = (((m_op_index + adjust)
20494         / m_line_header->maximum_ops_per_instruction)
20495        * m_line_header->minimum_instruction_length);
20496
20497   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20498   m_op_index = ((m_op_index + adjust)
20499                 % m_line_header->maximum_ops_per_instruction);
20500 }
20501
20502 /* Ignore this record_line request.  */
20503
20504 static void
20505 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20506 {
20507   return;
20508 }
20509
20510 /* Return non-zero if we should add LINE to the line number table.
20511    LINE is the line to add, LAST_LINE is the last line that was added,
20512    LAST_SUBFILE is the subfile for LAST_LINE.
20513    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20514    had a non-zero discriminator.
20515
20516    We have to be careful in the presence of discriminators.
20517    E.g., for this line:
20518
20519      for (i = 0; i < 100000; i++);
20520
20521    clang can emit four line number entries for that one line,
20522    each with a different discriminator.
20523    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20524
20525    However, we want gdb to coalesce all four entries into one.
20526    Otherwise the user could stepi into the middle of the line and
20527    gdb would get confused about whether the pc really was in the
20528    middle of the line.
20529
20530    Things are further complicated by the fact that two consecutive
20531    line number entries for the same line is a heuristic used by gcc
20532    to denote the end of the prologue.  So we can't just discard duplicate
20533    entries, we have to be selective about it.  The heuristic we use is
20534    that we only collapse consecutive entries for the same line if at least
20535    one of those entries has a non-zero discriminator.  PR 17276.
20536
20537    Note: Addresses in the line number state machine can never go backwards
20538    within one sequence, thus this coalescing is ok.  */
20539
20540 static int
20541 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20542                      int line_has_non_zero_discriminator,
20543                      struct subfile *last_subfile)
20544 {
20545   if (current_subfile != last_subfile)
20546     return 1;
20547   if (line != last_line)
20548     return 1;
20549   /* Same line for the same file that we've seen already.
20550      As a last check, for pr 17276, only record the line if the line
20551      has never had a non-zero discriminator.  */
20552   if (!line_has_non_zero_discriminator)
20553     return 1;
20554   return 0;
20555 }
20556
20557 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20558    in the line table of subfile SUBFILE.  */
20559
20560 static void
20561 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20562                      unsigned int line, CORE_ADDR address,
20563                      record_line_ftype p_record_line)
20564 {
20565   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20566
20567   if (dwarf_line_debug)
20568     {
20569       fprintf_unfiltered (gdb_stdlog,
20570                           "Recording line %u, file %s, address %s\n",
20571                           line, lbasename (subfile->name),
20572                           paddress (gdbarch, address));
20573     }
20574
20575   (*p_record_line) (subfile, line, addr);
20576 }
20577
20578 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20579    Mark the end of a set of line number records.
20580    The arguments are the same as for dwarf_record_line_1.
20581    If SUBFILE is NULL the request is ignored.  */
20582
20583 static void
20584 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20585                    CORE_ADDR address, record_line_ftype p_record_line)
20586 {
20587   if (subfile == NULL)
20588     return;
20589
20590   if (dwarf_line_debug)
20591     {
20592       fprintf_unfiltered (gdb_stdlog,
20593                           "Finishing current line, file %s, address %s\n",
20594                           lbasename (subfile->name),
20595                           paddress (gdbarch, address));
20596     }
20597
20598   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20599 }
20600
20601 void
20602 lnp_state_machine::record_line (bool end_sequence)
20603 {
20604   if (dwarf_line_debug)
20605     {
20606       fprintf_unfiltered (gdb_stdlog,
20607                           "Processing actual line %u: file %u,"
20608                           " address %s, is_stmt %u, discrim %u\n",
20609                           m_line, to_underlying (m_file),
20610                           paddress (m_gdbarch, m_address),
20611                           m_is_stmt, m_discriminator);
20612     }
20613
20614   file_entry *fe = current_file ();
20615
20616   if (fe == NULL)
20617     dwarf2_debug_line_missing_file_complaint ();
20618   /* For now we ignore lines not starting on an instruction boundary.
20619      But not when processing end_sequence for compatibility with the
20620      previous version of the code.  */
20621   else if (m_op_index == 0 || end_sequence)
20622     {
20623       fe->included_p = 1;
20624       if (m_record_lines_p && m_is_stmt)
20625         {
20626           if (m_last_subfile != current_subfile || end_sequence)
20627             {
20628               dwarf_finish_line (m_gdbarch, m_last_subfile,
20629                                  m_address, m_record_line_callback);
20630             }
20631
20632           if (!end_sequence)
20633             {
20634               if (dwarf_record_line_p (m_line, m_last_line,
20635                                        m_line_has_non_zero_discriminator,
20636                                        m_last_subfile))
20637                 {
20638                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20639                                        m_line, m_address,
20640                                        m_record_line_callback);
20641                 }
20642               m_last_subfile = current_subfile;
20643               m_last_line = m_line;
20644             }
20645         }
20646     }
20647 }
20648
20649 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20650                                       bool record_lines_p)
20651 {
20652   m_gdbarch = arch;
20653   m_record_lines_p = record_lines_p;
20654   m_line_header = lh;
20655
20656   m_record_line_callback = ::record_line;
20657
20658   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20659      was a line entry for it so that the backend has a chance to adjust it
20660      and also record it in case it needs it.  This is currently used by MIPS
20661      code, cf. `mips_adjust_dwarf2_line'.  */
20662   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20663   m_is_stmt = lh->default_is_stmt;
20664   m_discriminator = 0;
20665 }
20666
20667 void
20668 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20669                                        const gdb_byte *line_ptr,
20670                                        CORE_ADDR lowpc, CORE_ADDR address)
20671 {
20672   /* If address < lowpc then it's not a usable value, it's outside the
20673      pc range of the CU.  However, we restrict the test to only address
20674      values of zero to preserve GDB's previous behaviour which is to
20675      handle the specific case of a function being GC'd by the linker.  */
20676
20677   if (address == 0 && address < lowpc)
20678     {
20679       /* This line table is for a function which has been
20680          GCd by the linker.  Ignore it.  PR gdb/12528 */
20681
20682       struct objfile *objfile = cu->objfile;
20683       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20684
20685       complaint (&symfile_complaints,
20686                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20687                  line_offset, objfile_name (objfile));
20688       m_record_line_callback = noop_record_line;
20689       /* Note: record_line_callback is left as noop_record_line until
20690          we see DW_LNE_end_sequence.  */
20691     }
20692 }
20693
20694 /* Subroutine of dwarf_decode_lines to simplify it.
20695    Process the line number information in LH.
20696    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20697    program in order to set included_p for every referenced header.  */
20698
20699 static void
20700 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20701                       const int decode_for_pst_p, CORE_ADDR lowpc)
20702 {
20703   const gdb_byte *line_ptr, *extended_end;
20704   const gdb_byte *line_end;
20705   unsigned int bytes_read, extended_len;
20706   unsigned char op_code, extended_op;
20707   CORE_ADDR baseaddr;
20708   struct objfile *objfile = cu->objfile;
20709   bfd *abfd = objfile->obfd;
20710   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20711   /* True if we're recording line info (as opposed to building partial
20712      symtabs and just interested in finding include files mentioned by
20713      the line number program).  */
20714   bool record_lines_p = !decode_for_pst_p;
20715
20716   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20717
20718   line_ptr = lh->statement_program_start;
20719   line_end = lh->statement_program_end;
20720
20721   /* Read the statement sequences until there's nothing left.  */
20722   while (line_ptr < line_end)
20723     {
20724       /* The DWARF line number program state machine.  Reset the state
20725          machine at the start of each sequence.  */
20726       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20727       bool end_sequence = false;
20728
20729       if (record_lines_p)
20730         {
20731           /* Start a subfile for the current file of the state
20732              machine.  */
20733           const file_entry *fe = state_machine.current_file ();
20734
20735           if (fe != NULL)
20736             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20737         }
20738
20739       /* Decode the table.  */
20740       while (line_ptr < line_end && !end_sequence)
20741         {
20742           op_code = read_1_byte (abfd, line_ptr);
20743           line_ptr += 1;
20744
20745           if (op_code >= lh->opcode_base)
20746             {
20747               /* Special opcode.  */
20748               state_machine.handle_special_opcode (op_code);
20749             }
20750           else switch (op_code)
20751             {
20752             case DW_LNS_extended_op:
20753               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20754                                                    &bytes_read);
20755               line_ptr += bytes_read;
20756               extended_end = line_ptr + extended_len;
20757               extended_op = read_1_byte (abfd, line_ptr);
20758               line_ptr += 1;
20759               switch (extended_op)
20760                 {
20761                 case DW_LNE_end_sequence:
20762                   state_machine.handle_end_sequence ();
20763                   end_sequence = true;
20764                   break;
20765                 case DW_LNE_set_address:
20766                   {
20767                     CORE_ADDR address
20768                       = read_address (abfd, line_ptr, cu, &bytes_read);
20769                     line_ptr += bytes_read;
20770
20771                     state_machine.check_line_address (cu, line_ptr,
20772                                                       lowpc, address);
20773                     state_machine.handle_set_address (baseaddr, address);
20774                   }
20775                   break;
20776                 case DW_LNE_define_file:
20777                   {
20778                     const char *cur_file;
20779                     unsigned int mod_time, length;
20780                     dir_index dindex;
20781
20782                     cur_file = read_direct_string (abfd, line_ptr,
20783                                                    &bytes_read);
20784                     line_ptr += bytes_read;
20785                     dindex = (dir_index)
20786                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20787                     line_ptr += bytes_read;
20788                     mod_time =
20789                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20790                     line_ptr += bytes_read;
20791                     length =
20792                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20793                     line_ptr += bytes_read;
20794                     lh->add_file_name (cur_file, dindex, mod_time, length);
20795                   }
20796                   break;
20797                 case DW_LNE_set_discriminator:
20798                   {
20799                     /* The discriminator is not interesting to the
20800                        debugger; just ignore it.  We still need to
20801                        check its value though:
20802                        if there are consecutive entries for the same
20803                        (non-prologue) line we want to coalesce them.
20804                        PR 17276.  */
20805                     unsigned int discr
20806                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20807                     line_ptr += bytes_read;
20808
20809                     state_machine.handle_set_discriminator (discr);
20810                   }
20811                   break;
20812                 default:
20813                   complaint (&symfile_complaints,
20814                              _("mangled .debug_line section"));
20815                   return;
20816                 }
20817               /* Make sure that we parsed the extended op correctly.  If e.g.
20818                  we expected a different address size than the producer used,
20819                  we may have read the wrong number of bytes.  */
20820               if (line_ptr != extended_end)
20821                 {
20822                   complaint (&symfile_complaints,
20823                              _("mangled .debug_line section"));
20824                   return;
20825                 }
20826               break;
20827             case DW_LNS_copy:
20828               state_machine.handle_copy ();
20829               break;
20830             case DW_LNS_advance_pc:
20831               {
20832                 CORE_ADDR adjust
20833                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20834                 line_ptr += bytes_read;
20835
20836                 state_machine.handle_advance_pc (adjust);
20837               }
20838               break;
20839             case DW_LNS_advance_line:
20840               {
20841                 int line_delta
20842                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20843                 line_ptr += bytes_read;
20844
20845                 state_machine.handle_advance_line (line_delta);
20846               }
20847               break;
20848             case DW_LNS_set_file:
20849               {
20850                 file_name_index file
20851                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20852                                                             &bytes_read);
20853                 line_ptr += bytes_read;
20854
20855                 state_machine.handle_set_file (file);
20856               }
20857               break;
20858             case DW_LNS_set_column:
20859               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20860               line_ptr += bytes_read;
20861               break;
20862             case DW_LNS_negate_stmt:
20863               state_machine.handle_negate_stmt ();
20864               break;
20865             case DW_LNS_set_basic_block:
20866               break;
20867             /* Add to the address register of the state machine the
20868                address increment value corresponding to special opcode
20869                255.  I.e., this value is scaled by the minimum
20870                instruction length since special opcode 255 would have
20871                scaled the increment.  */
20872             case DW_LNS_const_add_pc:
20873               state_machine.handle_const_add_pc ();
20874               break;
20875             case DW_LNS_fixed_advance_pc:
20876               {
20877                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20878                 line_ptr += 2;
20879
20880                 state_machine.handle_fixed_advance_pc (addr_adj);
20881               }
20882               break;
20883             default:
20884               {
20885                 /* Unknown standard opcode, ignore it.  */
20886                 int i;
20887
20888                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20889                   {
20890                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20891                     line_ptr += bytes_read;
20892                   }
20893               }
20894             }
20895         }
20896
20897       if (!end_sequence)
20898         dwarf2_debug_line_missing_end_sequence_complaint ();
20899
20900       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20901          in which case we still finish recording the last line).  */
20902       state_machine.record_line (true);
20903     }
20904 }
20905
20906 /* Decode the Line Number Program (LNP) for the given line_header
20907    structure and CU.  The actual information extracted and the type
20908    of structures created from the LNP depends on the value of PST.
20909
20910    1. If PST is NULL, then this procedure uses the data from the program
20911       to create all necessary symbol tables, and their linetables.
20912
20913    2. If PST is not NULL, this procedure reads the program to determine
20914       the list of files included by the unit represented by PST, and
20915       builds all the associated partial symbol tables.
20916
20917    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20918    It is used for relative paths in the line table.
20919    NOTE: When processing partial symtabs (pst != NULL),
20920    comp_dir == pst->dirname.
20921
20922    NOTE: It is important that psymtabs have the same file name (via strcmp)
20923    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20924    symtab we don't use it in the name of the psymtabs we create.
20925    E.g. expand_line_sal requires this when finding psymtabs to expand.
20926    A good testcase for this is mb-inline.exp.
20927
20928    LOWPC is the lowest address in CU (or 0 if not known).
20929
20930    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20931    for its PC<->lines mapping information.  Otherwise only the filename
20932    table is read in.  */
20933
20934 static void
20935 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20936                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20937                     CORE_ADDR lowpc, int decode_mapping)
20938 {
20939   struct objfile *objfile = cu->objfile;
20940   const int decode_for_pst_p = (pst != NULL);
20941
20942   if (decode_mapping)
20943     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20944
20945   if (decode_for_pst_p)
20946     {
20947       int file_index;
20948
20949       /* Now that we're done scanning the Line Header Program, we can
20950          create the psymtab of each included file.  */
20951       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20952         if (lh->file_names[file_index].included_p == 1)
20953           {
20954             const char *include_name =
20955               psymtab_include_file_name (lh, file_index, pst, comp_dir);
20956             if (include_name != NULL)
20957               dwarf2_create_include_psymtab (include_name, pst, objfile);
20958           }
20959     }
20960   else
20961     {
20962       /* Make sure a symtab is created for every file, even files
20963          which contain only variables (i.e. no code with associated
20964          line numbers).  */
20965       struct compunit_symtab *cust = buildsym_compunit_symtab ();
20966       int i;
20967
20968       for (i = 0; i < lh->file_names.size (); i++)
20969         {
20970           file_entry &fe = lh->file_names[i];
20971
20972           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
20973
20974           if (current_subfile->symtab == NULL)
20975             {
20976               current_subfile->symtab
20977                 = allocate_symtab (cust, current_subfile->name);
20978             }
20979           fe.symtab = current_subfile->symtab;
20980         }
20981     }
20982 }
20983
20984 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20985    DIRNAME the name of the source directory which contains FILENAME
20986    or NULL if not known.
20987    This routine tries to keep line numbers from identical absolute and
20988    relative file names in a common subfile.
20989
20990    Using the `list' example from the GDB testsuite, which resides in
20991    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20992    of /srcdir/list0.c yields the following debugging information for list0.c:
20993
20994    DW_AT_name:          /srcdir/list0.c
20995    DW_AT_comp_dir:      /compdir
20996    files.files[0].name: list0.h
20997    files.files[0].dir:  /srcdir
20998    files.files[1].name: list0.c
20999    files.files[1].dir:  /srcdir
21000
21001    The line number information for list0.c has to end up in a single
21002    subfile, so that `break /srcdir/list0.c:1' works as expected.
21003    start_subfile will ensure that this happens provided that we pass the
21004    concatenation of files.files[1].dir and files.files[1].name as the
21005    subfile's name.  */
21006
21007 static void
21008 dwarf2_start_subfile (const char *filename, const char *dirname)
21009 {
21010   char *copy = NULL;
21011
21012   /* In order not to lose the line information directory,
21013      we concatenate it to the filename when it makes sense.
21014      Note that the Dwarf3 standard says (speaking of filenames in line
21015      information): ``The directory index is ignored for file names
21016      that represent full path names''.  Thus ignoring dirname in the
21017      `else' branch below isn't an issue.  */
21018
21019   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21020     {
21021       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21022       filename = copy;
21023     }
21024
21025   start_subfile (filename);
21026
21027   if (copy != NULL)
21028     xfree (copy);
21029 }
21030
21031 /* Start a symtab for DWARF.
21032    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21033
21034 static struct compunit_symtab *
21035 dwarf2_start_symtab (struct dwarf2_cu *cu,
21036                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21037 {
21038   struct compunit_symtab *cust
21039     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
21040
21041   record_debugformat ("DWARF 2");
21042   record_producer (cu->producer);
21043
21044   /* We assume that we're processing GCC output.  */
21045   processing_gcc_compilation = 2;
21046
21047   cu->processing_has_namespace_info = 0;
21048
21049   return cust;
21050 }
21051
21052 static void
21053 var_decode_location (struct attribute *attr, struct symbol *sym,
21054                      struct dwarf2_cu *cu)
21055 {
21056   struct objfile *objfile = cu->objfile;
21057   struct comp_unit_head *cu_header = &cu->header;
21058
21059   /* NOTE drow/2003-01-30: There used to be a comment and some special
21060      code here to turn a symbol with DW_AT_external and a
21061      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21062      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21063      with some versions of binutils) where shared libraries could have
21064      relocations against symbols in their debug information - the
21065      minimal symbol would have the right address, but the debug info
21066      would not.  It's no longer necessary, because we will explicitly
21067      apply relocations when we read in the debug information now.  */
21068
21069   /* A DW_AT_location attribute with no contents indicates that a
21070      variable has been optimized away.  */
21071   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21072     {
21073       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21074       return;
21075     }
21076
21077   /* Handle one degenerate form of location expression specially, to
21078      preserve GDB's previous behavior when section offsets are
21079      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21080      then mark this symbol as LOC_STATIC.  */
21081
21082   if (attr_form_is_block (attr)
21083       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21084            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21085           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21086               && (DW_BLOCK (attr)->size
21087                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21088     {
21089       unsigned int dummy;
21090
21091       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21092         SYMBOL_VALUE_ADDRESS (sym) =
21093           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21094       else
21095         SYMBOL_VALUE_ADDRESS (sym) =
21096           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21097       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21098       fixup_symbol_section (sym, objfile);
21099       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21100                                               SYMBOL_SECTION (sym));
21101       return;
21102     }
21103
21104   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21105      expression evaluator, and use LOC_COMPUTED only when necessary
21106      (i.e. when the value of a register or memory location is
21107      referenced, or a thread-local block, etc.).  Then again, it might
21108      not be worthwhile.  I'm assuming that it isn't unless performance
21109      or memory numbers show me otherwise.  */
21110
21111   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21112
21113   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21114     cu->has_loclist = 1;
21115 }
21116
21117 /* Given a pointer to a DWARF information entry, figure out if we need
21118    to make a symbol table entry for it, and if so, create a new entry
21119    and return a pointer to it.
21120    If TYPE is NULL, determine symbol type from the die, otherwise
21121    used the passed type.
21122    If SPACE is not NULL, use it to hold the new symbol.  If it is
21123    NULL, allocate a new symbol on the objfile's obstack.  */
21124
21125 static struct symbol *
21126 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21127                  struct symbol *space)
21128 {
21129   struct objfile *objfile = cu->objfile;
21130   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21131   struct symbol *sym = NULL;
21132   const char *name;
21133   struct attribute *attr = NULL;
21134   struct attribute *attr2 = NULL;
21135   CORE_ADDR baseaddr;
21136   struct pending **list_to_add = NULL;
21137
21138   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21139
21140   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21141
21142   name = dwarf2_name (die, cu);
21143   if (name)
21144     {
21145       const char *linkagename;
21146       int suppress_add = 0;
21147
21148       if (space)
21149         sym = space;
21150       else
21151         sym = allocate_symbol (objfile);
21152       OBJSTAT (objfile, n_syms++);
21153
21154       /* Cache this symbol's name and the name's demangled form (if any).  */
21155       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21156       linkagename = dwarf2_physname (name, die, cu);
21157       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21158
21159       /* Fortran does not have mangling standard and the mangling does differ
21160          between gfortran, iFort etc.  */
21161       if (cu->language == language_fortran
21162           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21163         symbol_set_demangled_name (&(sym->ginfo),
21164                                    dwarf2_full_name (name, die, cu),
21165                                    NULL);
21166
21167       /* Default assumptions.
21168          Use the passed type or decode it from the die.  */
21169       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21170       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21171       if (type != NULL)
21172         SYMBOL_TYPE (sym) = type;
21173       else
21174         SYMBOL_TYPE (sym) = die_type (die, cu);
21175       attr = dwarf2_attr (die,
21176                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21177                           cu);
21178       if (attr)
21179         {
21180           SYMBOL_LINE (sym) = DW_UNSND (attr);
21181         }
21182
21183       attr = dwarf2_attr (die,
21184                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21185                           cu);
21186       if (attr)
21187         {
21188           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21189           struct file_entry *fe;
21190
21191           if (cu->line_header != NULL)
21192             fe = cu->line_header->file_name_at (file_index);
21193           else
21194             fe = NULL;
21195
21196           if (fe == NULL)
21197             complaint (&symfile_complaints,
21198                        _("file index out of range"));
21199           else
21200             symbol_set_symtab (sym, fe->symtab);
21201         }
21202
21203       switch (die->tag)
21204         {
21205         case DW_TAG_label:
21206           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21207           if (attr)
21208             {
21209               CORE_ADDR addr;
21210
21211               addr = attr_value_as_address (attr);
21212               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21213               SYMBOL_VALUE_ADDRESS (sym) = addr;
21214             }
21215           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21216           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21217           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21218           add_symbol_to_list (sym, cu->list_in_scope);
21219           break;
21220         case DW_TAG_subprogram:
21221           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21222              finish_block.  */
21223           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21224           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21225           if ((attr2 && (DW_UNSND (attr2) != 0))
21226               || cu->language == language_ada)
21227             {
21228               /* Subprograms marked external are stored as a global symbol.
21229                  Ada subprograms, whether marked external or not, are always
21230                  stored as a global symbol, because we want to be able to
21231                  access them globally.  For instance, we want to be able
21232                  to break on a nested subprogram without having to
21233                  specify the context.  */
21234               list_to_add = &global_symbols;
21235             }
21236           else
21237             {
21238               list_to_add = cu->list_in_scope;
21239             }
21240           break;
21241         case DW_TAG_inlined_subroutine:
21242           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21243              finish_block.  */
21244           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21245           SYMBOL_INLINED (sym) = 1;
21246           list_to_add = cu->list_in_scope;
21247           break;
21248         case DW_TAG_template_value_param:
21249           suppress_add = 1;
21250           /* Fall through.  */
21251         case DW_TAG_constant:
21252         case DW_TAG_variable:
21253         case DW_TAG_member:
21254           /* Compilation with minimal debug info may result in
21255              variables with missing type entries.  Change the
21256              misleading `void' type to something sensible.  */
21257           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21258             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21259
21260           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21261           /* In the case of DW_TAG_member, we should only be called for
21262              static const members.  */
21263           if (die->tag == DW_TAG_member)
21264             {
21265               /* dwarf2_add_field uses die_is_declaration,
21266                  so we do the same.  */
21267               gdb_assert (die_is_declaration (die, cu));
21268               gdb_assert (attr);
21269             }
21270           if (attr)
21271             {
21272               dwarf2_const_value (attr, sym, cu);
21273               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21274               if (!suppress_add)
21275                 {
21276                   if (attr2 && (DW_UNSND (attr2) != 0))
21277                     list_to_add = &global_symbols;
21278                   else
21279                     list_to_add = cu->list_in_scope;
21280                 }
21281               break;
21282             }
21283           attr = dwarf2_attr (die, DW_AT_location, cu);
21284           if (attr)
21285             {
21286               var_decode_location (attr, sym, cu);
21287               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21288
21289               /* Fortran explicitly imports any global symbols to the local
21290                  scope by DW_TAG_common_block.  */
21291               if (cu->language == language_fortran && die->parent
21292                   && die->parent->tag == DW_TAG_common_block)
21293                 attr2 = NULL;
21294
21295               if (SYMBOL_CLASS (sym) == LOC_STATIC
21296                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21297                   && !dwarf2_per_objfile->has_section_at_zero)
21298                 {
21299                   /* When a static variable is eliminated by the linker,
21300                      the corresponding debug information is not stripped
21301                      out, but the variable address is set to null;
21302                      do not add such variables into symbol table.  */
21303                 }
21304               else if (attr2 && (DW_UNSND (attr2) != 0))
21305                 {
21306                   /* Workaround gfortran PR debug/40040 - it uses
21307                      DW_AT_location for variables in -fPIC libraries which may
21308                      get overriden by other libraries/executable and get
21309                      a different address.  Resolve it by the minimal symbol
21310                      which may come from inferior's executable using copy
21311                      relocation.  Make this workaround only for gfortran as for
21312                      other compilers GDB cannot guess the minimal symbol
21313                      Fortran mangling kind.  */
21314                   if (cu->language == language_fortran && die->parent
21315                       && die->parent->tag == DW_TAG_module
21316                       && cu->producer
21317                       && startswith (cu->producer, "GNU Fortran"))
21318                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21319
21320                   /* A variable with DW_AT_external is never static,
21321                      but it may be block-scoped.  */
21322                   list_to_add = (cu->list_in_scope == &file_symbols
21323                                  ? &global_symbols : cu->list_in_scope);
21324                 }
21325               else
21326                 list_to_add = cu->list_in_scope;
21327             }
21328           else
21329             {
21330               /* We do not know the address of this symbol.
21331                  If it is an external symbol and we have type information
21332                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21333                  The address of the variable will then be determined from
21334                  the minimal symbol table whenever the variable is
21335                  referenced.  */
21336               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21337
21338               /* Fortran explicitly imports any global symbols to the local
21339                  scope by DW_TAG_common_block.  */
21340               if (cu->language == language_fortran && die->parent
21341                   && die->parent->tag == DW_TAG_common_block)
21342                 {
21343                   /* SYMBOL_CLASS doesn't matter here because
21344                      read_common_block is going to reset it.  */
21345                   if (!suppress_add)
21346                     list_to_add = cu->list_in_scope;
21347                 }
21348               else if (attr2 && (DW_UNSND (attr2) != 0)
21349                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21350                 {
21351                   /* A variable with DW_AT_external is never static, but it
21352                      may be block-scoped.  */
21353                   list_to_add = (cu->list_in_scope == &file_symbols
21354                                  ? &global_symbols : cu->list_in_scope);
21355
21356                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21357                 }
21358               else if (!die_is_declaration (die, cu))
21359                 {
21360                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21361                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21362                   if (!suppress_add)
21363                     list_to_add = cu->list_in_scope;
21364                 }
21365             }
21366           break;
21367         case DW_TAG_formal_parameter:
21368           /* If we are inside a function, mark this as an argument.  If
21369              not, we might be looking at an argument to an inlined function
21370              when we do not have enough information to show inlined frames;
21371              pretend it's a local variable in that case so that the user can
21372              still see it.  */
21373           if (context_stack_depth > 0
21374               && context_stack[context_stack_depth - 1].name != NULL)
21375             SYMBOL_IS_ARGUMENT (sym) = 1;
21376           attr = dwarf2_attr (die, DW_AT_location, cu);
21377           if (attr)
21378             {
21379               var_decode_location (attr, sym, cu);
21380             }
21381           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21382           if (attr)
21383             {
21384               dwarf2_const_value (attr, sym, cu);
21385             }
21386
21387           list_to_add = cu->list_in_scope;
21388           break;
21389         case DW_TAG_unspecified_parameters:
21390           /* From varargs functions; gdb doesn't seem to have any
21391              interest in this information, so just ignore it for now.
21392              (FIXME?) */
21393           break;
21394         case DW_TAG_template_type_param:
21395           suppress_add = 1;
21396           /* Fall through.  */
21397         case DW_TAG_class_type:
21398         case DW_TAG_interface_type:
21399         case DW_TAG_structure_type:
21400         case DW_TAG_union_type:
21401         case DW_TAG_set_type:
21402         case DW_TAG_enumeration_type:
21403           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21404           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21405
21406           {
21407             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21408                really ever be static objects: otherwise, if you try
21409                to, say, break of a class's method and you're in a file
21410                which doesn't mention that class, it won't work unless
21411                the check for all static symbols in lookup_symbol_aux
21412                saves you.  See the OtherFileClass tests in
21413                gdb.c++/namespace.exp.  */
21414
21415             if (!suppress_add)
21416               {
21417                 list_to_add = (cu->list_in_scope == &file_symbols
21418                                && cu->language == language_cplus
21419                                ? &global_symbols : cu->list_in_scope);
21420
21421                 /* The semantics of C++ state that "struct foo {
21422                    ... }" also defines a typedef for "foo".  */
21423                 if (cu->language == language_cplus
21424                     || cu->language == language_ada
21425                     || cu->language == language_d
21426                     || cu->language == language_rust)
21427                   {
21428                     /* The symbol's name is already allocated along
21429                        with this objfile, so we don't need to
21430                        duplicate it for the type.  */
21431                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21432                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21433                   }
21434               }
21435           }
21436           break;
21437         case DW_TAG_typedef:
21438           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21439           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21440           list_to_add = cu->list_in_scope;
21441           break;
21442         case DW_TAG_base_type:
21443         case DW_TAG_subrange_type:
21444           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21445           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21446           list_to_add = cu->list_in_scope;
21447           break;
21448         case DW_TAG_enumerator:
21449           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21450           if (attr)
21451             {
21452               dwarf2_const_value (attr, sym, cu);
21453             }
21454           {
21455             /* NOTE: carlton/2003-11-10: See comment above in the
21456                DW_TAG_class_type, etc. block.  */
21457
21458             list_to_add = (cu->list_in_scope == &file_symbols
21459                            && cu->language == language_cplus
21460                            ? &global_symbols : cu->list_in_scope);
21461           }
21462           break;
21463         case DW_TAG_imported_declaration:
21464         case DW_TAG_namespace:
21465           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21466           list_to_add = &global_symbols;
21467           break;
21468         case DW_TAG_module:
21469           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21470           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21471           list_to_add = &global_symbols;
21472           break;
21473         case DW_TAG_common_block:
21474           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21475           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21476           add_symbol_to_list (sym, cu->list_in_scope);
21477           break;
21478         default:
21479           /* Not a tag we recognize.  Hopefully we aren't processing
21480              trash data, but since we must specifically ignore things
21481              we don't recognize, there is nothing else we should do at
21482              this point.  */
21483           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21484                      dwarf_tag_name (die->tag));
21485           break;
21486         }
21487
21488       if (suppress_add)
21489         {
21490           sym->hash_next = objfile->template_symbols;
21491           objfile->template_symbols = sym;
21492           list_to_add = NULL;
21493         }
21494
21495       if (list_to_add != NULL)
21496         add_symbol_to_list (sym, list_to_add);
21497
21498       /* For the benefit of old versions of GCC, check for anonymous
21499          namespaces based on the demangled name.  */
21500       if (!cu->processing_has_namespace_info
21501           && cu->language == language_cplus)
21502         cp_scan_for_anonymous_namespaces (sym, objfile);
21503     }
21504   return (sym);
21505 }
21506
21507 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
21508
21509 static struct symbol *
21510 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21511 {
21512   return new_symbol_full (die, type, cu, NULL);
21513 }
21514
21515 /* Given an attr with a DW_FORM_dataN value in host byte order,
21516    zero-extend it as appropriate for the symbol's type.  The DWARF
21517    standard (v4) is not entirely clear about the meaning of using
21518    DW_FORM_dataN for a constant with a signed type, where the type is
21519    wider than the data.  The conclusion of a discussion on the DWARF
21520    list was that this is unspecified.  We choose to always zero-extend
21521    because that is the interpretation long in use by GCC.  */
21522
21523 static gdb_byte *
21524 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21525                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21526 {
21527   struct objfile *objfile = cu->objfile;
21528   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21529                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21530   LONGEST l = DW_UNSND (attr);
21531
21532   if (bits < sizeof (*value) * 8)
21533     {
21534       l &= ((LONGEST) 1 << bits) - 1;
21535       *value = l;
21536     }
21537   else if (bits == sizeof (*value) * 8)
21538     *value = l;
21539   else
21540     {
21541       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21542       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21543       return bytes;
21544     }
21545
21546   return NULL;
21547 }
21548
21549 /* Read a constant value from an attribute.  Either set *VALUE, or if
21550    the value does not fit in *VALUE, set *BYTES - either already
21551    allocated on the objfile obstack, or newly allocated on OBSTACK,
21552    or, set *BATON, if we translated the constant to a location
21553    expression.  */
21554
21555 static void
21556 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21557                          const char *name, struct obstack *obstack,
21558                          struct dwarf2_cu *cu,
21559                          LONGEST *value, const gdb_byte **bytes,
21560                          struct dwarf2_locexpr_baton **baton)
21561 {
21562   struct objfile *objfile = cu->objfile;
21563   struct comp_unit_head *cu_header = &cu->header;
21564   struct dwarf_block *blk;
21565   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21566                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21567
21568   *value = 0;
21569   *bytes = NULL;
21570   *baton = NULL;
21571
21572   switch (attr->form)
21573     {
21574     case DW_FORM_addr:
21575     case DW_FORM_GNU_addr_index:
21576       {
21577         gdb_byte *data;
21578
21579         if (TYPE_LENGTH (type) != cu_header->addr_size)
21580           dwarf2_const_value_length_mismatch_complaint (name,
21581                                                         cu_header->addr_size,
21582                                                         TYPE_LENGTH (type));
21583         /* Symbols of this form are reasonably rare, so we just
21584            piggyback on the existing location code rather than writing
21585            a new implementation of symbol_computed_ops.  */
21586         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21587         (*baton)->per_cu = cu->per_cu;
21588         gdb_assert ((*baton)->per_cu);
21589
21590         (*baton)->size = 2 + cu_header->addr_size;
21591         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21592         (*baton)->data = data;
21593
21594         data[0] = DW_OP_addr;
21595         store_unsigned_integer (&data[1], cu_header->addr_size,
21596                                 byte_order, DW_ADDR (attr));
21597         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21598       }
21599       break;
21600     case DW_FORM_string:
21601     case DW_FORM_strp:
21602     case DW_FORM_GNU_str_index:
21603     case DW_FORM_GNU_strp_alt:
21604       /* DW_STRING is already allocated on the objfile obstack, point
21605          directly to it.  */
21606       *bytes = (const gdb_byte *) DW_STRING (attr);
21607       break;
21608     case DW_FORM_block1:
21609     case DW_FORM_block2:
21610     case DW_FORM_block4:
21611     case DW_FORM_block:
21612     case DW_FORM_exprloc:
21613     case DW_FORM_data16:
21614       blk = DW_BLOCK (attr);
21615       if (TYPE_LENGTH (type) != blk->size)
21616         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21617                                                       TYPE_LENGTH (type));
21618       *bytes = blk->data;
21619       break;
21620
21621       /* The DW_AT_const_value attributes are supposed to carry the
21622          symbol's value "represented as it would be on the target
21623          architecture."  By the time we get here, it's already been
21624          converted to host endianness, so we just need to sign- or
21625          zero-extend it as appropriate.  */
21626     case DW_FORM_data1:
21627       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21628       break;
21629     case DW_FORM_data2:
21630       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21631       break;
21632     case DW_FORM_data4:
21633       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21634       break;
21635     case DW_FORM_data8:
21636       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21637       break;
21638
21639     case DW_FORM_sdata:
21640     case DW_FORM_implicit_const:
21641       *value = DW_SND (attr);
21642       break;
21643
21644     case DW_FORM_udata:
21645       *value = DW_UNSND (attr);
21646       break;
21647
21648     default:
21649       complaint (&symfile_complaints,
21650                  _("unsupported const value attribute form: '%s'"),
21651                  dwarf_form_name (attr->form));
21652       *value = 0;
21653       break;
21654     }
21655 }
21656
21657
21658 /* Copy constant value from an attribute to a symbol.  */
21659
21660 static void
21661 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21662                     struct dwarf2_cu *cu)
21663 {
21664   struct objfile *objfile = cu->objfile;
21665   LONGEST value;
21666   const gdb_byte *bytes;
21667   struct dwarf2_locexpr_baton *baton;
21668
21669   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21670                            SYMBOL_PRINT_NAME (sym),
21671                            &objfile->objfile_obstack, cu,
21672                            &value, &bytes, &baton);
21673
21674   if (baton != NULL)
21675     {
21676       SYMBOL_LOCATION_BATON (sym) = baton;
21677       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21678     }
21679   else if (bytes != NULL)
21680      {
21681       SYMBOL_VALUE_BYTES (sym) = bytes;
21682       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21683     }
21684   else
21685     {
21686       SYMBOL_VALUE (sym) = value;
21687       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21688     }
21689 }
21690
21691 /* Return the type of the die in question using its DW_AT_type attribute.  */
21692
21693 static struct type *
21694 die_type (struct die_info *die, struct dwarf2_cu *cu)
21695 {
21696   struct attribute *type_attr;
21697
21698   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21699   if (!type_attr)
21700     {
21701       /* A missing DW_AT_type represents a void type.  */
21702       return objfile_type (cu->objfile)->builtin_void;
21703     }
21704
21705   return lookup_die_type (die, type_attr, cu);
21706 }
21707
21708 /* True iff CU's producer generates GNAT Ada auxiliary information
21709    that allows to find parallel types through that information instead
21710    of having to do expensive parallel lookups by type name.  */
21711
21712 static int
21713 need_gnat_info (struct dwarf2_cu *cu)
21714 {
21715   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21716      of GNAT produces this auxiliary information, without any indication
21717      that it is produced.  Part of enhancing the FSF version of GNAT
21718      to produce that information will be to put in place an indicator
21719      that we can use in order to determine whether the descriptive type
21720      info is available or not.  One suggestion that has been made is
21721      to use a new attribute, attached to the CU die.  For now, assume
21722      that the descriptive type info is not available.  */
21723   return 0;
21724 }
21725
21726 /* Return the auxiliary type of the die in question using its
21727    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21728    attribute is not present.  */
21729
21730 static struct type *
21731 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21732 {
21733   struct attribute *type_attr;
21734
21735   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21736   if (!type_attr)
21737     return NULL;
21738
21739   return lookup_die_type (die, type_attr, cu);
21740 }
21741
21742 /* If DIE has a descriptive_type attribute, then set the TYPE's
21743    descriptive type accordingly.  */
21744
21745 static void
21746 set_descriptive_type (struct type *type, struct die_info *die,
21747                       struct dwarf2_cu *cu)
21748 {
21749   struct type *descriptive_type = die_descriptive_type (die, cu);
21750
21751   if (descriptive_type)
21752     {
21753       ALLOCATE_GNAT_AUX_TYPE (type);
21754       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21755     }
21756 }
21757
21758 /* Return the containing type of the die in question using its
21759    DW_AT_containing_type attribute.  */
21760
21761 static struct type *
21762 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21763 {
21764   struct attribute *type_attr;
21765
21766   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21767   if (!type_attr)
21768     error (_("Dwarf Error: Problem turning containing type into gdb type "
21769              "[in module %s]"), objfile_name (cu->objfile));
21770
21771   return lookup_die_type (die, type_attr, cu);
21772 }
21773
21774 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21775
21776 static struct type *
21777 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21778 {
21779   struct objfile *objfile = dwarf2_per_objfile->objfile;
21780   char *message, *saved;
21781
21782   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21783                         objfile_name (objfile),
21784                         to_underlying (cu->header.sect_off),
21785                         to_underlying (die->sect_off));
21786   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21787                                   message, strlen (message));
21788   xfree (message);
21789
21790   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21791 }
21792
21793 /* Look up the type of DIE in CU using its type attribute ATTR.
21794    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21795    DW_AT_containing_type.
21796    If there is no type substitute an error marker.  */
21797
21798 static struct type *
21799 lookup_die_type (struct die_info *die, const struct attribute *attr,
21800                  struct dwarf2_cu *cu)
21801 {
21802   struct objfile *objfile = cu->objfile;
21803   struct type *this_type;
21804
21805   gdb_assert (attr->name == DW_AT_type
21806               || attr->name == DW_AT_GNAT_descriptive_type
21807               || attr->name == DW_AT_containing_type);
21808
21809   /* First see if we have it cached.  */
21810
21811   if (attr->form == DW_FORM_GNU_ref_alt)
21812     {
21813       struct dwarf2_per_cu_data *per_cu;
21814       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21815
21816       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
21817       this_type = get_die_type_at_offset (sect_off, per_cu);
21818     }
21819   else if (attr_form_is_ref (attr))
21820     {
21821       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21822
21823       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21824     }
21825   else if (attr->form == DW_FORM_ref_sig8)
21826     {
21827       ULONGEST signature = DW_SIGNATURE (attr);
21828
21829       return get_signatured_type (die, signature, cu);
21830     }
21831   else
21832     {
21833       complaint (&symfile_complaints,
21834                  _("Dwarf Error: Bad type attribute %s in DIE"
21835                    " at 0x%x [in module %s]"),
21836                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
21837                  objfile_name (objfile));
21838       return build_error_marker_type (cu, die);
21839     }
21840
21841   /* If not cached we need to read it in.  */
21842
21843   if (this_type == NULL)
21844     {
21845       struct die_info *type_die = NULL;
21846       struct dwarf2_cu *type_cu = cu;
21847
21848       if (attr_form_is_ref (attr))
21849         type_die = follow_die_ref (die, attr, &type_cu);
21850       if (type_die == NULL)
21851         return build_error_marker_type (cu, die);
21852       /* If we find the type now, it's probably because the type came
21853          from an inter-CU reference and the type's CU got expanded before
21854          ours.  */
21855       this_type = read_type_die (type_die, type_cu);
21856     }
21857
21858   /* If we still don't have a type use an error marker.  */
21859
21860   if (this_type == NULL)
21861     return build_error_marker_type (cu, die);
21862
21863   return this_type;
21864 }
21865
21866 /* Return the type in DIE, CU.
21867    Returns NULL for invalid types.
21868
21869    This first does a lookup in die_type_hash,
21870    and only reads the die in if necessary.
21871
21872    NOTE: This can be called when reading in partial or full symbols.  */
21873
21874 static struct type *
21875 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21876 {
21877   struct type *this_type;
21878
21879   this_type = get_die_type (die, cu);
21880   if (this_type)
21881     return this_type;
21882
21883   return read_type_die_1 (die, cu);
21884 }
21885
21886 /* Read the type in DIE, CU.
21887    Returns NULL for invalid types.  */
21888
21889 static struct type *
21890 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21891 {
21892   struct type *this_type = NULL;
21893
21894   switch (die->tag)
21895     {
21896     case DW_TAG_class_type:
21897     case DW_TAG_interface_type:
21898     case DW_TAG_structure_type:
21899     case DW_TAG_union_type:
21900       this_type = read_structure_type (die, cu);
21901       break;
21902     case DW_TAG_enumeration_type:
21903       this_type = read_enumeration_type (die, cu);
21904       break;
21905     case DW_TAG_subprogram:
21906     case DW_TAG_subroutine_type:
21907     case DW_TAG_inlined_subroutine:
21908       this_type = read_subroutine_type (die, cu);
21909       break;
21910     case DW_TAG_array_type:
21911       this_type = read_array_type (die, cu);
21912       break;
21913     case DW_TAG_set_type:
21914       this_type = read_set_type (die, cu);
21915       break;
21916     case DW_TAG_pointer_type:
21917       this_type = read_tag_pointer_type (die, cu);
21918       break;
21919     case DW_TAG_ptr_to_member_type:
21920       this_type = read_tag_ptr_to_member_type (die, cu);
21921       break;
21922     case DW_TAG_reference_type:
21923       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21924       break;
21925     case DW_TAG_rvalue_reference_type:
21926       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21927       break;
21928     case DW_TAG_const_type:
21929       this_type = read_tag_const_type (die, cu);
21930       break;
21931     case DW_TAG_volatile_type:
21932       this_type = read_tag_volatile_type (die, cu);
21933       break;
21934     case DW_TAG_restrict_type:
21935       this_type = read_tag_restrict_type (die, cu);
21936       break;
21937     case DW_TAG_string_type:
21938       this_type = read_tag_string_type (die, cu);
21939       break;
21940     case DW_TAG_typedef:
21941       this_type = read_typedef (die, cu);
21942       break;
21943     case DW_TAG_subrange_type:
21944       this_type = read_subrange_type (die, cu);
21945       break;
21946     case DW_TAG_base_type:
21947       this_type = read_base_type (die, cu);
21948       break;
21949     case DW_TAG_unspecified_type:
21950       this_type = read_unspecified_type (die, cu);
21951       break;
21952     case DW_TAG_namespace:
21953       this_type = read_namespace_type (die, cu);
21954       break;
21955     case DW_TAG_module:
21956       this_type = read_module_type (die, cu);
21957       break;
21958     case DW_TAG_atomic_type:
21959       this_type = read_tag_atomic_type (die, cu);
21960       break;
21961     default:
21962       complaint (&symfile_complaints,
21963                  _("unexpected tag in read_type_die: '%s'"),
21964                  dwarf_tag_name (die->tag));
21965       break;
21966     }
21967
21968   return this_type;
21969 }
21970
21971 /* See if we can figure out if the class lives in a namespace.  We do
21972    this by looking for a member function; its demangled name will
21973    contain namespace info, if there is any.
21974    Return the computed name or NULL.
21975    Space for the result is allocated on the objfile's obstack.
21976    This is the full-die version of guess_partial_die_structure_name.
21977    In this case we know DIE has no useful parent.  */
21978
21979 static char *
21980 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21981 {
21982   struct die_info *spec_die;
21983   struct dwarf2_cu *spec_cu;
21984   struct die_info *child;
21985
21986   spec_cu = cu;
21987   spec_die = die_specification (die, &spec_cu);
21988   if (spec_die != NULL)
21989     {
21990       die = spec_die;
21991       cu = spec_cu;
21992     }
21993
21994   for (child = die->child;
21995        child != NULL;
21996        child = child->sibling)
21997     {
21998       if (child->tag == DW_TAG_subprogram)
21999         {
22000           const char *linkage_name = dw2_linkage_name (child, cu);
22001
22002           if (linkage_name != NULL)
22003             {
22004               char *actual_name
22005                 = language_class_name_from_physname (cu->language_defn,
22006                                                      linkage_name);
22007               char *name = NULL;
22008
22009               if (actual_name != NULL)
22010                 {
22011                   const char *die_name = dwarf2_name (die, cu);
22012
22013                   if (die_name != NULL
22014                       && strcmp (die_name, actual_name) != 0)
22015                     {
22016                       /* Strip off the class name from the full name.
22017                          We want the prefix.  */
22018                       int die_name_len = strlen (die_name);
22019                       int actual_name_len = strlen (actual_name);
22020
22021                       /* Test for '::' as a sanity check.  */
22022                       if (actual_name_len > die_name_len + 2
22023                           && actual_name[actual_name_len
22024                                          - die_name_len - 1] == ':')
22025                         name = (char *) obstack_copy0 (
22026                           &cu->objfile->per_bfd->storage_obstack,
22027                           actual_name, actual_name_len - die_name_len - 2);
22028                     }
22029                 }
22030               xfree (actual_name);
22031               return name;
22032             }
22033         }
22034     }
22035
22036   return NULL;
22037 }
22038
22039 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22040    prefix part in such case.  See
22041    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22042
22043 static const char *
22044 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22045 {
22046   struct attribute *attr;
22047   const char *base;
22048
22049   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22050       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22051     return NULL;
22052
22053   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22054     return NULL;
22055
22056   attr = dw2_linkage_name_attr (die, cu);
22057   if (attr == NULL || DW_STRING (attr) == NULL)
22058     return NULL;
22059
22060   /* dwarf2_name had to be already called.  */
22061   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22062
22063   /* Strip the base name, keep any leading namespaces/classes.  */
22064   base = strrchr (DW_STRING (attr), ':');
22065   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22066     return "";
22067
22068   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
22069                                  DW_STRING (attr),
22070                                  &base[-1] - DW_STRING (attr));
22071 }
22072
22073 /* Return the name of the namespace/class that DIE is defined within,
22074    or "" if we can't tell.  The caller should not xfree the result.
22075
22076    For example, if we're within the method foo() in the following
22077    code:
22078
22079    namespace N {
22080      class C {
22081        void foo () {
22082        }
22083      };
22084    }
22085
22086    then determine_prefix on foo's die will return "N::C".  */
22087
22088 static const char *
22089 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22090 {
22091   struct die_info *parent, *spec_die;
22092   struct dwarf2_cu *spec_cu;
22093   struct type *parent_type;
22094   const char *retval;
22095
22096   if (cu->language != language_cplus
22097       && cu->language != language_fortran && cu->language != language_d
22098       && cu->language != language_rust)
22099     return "";
22100
22101   retval = anonymous_struct_prefix (die, cu);
22102   if (retval)
22103     return retval;
22104
22105   /* We have to be careful in the presence of DW_AT_specification.
22106      For example, with GCC 3.4, given the code
22107
22108      namespace N {
22109        void foo() {
22110          // Definition of N::foo.
22111        }
22112      }
22113
22114      then we'll have a tree of DIEs like this:
22115
22116      1: DW_TAG_compile_unit
22117        2: DW_TAG_namespace        // N
22118          3: DW_TAG_subprogram     // declaration of N::foo
22119        4: DW_TAG_subprogram       // definition of N::foo
22120             DW_AT_specification   // refers to die #3
22121
22122      Thus, when processing die #4, we have to pretend that we're in
22123      the context of its DW_AT_specification, namely the contex of die
22124      #3.  */
22125   spec_cu = cu;
22126   spec_die = die_specification (die, &spec_cu);
22127   if (spec_die == NULL)
22128     parent = die->parent;
22129   else
22130     {
22131       parent = spec_die->parent;
22132       cu = spec_cu;
22133     }
22134
22135   if (parent == NULL)
22136     return "";
22137   else if (parent->building_fullname)
22138     {
22139       const char *name;
22140       const char *parent_name;
22141
22142       /* It has been seen on RealView 2.2 built binaries,
22143          DW_TAG_template_type_param types actually _defined_ as
22144          children of the parent class:
22145
22146          enum E {};
22147          template class <class Enum> Class{};
22148          Class<enum E> class_e;
22149
22150          1: DW_TAG_class_type (Class)
22151            2: DW_TAG_enumeration_type (E)
22152              3: DW_TAG_enumerator (enum1:0)
22153              3: DW_TAG_enumerator (enum2:1)
22154              ...
22155            2: DW_TAG_template_type_param
22156               DW_AT_type  DW_FORM_ref_udata (E)
22157
22158          Besides being broken debug info, it can put GDB into an
22159          infinite loop.  Consider:
22160
22161          When we're building the full name for Class<E>, we'll start
22162          at Class, and go look over its template type parameters,
22163          finding E.  We'll then try to build the full name of E, and
22164          reach here.  We're now trying to build the full name of E,
22165          and look over the parent DIE for containing scope.  In the
22166          broken case, if we followed the parent DIE of E, we'd again
22167          find Class, and once again go look at its template type
22168          arguments, etc., etc.  Simply don't consider such parent die
22169          as source-level parent of this die (it can't be, the language
22170          doesn't allow it), and break the loop here.  */
22171       name = dwarf2_name (die, cu);
22172       parent_name = dwarf2_name (parent, cu);
22173       complaint (&symfile_complaints,
22174                  _("template param type '%s' defined within parent '%s'"),
22175                  name ? name : "<unknown>",
22176                  parent_name ? parent_name : "<unknown>");
22177       return "";
22178     }
22179   else
22180     switch (parent->tag)
22181       {
22182       case DW_TAG_namespace:
22183         parent_type = read_type_die (parent, cu);
22184         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22185            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22186            Work around this problem here.  */
22187         if (cu->language == language_cplus
22188             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22189           return "";
22190         /* We give a name to even anonymous namespaces.  */
22191         return TYPE_TAG_NAME (parent_type);
22192       case DW_TAG_class_type:
22193       case DW_TAG_interface_type:
22194       case DW_TAG_structure_type:
22195       case DW_TAG_union_type:
22196       case DW_TAG_module:
22197         parent_type = read_type_die (parent, cu);
22198         if (TYPE_TAG_NAME (parent_type) != NULL)
22199           return TYPE_TAG_NAME (parent_type);
22200         else
22201           /* An anonymous structure is only allowed non-static data
22202              members; no typedefs, no member functions, et cetera.
22203              So it does not need a prefix.  */
22204           return "";
22205       case DW_TAG_compile_unit:
22206       case DW_TAG_partial_unit:
22207         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22208         if (cu->language == language_cplus
22209             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22210             && die->child != NULL
22211             && (die->tag == DW_TAG_class_type
22212                 || die->tag == DW_TAG_structure_type
22213                 || die->tag == DW_TAG_union_type))
22214           {
22215             char *name = guess_full_die_structure_name (die, cu);
22216             if (name != NULL)
22217               return name;
22218           }
22219         return "";
22220       case DW_TAG_enumeration_type:
22221         parent_type = read_type_die (parent, cu);
22222         if (TYPE_DECLARED_CLASS (parent_type))
22223           {
22224             if (TYPE_TAG_NAME (parent_type) != NULL)
22225               return TYPE_TAG_NAME (parent_type);
22226             return "";
22227           }
22228         /* Fall through.  */
22229       default:
22230         return determine_prefix (parent, cu);
22231       }
22232 }
22233
22234 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22235    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22236    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22237    an obconcat, otherwise allocate storage for the result.  The CU argument is
22238    used to determine the language and hence, the appropriate separator.  */
22239
22240 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22241
22242 static char *
22243 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22244                  int physname, struct dwarf2_cu *cu)
22245 {
22246   const char *lead = "";
22247   const char *sep;
22248
22249   if (suffix == NULL || suffix[0] == '\0'
22250       || prefix == NULL || prefix[0] == '\0')
22251     sep = "";
22252   else if (cu->language == language_d)
22253     {
22254       /* For D, the 'main' function could be defined in any module, but it
22255          should never be prefixed.  */
22256       if (strcmp (suffix, "D main") == 0)
22257         {
22258           prefix = "";
22259           sep = "";
22260         }
22261       else
22262         sep = ".";
22263     }
22264   else if (cu->language == language_fortran && physname)
22265     {
22266       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22267          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22268
22269       lead = "__";
22270       sep = "_MOD_";
22271     }
22272   else
22273     sep = "::";
22274
22275   if (prefix == NULL)
22276     prefix = "";
22277   if (suffix == NULL)
22278     suffix = "";
22279
22280   if (obs == NULL)
22281     {
22282       char *retval
22283         = ((char *)
22284            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22285
22286       strcpy (retval, lead);
22287       strcat (retval, prefix);
22288       strcat (retval, sep);
22289       strcat (retval, suffix);
22290       return retval;
22291     }
22292   else
22293     {
22294       /* We have an obstack.  */
22295       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22296     }
22297 }
22298
22299 /* Return sibling of die, NULL if no sibling.  */
22300
22301 static struct die_info *
22302 sibling_die (struct die_info *die)
22303 {
22304   return die->sibling;
22305 }
22306
22307 /* Get name of a die, return NULL if not found.  */
22308
22309 static const char *
22310 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22311                           struct obstack *obstack)
22312 {
22313   if (name && cu->language == language_cplus)
22314     {
22315       std::string canon_name = cp_canonicalize_string (name);
22316
22317       if (!canon_name.empty ())
22318         {
22319           if (canon_name != name)
22320             name = (const char *) obstack_copy0 (obstack,
22321                                                  canon_name.c_str (),
22322                                                  canon_name.length ());
22323         }
22324     }
22325
22326   return name;
22327 }
22328
22329 /* Get name of a die, return NULL if not found.
22330    Anonymous namespaces are converted to their magic string.  */
22331
22332 static const char *
22333 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22334 {
22335   struct attribute *attr;
22336
22337   attr = dwarf2_attr (die, DW_AT_name, cu);
22338   if ((!attr || !DW_STRING (attr))
22339       && die->tag != DW_TAG_namespace
22340       && die->tag != DW_TAG_class_type
22341       && die->tag != DW_TAG_interface_type
22342       && die->tag != DW_TAG_structure_type
22343       && die->tag != DW_TAG_union_type)
22344     return NULL;
22345
22346   switch (die->tag)
22347     {
22348     case DW_TAG_compile_unit:
22349     case DW_TAG_partial_unit:
22350       /* Compilation units have a DW_AT_name that is a filename, not
22351          a source language identifier.  */
22352     case DW_TAG_enumeration_type:
22353     case DW_TAG_enumerator:
22354       /* These tags always have simple identifiers already; no need
22355          to canonicalize them.  */
22356       return DW_STRING (attr);
22357
22358     case DW_TAG_namespace:
22359       if (attr != NULL && DW_STRING (attr) != NULL)
22360         return DW_STRING (attr);
22361       return CP_ANONYMOUS_NAMESPACE_STR;
22362
22363     case DW_TAG_class_type:
22364     case DW_TAG_interface_type:
22365     case DW_TAG_structure_type:
22366     case DW_TAG_union_type:
22367       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22368          structures or unions.  These were of the form "._%d" in GCC 4.1,
22369          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22370          and GCC 4.4.  We work around this problem by ignoring these.  */
22371       if (attr && DW_STRING (attr)
22372           && (startswith (DW_STRING (attr), "._")
22373               || startswith (DW_STRING (attr), "<anonymous")))
22374         return NULL;
22375
22376       /* GCC might emit a nameless typedef that has a linkage name.  See
22377          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22378       if (!attr || DW_STRING (attr) == NULL)
22379         {
22380           char *demangled = NULL;
22381
22382           attr = dw2_linkage_name_attr (die, cu);
22383           if (attr == NULL || DW_STRING (attr) == NULL)
22384             return NULL;
22385
22386           /* Avoid demangling DW_STRING (attr) the second time on a second
22387              call for the same DIE.  */
22388           if (!DW_STRING_IS_CANONICAL (attr))
22389             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22390
22391           if (demangled)
22392             {
22393               const char *base;
22394
22395               /* FIXME: we already did this for the partial symbol... */
22396               DW_STRING (attr)
22397                 = ((const char *)
22398                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
22399                                   demangled, strlen (demangled)));
22400               DW_STRING_IS_CANONICAL (attr) = 1;
22401               xfree (demangled);
22402
22403               /* Strip any leading namespaces/classes, keep only the base name.
22404                  DW_AT_name for named DIEs does not contain the prefixes.  */
22405               base = strrchr (DW_STRING (attr), ':');
22406               if (base && base > DW_STRING (attr) && base[-1] == ':')
22407                 return &base[1];
22408               else
22409                 return DW_STRING (attr);
22410             }
22411         }
22412       break;
22413
22414     default:
22415       break;
22416     }
22417
22418   if (!DW_STRING_IS_CANONICAL (attr))
22419     {
22420       DW_STRING (attr)
22421         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22422                                     &cu->objfile->per_bfd->storage_obstack);
22423       DW_STRING_IS_CANONICAL (attr) = 1;
22424     }
22425   return DW_STRING (attr);
22426 }
22427
22428 /* Return the die that this die in an extension of, or NULL if there
22429    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22430    containing the return value on output.  */
22431
22432 static struct die_info *
22433 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22434 {
22435   struct attribute *attr;
22436
22437   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22438   if (attr == NULL)
22439     return NULL;
22440
22441   return follow_die_ref (die, attr, ext_cu);
22442 }
22443
22444 /* Convert a DIE tag into its string name.  */
22445
22446 static const char *
22447 dwarf_tag_name (unsigned tag)
22448 {
22449   const char *name = get_DW_TAG_name (tag);
22450
22451   if (name == NULL)
22452     return "DW_TAG_<unknown>";
22453
22454   return name;
22455 }
22456
22457 /* Convert a DWARF attribute code into its string name.  */
22458
22459 static const char *
22460 dwarf_attr_name (unsigned attr)
22461 {
22462   const char *name;
22463
22464 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22465   if (attr == DW_AT_MIPS_fde)
22466     return "DW_AT_MIPS_fde";
22467 #else
22468   if (attr == DW_AT_HP_block_index)
22469     return "DW_AT_HP_block_index";
22470 #endif
22471
22472   name = get_DW_AT_name (attr);
22473
22474   if (name == NULL)
22475     return "DW_AT_<unknown>";
22476
22477   return name;
22478 }
22479
22480 /* Convert a DWARF value form code into its string name.  */
22481
22482 static const char *
22483 dwarf_form_name (unsigned form)
22484 {
22485   const char *name = get_DW_FORM_name (form);
22486
22487   if (name == NULL)
22488     return "DW_FORM_<unknown>";
22489
22490   return name;
22491 }
22492
22493 static const char *
22494 dwarf_bool_name (unsigned mybool)
22495 {
22496   if (mybool)
22497     return "TRUE";
22498   else
22499     return "FALSE";
22500 }
22501
22502 /* Convert a DWARF type code into its string name.  */
22503
22504 static const char *
22505 dwarf_type_encoding_name (unsigned enc)
22506 {
22507   const char *name = get_DW_ATE_name (enc);
22508
22509   if (name == NULL)
22510     return "DW_ATE_<unknown>";
22511
22512   return name;
22513 }
22514
22515 static void
22516 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22517 {
22518   unsigned int i;
22519
22520   print_spaces (indent, f);
22521   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22522                       dwarf_tag_name (die->tag), die->abbrev,
22523                       to_underlying (die->sect_off));
22524
22525   if (die->parent != NULL)
22526     {
22527       print_spaces (indent, f);
22528       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22529                           to_underlying (die->parent->sect_off));
22530     }
22531
22532   print_spaces (indent, f);
22533   fprintf_unfiltered (f, "  has children: %s\n",
22534            dwarf_bool_name (die->child != NULL));
22535
22536   print_spaces (indent, f);
22537   fprintf_unfiltered (f, "  attributes:\n");
22538
22539   for (i = 0; i < die->num_attrs; ++i)
22540     {
22541       print_spaces (indent, f);
22542       fprintf_unfiltered (f, "    %s (%s) ",
22543                dwarf_attr_name (die->attrs[i].name),
22544                dwarf_form_name (die->attrs[i].form));
22545
22546       switch (die->attrs[i].form)
22547         {
22548         case DW_FORM_addr:
22549         case DW_FORM_GNU_addr_index:
22550           fprintf_unfiltered (f, "address: ");
22551           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22552           break;
22553         case DW_FORM_block2:
22554         case DW_FORM_block4:
22555         case DW_FORM_block:
22556         case DW_FORM_block1:
22557           fprintf_unfiltered (f, "block: size %s",
22558                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22559           break;
22560         case DW_FORM_exprloc:
22561           fprintf_unfiltered (f, "expression: size %s",
22562                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22563           break;
22564         case DW_FORM_data16:
22565           fprintf_unfiltered (f, "constant of 16 bytes");
22566           break;
22567         case DW_FORM_ref_addr:
22568           fprintf_unfiltered (f, "ref address: ");
22569           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22570           break;
22571         case DW_FORM_GNU_ref_alt:
22572           fprintf_unfiltered (f, "alt ref address: ");
22573           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22574           break;
22575         case DW_FORM_ref1:
22576         case DW_FORM_ref2:
22577         case DW_FORM_ref4:
22578         case DW_FORM_ref8:
22579         case DW_FORM_ref_udata:
22580           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22581                               (long) (DW_UNSND (&die->attrs[i])));
22582           break;
22583         case DW_FORM_data1:
22584         case DW_FORM_data2:
22585         case DW_FORM_data4:
22586         case DW_FORM_data8:
22587         case DW_FORM_udata:
22588         case DW_FORM_sdata:
22589           fprintf_unfiltered (f, "constant: %s",
22590                               pulongest (DW_UNSND (&die->attrs[i])));
22591           break;
22592         case DW_FORM_sec_offset:
22593           fprintf_unfiltered (f, "section offset: %s",
22594                               pulongest (DW_UNSND (&die->attrs[i])));
22595           break;
22596         case DW_FORM_ref_sig8:
22597           fprintf_unfiltered (f, "signature: %s",
22598                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22599           break;
22600         case DW_FORM_string:
22601         case DW_FORM_strp:
22602         case DW_FORM_line_strp:
22603         case DW_FORM_GNU_str_index:
22604         case DW_FORM_GNU_strp_alt:
22605           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22606                    DW_STRING (&die->attrs[i])
22607                    ? DW_STRING (&die->attrs[i]) : "",
22608                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22609           break;
22610         case DW_FORM_flag:
22611           if (DW_UNSND (&die->attrs[i]))
22612             fprintf_unfiltered (f, "flag: TRUE");
22613           else
22614             fprintf_unfiltered (f, "flag: FALSE");
22615           break;
22616         case DW_FORM_flag_present:
22617           fprintf_unfiltered (f, "flag: TRUE");
22618           break;
22619         case DW_FORM_indirect:
22620           /* The reader will have reduced the indirect form to
22621              the "base form" so this form should not occur.  */
22622           fprintf_unfiltered (f, 
22623                               "unexpected attribute form: DW_FORM_indirect");
22624           break;
22625         case DW_FORM_implicit_const:
22626           fprintf_unfiltered (f, "constant: %s",
22627                               plongest (DW_SND (&die->attrs[i])));
22628           break;
22629         default:
22630           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22631                    die->attrs[i].form);
22632           break;
22633         }
22634       fprintf_unfiltered (f, "\n");
22635     }
22636 }
22637
22638 static void
22639 dump_die_for_error (struct die_info *die)
22640 {
22641   dump_die_shallow (gdb_stderr, 0, die);
22642 }
22643
22644 static void
22645 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22646 {
22647   int indent = level * 4;
22648
22649   gdb_assert (die != NULL);
22650
22651   if (level >= max_level)
22652     return;
22653
22654   dump_die_shallow (f, indent, die);
22655
22656   if (die->child != NULL)
22657     {
22658       print_spaces (indent, f);
22659       fprintf_unfiltered (f, "  Children:");
22660       if (level + 1 < max_level)
22661         {
22662           fprintf_unfiltered (f, "\n");
22663           dump_die_1 (f, level + 1, max_level, die->child);
22664         }
22665       else
22666         {
22667           fprintf_unfiltered (f,
22668                               " [not printed, max nesting level reached]\n");
22669         }
22670     }
22671
22672   if (die->sibling != NULL && level > 0)
22673     {
22674       dump_die_1 (f, level, max_level, die->sibling);
22675     }
22676 }
22677
22678 /* This is called from the pdie macro in gdbinit.in.
22679    It's not static so gcc will keep a copy callable from gdb.  */
22680
22681 void
22682 dump_die (struct die_info *die, int max_level)
22683 {
22684   dump_die_1 (gdb_stdlog, 0, max_level, die);
22685 }
22686
22687 static void
22688 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22689 {
22690   void **slot;
22691
22692   slot = htab_find_slot_with_hash (cu->die_hash, die,
22693                                    to_underlying (die->sect_off),
22694                                    INSERT);
22695
22696   *slot = die;
22697 }
22698
22699 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22700    required kind.  */
22701
22702 static sect_offset
22703 dwarf2_get_ref_die_offset (const struct attribute *attr)
22704 {
22705   if (attr_form_is_ref (attr))
22706     return (sect_offset) DW_UNSND (attr);
22707
22708   complaint (&symfile_complaints,
22709              _("unsupported die ref attribute form: '%s'"),
22710              dwarf_form_name (attr->form));
22711   return {};
22712 }
22713
22714 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22715  * the value held by the attribute is not constant.  */
22716
22717 static LONGEST
22718 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22719 {
22720   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22721     return DW_SND (attr);
22722   else if (attr->form == DW_FORM_udata
22723            || attr->form == DW_FORM_data1
22724            || attr->form == DW_FORM_data2
22725            || attr->form == DW_FORM_data4
22726            || attr->form == DW_FORM_data8)
22727     return DW_UNSND (attr);
22728   else
22729     {
22730       /* For DW_FORM_data16 see attr_form_is_constant.  */
22731       complaint (&symfile_complaints,
22732                  _("Attribute value is not a constant (%s)"),
22733                  dwarf_form_name (attr->form));
22734       return default_value;
22735     }
22736 }
22737
22738 /* Follow reference or signature attribute ATTR of SRC_DIE.
22739    On entry *REF_CU is the CU of SRC_DIE.
22740    On exit *REF_CU is the CU of the result.  */
22741
22742 static struct die_info *
22743 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22744                        struct dwarf2_cu **ref_cu)
22745 {
22746   struct die_info *die;
22747
22748   if (attr_form_is_ref (attr))
22749     die = follow_die_ref (src_die, attr, ref_cu);
22750   else if (attr->form == DW_FORM_ref_sig8)
22751     die = follow_die_sig (src_die, attr, ref_cu);
22752   else
22753     {
22754       dump_die_for_error (src_die);
22755       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22756              objfile_name ((*ref_cu)->objfile));
22757     }
22758
22759   return die;
22760 }
22761
22762 /* Follow reference OFFSET.
22763    On entry *REF_CU is the CU of the source die referencing OFFSET.
22764    On exit *REF_CU is the CU of the result.
22765    Returns NULL if OFFSET is invalid.  */
22766
22767 static struct die_info *
22768 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22769                    struct dwarf2_cu **ref_cu)
22770 {
22771   struct die_info temp_die;
22772   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22773
22774   gdb_assert (cu->per_cu != NULL);
22775
22776   target_cu = cu;
22777
22778   if (cu->per_cu->is_debug_types)
22779     {
22780       /* .debug_types CUs cannot reference anything outside their CU.
22781          If they need to, they have to reference a signatured type via
22782          DW_FORM_ref_sig8.  */
22783       if (!offset_in_cu_p (&cu->header, sect_off))
22784         return NULL;
22785     }
22786   else if (offset_in_dwz != cu->per_cu->is_dwz
22787            || !offset_in_cu_p (&cu->header, sect_off))
22788     {
22789       struct dwarf2_per_cu_data *per_cu;
22790
22791       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22792                                                  cu->objfile);
22793
22794       /* If necessary, add it to the queue and load its DIEs.  */
22795       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22796         load_full_comp_unit (per_cu, cu->language);
22797
22798       target_cu = per_cu->cu;
22799     }
22800   else if (cu->dies == NULL)
22801     {
22802       /* We're loading full DIEs during partial symbol reading.  */
22803       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22804       load_full_comp_unit (cu->per_cu, language_minimal);
22805     }
22806
22807   *ref_cu = target_cu;
22808   temp_die.sect_off = sect_off;
22809   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22810                                                   &temp_die,
22811                                                   to_underlying (sect_off));
22812 }
22813
22814 /* Follow reference attribute ATTR of SRC_DIE.
22815    On entry *REF_CU is the CU of SRC_DIE.
22816    On exit *REF_CU is the CU of the result.  */
22817
22818 static struct die_info *
22819 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22820                 struct dwarf2_cu **ref_cu)
22821 {
22822   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22823   struct dwarf2_cu *cu = *ref_cu;
22824   struct die_info *die;
22825
22826   die = follow_die_offset (sect_off,
22827                            (attr->form == DW_FORM_GNU_ref_alt
22828                             || cu->per_cu->is_dwz),
22829                            ref_cu);
22830   if (!die)
22831     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
22832            "at 0x%x [in module %s]"),
22833            to_underlying (sect_off), to_underlying (src_die->sect_off),
22834            objfile_name (cu->objfile));
22835
22836   return die;
22837 }
22838
22839 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22840    Returned value is intended for DW_OP_call*.  Returned
22841    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
22842
22843 struct dwarf2_locexpr_baton
22844 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22845                                struct dwarf2_per_cu_data *per_cu,
22846                                CORE_ADDR (*get_frame_pc) (void *baton),
22847                                void *baton)
22848 {
22849   struct dwarf2_cu *cu;
22850   struct die_info *die;
22851   struct attribute *attr;
22852   struct dwarf2_locexpr_baton retval;
22853
22854   dw2_setup (per_cu->objfile);
22855
22856   if (per_cu->cu == NULL)
22857     load_cu (per_cu);
22858   cu = per_cu->cu;
22859   if (cu == NULL)
22860     {
22861       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22862          Instead just throw an error, not much else we can do.  */
22863       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22864              to_underlying (sect_off), objfile_name (per_cu->objfile));
22865     }
22866
22867   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22868   if (!die)
22869     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
22870            to_underlying (sect_off), objfile_name (per_cu->objfile));
22871
22872   attr = dwarf2_attr (die, DW_AT_location, cu);
22873   if (!attr)
22874     {
22875       /* DWARF: "If there is no such attribute, then there is no effect.".
22876          DATA is ignored if SIZE is 0.  */
22877
22878       retval.data = NULL;
22879       retval.size = 0;
22880     }
22881   else if (attr_form_is_section_offset (attr))
22882     {
22883       struct dwarf2_loclist_baton loclist_baton;
22884       CORE_ADDR pc = (*get_frame_pc) (baton);
22885       size_t size;
22886
22887       fill_in_loclist_baton (cu, &loclist_baton, attr);
22888
22889       retval.data = dwarf2_find_location_expression (&loclist_baton,
22890                                                      &size, pc);
22891       retval.size = size;
22892     }
22893   else
22894     {
22895       if (!attr_form_is_block (attr))
22896         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
22897                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22898                to_underlying (sect_off), objfile_name (per_cu->objfile));
22899
22900       retval.data = DW_BLOCK (attr)->data;
22901       retval.size = DW_BLOCK (attr)->size;
22902     }
22903   retval.per_cu = cu->per_cu;
22904
22905   age_cached_comp_units ();
22906
22907   return retval;
22908 }
22909
22910 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22911    offset.  */
22912
22913 struct dwarf2_locexpr_baton
22914 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22915                              struct dwarf2_per_cu_data *per_cu,
22916                              CORE_ADDR (*get_frame_pc) (void *baton),
22917                              void *baton)
22918 {
22919   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22920
22921   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22922 }
22923
22924 /* Write a constant of a given type as target-ordered bytes into
22925    OBSTACK.  */
22926
22927 static const gdb_byte *
22928 write_constant_as_bytes (struct obstack *obstack,
22929                          enum bfd_endian byte_order,
22930                          struct type *type,
22931                          ULONGEST value,
22932                          LONGEST *len)
22933 {
22934   gdb_byte *result;
22935
22936   *len = TYPE_LENGTH (type);
22937   result = (gdb_byte *) obstack_alloc (obstack, *len);
22938   store_unsigned_integer (result, *len, byte_order, value);
22939
22940   return result;
22941 }
22942
22943 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22944    pointer to the constant bytes and set LEN to the length of the
22945    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22946    does not have a DW_AT_const_value, return NULL.  */
22947
22948 const gdb_byte *
22949 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22950                              struct dwarf2_per_cu_data *per_cu,
22951                              struct obstack *obstack,
22952                              LONGEST *len)
22953 {
22954   struct dwarf2_cu *cu;
22955   struct die_info *die;
22956   struct attribute *attr;
22957   const gdb_byte *result = NULL;
22958   struct type *type;
22959   LONGEST value;
22960   enum bfd_endian byte_order;
22961
22962   dw2_setup (per_cu->objfile);
22963
22964   if (per_cu->cu == NULL)
22965     load_cu (per_cu);
22966   cu = per_cu->cu;
22967   if (cu == NULL)
22968     {
22969       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22970          Instead just throw an error, not much else we can do.  */
22971       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22972              to_underlying (sect_off), objfile_name (per_cu->objfile));
22973     }
22974
22975   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22976   if (!die)
22977     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
22978            to_underlying (sect_off), objfile_name (per_cu->objfile));
22979
22980
22981   attr = dwarf2_attr (die, DW_AT_const_value, cu);
22982   if (attr == NULL)
22983     return NULL;
22984
22985   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
22986                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22987
22988   switch (attr->form)
22989     {
22990     case DW_FORM_addr:
22991     case DW_FORM_GNU_addr_index:
22992       {
22993         gdb_byte *tem;
22994
22995         *len = cu->header.addr_size;
22996         tem = (gdb_byte *) obstack_alloc (obstack, *len);
22997         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
22998         result = tem;
22999       }
23000       break;
23001     case DW_FORM_string:
23002     case DW_FORM_strp:
23003     case DW_FORM_GNU_str_index:
23004     case DW_FORM_GNU_strp_alt:
23005       /* DW_STRING is already allocated on the objfile obstack, point
23006          directly to it.  */
23007       result = (const gdb_byte *) DW_STRING (attr);
23008       *len = strlen (DW_STRING (attr));
23009       break;
23010     case DW_FORM_block1:
23011     case DW_FORM_block2:
23012     case DW_FORM_block4:
23013     case DW_FORM_block:
23014     case DW_FORM_exprloc:
23015     case DW_FORM_data16:
23016       result = DW_BLOCK (attr)->data;
23017       *len = DW_BLOCK (attr)->size;
23018       break;
23019
23020       /* The DW_AT_const_value attributes are supposed to carry the
23021          symbol's value "represented as it would be on the target
23022          architecture."  By the time we get here, it's already been
23023          converted to host endianness, so we just need to sign- or
23024          zero-extend it as appropriate.  */
23025     case DW_FORM_data1:
23026       type = die_type (die, cu);
23027       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23028       if (result == NULL)
23029         result = write_constant_as_bytes (obstack, byte_order,
23030                                           type, value, len);
23031       break;
23032     case DW_FORM_data2:
23033       type = die_type (die, cu);
23034       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23035       if (result == NULL)
23036         result = write_constant_as_bytes (obstack, byte_order,
23037                                           type, value, len);
23038       break;
23039     case DW_FORM_data4:
23040       type = die_type (die, cu);
23041       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23042       if (result == NULL)
23043         result = write_constant_as_bytes (obstack, byte_order,
23044                                           type, value, len);
23045       break;
23046     case DW_FORM_data8:
23047       type = die_type (die, cu);
23048       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23049       if (result == NULL)
23050         result = write_constant_as_bytes (obstack, byte_order,
23051                                           type, value, len);
23052       break;
23053
23054     case DW_FORM_sdata:
23055     case DW_FORM_implicit_const:
23056       type = die_type (die, cu);
23057       result = write_constant_as_bytes (obstack, byte_order,
23058                                         type, DW_SND (attr), len);
23059       break;
23060
23061     case DW_FORM_udata:
23062       type = die_type (die, cu);
23063       result = write_constant_as_bytes (obstack, byte_order,
23064                                         type, DW_UNSND (attr), len);
23065       break;
23066
23067     default:
23068       complaint (&symfile_complaints,
23069                  _("unsupported const value attribute form: '%s'"),
23070                  dwarf_form_name (attr->form));
23071       break;
23072     }
23073
23074   return result;
23075 }
23076
23077 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23078    valid type for this die is found.  */
23079
23080 struct type *
23081 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23082                                 struct dwarf2_per_cu_data *per_cu)
23083 {
23084   struct dwarf2_cu *cu;
23085   struct die_info *die;
23086
23087   dw2_setup (per_cu->objfile);
23088
23089   if (per_cu->cu == NULL)
23090     load_cu (per_cu);
23091   cu = per_cu->cu;
23092   if (!cu)
23093     return NULL;
23094
23095   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23096   if (!die)
23097     return NULL;
23098
23099   return die_type (die, cu);
23100 }
23101
23102 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23103    PER_CU.  */
23104
23105 struct type *
23106 dwarf2_get_die_type (cu_offset die_offset,
23107                      struct dwarf2_per_cu_data *per_cu)
23108 {
23109   dw2_setup (per_cu->objfile);
23110
23111   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23112   return get_die_type_at_offset (die_offset_sect, per_cu);
23113 }
23114
23115 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23116    On entry *REF_CU is the CU of SRC_DIE.
23117    On exit *REF_CU is the CU of the result.
23118    Returns NULL if the referenced DIE isn't found.  */
23119
23120 static struct die_info *
23121 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23122                   struct dwarf2_cu **ref_cu)
23123 {
23124   struct die_info temp_die;
23125   struct dwarf2_cu *sig_cu;
23126   struct die_info *die;
23127
23128   /* While it might be nice to assert sig_type->type == NULL here,
23129      we can get here for DW_AT_imported_declaration where we need
23130      the DIE not the type.  */
23131
23132   /* If necessary, add it to the queue and load its DIEs.  */
23133
23134   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23135     read_signatured_type (sig_type);
23136
23137   sig_cu = sig_type->per_cu.cu;
23138   gdb_assert (sig_cu != NULL);
23139   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23140   temp_die.sect_off = sig_type->type_offset_in_section;
23141   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23142                                                  to_underlying (temp_die.sect_off));
23143   if (die)
23144     {
23145       /* For .gdb_index version 7 keep track of included TUs.
23146          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23147       if (dwarf2_per_objfile->index_table != NULL
23148           && dwarf2_per_objfile->index_table->version <= 7)
23149         {
23150           VEC_safe_push (dwarf2_per_cu_ptr,
23151                          (*ref_cu)->per_cu->imported_symtabs,
23152                          sig_cu->per_cu);
23153         }
23154
23155       *ref_cu = sig_cu;
23156       return die;
23157     }
23158
23159   return NULL;
23160 }
23161
23162 /* Follow signatured type referenced by ATTR in SRC_DIE.
23163    On entry *REF_CU is the CU of SRC_DIE.
23164    On exit *REF_CU is the CU of the result.
23165    The result is the DIE of the type.
23166    If the referenced type cannot be found an error is thrown.  */
23167
23168 static struct die_info *
23169 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23170                 struct dwarf2_cu **ref_cu)
23171 {
23172   ULONGEST signature = DW_SIGNATURE (attr);
23173   struct signatured_type *sig_type;
23174   struct die_info *die;
23175
23176   gdb_assert (attr->form == DW_FORM_ref_sig8);
23177
23178   sig_type = lookup_signatured_type (*ref_cu, signature);
23179   /* sig_type will be NULL if the signatured type is missing from
23180      the debug info.  */
23181   if (sig_type == NULL)
23182     {
23183       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23184                " from DIE at 0x%x [in module %s]"),
23185              hex_string (signature), to_underlying (src_die->sect_off),
23186              objfile_name ((*ref_cu)->objfile));
23187     }
23188
23189   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23190   if (die == NULL)
23191     {
23192       dump_die_for_error (src_die);
23193       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23194                " from DIE at 0x%x [in module %s]"),
23195              hex_string (signature), to_underlying (src_die->sect_off),
23196              objfile_name ((*ref_cu)->objfile));
23197     }
23198
23199   return die;
23200 }
23201
23202 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23203    reading in and processing the type unit if necessary.  */
23204
23205 static struct type *
23206 get_signatured_type (struct die_info *die, ULONGEST signature,
23207                      struct dwarf2_cu *cu)
23208 {
23209   struct signatured_type *sig_type;
23210   struct dwarf2_cu *type_cu;
23211   struct die_info *type_die;
23212   struct type *type;
23213
23214   sig_type = lookup_signatured_type (cu, signature);
23215   /* sig_type will be NULL if the signatured type is missing from
23216      the debug info.  */
23217   if (sig_type == NULL)
23218     {
23219       complaint (&symfile_complaints,
23220                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23221                    " from DIE at 0x%x [in module %s]"),
23222                  hex_string (signature), to_underlying (die->sect_off),
23223                  objfile_name (dwarf2_per_objfile->objfile));
23224       return build_error_marker_type (cu, die);
23225     }
23226
23227   /* If we already know the type we're done.  */
23228   if (sig_type->type != NULL)
23229     return sig_type->type;
23230
23231   type_cu = cu;
23232   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23233   if (type_die != NULL)
23234     {
23235       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23236          is created.  This is important, for example, because for c++ classes
23237          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23238       type = read_type_die (type_die, type_cu);
23239       if (type == NULL)
23240         {
23241           complaint (&symfile_complaints,
23242                      _("Dwarf Error: Cannot build signatured type %s"
23243                        " referenced from DIE at 0x%x [in module %s]"),
23244                      hex_string (signature), to_underlying (die->sect_off),
23245                      objfile_name (dwarf2_per_objfile->objfile));
23246           type = build_error_marker_type (cu, die);
23247         }
23248     }
23249   else
23250     {
23251       complaint (&symfile_complaints,
23252                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23253                    " from DIE at 0x%x [in module %s]"),
23254                  hex_string (signature), to_underlying (die->sect_off),
23255                  objfile_name (dwarf2_per_objfile->objfile));
23256       type = build_error_marker_type (cu, die);
23257     }
23258   sig_type->type = type;
23259
23260   return type;
23261 }
23262
23263 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23264    reading in and processing the type unit if necessary.  */
23265
23266 static struct type *
23267 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23268                           struct dwarf2_cu *cu) /* ARI: editCase function */
23269 {
23270   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23271   if (attr_form_is_ref (attr))
23272     {
23273       struct dwarf2_cu *type_cu = cu;
23274       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23275
23276       return read_type_die (type_die, type_cu);
23277     }
23278   else if (attr->form == DW_FORM_ref_sig8)
23279     {
23280       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23281     }
23282   else
23283     {
23284       complaint (&symfile_complaints,
23285                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23286                    " at 0x%x [in module %s]"),
23287                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23288                  objfile_name (dwarf2_per_objfile->objfile));
23289       return build_error_marker_type (cu, die);
23290     }
23291 }
23292
23293 /* Load the DIEs associated with type unit PER_CU into memory.  */
23294
23295 static void
23296 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23297 {
23298   struct signatured_type *sig_type;
23299
23300   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23301   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23302
23303   /* We have the per_cu, but we need the signatured_type.
23304      Fortunately this is an easy translation.  */
23305   gdb_assert (per_cu->is_debug_types);
23306   sig_type = (struct signatured_type *) per_cu;
23307
23308   gdb_assert (per_cu->cu == NULL);
23309
23310   read_signatured_type (sig_type);
23311
23312   gdb_assert (per_cu->cu != NULL);
23313 }
23314
23315 /* die_reader_func for read_signatured_type.
23316    This is identical to load_full_comp_unit_reader,
23317    but is kept separate for now.  */
23318
23319 static void
23320 read_signatured_type_reader (const struct die_reader_specs *reader,
23321                              const gdb_byte *info_ptr,
23322                              struct die_info *comp_unit_die,
23323                              int has_children,
23324                              void *data)
23325 {
23326   struct dwarf2_cu *cu = reader->cu;
23327
23328   gdb_assert (cu->die_hash == NULL);
23329   cu->die_hash =
23330     htab_create_alloc_ex (cu->header.length / 12,
23331                           die_hash,
23332                           die_eq,
23333                           NULL,
23334                           &cu->comp_unit_obstack,
23335                           hashtab_obstack_allocate,
23336                           dummy_obstack_deallocate);
23337
23338   if (has_children)
23339     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23340                                                   &info_ptr, comp_unit_die);
23341   cu->dies = comp_unit_die;
23342   /* comp_unit_die is not stored in die_hash, no need.  */
23343
23344   /* We try not to read any attributes in this function, because not
23345      all CUs needed for references have been loaded yet, and symbol
23346      table processing isn't initialized.  But we have to set the CU language,
23347      or we won't be able to build types correctly.
23348      Similarly, if we do not read the producer, we can not apply
23349      producer-specific interpretation.  */
23350   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23351 }
23352
23353 /* Read in a signatured type and build its CU and DIEs.
23354    If the type is a stub for the real type in a DWO file,
23355    read in the real type from the DWO file as well.  */
23356
23357 static void
23358 read_signatured_type (struct signatured_type *sig_type)
23359 {
23360   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23361
23362   gdb_assert (per_cu->is_debug_types);
23363   gdb_assert (per_cu->cu == NULL);
23364
23365   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23366                            read_signatured_type_reader, NULL);
23367   sig_type->per_cu.tu_read = 1;
23368 }
23369
23370 /* Decode simple location descriptions.
23371    Given a pointer to a dwarf block that defines a location, compute
23372    the location and return the value.
23373
23374    NOTE drow/2003-11-18: This function is called in two situations
23375    now: for the address of static or global variables (partial symbols
23376    only) and for offsets into structures which are expected to be
23377    (more or less) constant.  The partial symbol case should go away,
23378    and only the constant case should remain.  That will let this
23379    function complain more accurately.  A few special modes are allowed
23380    without complaint for global variables (for instance, global
23381    register values and thread-local values).
23382
23383    A location description containing no operations indicates that the
23384    object is optimized out.  The return value is 0 for that case.
23385    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23386    callers will only want a very basic result and this can become a
23387    complaint.
23388
23389    Note that stack[0] is unused except as a default error return.  */
23390
23391 static CORE_ADDR
23392 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23393 {
23394   struct objfile *objfile = cu->objfile;
23395   size_t i;
23396   size_t size = blk->size;
23397   const gdb_byte *data = blk->data;
23398   CORE_ADDR stack[64];
23399   int stacki;
23400   unsigned int bytes_read, unsnd;
23401   gdb_byte op;
23402
23403   i = 0;
23404   stacki = 0;
23405   stack[stacki] = 0;
23406   stack[++stacki] = 0;
23407
23408   while (i < size)
23409     {
23410       op = data[i++];
23411       switch (op)
23412         {
23413         case DW_OP_lit0:
23414         case DW_OP_lit1:
23415         case DW_OP_lit2:
23416         case DW_OP_lit3:
23417         case DW_OP_lit4:
23418         case DW_OP_lit5:
23419         case DW_OP_lit6:
23420         case DW_OP_lit7:
23421         case DW_OP_lit8:
23422         case DW_OP_lit9:
23423         case DW_OP_lit10:
23424         case DW_OP_lit11:
23425         case DW_OP_lit12:
23426         case DW_OP_lit13:
23427         case DW_OP_lit14:
23428         case DW_OP_lit15:
23429         case DW_OP_lit16:
23430         case DW_OP_lit17:
23431         case DW_OP_lit18:
23432         case DW_OP_lit19:
23433         case DW_OP_lit20:
23434         case DW_OP_lit21:
23435         case DW_OP_lit22:
23436         case DW_OP_lit23:
23437         case DW_OP_lit24:
23438         case DW_OP_lit25:
23439         case DW_OP_lit26:
23440         case DW_OP_lit27:
23441         case DW_OP_lit28:
23442         case DW_OP_lit29:
23443         case DW_OP_lit30:
23444         case DW_OP_lit31:
23445           stack[++stacki] = op - DW_OP_lit0;
23446           break;
23447
23448         case DW_OP_reg0:
23449         case DW_OP_reg1:
23450         case DW_OP_reg2:
23451         case DW_OP_reg3:
23452         case DW_OP_reg4:
23453         case DW_OP_reg5:
23454         case DW_OP_reg6:
23455         case DW_OP_reg7:
23456         case DW_OP_reg8:
23457         case DW_OP_reg9:
23458         case DW_OP_reg10:
23459         case DW_OP_reg11:
23460         case DW_OP_reg12:
23461         case DW_OP_reg13:
23462         case DW_OP_reg14:
23463         case DW_OP_reg15:
23464         case DW_OP_reg16:
23465         case DW_OP_reg17:
23466         case DW_OP_reg18:
23467         case DW_OP_reg19:
23468         case DW_OP_reg20:
23469         case DW_OP_reg21:
23470         case DW_OP_reg22:
23471         case DW_OP_reg23:
23472         case DW_OP_reg24:
23473         case DW_OP_reg25:
23474         case DW_OP_reg26:
23475         case DW_OP_reg27:
23476         case DW_OP_reg28:
23477         case DW_OP_reg29:
23478         case DW_OP_reg30:
23479         case DW_OP_reg31:
23480           stack[++stacki] = op - DW_OP_reg0;
23481           if (i < size)
23482             dwarf2_complex_location_expr_complaint ();
23483           break;
23484
23485         case DW_OP_regx:
23486           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23487           i += bytes_read;
23488           stack[++stacki] = unsnd;
23489           if (i < size)
23490             dwarf2_complex_location_expr_complaint ();
23491           break;
23492
23493         case DW_OP_addr:
23494           stack[++stacki] = read_address (objfile->obfd, &data[i],
23495                                           cu, &bytes_read);
23496           i += bytes_read;
23497           break;
23498
23499         case DW_OP_const1u:
23500           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23501           i += 1;
23502           break;
23503
23504         case DW_OP_const1s:
23505           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23506           i += 1;
23507           break;
23508
23509         case DW_OP_const2u:
23510           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23511           i += 2;
23512           break;
23513
23514         case DW_OP_const2s:
23515           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23516           i += 2;
23517           break;
23518
23519         case DW_OP_const4u:
23520           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23521           i += 4;
23522           break;
23523
23524         case DW_OP_const4s:
23525           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23526           i += 4;
23527           break;
23528
23529         case DW_OP_const8u:
23530           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23531           i += 8;
23532           break;
23533
23534         case DW_OP_constu:
23535           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23536                                                   &bytes_read);
23537           i += bytes_read;
23538           break;
23539
23540         case DW_OP_consts:
23541           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23542           i += bytes_read;
23543           break;
23544
23545         case DW_OP_dup:
23546           stack[stacki + 1] = stack[stacki];
23547           stacki++;
23548           break;
23549
23550         case DW_OP_plus:
23551           stack[stacki - 1] += stack[stacki];
23552           stacki--;
23553           break;
23554
23555         case DW_OP_plus_uconst:
23556           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23557                                                  &bytes_read);
23558           i += bytes_read;
23559           break;
23560
23561         case DW_OP_minus:
23562           stack[stacki - 1] -= stack[stacki];
23563           stacki--;
23564           break;
23565
23566         case DW_OP_deref:
23567           /* If we're not the last op, then we definitely can't encode
23568              this using GDB's address_class enum.  This is valid for partial
23569              global symbols, although the variable's address will be bogus
23570              in the psymtab.  */
23571           if (i < size)
23572             dwarf2_complex_location_expr_complaint ();
23573           break;
23574
23575         case DW_OP_GNU_push_tls_address:
23576         case DW_OP_form_tls_address:
23577           /* The top of the stack has the offset from the beginning
23578              of the thread control block at which the variable is located.  */
23579           /* Nothing should follow this operator, so the top of stack would
23580              be returned.  */
23581           /* This is valid for partial global symbols, but the variable's
23582              address will be bogus in the psymtab.  Make it always at least
23583              non-zero to not look as a variable garbage collected by linker
23584              which have DW_OP_addr 0.  */
23585           if (i < size)
23586             dwarf2_complex_location_expr_complaint ();
23587           stack[stacki]++;
23588           break;
23589
23590         case DW_OP_GNU_uninit:
23591           break;
23592
23593         case DW_OP_GNU_addr_index:
23594         case DW_OP_GNU_const_index:
23595           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23596                                                          &bytes_read);
23597           i += bytes_read;
23598           break;
23599
23600         default:
23601           {
23602             const char *name = get_DW_OP_name (op);
23603
23604             if (name)
23605               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23606                          name);
23607             else
23608               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23609                          op);
23610           }
23611
23612           return (stack[stacki]);
23613         }
23614
23615       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23616          outside of the allocated space.  Also enforce minimum>0.  */
23617       if (stacki >= ARRAY_SIZE (stack) - 1)
23618         {
23619           complaint (&symfile_complaints,
23620                      _("location description stack overflow"));
23621           return 0;
23622         }
23623
23624       if (stacki <= 0)
23625         {
23626           complaint (&symfile_complaints,
23627                      _("location description stack underflow"));
23628           return 0;
23629         }
23630     }
23631   return (stack[stacki]);
23632 }
23633
23634 /* memory allocation interface */
23635
23636 static struct dwarf_block *
23637 dwarf_alloc_block (struct dwarf2_cu *cu)
23638 {
23639   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23640 }
23641
23642 static struct die_info *
23643 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23644 {
23645   struct die_info *die;
23646   size_t size = sizeof (struct die_info);
23647
23648   if (num_attrs > 1)
23649     size += (num_attrs - 1) * sizeof (struct attribute);
23650
23651   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23652   memset (die, 0, sizeof (struct die_info));
23653   return (die);
23654 }
23655
23656 \f
23657 /* Macro support.  */
23658
23659 /* Return file name relative to the compilation directory of file number I in
23660    *LH's file name table.  The result is allocated using xmalloc; the caller is
23661    responsible for freeing it.  */
23662
23663 static char *
23664 file_file_name (int file, struct line_header *lh)
23665 {
23666   /* Is the file number a valid index into the line header's file name
23667      table?  Remember that file numbers start with one, not zero.  */
23668   if (1 <= file && file <= lh->file_names.size ())
23669     {
23670       const file_entry &fe = lh->file_names[file - 1];
23671
23672       if (!IS_ABSOLUTE_PATH (fe.name))
23673         {
23674           const char *dir = fe.include_dir (lh);
23675           if (dir != NULL)
23676             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23677         }
23678       return xstrdup (fe.name);
23679     }
23680   else
23681     {
23682       /* The compiler produced a bogus file number.  We can at least
23683          record the macro definitions made in the file, even if we
23684          won't be able to find the file by name.  */
23685       char fake_name[80];
23686
23687       xsnprintf (fake_name, sizeof (fake_name),
23688                  "<bad macro file number %d>", file);
23689
23690       complaint (&symfile_complaints,
23691                  _("bad file number in macro information (%d)"),
23692                  file);
23693
23694       return xstrdup (fake_name);
23695     }
23696 }
23697
23698 /* Return the full name of file number I in *LH's file name table.
23699    Use COMP_DIR as the name of the current directory of the
23700    compilation.  The result is allocated using xmalloc; the caller is
23701    responsible for freeing it.  */
23702 static char *
23703 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23704 {
23705   /* Is the file number a valid index into the line header's file name
23706      table?  Remember that file numbers start with one, not zero.  */
23707   if (1 <= file && file <= lh->file_names.size ())
23708     {
23709       char *relative = file_file_name (file, lh);
23710
23711       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23712         return relative;
23713       return reconcat (relative, comp_dir, SLASH_STRING,
23714                        relative, (char *) NULL);
23715     }
23716   else
23717     return file_file_name (file, lh);
23718 }
23719
23720
23721 static struct macro_source_file *
23722 macro_start_file (int file, int line,
23723                   struct macro_source_file *current_file,
23724                   struct line_header *lh)
23725 {
23726   /* File name relative to the compilation directory of this source file.  */
23727   char *file_name = file_file_name (file, lh);
23728
23729   if (! current_file)
23730     {
23731       /* Note: We don't create a macro table for this compilation unit
23732          at all until we actually get a filename.  */
23733       struct macro_table *macro_table = get_macro_table ();
23734
23735       /* If we have no current file, then this must be the start_file
23736          directive for the compilation unit's main source file.  */
23737       current_file = macro_set_main (macro_table, file_name);
23738       macro_define_special (macro_table);
23739     }
23740   else
23741     current_file = macro_include (current_file, line, file_name);
23742
23743   xfree (file_name);
23744
23745   return current_file;
23746 }
23747
23748 static const char *
23749 consume_improper_spaces (const char *p, const char *body)
23750 {
23751   if (*p == ' ')
23752     {
23753       complaint (&symfile_complaints,
23754                  _("macro definition contains spaces "
23755                    "in formal argument list:\n`%s'"),
23756                  body);
23757
23758       while (*p == ' ')
23759         p++;
23760     }
23761
23762   return p;
23763 }
23764
23765
23766 static void
23767 parse_macro_definition (struct macro_source_file *file, int line,
23768                         const char *body)
23769 {
23770   const char *p;
23771
23772   /* The body string takes one of two forms.  For object-like macro
23773      definitions, it should be:
23774
23775         <macro name> " " <definition>
23776
23777      For function-like macro definitions, it should be:
23778
23779         <macro name> "() " <definition>
23780      or
23781         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23782
23783      Spaces may appear only where explicitly indicated, and in the
23784      <definition>.
23785
23786      The Dwarf 2 spec says that an object-like macro's name is always
23787      followed by a space, but versions of GCC around March 2002 omit
23788      the space when the macro's definition is the empty string.
23789
23790      The Dwarf 2 spec says that there should be no spaces between the
23791      formal arguments in a function-like macro's formal argument list,
23792      but versions of GCC around March 2002 include spaces after the
23793      commas.  */
23794
23795
23796   /* Find the extent of the macro name.  The macro name is terminated
23797      by either a space or null character (for an object-like macro) or
23798      an opening paren (for a function-like macro).  */
23799   for (p = body; *p; p++)
23800     if (*p == ' ' || *p == '(')
23801       break;
23802
23803   if (*p == ' ' || *p == '\0')
23804     {
23805       /* It's an object-like macro.  */
23806       int name_len = p - body;
23807       char *name = savestring (body, name_len);
23808       const char *replacement;
23809
23810       if (*p == ' ')
23811         replacement = body + name_len + 1;
23812       else
23813         {
23814           dwarf2_macro_malformed_definition_complaint (body);
23815           replacement = body + name_len;
23816         }
23817
23818       macro_define_object (file, line, name, replacement);
23819
23820       xfree (name);
23821     }
23822   else if (*p == '(')
23823     {
23824       /* It's a function-like macro.  */
23825       char *name = savestring (body, p - body);
23826       int argc = 0;
23827       int argv_size = 1;
23828       char **argv = XNEWVEC (char *, argv_size);
23829
23830       p++;
23831
23832       p = consume_improper_spaces (p, body);
23833
23834       /* Parse the formal argument list.  */
23835       while (*p && *p != ')')
23836         {
23837           /* Find the extent of the current argument name.  */
23838           const char *arg_start = p;
23839
23840           while (*p && *p != ',' && *p != ')' && *p != ' ')
23841             p++;
23842
23843           if (! *p || p == arg_start)
23844             dwarf2_macro_malformed_definition_complaint (body);
23845           else
23846             {
23847               /* Make sure argv has room for the new argument.  */
23848               if (argc >= argv_size)
23849                 {
23850                   argv_size *= 2;
23851                   argv = XRESIZEVEC (char *, argv, argv_size);
23852                 }
23853
23854               argv[argc++] = savestring (arg_start, p - arg_start);
23855             }
23856
23857           p = consume_improper_spaces (p, body);
23858
23859           /* Consume the comma, if present.  */
23860           if (*p == ',')
23861             {
23862               p++;
23863
23864               p = consume_improper_spaces (p, body);
23865             }
23866         }
23867
23868       if (*p == ')')
23869         {
23870           p++;
23871
23872           if (*p == ' ')
23873             /* Perfectly formed definition, no complaints.  */
23874             macro_define_function (file, line, name,
23875                                    argc, (const char **) argv,
23876                                    p + 1);
23877           else if (*p == '\0')
23878             {
23879               /* Complain, but do define it.  */
23880               dwarf2_macro_malformed_definition_complaint (body);
23881               macro_define_function (file, line, name,
23882                                      argc, (const char **) argv,
23883                                      p);
23884             }
23885           else
23886             /* Just complain.  */
23887             dwarf2_macro_malformed_definition_complaint (body);
23888         }
23889       else
23890         /* Just complain.  */
23891         dwarf2_macro_malformed_definition_complaint (body);
23892
23893       xfree (name);
23894       {
23895         int i;
23896
23897         for (i = 0; i < argc; i++)
23898           xfree (argv[i]);
23899       }
23900       xfree (argv);
23901     }
23902   else
23903     dwarf2_macro_malformed_definition_complaint (body);
23904 }
23905
23906 /* Skip some bytes from BYTES according to the form given in FORM.
23907    Returns the new pointer.  */
23908
23909 static const gdb_byte *
23910 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23911                  enum dwarf_form form,
23912                  unsigned int offset_size,
23913                  struct dwarf2_section_info *section)
23914 {
23915   unsigned int bytes_read;
23916
23917   switch (form)
23918     {
23919     case DW_FORM_data1:
23920     case DW_FORM_flag:
23921       ++bytes;
23922       break;
23923
23924     case DW_FORM_data2:
23925       bytes += 2;
23926       break;
23927
23928     case DW_FORM_data4:
23929       bytes += 4;
23930       break;
23931
23932     case DW_FORM_data8:
23933       bytes += 8;
23934       break;
23935
23936     case DW_FORM_data16:
23937       bytes += 16;
23938       break;
23939
23940     case DW_FORM_string:
23941       read_direct_string (abfd, bytes, &bytes_read);
23942       bytes += bytes_read;
23943       break;
23944
23945     case DW_FORM_sec_offset:
23946     case DW_FORM_strp:
23947     case DW_FORM_GNU_strp_alt:
23948       bytes += offset_size;
23949       break;
23950
23951     case DW_FORM_block:
23952       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23953       bytes += bytes_read;
23954       break;
23955
23956     case DW_FORM_block1:
23957       bytes += 1 + read_1_byte (abfd, bytes);
23958       break;
23959     case DW_FORM_block2:
23960       bytes += 2 + read_2_bytes (abfd, bytes);
23961       break;
23962     case DW_FORM_block4:
23963       bytes += 4 + read_4_bytes (abfd, bytes);
23964       break;
23965
23966     case DW_FORM_sdata:
23967     case DW_FORM_udata:
23968     case DW_FORM_GNU_addr_index:
23969     case DW_FORM_GNU_str_index:
23970       bytes = gdb_skip_leb128 (bytes, buffer_end);
23971       if (bytes == NULL)
23972         {
23973           dwarf2_section_buffer_overflow_complaint (section);
23974           return NULL;
23975         }
23976       break;
23977
23978     case DW_FORM_implicit_const:
23979       break;
23980
23981     default:
23982       {
23983         complaint (&symfile_complaints,
23984                    _("invalid form 0x%x in `%s'"),
23985                    form, get_section_name (section));
23986         return NULL;
23987       }
23988     }
23989
23990   return bytes;
23991 }
23992
23993 /* A helper for dwarf_decode_macros that handles skipping an unknown
23994    opcode.  Returns an updated pointer to the macro data buffer; or,
23995    on error, issues a complaint and returns NULL.  */
23996
23997 static const gdb_byte *
23998 skip_unknown_opcode (unsigned int opcode,
23999                      const gdb_byte **opcode_definitions,
24000                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24001                      bfd *abfd,
24002                      unsigned int offset_size,
24003                      struct dwarf2_section_info *section)
24004 {
24005   unsigned int bytes_read, i;
24006   unsigned long arg;
24007   const gdb_byte *defn;
24008
24009   if (opcode_definitions[opcode] == NULL)
24010     {
24011       complaint (&symfile_complaints,
24012                  _("unrecognized DW_MACFINO opcode 0x%x"),
24013                  opcode);
24014       return NULL;
24015     }
24016
24017   defn = opcode_definitions[opcode];
24018   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24019   defn += bytes_read;
24020
24021   for (i = 0; i < arg; ++i)
24022     {
24023       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24024                                  (enum dwarf_form) defn[i], offset_size,
24025                                  section);
24026       if (mac_ptr == NULL)
24027         {
24028           /* skip_form_bytes already issued the complaint.  */
24029           return NULL;
24030         }
24031     }
24032
24033   return mac_ptr;
24034 }
24035
24036 /* A helper function which parses the header of a macro section.
24037    If the macro section is the extended (for now called "GNU") type,
24038    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24039    the header, or issues a complaint and returns NULL on error.  */
24040
24041 static const gdb_byte *
24042 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24043                           bfd *abfd,
24044                           const gdb_byte *mac_ptr,
24045                           unsigned int *offset_size,
24046                           int section_is_gnu)
24047 {
24048   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24049
24050   if (section_is_gnu)
24051     {
24052       unsigned int version, flags;
24053
24054       version = read_2_bytes (abfd, mac_ptr);
24055       if (version != 4 && version != 5)
24056         {
24057           complaint (&symfile_complaints,
24058                      _("unrecognized version `%d' in .debug_macro section"),
24059                      version);
24060           return NULL;
24061         }
24062       mac_ptr += 2;
24063
24064       flags = read_1_byte (abfd, mac_ptr);
24065       ++mac_ptr;
24066       *offset_size = (flags & 1) ? 8 : 4;
24067
24068       if ((flags & 2) != 0)
24069         /* We don't need the line table offset.  */
24070         mac_ptr += *offset_size;
24071
24072       /* Vendor opcode descriptions.  */
24073       if ((flags & 4) != 0)
24074         {
24075           unsigned int i, count;
24076
24077           count = read_1_byte (abfd, mac_ptr);
24078           ++mac_ptr;
24079           for (i = 0; i < count; ++i)
24080             {
24081               unsigned int opcode, bytes_read;
24082               unsigned long arg;
24083
24084               opcode = read_1_byte (abfd, mac_ptr);
24085               ++mac_ptr;
24086               opcode_definitions[opcode] = mac_ptr;
24087               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24088               mac_ptr += bytes_read;
24089               mac_ptr += arg;
24090             }
24091         }
24092     }
24093
24094   return mac_ptr;
24095 }
24096
24097 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24098    including DW_MACRO_import.  */
24099
24100 static void
24101 dwarf_decode_macro_bytes (bfd *abfd,
24102                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24103                           struct macro_source_file *current_file,
24104                           struct line_header *lh,
24105                           struct dwarf2_section_info *section,
24106                           int section_is_gnu, int section_is_dwz,
24107                           unsigned int offset_size,
24108                           htab_t include_hash)
24109 {
24110   struct objfile *objfile = dwarf2_per_objfile->objfile;
24111   enum dwarf_macro_record_type macinfo_type;
24112   int at_commandline;
24113   const gdb_byte *opcode_definitions[256];
24114
24115   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24116                                       &offset_size, section_is_gnu);
24117   if (mac_ptr == NULL)
24118     {
24119       /* We already issued a complaint.  */
24120       return;
24121     }
24122
24123   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24124      GDB is still reading the definitions from command line.  First
24125      DW_MACINFO_start_file will need to be ignored as it was already executed
24126      to create CURRENT_FILE for the main source holding also the command line
24127      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24128      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24129
24130   at_commandline = 1;
24131
24132   do
24133     {
24134       /* Do we at least have room for a macinfo type byte?  */
24135       if (mac_ptr >= mac_end)
24136         {
24137           dwarf2_section_buffer_overflow_complaint (section);
24138           break;
24139         }
24140
24141       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24142       mac_ptr++;
24143
24144       /* Note that we rely on the fact that the corresponding GNU and
24145          DWARF constants are the same.  */
24146       switch (macinfo_type)
24147         {
24148           /* A zero macinfo type indicates the end of the macro
24149              information.  */
24150         case 0:
24151           break;
24152
24153         case DW_MACRO_define:
24154         case DW_MACRO_undef:
24155         case DW_MACRO_define_strp:
24156         case DW_MACRO_undef_strp:
24157         case DW_MACRO_define_sup:
24158         case DW_MACRO_undef_sup:
24159           {
24160             unsigned int bytes_read;
24161             int line;
24162             const char *body;
24163             int is_define;
24164
24165             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24166             mac_ptr += bytes_read;
24167
24168             if (macinfo_type == DW_MACRO_define
24169                 || macinfo_type == DW_MACRO_undef)
24170               {
24171                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24172                 mac_ptr += bytes_read;
24173               }
24174             else
24175               {
24176                 LONGEST str_offset;
24177
24178                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24179                 mac_ptr += offset_size;
24180
24181                 if (macinfo_type == DW_MACRO_define_sup
24182                     || macinfo_type == DW_MACRO_undef_sup
24183                     || section_is_dwz)
24184                   {
24185                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
24186
24187                     body = read_indirect_string_from_dwz (dwz, str_offset);
24188                   }
24189                 else
24190                   body = read_indirect_string_at_offset (abfd, str_offset);
24191               }
24192
24193             is_define = (macinfo_type == DW_MACRO_define
24194                          || macinfo_type == DW_MACRO_define_strp
24195                          || macinfo_type == DW_MACRO_define_sup);
24196             if (! current_file)
24197               {
24198                 /* DWARF violation as no main source is present.  */
24199                 complaint (&symfile_complaints,
24200                            _("debug info with no main source gives macro %s "
24201                              "on line %d: %s"),
24202                            is_define ? _("definition") : _("undefinition"),
24203                            line, body);
24204                 break;
24205               }
24206             if ((line == 0 && !at_commandline)
24207                 || (line != 0 && at_commandline))
24208               complaint (&symfile_complaints,
24209                          _("debug info gives %s macro %s with %s line %d: %s"),
24210                          at_commandline ? _("command-line") : _("in-file"),
24211                          is_define ? _("definition") : _("undefinition"),
24212                          line == 0 ? _("zero") : _("non-zero"), line, body);
24213
24214             if (is_define)
24215               parse_macro_definition (current_file, line, body);
24216             else
24217               {
24218                 gdb_assert (macinfo_type == DW_MACRO_undef
24219                             || macinfo_type == DW_MACRO_undef_strp
24220                             || macinfo_type == DW_MACRO_undef_sup);
24221                 macro_undef (current_file, line, body);
24222               }
24223           }
24224           break;
24225
24226         case DW_MACRO_start_file:
24227           {
24228             unsigned int bytes_read;
24229             int line, file;
24230
24231             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24232             mac_ptr += bytes_read;
24233             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24234             mac_ptr += bytes_read;
24235
24236             if ((line == 0 && !at_commandline)
24237                 || (line != 0 && at_commandline))
24238               complaint (&symfile_complaints,
24239                          _("debug info gives source %d included "
24240                            "from %s at %s line %d"),
24241                          file, at_commandline ? _("command-line") : _("file"),
24242                          line == 0 ? _("zero") : _("non-zero"), line);
24243
24244             if (at_commandline)
24245               {
24246                 /* This DW_MACRO_start_file was executed in the
24247                    pass one.  */
24248                 at_commandline = 0;
24249               }
24250             else
24251               current_file = macro_start_file (file, line, current_file, lh);
24252           }
24253           break;
24254
24255         case DW_MACRO_end_file:
24256           if (! current_file)
24257             complaint (&symfile_complaints,
24258                        _("macro debug info has an unmatched "
24259                          "`close_file' directive"));
24260           else
24261             {
24262               current_file = current_file->included_by;
24263               if (! current_file)
24264                 {
24265                   enum dwarf_macro_record_type next_type;
24266
24267                   /* GCC circa March 2002 doesn't produce the zero
24268                      type byte marking the end of the compilation
24269                      unit.  Complain if it's not there, but exit no
24270                      matter what.  */
24271
24272                   /* Do we at least have room for a macinfo type byte?  */
24273                   if (mac_ptr >= mac_end)
24274                     {
24275                       dwarf2_section_buffer_overflow_complaint (section);
24276                       return;
24277                     }
24278
24279                   /* We don't increment mac_ptr here, so this is just
24280                      a look-ahead.  */
24281                   next_type
24282                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24283                                                                   mac_ptr);
24284                   if (next_type != 0)
24285                     complaint (&symfile_complaints,
24286                                _("no terminating 0-type entry for "
24287                                  "macros in `.debug_macinfo' section"));
24288
24289                   return;
24290                 }
24291             }
24292           break;
24293
24294         case DW_MACRO_import:
24295         case DW_MACRO_import_sup:
24296           {
24297             LONGEST offset;
24298             void **slot;
24299             bfd *include_bfd = abfd;
24300             struct dwarf2_section_info *include_section = section;
24301             const gdb_byte *include_mac_end = mac_end;
24302             int is_dwz = section_is_dwz;
24303             const gdb_byte *new_mac_ptr;
24304
24305             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24306             mac_ptr += offset_size;
24307
24308             if (macinfo_type == DW_MACRO_import_sup)
24309               {
24310                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
24311
24312                 dwarf2_read_section (objfile, &dwz->macro);
24313
24314                 include_section = &dwz->macro;
24315                 include_bfd = get_section_bfd_owner (include_section);
24316                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24317                 is_dwz = 1;
24318               }
24319
24320             new_mac_ptr = include_section->buffer + offset;
24321             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24322
24323             if (*slot != NULL)
24324               {
24325                 /* This has actually happened; see
24326                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24327                 complaint (&symfile_complaints,
24328                            _("recursive DW_MACRO_import in "
24329                              ".debug_macro section"));
24330               }
24331             else
24332               {
24333                 *slot = (void *) new_mac_ptr;
24334
24335                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
24336                                           include_mac_end, current_file, lh,
24337                                           section, section_is_gnu, is_dwz,
24338                                           offset_size, include_hash);
24339
24340                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24341               }
24342           }
24343           break;
24344
24345         case DW_MACINFO_vendor_ext:
24346           if (!section_is_gnu)
24347             {
24348               unsigned int bytes_read;
24349
24350               /* This reads the constant, but since we don't recognize
24351                  any vendor extensions, we ignore it.  */
24352               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24353               mac_ptr += bytes_read;
24354               read_direct_string (abfd, mac_ptr, &bytes_read);
24355               mac_ptr += bytes_read;
24356
24357               /* We don't recognize any vendor extensions.  */
24358               break;
24359             }
24360           /* FALLTHROUGH */
24361
24362         default:
24363           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24364                                          mac_ptr, mac_end, abfd, offset_size,
24365                                          section);
24366           if (mac_ptr == NULL)
24367             return;
24368           break;
24369         }
24370     } while (macinfo_type != 0);
24371 }
24372
24373 static void
24374 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24375                      int section_is_gnu)
24376 {
24377   struct objfile *objfile = dwarf2_per_objfile->objfile;
24378   struct line_header *lh = cu->line_header;
24379   bfd *abfd;
24380   const gdb_byte *mac_ptr, *mac_end;
24381   struct macro_source_file *current_file = 0;
24382   enum dwarf_macro_record_type macinfo_type;
24383   unsigned int offset_size = cu->header.offset_size;
24384   const gdb_byte *opcode_definitions[256];
24385   void **slot;
24386   struct dwarf2_section_info *section;
24387   const char *section_name;
24388
24389   if (cu->dwo_unit != NULL)
24390     {
24391       if (section_is_gnu)
24392         {
24393           section = &cu->dwo_unit->dwo_file->sections.macro;
24394           section_name = ".debug_macro.dwo";
24395         }
24396       else
24397         {
24398           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24399           section_name = ".debug_macinfo.dwo";
24400         }
24401     }
24402   else
24403     {
24404       if (section_is_gnu)
24405         {
24406           section = &dwarf2_per_objfile->macro;
24407           section_name = ".debug_macro";
24408         }
24409       else
24410         {
24411           section = &dwarf2_per_objfile->macinfo;
24412           section_name = ".debug_macinfo";
24413         }
24414     }
24415
24416   dwarf2_read_section (objfile, section);
24417   if (section->buffer == NULL)
24418     {
24419       complaint (&symfile_complaints, _("missing %s section"), section_name);
24420       return;
24421     }
24422   abfd = get_section_bfd_owner (section);
24423
24424   /* First pass: Find the name of the base filename.
24425      This filename is needed in order to process all macros whose definition
24426      (or undefinition) comes from the command line.  These macros are defined
24427      before the first DW_MACINFO_start_file entry, and yet still need to be
24428      associated to the base file.
24429
24430      To determine the base file name, we scan the macro definitions until we
24431      reach the first DW_MACINFO_start_file entry.  We then initialize
24432      CURRENT_FILE accordingly so that any macro definition found before the
24433      first DW_MACINFO_start_file can still be associated to the base file.  */
24434
24435   mac_ptr = section->buffer + offset;
24436   mac_end = section->buffer + section->size;
24437
24438   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24439                                       &offset_size, section_is_gnu);
24440   if (mac_ptr == NULL)
24441     {
24442       /* We already issued a complaint.  */
24443       return;
24444     }
24445
24446   do
24447     {
24448       /* Do we at least have room for a macinfo type byte?  */
24449       if (mac_ptr >= mac_end)
24450         {
24451           /* Complaint is printed during the second pass as GDB will probably
24452              stop the first pass earlier upon finding
24453              DW_MACINFO_start_file.  */
24454           break;
24455         }
24456
24457       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24458       mac_ptr++;
24459
24460       /* Note that we rely on the fact that the corresponding GNU and
24461          DWARF constants are the same.  */
24462       switch (macinfo_type)
24463         {
24464           /* A zero macinfo type indicates the end of the macro
24465              information.  */
24466         case 0:
24467           break;
24468
24469         case DW_MACRO_define:
24470         case DW_MACRO_undef:
24471           /* Only skip the data by MAC_PTR.  */
24472           {
24473             unsigned int bytes_read;
24474
24475             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24476             mac_ptr += bytes_read;
24477             read_direct_string (abfd, mac_ptr, &bytes_read);
24478             mac_ptr += bytes_read;
24479           }
24480           break;
24481
24482         case DW_MACRO_start_file:
24483           {
24484             unsigned int bytes_read;
24485             int line, file;
24486
24487             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24488             mac_ptr += bytes_read;
24489             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24490             mac_ptr += bytes_read;
24491
24492             current_file = macro_start_file (file, line, current_file, lh);
24493           }
24494           break;
24495
24496         case DW_MACRO_end_file:
24497           /* No data to skip by MAC_PTR.  */
24498           break;
24499
24500         case DW_MACRO_define_strp:
24501         case DW_MACRO_undef_strp:
24502         case DW_MACRO_define_sup:
24503         case DW_MACRO_undef_sup:
24504           {
24505             unsigned int bytes_read;
24506
24507             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24508             mac_ptr += bytes_read;
24509             mac_ptr += offset_size;
24510           }
24511           break;
24512
24513         case DW_MACRO_import:
24514         case DW_MACRO_import_sup:
24515           /* Note that, according to the spec, a transparent include
24516              chain cannot call DW_MACRO_start_file.  So, we can just
24517              skip this opcode.  */
24518           mac_ptr += offset_size;
24519           break;
24520
24521         case DW_MACINFO_vendor_ext:
24522           /* Only skip the data by MAC_PTR.  */
24523           if (!section_is_gnu)
24524             {
24525               unsigned int bytes_read;
24526
24527               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24528               mac_ptr += bytes_read;
24529               read_direct_string (abfd, mac_ptr, &bytes_read);
24530               mac_ptr += bytes_read;
24531             }
24532           /* FALLTHROUGH */
24533
24534         default:
24535           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24536                                          mac_ptr, mac_end, abfd, offset_size,
24537                                          section);
24538           if (mac_ptr == NULL)
24539             return;
24540           break;
24541         }
24542     } while (macinfo_type != 0 && current_file == NULL);
24543
24544   /* Second pass: Process all entries.
24545
24546      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24547      command-line macro definitions/undefinitions.  This flag is unset when we
24548      reach the first DW_MACINFO_start_file entry.  */
24549
24550   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24551                                            htab_eq_pointer,
24552                                            NULL, xcalloc, xfree));
24553   mac_ptr = section->buffer + offset;
24554   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24555   *slot = (void *) mac_ptr;
24556   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
24557                             current_file, lh, section,
24558                             section_is_gnu, 0, offset_size,
24559                             include_hash.get ());
24560 }
24561
24562 /* Check if the attribute's form is a DW_FORM_block*
24563    if so return true else false.  */
24564
24565 static int
24566 attr_form_is_block (const struct attribute *attr)
24567 {
24568   return (attr == NULL ? 0 :
24569       attr->form == DW_FORM_block1
24570       || attr->form == DW_FORM_block2
24571       || attr->form == DW_FORM_block4
24572       || attr->form == DW_FORM_block
24573       || attr->form == DW_FORM_exprloc);
24574 }
24575
24576 /* Return non-zero if ATTR's value is a section offset --- classes
24577    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24578    You may use DW_UNSND (attr) to retrieve such offsets.
24579
24580    Section 7.5.4, "Attribute Encodings", explains that no attribute
24581    may have a value that belongs to more than one of these classes; it
24582    would be ambiguous if we did, because we use the same forms for all
24583    of them.  */
24584
24585 static int
24586 attr_form_is_section_offset (const struct attribute *attr)
24587 {
24588   return (attr->form == DW_FORM_data4
24589           || attr->form == DW_FORM_data8
24590           || attr->form == DW_FORM_sec_offset);
24591 }
24592
24593 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24594    zero otherwise.  When this function returns true, you can apply
24595    dwarf2_get_attr_constant_value to it.
24596
24597    However, note that for some attributes you must check
24598    attr_form_is_section_offset before using this test.  DW_FORM_data4
24599    and DW_FORM_data8 are members of both the constant class, and of
24600    the classes that contain offsets into other debug sections
24601    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24602    that, if an attribute's can be either a constant or one of the
24603    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24604    taken as section offsets, not constants.
24605
24606    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24607    cannot handle that.  */
24608
24609 static int
24610 attr_form_is_constant (const struct attribute *attr)
24611 {
24612   switch (attr->form)
24613     {
24614     case DW_FORM_sdata:
24615     case DW_FORM_udata:
24616     case DW_FORM_data1:
24617     case DW_FORM_data2:
24618     case DW_FORM_data4:
24619     case DW_FORM_data8:
24620     case DW_FORM_implicit_const:
24621       return 1;
24622     default:
24623       return 0;
24624     }
24625 }
24626
24627
24628 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24629    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24630
24631 static int
24632 attr_form_is_ref (const struct attribute *attr)
24633 {
24634   switch (attr->form)
24635     {
24636     case DW_FORM_ref_addr:
24637     case DW_FORM_ref1:
24638     case DW_FORM_ref2:
24639     case DW_FORM_ref4:
24640     case DW_FORM_ref8:
24641     case DW_FORM_ref_udata:
24642     case DW_FORM_GNU_ref_alt:
24643       return 1;
24644     default:
24645       return 0;
24646     }
24647 }
24648
24649 /* Return the .debug_loc section to use for CU.
24650    For DWO files use .debug_loc.dwo.  */
24651
24652 static struct dwarf2_section_info *
24653 cu_debug_loc_section (struct dwarf2_cu *cu)
24654 {
24655   if (cu->dwo_unit)
24656     {
24657       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24658       
24659       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24660     }
24661   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24662                                   : &dwarf2_per_objfile->loc);
24663 }
24664
24665 /* A helper function that fills in a dwarf2_loclist_baton.  */
24666
24667 static void
24668 fill_in_loclist_baton (struct dwarf2_cu *cu,
24669                        struct dwarf2_loclist_baton *baton,
24670                        const struct attribute *attr)
24671 {
24672   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24673
24674   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24675
24676   baton->per_cu = cu->per_cu;
24677   gdb_assert (baton->per_cu);
24678   /* We don't know how long the location list is, but make sure we
24679      don't run off the edge of the section.  */
24680   baton->size = section->size - DW_UNSND (attr);
24681   baton->data = section->buffer + DW_UNSND (attr);
24682   baton->base_address = cu->base_address;
24683   baton->from_dwo = cu->dwo_unit != NULL;
24684 }
24685
24686 static void
24687 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24688                              struct dwarf2_cu *cu, int is_block)
24689 {
24690   struct objfile *objfile = dwarf2_per_objfile->objfile;
24691   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24692
24693   if (attr_form_is_section_offset (attr)
24694       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24695          the section.  If so, fall through to the complaint in the
24696          other branch.  */
24697       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24698     {
24699       struct dwarf2_loclist_baton *baton;
24700
24701       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24702
24703       fill_in_loclist_baton (cu, baton, attr);
24704
24705       if (cu->base_known == 0)
24706         complaint (&symfile_complaints,
24707                    _("Location list used without "
24708                      "specifying the CU base address."));
24709
24710       SYMBOL_ACLASS_INDEX (sym) = (is_block
24711                                    ? dwarf2_loclist_block_index
24712                                    : dwarf2_loclist_index);
24713       SYMBOL_LOCATION_BATON (sym) = baton;
24714     }
24715   else
24716     {
24717       struct dwarf2_locexpr_baton *baton;
24718
24719       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24720       baton->per_cu = cu->per_cu;
24721       gdb_assert (baton->per_cu);
24722
24723       if (attr_form_is_block (attr))
24724         {
24725           /* Note that we're just copying the block's data pointer
24726              here, not the actual data.  We're still pointing into the
24727              info_buffer for SYM's objfile; right now we never release
24728              that buffer, but when we do clean up properly this may
24729              need to change.  */
24730           baton->size = DW_BLOCK (attr)->size;
24731           baton->data = DW_BLOCK (attr)->data;
24732         }
24733       else
24734         {
24735           dwarf2_invalid_attrib_class_complaint ("location description",
24736                                                  SYMBOL_NATURAL_NAME (sym));
24737           baton->size = 0;
24738         }
24739
24740       SYMBOL_ACLASS_INDEX (sym) = (is_block
24741                                    ? dwarf2_locexpr_block_index
24742                                    : dwarf2_locexpr_index);
24743       SYMBOL_LOCATION_BATON (sym) = baton;
24744     }
24745 }
24746
24747 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24748    came from a separate debuginfo file, then the master objfile is
24749    returned.  */
24750
24751 struct objfile *
24752 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24753 {
24754   struct objfile *objfile = per_cu->objfile;
24755
24756   /* Return the master objfile, so that we can report and look up the
24757      correct file containing this variable.  */
24758   if (objfile->separate_debug_objfile_backlink)
24759     objfile = objfile->separate_debug_objfile_backlink;
24760
24761   return objfile;
24762 }
24763
24764 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24765    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24766    CU_HEADERP first.  */
24767
24768 static const struct comp_unit_head *
24769 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24770                        struct dwarf2_per_cu_data *per_cu)
24771 {
24772   const gdb_byte *info_ptr;
24773
24774   if (per_cu->cu)
24775     return &per_cu->cu->header;
24776
24777   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24778
24779   memset (cu_headerp, 0, sizeof (*cu_headerp));
24780   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24781                        rcuh_kind::COMPILE);
24782
24783   return cu_headerp;
24784 }
24785
24786 /* Return the address size given in the compilation unit header for CU.  */
24787
24788 int
24789 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24790 {
24791   struct comp_unit_head cu_header_local;
24792   const struct comp_unit_head *cu_headerp;
24793
24794   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24795
24796   return cu_headerp->addr_size;
24797 }
24798
24799 /* Return the offset size given in the compilation unit header for CU.  */
24800
24801 int
24802 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24803 {
24804   struct comp_unit_head cu_header_local;
24805   const struct comp_unit_head *cu_headerp;
24806
24807   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24808
24809   return cu_headerp->offset_size;
24810 }
24811
24812 /* See its dwarf2loc.h declaration.  */
24813
24814 int
24815 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24816 {
24817   struct comp_unit_head cu_header_local;
24818   const struct comp_unit_head *cu_headerp;
24819
24820   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24821
24822   if (cu_headerp->version == 2)
24823     return cu_headerp->addr_size;
24824   else
24825     return cu_headerp->offset_size;
24826 }
24827
24828 /* Return the text offset of the CU.  The returned offset comes from
24829    this CU's objfile.  If this objfile came from a separate debuginfo
24830    file, then the offset may be different from the corresponding
24831    offset in the parent objfile.  */
24832
24833 CORE_ADDR
24834 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24835 {
24836   struct objfile *objfile = per_cu->objfile;
24837
24838   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24839 }
24840
24841 /* Return DWARF version number of PER_CU.  */
24842
24843 short
24844 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24845 {
24846   return per_cu->dwarf_version;
24847 }
24848
24849 /* Locate the .debug_info compilation unit from CU's objfile which contains
24850    the DIE at OFFSET.  Raises an error on failure.  */
24851
24852 static struct dwarf2_per_cu_data *
24853 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24854                                   unsigned int offset_in_dwz,
24855                                   struct objfile *objfile)
24856 {
24857   struct dwarf2_per_cu_data *this_cu;
24858   int low, high;
24859   const sect_offset *cu_off;
24860
24861   low = 0;
24862   high = dwarf2_per_objfile->n_comp_units - 1;
24863   while (high > low)
24864     {
24865       struct dwarf2_per_cu_data *mid_cu;
24866       int mid = low + (high - low) / 2;
24867
24868       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24869       cu_off = &mid_cu->sect_off;
24870       if (mid_cu->is_dwz > offset_in_dwz
24871           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24872         high = mid;
24873       else
24874         low = mid + 1;
24875     }
24876   gdb_assert (low == high);
24877   this_cu = dwarf2_per_objfile->all_comp_units[low];
24878   cu_off = &this_cu->sect_off;
24879   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24880     {
24881       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24882         error (_("Dwarf Error: could not find partial DIE containing "
24883                "offset 0x%x [in module %s]"),
24884                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
24885
24886       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24887                   <= sect_off);
24888       return dwarf2_per_objfile->all_comp_units[low-1];
24889     }
24890   else
24891     {
24892       this_cu = dwarf2_per_objfile->all_comp_units[low];
24893       if (low == dwarf2_per_objfile->n_comp_units - 1
24894           && sect_off >= this_cu->sect_off + this_cu->length)
24895         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
24896       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24897       return this_cu;
24898     }
24899 }
24900
24901 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24902
24903 static void
24904 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
24905 {
24906   memset (cu, 0, sizeof (*cu));
24907   per_cu->cu = cu;
24908   cu->per_cu = per_cu;
24909   cu->objfile = per_cu->objfile;
24910   obstack_init (&cu->comp_unit_obstack);
24911 }
24912
24913 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24914
24915 static void
24916 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24917                        enum language pretend_language)
24918 {
24919   struct attribute *attr;
24920
24921   /* Set the language we're debugging.  */
24922   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24923   if (attr)
24924     set_cu_language (DW_UNSND (attr), cu);
24925   else
24926     {
24927       cu->language = pretend_language;
24928       cu->language_defn = language_def (cu->language);
24929     }
24930
24931   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24932 }
24933
24934 /* Release one cached compilation unit, CU.  We unlink it from the tree
24935    of compilation units, but we don't remove it from the read_in_chain;
24936    the caller is responsible for that.
24937    NOTE: DATA is a void * because this function is also used as a
24938    cleanup routine.  */
24939
24940 static void
24941 free_heap_comp_unit (void *data)
24942 {
24943   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
24944
24945   gdb_assert (cu->per_cu != NULL);
24946   cu->per_cu->cu = NULL;
24947   cu->per_cu = NULL;
24948
24949   obstack_free (&cu->comp_unit_obstack, NULL);
24950
24951   xfree (cu);
24952 }
24953
24954 /* This cleanup function is passed the address of a dwarf2_cu on the stack
24955    when we're finished with it.  We can't free the pointer itself, but be
24956    sure to unlink it from the cache.  Also release any associated storage.  */
24957
24958 static void
24959 free_stack_comp_unit (void *data)
24960 {
24961   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
24962
24963   gdb_assert (cu->per_cu != NULL);
24964   cu->per_cu->cu = NULL;
24965   cu->per_cu = NULL;
24966
24967   obstack_free (&cu->comp_unit_obstack, NULL);
24968   cu->partial_dies = NULL;
24969 }
24970
24971 /* Free all cached compilation units.  */
24972
24973 static void
24974 free_cached_comp_units (void *data)
24975 {
24976   dwarf2_per_objfile->free_cached_comp_units ();
24977 }
24978
24979 /* Increase the age counter on each cached compilation unit, and free
24980    any that are too old.  */
24981
24982 static void
24983 age_cached_comp_units (void)
24984 {
24985   struct dwarf2_per_cu_data *per_cu, **last_chain;
24986
24987   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24988   per_cu = dwarf2_per_objfile->read_in_chain;
24989   while (per_cu != NULL)
24990     {
24991       per_cu->cu->last_used ++;
24992       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24993         dwarf2_mark (per_cu->cu);
24994       per_cu = per_cu->cu->read_in_chain;
24995     }
24996
24997   per_cu = dwarf2_per_objfile->read_in_chain;
24998   last_chain = &dwarf2_per_objfile->read_in_chain;
24999   while (per_cu != NULL)
25000     {
25001       struct dwarf2_per_cu_data *next_cu;
25002
25003       next_cu = per_cu->cu->read_in_chain;
25004
25005       if (!per_cu->cu->mark)
25006         {
25007           free_heap_comp_unit (per_cu->cu);
25008           *last_chain = next_cu;
25009         }
25010       else
25011         last_chain = &per_cu->cu->read_in_chain;
25012
25013       per_cu = next_cu;
25014     }
25015 }
25016
25017 /* Remove a single compilation unit from the cache.  */
25018
25019 static void
25020 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25021 {
25022   struct dwarf2_per_cu_data *per_cu, **last_chain;
25023
25024   per_cu = dwarf2_per_objfile->read_in_chain;
25025   last_chain = &dwarf2_per_objfile->read_in_chain;
25026   while (per_cu != NULL)
25027     {
25028       struct dwarf2_per_cu_data *next_cu;
25029
25030       next_cu = per_cu->cu->read_in_chain;
25031
25032       if (per_cu == target_per_cu)
25033         {
25034           free_heap_comp_unit (per_cu->cu);
25035           per_cu->cu = NULL;
25036           *last_chain = next_cu;
25037           break;
25038         }
25039       else
25040         last_chain = &per_cu->cu->read_in_chain;
25041
25042       per_cu = next_cu;
25043     }
25044 }
25045
25046 /* Release all extra memory associated with OBJFILE.  */
25047
25048 void
25049 dwarf2_free_objfile (struct objfile *objfile)
25050 {
25051   dwarf2_per_objfile
25052     = (struct dwarf2_per_objfile *) objfile_data (objfile,
25053                                                   dwarf2_objfile_data_key);
25054
25055   if (dwarf2_per_objfile == NULL)
25056     return;
25057
25058   dwarf2_per_objfile->~dwarf2_per_objfile ();
25059 }
25060
25061 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25062    We store these in a hash table separate from the DIEs, and preserve them
25063    when the DIEs are flushed out of cache.
25064
25065    The CU "per_cu" pointer is needed because offset alone is not enough to
25066    uniquely identify the type.  A file may have multiple .debug_types sections,
25067    or the type may come from a DWO file.  Furthermore, while it's more logical
25068    to use per_cu->section+offset, with Fission the section with the data is in
25069    the DWO file but we don't know that section at the point we need it.
25070    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25071    because we can enter the lookup routine, get_die_type_at_offset, from
25072    outside this file, and thus won't necessarily have PER_CU->cu.
25073    Fortunately, PER_CU is stable for the life of the objfile.  */
25074
25075 struct dwarf2_per_cu_offset_and_type
25076 {
25077   const struct dwarf2_per_cu_data *per_cu;
25078   sect_offset sect_off;
25079   struct type *type;
25080 };
25081
25082 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25083
25084 static hashval_t
25085 per_cu_offset_and_type_hash (const void *item)
25086 {
25087   const struct dwarf2_per_cu_offset_and_type *ofs
25088     = (const struct dwarf2_per_cu_offset_and_type *) item;
25089
25090   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25091 }
25092
25093 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25094
25095 static int
25096 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25097 {
25098   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25099     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25100   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25101     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25102
25103   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25104           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25105 }
25106
25107 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25108    table if necessary.  For convenience, return TYPE.
25109
25110    The DIEs reading must have careful ordering to:
25111     * Not cause infite loops trying to read in DIEs as a prerequisite for
25112       reading current DIE.
25113     * Not trying to dereference contents of still incompletely read in types
25114       while reading in other DIEs.
25115     * Enable referencing still incompletely read in types just by a pointer to
25116       the type without accessing its fields.
25117
25118    Therefore caller should follow these rules:
25119      * Try to fetch any prerequisite types we may need to build this DIE type
25120        before building the type and calling set_die_type.
25121      * After building type call set_die_type for current DIE as soon as
25122        possible before fetching more types to complete the current type.
25123      * Make the type as complete as possible before fetching more types.  */
25124
25125 static struct type *
25126 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25127 {
25128   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25129   struct objfile *objfile = cu->objfile;
25130   struct attribute *attr;
25131   struct dynamic_prop prop;
25132
25133   /* For Ada types, make sure that the gnat-specific data is always
25134      initialized (if not already set).  There are a few types where
25135      we should not be doing so, because the type-specific area is
25136      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25137      where the type-specific area is used to store the floatformat).
25138      But this is not a problem, because the gnat-specific information
25139      is actually not needed for these types.  */
25140   if (need_gnat_info (cu)
25141       && TYPE_CODE (type) != TYPE_CODE_FUNC
25142       && TYPE_CODE (type) != TYPE_CODE_FLT
25143       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25144       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25145       && TYPE_CODE (type) != TYPE_CODE_METHOD
25146       && !HAVE_GNAT_AUX_INFO (type))
25147     INIT_GNAT_SPECIFIC (type);
25148
25149   /* Read DW_AT_allocated and set in type.  */
25150   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25151   if (attr_form_is_block (attr))
25152     {
25153       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25154         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
25155     }
25156   else if (attr != NULL)
25157     {
25158       complaint (&symfile_complaints,
25159                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25160                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25161                  to_underlying (die->sect_off));
25162     }
25163
25164   /* Read DW_AT_associated and set in type.  */
25165   attr = dwarf2_attr (die, DW_AT_associated, cu);
25166   if (attr_form_is_block (attr))
25167     {
25168       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25169         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
25170     }
25171   else if (attr != NULL)
25172     {
25173       complaint (&symfile_complaints,
25174                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25175                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25176                  to_underlying (die->sect_off));
25177     }
25178
25179   /* Read DW_AT_data_location and set in type.  */
25180   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25181   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25182     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
25183
25184   if (dwarf2_per_objfile->die_type_hash == NULL)
25185     {
25186       dwarf2_per_objfile->die_type_hash =
25187         htab_create_alloc_ex (127,
25188                               per_cu_offset_and_type_hash,
25189                               per_cu_offset_and_type_eq,
25190                               NULL,
25191                               &objfile->objfile_obstack,
25192                               hashtab_obstack_allocate,
25193                               dummy_obstack_deallocate);
25194     }
25195
25196   ofs.per_cu = cu->per_cu;
25197   ofs.sect_off = die->sect_off;
25198   ofs.type = type;
25199   slot = (struct dwarf2_per_cu_offset_and_type **)
25200     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25201   if (*slot)
25202     complaint (&symfile_complaints,
25203                _("A problem internal to GDB: DIE 0x%x has type already set"),
25204                to_underlying (die->sect_off));
25205   *slot = XOBNEW (&objfile->objfile_obstack,
25206                   struct dwarf2_per_cu_offset_and_type);
25207   **slot = ofs;
25208   return type;
25209 }
25210
25211 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25212    or return NULL if the die does not have a saved type.  */
25213
25214 static struct type *
25215 get_die_type_at_offset (sect_offset sect_off,
25216                         struct dwarf2_per_cu_data *per_cu)
25217 {
25218   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25219
25220   if (dwarf2_per_objfile->die_type_hash == NULL)
25221     return NULL;
25222
25223   ofs.per_cu = per_cu;
25224   ofs.sect_off = sect_off;
25225   slot = ((struct dwarf2_per_cu_offset_and_type *)
25226           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25227   if (slot)
25228     return slot->type;
25229   else
25230     return NULL;
25231 }
25232
25233 /* Look up the type for DIE in CU in die_type_hash,
25234    or return NULL if DIE does not have a saved type.  */
25235
25236 static struct type *
25237 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25238 {
25239   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25240 }
25241
25242 /* Add a dependence relationship from CU to REF_PER_CU.  */
25243
25244 static void
25245 dwarf2_add_dependence (struct dwarf2_cu *cu,
25246                        struct dwarf2_per_cu_data *ref_per_cu)
25247 {
25248   void **slot;
25249
25250   if (cu->dependencies == NULL)
25251     cu->dependencies
25252       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25253                               NULL, &cu->comp_unit_obstack,
25254                               hashtab_obstack_allocate,
25255                               dummy_obstack_deallocate);
25256
25257   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25258   if (*slot == NULL)
25259     *slot = ref_per_cu;
25260 }
25261
25262 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25263    Set the mark field in every compilation unit in the
25264    cache that we must keep because we are keeping CU.  */
25265
25266 static int
25267 dwarf2_mark_helper (void **slot, void *data)
25268 {
25269   struct dwarf2_per_cu_data *per_cu;
25270
25271   per_cu = (struct dwarf2_per_cu_data *) *slot;
25272
25273   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25274      reading of the chain.  As such dependencies remain valid it is not much
25275      useful to track and undo them during QUIT cleanups.  */
25276   if (per_cu->cu == NULL)
25277     return 1;
25278
25279   if (per_cu->cu->mark)
25280     return 1;
25281   per_cu->cu->mark = 1;
25282
25283   if (per_cu->cu->dependencies != NULL)
25284     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25285
25286   return 1;
25287 }
25288
25289 /* Set the mark field in CU and in every other compilation unit in the
25290    cache that we must keep because we are keeping CU.  */
25291
25292 static void
25293 dwarf2_mark (struct dwarf2_cu *cu)
25294 {
25295   if (cu->mark)
25296     return;
25297   cu->mark = 1;
25298   if (cu->dependencies != NULL)
25299     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25300 }
25301
25302 static void
25303 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25304 {
25305   while (per_cu)
25306     {
25307       per_cu->cu->mark = 0;
25308       per_cu = per_cu->cu->read_in_chain;
25309     }
25310 }
25311
25312 /* Trivial hash function for partial_die_info: the hash value of a DIE
25313    is its offset in .debug_info for this objfile.  */
25314
25315 static hashval_t
25316 partial_die_hash (const void *item)
25317 {
25318   const struct partial_die_info *part_die
25319     = (const struct partial_die_info *) item;
25320
25321   return to_underlying (part_die->sect_off);
25322 }
25323
25324 /* Trivial comparison function for partial_die_info structures: two DIEs
25325    are equal if they have the same offset.  */
25326
25327 static int
25328 partial_die_eq (const void *item_lhs, const void *item_rhs)
25329 {
25330   const struct partial_die_info *part_die_lhs
25331     = (const struct partial_die_info *) item_lhs;
25332   const struct partial_die_info *part_die_rhs
25333     = (const struct partial_die_info *) item_rhs;
25334
25335   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25336 }
25337
25338 static struct cmd_list_element *set_dwarf_cmdlist;
25339 static struct cmd_list_element *show_dwarf_cmdlist;
25340
25341 static void
25342 set_dwarf_cmd (const char *args, int from_tty)
25343 {
25344   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25345              gdb_stdout);
25346 }
25347
25348 static void
25349 show_dwarf_cmd (const char *args, int from_tty)
25350 {
25351   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25352 }
25353
25354 /* Free data associated with OBJFILE, if necessary.  */
25355
25356 static void
25357 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25358 {
25359   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25360   int ix;
25361
25362   /* Make sure we don't accidentally use dwarf2_per_objfile while
25363      cleaning up.  */
25364   dwarf2_per_objfile = NULL;
25365
25366   for (ix = 0; ix < data->n_comp_units; ++ix)
25367    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25368
25369   for (ix = 0; ix < data->n_type_units; ++ix)
25370     VEC_free (dwarf2_per_cu_ptr,
25371               data->all_type_units[ix]->per_cu.imported_symtabs);
25372   xfree (data->all_type_units);
25373
25374   VEC_free (dwarf2_section_info_def, data->types);
25375
25376   if (data->dwo_files)
25377     free_dwo_files (data->dwo_files, objfile);
25378   if (data->dwp_file)
25379     gdb_bfd_unref (data->dwp_file->dbfd);
25380
25381   if (data->dwz_file && data->dwz_file->dwz_bfd)
25382     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25383
25384   if (data->index_table != NULL)
25385     data->index_table->~mapped_index ();
25386 }
25387
25388 \f
25389 /* The "save gdb-index" command.  */
25390
25391 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25392    error checking.  */
25393
25394 static void
25395 file_write (FILE *file, const void *data, size_t size)
25396 {
25397   if (fwrite (data, 1, size, file) != size)
25398     error (_("couldn't data write to file"));
25399 }
25400
25401 /* Write the contents of VEC to FILE, with error checking.  */
25402
25403 template<typename Elem, typename Alloc>
25404 static void
25405 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25406 {
25407   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25408 }
25409
25410 /* In-memory buffer to prepare data to be written later to a file.  */
25411 class data_buf
25412 {
25413 public:
25414   /* Copy DATA to the end of the buffer.  */
25415   template<typename T>
25416   void append_data (const T &data)
25417   {
25418     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25419                reinterpret_cast<const gdb_byte *> (&data + 1),
25420                grow (sizeof (data)));
25421   }
25422
25423   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25424      terminating zero is appended too.  */
25425   void append_cstr0 (const char *cstr)
25426   {
25427     const size_t size = strlen (cstr) + 1;
25428     std::copy (cstr, cstr + size, grow (size));
25429   }
25430
25431   /* Store INPUT as ULEB128 to the end of buffer.  */
25432   void append_unsigned_leb128 (ULONGEST input)
25433   {
25434     for (;;)
25435       {
25436         gdb_byte output = input & 0x7f;
25437         input >>= 7;
25438         if (input)
25439           output |= 0x80;
25440         append_data (output);
25441         if (input == 0)
25442           break;
25443       }
25444   }
25445
25446   /* Accept a host-format integer in VAL and append it to the buffer
25447      as a target-format integer which is LEN bytes long.  */
25448   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25449   {
25450     ::store_unsigned_integer (grow (len), len, byte_order, val);
25451   }
25452
25453   /* Return the size of the buffer.  */
25454   size_t size () const
25455   {
25456     return m_vec.size ();
25457   }
25458
25459   /* Return true iff the buffer is empty.  */
25460   bool empty () const
25461   {
25462     return m_vec.empty ();
25463   }
25464
25465   /* Write the buffer to FILE.  */
25466   void file_write (FILE *file) const
25467   {
25468     ::file_write (file, m_vec);
25469   }
25470
25471 private:
25472   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25473      the start of the new block.  */
25474   gdb_byte *grow (size_t size)
25475   {
25476     m_vec.resize (m_vec.size () + size);
25477     return &*m_vec.end () - size;
25478   }
25479
25480   gdb::byte_vector m_vec;
25481 };
25482
25483 /* An entry in the symbol table.  */
25484 struct symtab_index_entry
25485 {
25486   /* The name of the symbol.  */
25487   const char *name;
25488   /* The offset of the name in the constant pool.  */
25489   offset_type index_offset;
25490   /* A sorted vector of the indices of all the CUs that hold an object
25491      of this name.  */
25492   std::vector<offset_type> cu_indices;
25493 };
25494
25495 /* The symbol table.  This is a power-of-2-sized hash table.  */
25496 struct mapped_symtab
25497 {
25498   mapped_symtab ()
25499   {
25500     data.resize (1024);
25501   }
25502
25503   offset_type n_elements = 0;
25504   std::vector<symtab_index_entry> data;
25505 };
25506
25507 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25508    the slot.
25509    
25510    Function is used only during write_hash_table so no index format backward
25511    compatibility is needed.  */
25512
25513 static symtab_index_entry &
25514 find_slot (struct mapped_symtab *symtab, const char *name)
25515 {
25516   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25517
25518   index = hash & (symtab->data.size () - 1);
25519   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25520
25521   for (;;)
25522     {
25523       if (symtab->data[index].name == NULL
25524           || strcmp (name, symtab->data[index].name) == 0)
25525         return symtab->data[index];
25526       index = (index + step) & (symtab->data.size () - 1);
25527     }
25528 }
25529
25530 /* Expand SYMTAB's hash table.  */
25531
25532 static void
25533 hash_expand (struct mapped_symtab *symtab)
25534 {
25535   auto old_entries = std::move (symtab->data);
25536
25537   symtab->data.clear ();
25538   symtab->data.resize (old_entries.size () * 2);
25539
25540   for (auto &it : old_entries)
25541     if (it.name != NULL)
25542       {
25543         auto &ref = find_slot (symtab, it.name);
25544         ref = std::move (it);
25545       }
25546 }
25547
25548 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25549    CU_INDEX is the index of the CU in which the symbol appears.
25550    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25551
25552 static void
25553 add_index_entry (struct mapped_symtab *symtab, const char *name,
25554                  int is_static, gdb_index_symbol_kind kind,
25555                  offset_type cu_index)
25556 {
25557   offset_type cu_index_and_attrs;
25558
25559   ++symtab->n_elements;
25560   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25561     hash_expand (symtab);
25562
25563   symtab_index_entry &slot = find_slot (symtab, name);
25564   if (slot.name == NULL)
25565     {
25566       slot.name = name;
25567       /* index_offset is set later.  */
25568     }
25569
25570   cu_index_and_attrs = 0;
25571   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25572   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25573   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25574
25575   /* We don't want to record an index value twice as we want to avoid the
25576      duplication.
25577      We process all global symbols and then all static symbols
25578      (which would allow us to avoid the duplication by only having to check
25579      the last entry pushed), but a symbol could have multiple kinds in one CU.
25580      To keep things simple we don't worry about the duplication here and
25581      sort and uniqufy the list after we've processed all symbols.  */
25582   slot.cu_indices.push_back (cu_index_and_attrs);
25583 }
25584
25585 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25586
25587 static void
25588 uniquify_cu_indices (struct mapped_symtab *symtab)
25589 {
25590   for (auto &entry : symtab->data)
25591     {
25592       if (entry.name != NULL && !entry.cu_indices.empty ())
25593         {
25594           auto &cu_indices = entry.cu_indices;
25595           std::sort (cu_indices.begin (), cu_indices.end ());
25596           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25597           cu_indices.erase (from, cu_indices.end ());
25598         }
25599     }
25600 }
25601
25602 /* A form of 'const char *' suitable for container keys.  Only the
25603    pointer is stored.  The strings themselves are compared, not the
25604    pointers.  */
25605 class c_str_view
25606 {
25607 public:
25608   c_str_view (const char *cstr)
25609     : m_cstr (cstr)
25610   {}
25611
25612   bool operator== (const c_str_view &other) const
25613   {
25614     return strcmp (m_cstr, other.m_cstr) == 0;
25615   }
25616
25617   /* Return the underlying C string.  Note, the returned string is
25618      only a reference with lifetime of this object.  */
25619   const char *c_str () const
25620   {
25621     return m_cstr;
25622   }
25623
25624 private:
25625   friend class c_str_view_hasher;
25626   const char *const m_cstr;
25627 };
25628
25629 /* A std::unordered_map::hasher for c_str_view that uses the right
25630    hash function for strings in a mapped index.  */
25631 class c_str_view_hasher
25632 {
25633 public:
25634   size_t operator () (const c_str_view &x) const
25635   {
25636     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25637   }
25638 };
25639
25640 /* A std::unordered_map::hasher for std::vector<>.  */
25641 template<typename T>
25642 class vector_hasher
25643 {
25644 public:
25645   size_t operator () (const std::vector<T> &key) const
25646   {
25647     return iterative_hash (key.data (),
25648                            sizeof (key.front ()) * key.size (), 0);
25649   }
25650 };
25651
25652 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25653    constant pool entries going into the data buffer CPOOL.  */
25654
25655 static void
25656 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25657 {
25658   {
25659     /* Elements are sorted vectors of the indices of all the CUs that
25660        hold an object of this name.  */
25661     std::unordered_map<std::vector<offset_type>, offset_type,
25662                        vector_hasher<offset_type>>
25663       symbol_hash_table;
25664
25665     /* We add all the index vectors to the constant pool first, to
25666        ensure alignment is ok.  */
25667     for (symtab_index_entry &entry : symtab->data)
25668       {
25669         if (entry.name == NULL)
25670           continue;
25671         gdb_assert (entry.index_offset == 0);
25672
25673         /* Finding before inserting is faster than always trying to
25674            insert, because inserting always allocates a node, does the
25675            lookup, and then destroys the new node if another node
25676            already had the same key.  C++17 try_emplace will avoid
25677            this.  */
25678         const auto found
25679           = symbol_hash_table.find (entry.cu_indices);
25680         if (found != symbol_hash_table.end ())
25681           {
25682             entry.index_offset = found->second;
25683             continue;
25684           }
25685
25686         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25687         entry.index_offset = cpool.size ();
25688         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25689         for (const auto index : entry.cu_indices)
25690           cpool.append_data (MAYBE_SWAP (index));
25691       }
25692   }
25693
25694   /* Now write out the hash table.  */
25695   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25696   for (const auto &entry : symtab->data)
25697     {
25698       offset_type str_off, vec_off;
25699
25700       if (entry.name != NULL)
25701         {
25702           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25703           if (insertpair.second)
25704             cpool.append_cstr0 (entry.name);
25705           str_off = insertpair.first->second;
25706           vec_off = entry.index_offset;
25707         }
25708       else
25709         {
25710           /* While 0 is a valid constant pool index, it is not valid
25711              to have 0 for both offsets.  */
25712           str_off = 0;
25713           vec_off = 0;
25714         }
25715
25716       output.append_data (MAYBE_SWAP (str_off));
25717       output.append_data (MAYBE_SWAP (vec_off));
25718     }
25719 }
25720
25721 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25722
25723 /* Helper struct for building the address table.  */
25724 struct addrmap_index_data
25725 {
25726   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25727     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25728   {}
25729
25730   struct objfile *objfile;
25731   data_buf &addr_vec;
25732   psym_index_map &cu_index_htab;
25733
25734   /* Non-zero if the previous_* fields are valid.
25735      We can't write an entry until we see the next entry (since it is only then
25736      that we know the end of the entry).  */
25737   int previous_valid;
25738   /* Index of the CU in the table of all CUs in the index file.  */
25739   unsigned int previous_cu_index;
25740   /* Start address of the CU.  */
25741   CORE_ADDR previous_cu_start;
25742 };
25743
25744 /* Write an address entry to ADDR_VEC.  */
25745
25746 static void
25747 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25748                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25749 {
25750   CORE_ADDR baseaddr;
25751
25752   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25753
25754   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25755   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25756   addr_vec.append_data (MAYBE_SWAP (cu_index));
25757 }
25758
25759 /* Worker function for traversing an addrmap to build the address table.  */
25760
25761 static int
25762 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25763 {
25764   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25765   struct partial_symtab *pst = (struct partial_symtab *) obj;
25766
25767   if (data->previous_valid)
25768     add_address_entry (data->objfile, data->addr_vec,
25769                        data->previous_cu_start, start_addr,
25770                        data->previous_cu_index);
25771
25772   data->previous_cu_start = start_addr;
25773   if (pst != NULL)
25774     {
25775       const auto it = data->cu_index_htab.find (pst);
25776       gdb_assert (it != data->cu_index_htab.cend ());
25777       data->previous_cu_index = it->second;
25778       data->previous_valid = 1;
25779     }
25780   else
25781     data->previous_valid = 0;
25782
25783   return 0;
25784 }
25785
25786 /* Write OBJFILE's address map to ADDR_VEC.
25787    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25788    in the index file.  */
25789
25790 static void
25791 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25792                    psym_index_map &cu_index_htab)
25793 {
25794   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25795
25796   /* When writing the address table, we have to cope with the fact that
25797      the addrmap iterator only provides the start of a region; we have to
25798      wait until the next invocation to get the start of the next region.  */
25799
25800   addrmap_index_data.objfile = objfile;
25801   addrmap_index_data.previous_valid = 0;
25802
25803   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25804                    &addrmap_index_data);
25805
25806   /* It's highly unlikely the last entry (end address = 0xff...ff)
25807      is valid, but we should still handle it.
25808      The end address is recorded as the start of the next region, but that
25809      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25810      anyway.  */
25811   if (addrmap_index_data.previous_valid)
25812     add_address_entry (objfile, addr_vec,
25813                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25814                        addrmap_index_data.previous_cu_index);
25815 }
25816
25817 /* Return the symbol kind of PSYM.  */
25818
25819 static gdb_index_symbol_kind
25820 symbol_kind (struct partial_symbol *psym)
25821 {
25822   domain_enum domain = PSYMBOL_DOMAIN (psym);
25823   enum address_class aclass = PSYMBOL_CLASS (psym);
25824
25825   switch (domain)
25826     {
25827     case VAR_DOMAIN:
25828       switch (aclass)
25829         {
25830         case LOC_BLOCK:
25831           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25832         case LOC_TYPEDEF:
25833           return GDB_INDEX_SYMBOL_KIND_TYPE;
25834         case LOC_COMPUTED:
25835         case LOC_CONST_BYTES:
25836         case LOC_OPTIMIZED_OUT:
25837         case LOC_STATIC:
25838           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25839         case LOC_CONST:
25840           /* Note: It's currently impossible to recognize psyms as enum values
25841              short of reading the type info.  For now punt.  */
25842           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25843         default:
25844           /* There are other LOC_FOO values that one might want to classify
25845              as variables, but dwarf2read.c doesn't currently use them.  */
25846           return GDB_INDEX_SYMBOL_KIND_OTHER;
25847         }
25848     case STRUCT_DOMAIN:
25849       return GDB_INDEX_SYMBOL_KIND_TYPE;
25850     default:
25851       return GDB_INDEX_SYMBOL_KIND_OTHER;
25852     }
25853 }
25854
25855 /* Add a list of partial symbols to SYMTAB.  */
25856
25857 static void
25858 write_psymbols (struct mapped_symtab *symtab,
25859                 std::unordered_set<partial_symbol *> &psyms_seen,
25860                 struct partial_symbol **psymp,
25861                 int count,
25862                 offset_type cu_index,
25863                 int is_static)
25864 {
25865   for (; count-- > 0; ++psymp)
25866     {
25867       struct partial_symbol *psym = *psymp;
25868
25869       if (SYMBOL_LANGUAGE (psym) == language_ada)
25870         error (_("Ada is not currently supported by the index"));
25871
25872       /* Only add a given psymbol once.  */
25873       if (psyms_seen.insert (psym).second)
25874         {
25875           gdb_index_symbol_kind kind = symbol_kind (psym);
25876
25877           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25878                            is_static, kind, cu_index);
25879         }
25880     }
25881 }
25882
25883 /* A helper struct used when iterating over debug_types.  */
25884 struct signatured_type_index_data
25885 {
25886   signatured_type_index_data (data_buf &types_list_,
25887                               std::unordered_set<partial_symbol *> &psyms_seen_)
25888     : types_list (types_list_), psyms_seen (psyms_seen_)
25889   {}
25890
25891   struct objfile *objfile;
25892   struct mapped_symtab *symtab;
25893   data_buf &types_list;
25894   std::unordered_set<partial_symbol *> &psyms_seen;
25895   int cu_index;
25896 };
25897
25898 /* A helper function that writes a single signatured_type to an
25899    obstack.  */
25900
25901 static int
25902 write_one_signatured_type (void **slot, void *d)
25903 {
25904   struct signatured_type_index_data *info
25905     = (struct signatured_type_index_data *) d;
25906   struct signatured_type *entry = (struct signatured_type *) *slot;
25907   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
25908
25909   write_psymbols (info->symtab,
25910                   info->psyms_seen,
25911                   &info->objfile->global_psymbols[psymtab->globals_offset],
25912                   psymtab->n_global_syms, info->cu_index,
25913                   0);
25914   write_psymbols (info->symtab,
25915                   info->psyms_seen,
25916                   &info->objfile->static_psymbols[psymtab->statics_offset],
25917                   psymtab->n_static_syms, info->cu_index,
25918                   1);
25919
25920   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
25921                                 to_underlying (entry->per_cu.sect_off));
25922   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
25923                                 to_underlying (entry->type_offset_in_tu));
25924   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
25925
25926   ++info->cu_index;
25927
25928   return 1;
25929 }
25930
25931 /* Recurse into all "included" dependencies and count their symbols as
25932    if they appeared in this psymtab.  */
25933
25934 static void
25935 recursively_count_psymbols (struct partial_symtab *psymtab,
25936                             size_t &psyms_seen)
25937 {
25938   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
25939     if (psymtab->dependencies[i]->user != NULL)
25940       recursively_count_psymbols (psymtab->dependencies[i],
25941                                   psyms_seen);
25942
25943   psyms_seen += psymtab->n_global_syms;
25944   psyms_seen += psymtab->n_static_syms;
25945 }
25946
25947 /* Recurse into all "included" dependencies and write their symbols as
25948    if they appeared in this psymtab.  */
25949
25950 static void
25951 recursively_write_psymbols (struct objfile *objfile,
25952                             struct partial_symtab *psymtab,
25953                             struct mapped_symtab *symtab,
25954                             std::unordered_set<partial_symbol *> &psyms_seen,
25955                             offset_type cu_index)
25956 {
25957   int i;
25958
25959   for (i = 0; i < psymtab->number_of_dependencies; ++i)
25960     if (psymtab->dependencies[i]->user != NULL)
25961       recursively_write_psymbols (objfile, psymtab->dependencies[i],
25962                                   symtab, psyms_seen, cu_index);
25963
25964   write_psymbols (symtab,
25965                   psyms_seen,
25966                   &objfile->global_psymbols[psymtab->globals_offset],
25967                   psymtab->n_global_syms, cu_index,
25968                   0);
25969   write_psymbols (symtab,
25970                   psyms_seen,
25971                   &objfile->static_psymbols[psymtab->statics_offset],
25972                   psymtab->n_static_syms, cu_index,
25973                   1);
25974 }
25975
25976 /* DWARF-5 .debug_names builder.  */
25977 class debug_names
25978 {
25979 public:
25980   debug_names (bool is_dwarf64, bfd_endian dwarf5_byte_order)
25981     : m_dwarf5_byte_order (dwarf5_byte_order),
25982       m_dwarf32 (dwarf5_byte_order),
25983       m_dwarf64 (dwarf5_byte_order),
25984       m_dwarf (is_dwarf64
25985                ? static_cast<dwarf &> (m_dwarf64)
25986                : static_cast<dwarf &> (m_dwarf32)),
25987       m_name_table_string_offs (m_dwarf.name_table_string_offs),
25988       m_name_table_entry_offs (m_dwarf.name_table_entry_offs)
25989   {}
25990
25991   /* Insert one symbol.  */
25992   void insert (const partial_symbol *psym, int cu_index, bool is_static)
25993   {
25994     const int dwarf_tag = psymbol_tag (psym);
25995     if (dwarf_tag == 0)
25996       return;
25997     const char *const name = SYMBOL_SEARCH_NAME (psym);
25998     const auto insertpair
25999       = m_name_to_value_set.emplace (c_str_view (name),
26000                                      std::set<symbol_value> ());
26001     std::set<symbol_value> &value_set = insertpair.first->second;
26002     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static));
26003   }
26004
26005   /* Build all the tables.  All symbols must be already inserted.
26006      This function does not call file_write, caller has to do it
26007      afterwards.  */
26008   void build ()
26009   {
26010     /* Verify the build method has not be called twice.  */
26011     gdb_assert (m_abbrev_table.empty ());
26012     const size_t name_count = m_name_to_value_set.size ();
26013     m_bucket_table.resize
26014       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26015     m_hash_table.reserve (name_count);
26016     m_name_table_string_offs.reserve (name_count);
26017     m_name_table_entry_offs.reserve (name_count);
26018
26019     /* Map each hash of symbol to its name and value.  */
26020     struct hash_it_pair
26021     {
26022       uint32_t hash;
26023       decltype (m_name_to_value_set)::const_iterator it;
26024     };
26025     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26026     bucket_hash.resize (m_bucket_table.size ());
26027     for (decltype (m_name_to_value_set)::const_iterator it
26028            = m_name_to_value_set.cbegin ();
26029          it != m_name_to_value_set.cend ();
26030          ++it)
26031       {
26032         const char *const name = it->first.c_str ();
26033         const uint32_t hash = dwarf5_djb_hash (name);
26034         hash_it_pair hashitpair;
26035         hashitpair.hash = hash;
26036         hashitpair.it = it;
26037         auto &slot = bucket_hash[hash % bucket_hash.size()];
26038         slot.push_front (std::move (hashitpair));
26039       }
26040     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26041       {
26042         const std::forward_list<hash_it_pair> &hashitlist
26043           = bucket_hash[bucket_ix];
26044         if (hashitlist.empty ())
26045           continue;
26046         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26047         /* The hashes array is indexed starting at 1.  */
26048         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26049                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26050                                 m_hash_table.size () + 1);
26051         for (const hash_it_pair &hashitpair : hashitlist)
26052           {
26053             m_hash_table.push_back (0);
26054             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26055                                                         (&m_hash_table.back ()),
26056                                     sizeof (m_hash_table.back ()),
26057                                     m_dwarf5_byte_order, hashitpair.hash);
26058             const c_str_view &name = hashitpair.it->first;
26059             const std::set<symbol_value> &value_set = hashitpair.it->second;
26060             m_name_table_string_offs.push_back_reorder
26061               (m_debugstrlookup.lookup (name.c_str ()));
26062             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26063             gdb_assert (!value_set.empty ());
26064             for (const symbol_value &value : value_set)
26065               {
26066                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26067                                                         value.is_static)];
26068                 if (idx == 0)
26069                   {
26070                     idx = m_idx_next++;
26071                     m_abbrev_table.append_unsigned_leb128 (idx);
26072                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26073                     m_abbrev_table.append_unsigned_leb128 (DW_IDX_compile_unit);
26074                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26075                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26076                                                            ? DW_IDX_GNU_internal
26077                                                            : DW_IDX_GNU_external);
26078                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26079
26080                     /* Terminate attributes list.  */
26081                     m_abbrev_table.append_unsigned_leb128 (0);
26082                     m_abbrev_table.append_unsigned_leb128 (0);
26083                   }
26084
26085                 m_entry_pool.append_unsigned_leb128 (idx);
26086                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26087               }
26088
26089             /* Terminate the list of CUs.  */
26090             m_entry_pool.append_unsigned_leb128 (0);
26091           }
26092       }
26093     gdb_assert (m_hash_table.size () == name_count);
26094
26095     /* Terminate tags list.  */
26096     m_abbrev_table.append_unsigned_leb128 (0);
26097   }
26098
26099   /* Return .debug_names bucket count.  This must be called only after
26100      calling the build method.  */
26101   uint32_t bucket_count () const
26102   {
26103     /* Verify the build method has been already called.  */
26104     gdb_assert (!m_abbrev_table.empty ());
26105     const uint32_t retval = m_bucket_table.size ();
26106
26107     /* Check for overflow.  */
26108     gdb_assert (retval == m_bucket_table.size ());
26109     return retval;
26110   }
26111
26112   /* Return .debug_names names count.  This must be called only after
26113      calling the build method.  */
26114   uint32_t name_count () const
26115   {
26116     /* Verify the build method has been already called.  */
26117     gdb_assert (!m_abbrev_table.empty ());
26118     const uint32_t retval = m_hash_table.size ();
26119
26120     /* Check for overflow.  */
26121     gdb_assert (retval == m_hash_table.size ());
26122     return retval;
26123   }
26124
26125   /* Return number of bytes of .debug_names abbreviation table.  This
26126      must be called only after calling the build method.  */
26127   uint32_t abbrev_table_bytes () const
26128   {
26129     gdb_assert (!m_abbrev_table.empty ());
26130     return m_abbrev_table.size ();
26131   }
26132
26133   /* Recurse into all "included" dependencies and store their symbols
26134      as if they appeared in this psymtab.  */
26135   void recursively_write_psymbols
26136     (struct objfile *objfile,
26137      struct partial_symtab *psymtab,
26138      std::unordered_set<partial_symbol *> &psyms_seen,
26139      int cu_index)
26140   {
26141     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26142       if (psymtab->dependencies[i]->user != NULL)
26143         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26144                                     psyms_seen, cu_index);
26145
26146     write_psymbols (psyms_seen,
26147                     &objfile->global_psymbols[psymtab->globals_offset],
26148                     psymtab->n_global_syms, cu_index, false);
26149     write_psymbols (psyms_seen,
26150                     &objfile->static_psymbols[psymtab->statics_offset],
26151                     psymtab->n_static_syms, cu_index, true);
26152   }
26153
26154   /* Return number of bytes the .debug_names section will have.  This
26155      must be called only after calling the build method.  */
26156   size_t bytes () const
26157   {
26158     /* Verify the build method has been already called.  */
26159     gdb_assert (!m_abbrev_table.empty ());
26160     size_t expected_bytes = 0;
26161     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26162     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26163     expected_bytes += m_name_table_string_offs.bytes ();
26164     expected_bytes += m_name_table_entry_offs.bytes ();
26165     expected_bytes += m_abbrev_table.size ();
26166     expected_bytes += m_entry_pool.size ();
26167     return expected_bytes;
26168   }
26169
26170   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26171      FILE_STR.  This must be called only after calling the build
26172      method.  */
26173   void file_write (FILE *file_names, FILE *file_str) const
26174   {
26175     /* Verify the build method has been already called.  */
26176     gdb_assert (!m_abbrev_table.empty ());
26177     ::file_write (file_names, m_bucket_table);
26178     ::file_write (file_names, m_hash_table);
26179     m_name_table_string_offs.file_write (file_names);
26180     m_name_table_entry_offs.file_write (file_names);
26181     m_abbrev_table.file_write (file_names);
26182     m_entry_pool.file_write (file_names);
26183     m_debugstrlookup.file_write (file_str);
26184   }
26185
26186 private:
26187
26188   /* Storage for symbol names mapping them to their .debug_str section
26189      offsets.  */
26190   class debug_str_lookup
26191   {
26192   public:
26193
26194     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26195        All .debug_str section strings are automatically stored.  */
26196     debug_str_lookup ()
26197       : m_abfd (dwarf2_per_objfile->objfile->obfd)
26198     {
26199       dwarf2_read_section (dwarf2_per_objfile->objfile,
26200                            &dwarf2_per_objfile->str);
26201       if (dwarf2_per_objfile->str.buffer == NULL)
26202         return;
26203       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26204            data < (dwarf2_per_objfile->str.buffer
26205                    + dwarf2_per_objfile->str.size);)
26206         {
26207           const char *const s = reinterpret_cast<const char *> (data);
26208           const auto insertpair
26209             = m_str_table.emplace (c_str_view (s),
26210                                    data - dwarf2_per_objfile->str.buffer);
26211           if (!insertpair.second)
26212             complaint (&symfile_complaints,
26213                        _("Duplicate string \"%s\" in "
26214                          ".debug_str section [in module %s]"),
26215                        s, bfd_get_filename (m_abfd));
26216           data += strlen (s) + 1;
26217         }
26218     }
26219
26220     /* Return offset of symbol name S in the .debug_str section.  Add
26221        such symbol to the section's end if it does not exist there
26222        yet.  */
26223     size_t lookup (const char *s)
26224     {
26225       const auto it = m_str_table.find (c_str_view (s));
26226       if (it != m_str_table.end ())
26227         return it->second;
26228       const size_t offset = (dwarf2_per_objfile->str.size
26229                              + m_str_add_buf.size ());
26230       m_str_table.emplace (c_str_view (s), offset);
26231       m_str_add_buf.append_cstr0 (s);
26232       return offset;
26233     }
26234
26235     /* Append the end of the .debug_str section to FILE.  */
26236     void file_write (FILE *file) const
26237     {
26238       m_str_add_buf.file_write (file);
26239     }
26240
26241   private:
26242     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26243     bfd *const m_abfd;
26244
26245     /* Data to add at the end of .debug_str for new needed symbol names.  */
26246     data_buf m_str_add_buf;
26247   };
26248
26249   /* Container to map used DWARF tags to their .debug_names abbreviation
26250      tags.  */
26251   class index_key
26252   {
26253   public:
26254     index_key (int dwarf_tag_, bool is_static_)
26255       : dwarf_tag (dwarf_tag_), is_static (is_static_)
26256     {
26257     }
26258
26259     bool
26260     operator== (const index_key &other) const
26261     {
26262       return dwarf_tag == other.dwarf_tag && is_static == other.is_static;
26263     }
26264
26265     const int dwarf_tag;
26266     const bool is_static;
26267   };
26268
26269   /* Provide std::unordered_map::hasher for index_key.  */
26270   class index_key_hasher
26271   {
26272   public:
26273     size_t
26274     operator () (const index_key &key) const
26275     {
26276       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26277     }
26278   };
26279
26280   /* Parameters of one symbol entry.  */
26281   class symbol_value
26282   {
26283   public:
26284     const int dwarf_tag, cu_index;
26285     const bool is_static;
26286
26287     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_)
26288       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_)
26289     {}
26290
26291     bool
26292     operator< (const symbol_value &other) const
26293     {
26294 #define X(n) \
26295   do \
26296     { \
26297       if (n < other.n) \
26298         return true; \
26299       if (n > other.n) \
26300         return false; \
26301     } \
26302   while (0)
26303       X (dwarf_tag);
26304       X (is_static);
26305       X (cu_index);
26306 #undef X
26307       return false;
26308     }
26309   };
26310
26311   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26312      output.  */
26313   class offset_vec
26314   {
26315   protected:
26316     const bfd_endian dwarf5_byte_order;
26317   public:
26318     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26319       : dwarf5_byte_order (dwarf5_byte_order_)
26320     {}
26321
26322     /* Call std::vector::reserve for NELEM elements.  */
26323     virtual void reserve (size_t nelem) = 0;
26324
26325     /* Call std::vector::push_back with store_unsigned_integer byte
26326        reordering for ELEM.  */
26327     virtual void push_back_reorder (size_t elem) = 0;
26328
26329     /* Return expected output size in bytes.  */
26330     virtual size_t bytes () const = 0;
26331
26332     /* Write name table to FILE.  */
26333     virtual void file_write (FILE *file) const = 0;
26334   };
26335
26336   /* Template to unify DWARF-32 and DWARF-64 output.  */
26337   template<typename OffsetSize>
26338   class offset_vec_tmpl : public offset_vec
26339   {
26340   public:
26341     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26342       : offset_vec (dwarf5_byte_order_)
26343     {}
26344
26345     /* Implement offset_vec::reserve.  */
26346     void reserve (size_t nelem) override
26347     {
26348       m_vec.reserve (nelem);
26349     }
26350
26351     /* Implement offset_vec::push_back_reorder.  */
26352     void push_back_reorder (size_t elem) override
26353     {
26354       m_vec.push_back (elem);
26355       /* Check for overflow.  */
26356       gdb_assert (m_vec.back () == elem);
26357       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26358                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26359     }
26360
26361     /* Implement offset_vec::bytes.  */
26362     size_t bytes () const override
26363     {
26364       return m_vec.size () * sizeof (m_vec[0]);
26365     }
26366
26367     /* Implement offset_vec::file_write.  */
26368     void file_write (FILE *file) const override
26369     {
26370       ::file_write (file, m_vec);
26371     }
26372
26373   private:
26374     std::vector<OffsetSize> m_vec;
26375   };
26376
26377   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26378      respecting name table width.  */
26379   class dwarf
26380   {
26381   public:
26382     offset_vec &name_table_string_offs, &name_table_entry_offs;
26383
26384     dwarf (offset_vec &name_table_string_offs_,
26385            offset_vec &name_table_entry_offs_)
26386       : name_table_string_offs (name_table_string_offs_),
26387         name_table_entry_offs (name_table_entry_offs_)
26388     {
26389     }
26390   };
26391
26392   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26393      respecting name table width.  */
26394   template<typename OffsetSize>
26395   class dwarf_tmpl : public dwarf
26396   {
26397   public:
26398     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26399       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26400         m_name_table_string_offs (dwarf5_byte_order_),
26401         m_name_table_entry_offs (dwarf5_byte_order_)
26402     {}
26403
26404   private:
26405     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26406     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26407   };
26408
26409   /* Try to reconstruct original DWARF tag for given partial_symbol.
26410      This function is not DWARF-5 compliant but it is sufficient for
26411      GDB as a DWARF-5 index consumer.  */
26412   static int psymbol_tag (const struct partial_symbol *psym)
26413   {
26414     domain_enum domain = PSYMBOL_DOMAIN (psym);
26415     enum address_class aclass = PSYMBOL_CLASS (psym);
26416
26417     switch (domain)
26418       {
26419       case VAR_DOMAIN:
26420         switch (aclass)
26421           {
26422           case LOC_BLOCK:
26423             return DW_TAG_subprogram;
26424           case LOC_TYPEDEF:
26425             return DW_TAG_typedef;
26426           case LOC_COMPUTED:
26427           case LOC_CONST_BYTES:
26428           case LOC_OPTIMIZED_OUT:
26429           case LOC_STATIC:
26430             return DW_TAG_variable;
26431           case LOC_CONST:
26432             /* Note: It's currently impossible to recognize psyms as enum values
26433                short of reading the type info.  For now punt.  */
26434             return DW_TAG_variable;
26435           default:
26436             /* There are other LOC_FOO values that one might want to classify
26437                as variables, but dwarf2read.c doesn't currently use them.  */
26438             return DW_TAG_variable;
26439           }
26440       case STRUCT_DOMAIN:
26441         return DW_TAG_structure_type;
26442       default:
26443         return 0;
26444       }
26445   }
26446
26447   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26448   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26449                        struct partial_symbol **psymp, int count, int cu_index,
26450                        bool is_static)
26451   {
26452     for (; count-- > 0; ++psymp)
26453       {
26454         struct partial_symbol *psym = *psymp;
26455
26456         if (SYMBOL_LANGUAGE (psym) == language_ada)
26457           error (_("Ada is not currently supported by the index"));
26458
26459         /* Only add a given psymbol once.  */
26460         if (psyms_seen.insert (psym).second)
26461           insert (psym, cu_index, is_static);
26462       }
26463   }
26464
26465   /* Store value of each symbol.  */
26466   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26467     m_name_to_value_set;
26468
26469   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26470      order.  */
26471   std::vector<uint32_t> m_bucket_table;
26472   std::vector<uint32_t> m_hash_table;
26473
26474   const bfd_endian m_dwarf5_byte_order;
26475   dwarf_tmpl<uint32_t> m_dwarf32;
26476   dwarf_tmpl<uint64_t> m_dwarf64;
26477   dwarf &m_dwarf;
26478   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26479   debug_str_lookup m_debugstrlookup;
26480
26481   /* Map each used .debug_names abbreviation tag parameter to its
26482      index value.  */
26483   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26484
26485   /* Next unused .debug_names abbreviation tag for
26486      m_indexkey_to_idx.  */
26487   int m_idx_next = 1;
26488
26489   /* .debug_names abbreviation table.  */
26490   data_buf m_abbrev_table;
26491
26492   /* .debug_names entry pool.  */
26493   data_buf m_entry_pool;
26494 };
26495
26496 /* Return iff any of the needed offsets does not fit into 32-bit
26497    .debug_names section.  */
26498
26499 static bool
26500 check_dwarf64_offsets ()
26501 {
26502   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26503     {
26504       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26505
26506       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26507         return true;
26508     }
26509   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26510     {
26511       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26512       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26513
26514       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26515         return true;
26516     }
26517   return false;
26518 }
26519
26520 /* The psyms_seen set is potentially going to be largish (~40k
26521    elements when indexing a -g3 build of GDB itself).  Estimate the
26522    number of elements in order to avoid too many rehashes, which
26523    require rebuilding buckets and thus many trips to
26524    malloc/free.  */
26525
26526 static size_t
26527 psyms_seen_size ()
26528 {
26529   size_t psyms_count = 0;
26530   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26531     {
26532       struct dwarf2_per_cu_data *per_cu
26533         = dwarf2_per_objfile->all_comp_units[i];
26534       struct partial_symtab *psymtab = per_cu->v.psymtab;
26535
26536       if (psymtab != NULL && psymtab->user == NULL)
26537         recursively_count_psymbols (psymtab, psyms_count);
26538     }
26539   /* Generating an index for gdb itself shows a ratio of
26540      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26541   return psyms_count / 4;
26542 }
26543
26544 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26545    Return how many bytes were expected to be written into OUT_FILE.  */
26546
26547 static size_t
26548 write_gdbindex (struct objfile *objfile, FILE *out_file)
26549 {
26550   mapped_symtab symtab;
26551   data_buf cu_list;
26552
26553   /* While we're scanning CU's create a table that maps a psymtab pointer
26554      (which is what addrmap records) to its index (which is what is recorded
26555      in the index file).  This will later be needed to write the address
26556      table.  */
26557   psym_index_map cu_index_htab;
26558   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26559
26560   /* The CU list is already sorted, so we don't need to do additional
26561      work here.  Also, the debug_types entries do not appear in
26562      all_comp_units, but only in their own hash table.  */
26563
26564   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26565   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26566     {
26567       struct dwarf2_per_cu_data *per_cu
26568         = dwarf2_per_objfile->all_comp_units[i];
26569       struct partial_symtab *psymtab = per_cu->v.psymtab;
26570
26571       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26572          It may be referenced from a local scope but in such case it does not
26573          need to be present in .gdb_index.  */
26574       if (psymtab == NULL)
26575         continue;
26576
26577       if (psymtab->user == NULL)
26578         recursively_write_psymbols (objfile, psymtab, &symtab,
26579                                     psyms_seen, i);
26580
26581       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26582       gdb_assert (insertpair.second);
26583
26584       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26585                            to_underlying (per_cu->sect_off));
26586       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26587     }
26588
26589   /* Dump the address map.  */
26590   data_buf addr_vec;
26591   write_address_map (objfile, addr_vec, cu_index_htab);
26592
26593   /* Write out the .debug_type entries, if any.  */
26594   data_buf types_cu_list;
26595   if (dwarf2_per_objfile->signatured_types)
26596     {
26597       signatured_type_index_data sig_data (types_cu_list,
26598                                            psyms_seen);
26599
26600       sig_data.objfile = objfile;
26601       sig_data.symtab = &symtab;
26602       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26603       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26604                               write_one_signatured_type, &sig_data);
26605     }
26606
26607   /* Now that we've processed all symbols we can shrink their cu_indices
26608      lists.  */
26609   uniquify_cu_indices (&symtab);
26610
26611   data_buf symtab_vec, constant_pool;
26612   write_hash_table (&symtab, symtab_vec, constant_pool);
26613
26614   data_buf contents;
26615   const offset_type size_of_contents = 6 * sizeof (offset_type);
26616   offset_type total_len = size_of_contents;
26617
26618   /* The version number.  */
26619   contents.append_data (MAYBE_SWAP (8));
26620
26621   /* The offset of the CU list from the start of the file.  */
26622   contents.append_data (MAYBE_SWAP (total_len));
26623   total_len += cu_list.size ();
26624
26625   /* The offset of the types CU list from the start of the file.  */
26626   contents.append_data (MAYBE_SWAP (total_len));
26627   total_len += types_cu_list.size ();
26628
26629   /* The offset of the address table from the start of the file.  */
26630   contents.append_data (MAYBE_SWAP (total_len));
26631   total_len += addr_vec.size ();
26632
26633   /* The offset of the symbol table from the start of the file.  */
26634   contents.append_data (MAYBE_SWAP (total_len));
26635   total_len += symtab_vec.size ();
26636
26637   /* The offset of the constant pool from the start of the file.  */
26638   contents.append_data (MAYBE_SWAP (total_len));
26639   total_len += constant_pool.size ();
26640
26641   gdb_assert (contents.size () == size_of_contents);
26642
26643   contents.file_write (out_file);
26644   cu_list.file_write (out_file);
26645   types_cu_list.file_write (out_file);
26646   addr_vec.file_write (out_file);
26647   symtab_vec.file_write (out_file);
26648   constant_pool.file_write (out_file);
26649
26650   return total_len;
26651 }
26652
26653 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26654 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26655
26656 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26657    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26658    many bytes were expected to be written into OUT_FILE.  */
26659
26660 static size_t
26661 write_debug_names (struct objfile *objfile, FILE *out_file, FILE *out_file_str)
26662 {
26663   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets ();
26664   const int dwarf5_offset_size = dwarf5_is_dwarf64 ? 8 : 4;
26665   const enum bfd_endian dwarf5_byte_order
26666     = gdbarch_byte_order (get_objfile_arch (objfile));
26667
26668   /* The CU list is already sorted, so we don't need to do additional
26669      work here.  Also, the debug_types entries do not appear in
26670      all_comp_units, but only in their own hash table.  */
26671   data_buf cu_list;
26672   debug_names nametable (dwarf5_is_dwarf64, dwarf5_byte_order);
26673   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26674   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26675     {
26676       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26677       partial_symtab *psymtab = per_cu->v.psymtab;
26678
26679       /* CU of a shared file from 'dwz -m' may be unused by this main
26680          file.  It may be referenced from a local scope but in such
26681          case it does not need to be present in .debug_names.  */
26682       if (psymtab == NULL)
26683         continue;
26684
26685       if (psymtab->user == NULL)
26686         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26687
26688       cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
26689                            to_underlying (per_cu->sect_off));
26690     }
26691   nametable.build ();
26692
26693   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26694
26695   data_buf types_cu_list;
26696   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26697     {
26698       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26699       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26700
26701       types_cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
26702                                  to_underlying (per_cu.sect_off));
26703     }
26704
26705   const offset_type bytes_of_header
26706     = ((dwarf5_is_dwarf64 ? 12 : 4)
26707        + 2 + 2 + 7 * 4
26708        + sizeof (dwarf5_gdb_augmentation));
26709   size_t expected_bytes = 0;
26710   expected_bytes += bytes_of_header;
26711   expected_bytes += cu_list.size ();
26712   expected_bytes += types_cu_list.size ();
26713   expected_bytes += nametable.bytes ();
26714   data_buf header;
26715
26716   if (!dwarf5_is_dwarf64)
26717     {
26718       const uint64_t size64 = expected_bytes - 4;
26719       gdb_assert (size64 < 0xfffffff0);
26720       header.append_uint (4, dwarf5_byte_order, size64);
26721     }
26722   else
26723     {
26724       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26725       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26726     }
26727
26728   /* The version number.  */
26729   header.append_uint (2, dwarf5_byte_order, 5);
26730
26731   /* Padding.  */
26732   header.append_uint (2, dwarf5_byte_order, 0);
26733
26734   /* comp_unit_count - The number of CUs in the CU list.  */
26735   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26736
26737   /* local_type_unit_count - The number of TUs in the local TU
26738      list.  */
26739   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26740
26741   /* foreign_type_unit_count - The number of TUs in the foreign TU
26742      list.  */
26743   header.append_uint (4, dwarf5_byte_order, 0);
26744
26745   /* bucket_count - The number of hash buckets in the hash lookup
26746      table.  */
26747   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26748
26749   /* name_count - The number of unique names in the index.  */
26750   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26751
26752   /* abbrev_table_size - The size in bytes of the abbreviations
26753      table.  */
26754   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26755
26756   /* augmentation_string_size - The size in bytes of the augmentation
26757      string.  This value is rounded up to a multiple of 4.  */
26758   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26759   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26760   header.append_data (dwarf5_gdb_augmentation);
26761
26762   gdb_assert (header.size () == bytes_of_header);
26763
26764   header.file_write (out_file);
26765   cu_list.file_write (out_file);
26766   types_cu_list.file_write (out_file);
26767   nametable.file_write (out_file, out_file_str);
26768
26769   return expected_bytes;
26770 }
26771
26772 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26773    position is at the end of the file.  */
26774
26775 static void
26776 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26777 {
26778   const auto file_size = ftell (file);
26779   if (file_size == -1)
26780     error (_("Can't get `%s' size"), filename);
26781   gdb_assert (file_size == expected_size);
26782 }
26783
26784 /* An index variant.  */
26785 enum dw_index_kind
26786 {
26787   /* GDB's own .gdb_index format.   */
26788   GDB_INDEX,
26789
26790   /* DWARF5 .debug_names.  */
26791   DEBUG_NAMES,
26792 };
26793
26794 /* Create an index file for OBJFILE in the directory DIR.  */
26795
26796 static void
26797 write_psymtabs_to_index (struct objfile *objfile, const char *dir,
26798                          dw_index_kind index_kind)
26799 {
26800   if (dwarf2_per_objfile->using_index)
26801     error (_("Cannot use an index to create the index"));
26802
26803   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
26804     error (_("Cannot make an index when the file has multiple .debug_types sections"));
26805
26806   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
26807     return;
26808
26809   struct stat st;
26810   if (stat (objfile_name (objfile), &st) < 0)
26811     perror_with_name (objfile_name (objfile));
26812
26813   std::string filename (std::string (dir) + SLASH_STRING
26814                         + lbasename (objfile_name (objfile))
26815                         + (index_kind == dw_index_kind::DEBUG_NAMES
26816                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
26817
26818   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
26819   if (!out_file)
26820     error (_("Can't open `%s' for writing"), filename.c_str ());
26821
26822   /* Order matters here; we want FILE to be closed before FILENAME is
26823      unlinked, because on MS-Windows one cannot delete a file that is
26824      still open.  (Don't call anything here that might throw until
26825      file_closer is created.)  */
26826   gdb::unlinker unlink_file (filename.c_str ());
26827   gdb_file_up close_out_file (out_file);
26828
26829   if (index_kind == dw_index_kind::DEBUG_NAMES)
26830     {
26831       std::string filename_str (std::string (dir) + SLASH_STRING
26832                                 + lbasename (objfile_name (objfile))
26833                                 + DEBUG_STR_SUFFIX);
26834       FILE *out_file_str
26835         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
26836       if (!out_file_str)
26837         error (_("Can't open `%s' for writing"), filename_str.c_str ());
26838       gdb::unlinker unlink_file_str (filename_str.c_str ());
26839       gdb_file_up close_out_file_str (out_file_str);
26840
26841       const size_t total_len
26842         = write_debug_names (objfile, out_file, out_file_str);
26843       assert_file_size (out_file, filename.c_str (), total_len);
26844
26845       /* We want to keep the file .debug_str file too.  */
26846       unlink_file_str.keep ();
26847     }
26848   else
26849     {
26850       const size_t total_len
26851         = write_gdbindex (objfile, out_file);
26852       assert_file_size (out_file, filename.c_str (), total_len);
26853     }
26854
26855   /* We want to keep the file.  */
26856   unlink_file.keep ();
26857 }
26858
26859 /* Implementation of the `save gdb-index' command.
26860    
26861    Note that the .gdb_index file format used by this command is
26862    documented in the GDB manual.  Any changes here must be documented
26863    there.  */
26864
26865 static void
26866 save_gdb_index_command (const char *arg, int from_tty)
26867 {
26868   struct objfile *objfile;
26869   const char dwarf5space[] = "-dwarf-5 ";
26870   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
26871
26872   if (!arg)
26873     arg = "";
26874
26875   arg = skip_spaces (arg);
26876   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
26877     {
26878       index_kind = dw_index_kind::DEBUG_NAMES;
26879       arg += strlen (dwarf5space);
26880       arg = skip_spaces (arg);
26881     }
26882
26883   if (!*arg)
26884     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
26885
26886   ALL_OBJFILES (objfile)
26887   {
26888     struct stat st;
26889
26890     /* If the objfile does not correspond to an actual file, skip it.  */
26891     if (stat (objfile_name (objfile), &st) < 0)
26892       continue;
26893
26894     dwarf2_per_objfile
26895       = (struct dwarf2_per_objfile *) objfile_data (objfile,
26896                                                     dwarf2_objfile_data_key);
26897     if (dwarf2_per_objfile)
26898       {
26899
26900         TRY
26901           {
26902             write_psymtabs_to_index (objfile, arg, index_kind);
26903           }
26904         CATCH (except, RETURN_MASK_ERROR)
26905           {
26906             exception_fprintf (gdb_stderr, except,
26907                                _("Error while writing index for `%s': "),
26908                                objfile_name (objfile));
26909           }
26910         END_CATCH
26911       }
26912   }
26913 }
26914
26915 \f
26916
26917 int dwarf_always_disassemble;
26918
26919 static void
26920 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
26921                                struct cmd_list_element *c, const char *value)
26922 {
26923   fprintf_filtered (file,
26924                     _("Whether to always disassemble "
26925                       "DWARF expressions is %s.\n"),
26926                     value);
26927 }
26928
26929 static void
26930 show_check_physname (struct ui_file *file, int from_tty,
26931                      struct cmd_list_element *c, const char *value)
26932 {
26933   fprintf_filtered (file,
26934                     _("Whether to check \"physname\" is %s.\n"),
26935                     value);
26936 }
26937
26938 void
26939 _initialize_dwarf2_read (void)
26940 {
26941   struct cmd_list_element *c;
26942
26943   dwarf2_objfile_data_key
26944     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
26945
26946   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
26947 Set DWARF specific variables.\n\
26948 Configure DWARF variables such as the cache size"),
26949                   &set_dwarf_cmdlist, "maintenance set dwarf ",
26950                   0/*allow-unknown*/, &maintenance_set_cmdlist);
26951
26952   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
26953 Show DWARF specific variables\n\
26954 Show DWARF variables such as the cache size"),
26955                   &show_dwarf_cmdlist, "maintenance show dwarf ",
26956                   0/*allow-unknown*/, &maintenance_show_cmdlist);
26957
26958   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
26959                             &dwarf_max_cache_age, _("\
26960 Set the upper bound on the age of cached DWARF compilation units."), _("\
26961 Show the upper bound on the age of cached DWARF compilation units."), _("\
26962 A higher limit means that cached compilation units will be stored\n\
26963 in memory longer, and more total memory will be used.  Zero disables\n\
26964 caching, which can slow down startup."),
26965                             NULL,
26966                             show_dwarf_max_cache_age,
26967                             &set_dwarf_cmdlist,
26968                             &show_dwarf_cmdlist);
26969
26970   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
26971                            &dwarf_always_disassemble, _("\
26972 Set whether `info address' always disassembles DWARF expressions."), _("\
26973 Show whether `info address' always disassembles DWARF expressions."), _("\
26974 When enabled, DWARF expressions are always printed in an assembly-like\n\
26975 syntax.  When disabled, expressions will be printed in a more\n\
26976 conversational style, when possible."),
26977                            NULL,
26978                            show_dwarf_always_disassemble,
26979                            &set_dwarf_cmdlist,
26980                            &show_dwarf_cmdlist);
26981
26982   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
26983 Set debugging of the DWARF reader."), _("\
26984 Show debugging of the DWARF reader."), _("\
26985 When enabled (non-zero), debugging messages are printed during DWARF\n\
26986 reading and symtab expansion.  A value of 1 (one) provides basic\n\
26987 information.  A value greater than 1 provides more verbose information."),
26988                             NULL,
26989                             NULL,
26990                             &setdebuglist, &showdebuglist);
26991
26992   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
26993 Set debugging of the DWARF DIE reader."), _("\
26994 Show debugging of the DWARF DIE reader."), _("\
26995 When enabled (non-zero), DIEs are dumped after they are read in.\n\
26996 The value is the maximum depth to print."),
26997                              NULL,
26998                              NULL,
26999                              &setdebuglist, &showdebuglist);
27000
27001   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27002 Set debugging of the dwarf line reader."), _("\
27003 Show debugging of the dwarf line reader."), _("\
27004 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27005 A value of 1 (one) provides basic information.\n\
27006 A value greater than 1 provides more verbose information."),
27007                              NULL,
27008                              NULL,
27009                              &setdebuglist, &showdebuglist);
27010
27011   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27012 Set cross-checking of \"physname\" code against demangler."), _("\
27013 Show cross-checking of \"physname\" code against demangler."), _("\
27014 When enabled, GDB's internal \"physname\" code is checked against\n\
27015 the demangler."),
27016                            NULL, show_check_physname,
27017                            &setdebuglist, &showdebuglist);
27018
27019   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27020                            no_class, &use_deprecated_index_sections, _("\
27021 Set whether to use deprecated gdb_index sections."), _("\
27022 Show whether to use deprecated gdb_index sections."), _("\
27023 When enabled, deprecated .gdb_index sections are used anyway.\n\
27024 Normally they are ignored either because of a missing feature or\n\
27025 performance issue.\n\
27026 Warning: This option must be enabled before gdb reads the file."),
27027                            NULL,
27028                            NULL,
27029                            &setlist, &showlist);
27030
27031   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27032                _("\
27033 Save a gdb-index file.\n\
27034 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27035 \n\
27036 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27037 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27038 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27039                &save_cmdlist);
27040   set_cmd_completer (c, filename_completer);
27041
27042   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27043                                                         &dwarf2_locexpr_funcs);
27044   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27045                                                         &dwarf2_loclist_funcs);
27046
27047   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27048                                         &dwarf2_block_frame_base_locexpr_funcs);
27049   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27050                                         &dwarf2_block_frame_base_loclist_funcs);
27051
27052 #if GDB_SELF_TEST
27053   selftests::register_test ("dw2_expand_symtabs_matching",
27054                             selftests::dw2_expand_symtabs_matching::run_test);
27055 #endif
27056 }