dwarf2read.c:mapped_index, use gdb::array_view, simplify symbol table
[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   /* A slot/bucket in the symbol table hash.  */
242   struct symbol_table_slot
243   {
244     const offset_type name;
245     const offset_type vec;
246   };
247
248   /* Index data format version.  */
249   int version;
250
251   /* The total length of the buffer.  */
252   off_t total_size;
253
254   /* The address table data.  */
255   gdb::array_view<const gdb_byte> address_table;
256
257   /* The symbol table, implemented as a hash table.  */
258   gdb::array_view<symbol_table_slot> symbol_table;
259
260   /* A pointer to the constant pool.  */
261   const char *constant_pool;
262
263   /* The name_component table (a sorted vector).  See name_component's
264      description above.  */
265   std::vector<name_component> name_components;
266
267   /* How NAME_COMPONENTS is sorted.  */
268   enum case_sensitivity name_components_casing;
269
270   /* Convenience method to get at the name of the symbol at IDX in the
271      symbol table.  */
272   const char *symbol_name_at (offset_type idx) const
273   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
274
275   /* Build the symbol name component sorted vector, if we haven't
276      yet.  */
277   void build_name_components ();
278
279   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
280      possible matches for LN_NO_PARAMS in the name component
281      vector.  */
282   std::pair<std::vector<name_component>::const_iterator,
283             std::vector<name_component>::const_iterator>
284     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
285 };
286
287 /* A description of the mapped .debug_names.
288    Uninitialized map has CU_COUNT 0.  */
289 struct mapped_debug_names
290 {
291   bfd_endian dwarf5_byte_order;
292   bool dwarf5_is_dwarf64;
293   bool augmentation_is_gdb;
294   uint8_t offset_size;
295   uint32_t cu_count = 0;
296   uint32_t tu_count, bucket_count, name_count;
297   const gdb_byte *cu_table_reordered, *tu_table_reordered;
298   const uint32_t *bucket_table_reordered, *hash_table_reordered;
299   const gdb_byte *name_table_string_offs_reordered;
300   const gdb_byte *name_table_entry_offs_reordered;
301   const gdb_byte *entry_pool;
302
303   struct index_val
304   {
305     ULONGEST dwarf_tag;
306     struct attr
307     {
308       /* Attribute name DW_IDX_*.  */
309       ULONGEST dw_idx;
310
311       /* Attribute form DW_FORM_*.  */
312       ULONGEST form;
313
314       /* Value if FORM is DW_FORM_implicit_const.  */
315       LONGEST implicit_const;
316     };
317     std::vector<attr> attr_vec;
318   };
319
320   std::unordered_map<ULONGEST, index_val> abbrev_map;
321
322   const char *namei_to_name (uint32_t namei) const;
323 };
324
325 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
326 DEF_VEC_P (dwarf2_per_cu_ptr);
327
328 struct tu_stats
329 {
330   int nr_uniq_abbrev_tables;
331   int nr_symtabs;
332   int nr_symtab_sharers;
333   int nr_stmt_less_type_units;
334   int nr_all_type_units_reallocs;
335 };
336
337 /* Collection of data recorded per objfile.
338    This hangs off of dwarf2_objfile_data_key.  */
339
340 struct dwarf2_per_objfile
341 {
342   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
343      dwarf2 section names, or is NULL if the standard ELF names are
344      used.  */
345   dwarf2_per_objfile (struct objfile *objfile,
346                       const dwarf2_debug_sections *names);
347
348   ~dwarf2_per_objfile ();
349
350   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
351
352   /* Free all cached compilation units.  */
353   void free_cached_comp_units ();
354 private:
355   /* This function is mapped across the sections and remembers the
356      offset and size of each of the debugging sections we are
357      interested in.  */
358   void locate_sections (bfd *abfd, asection *sectp,
359                         const dwarf2_debug_sections &names);
360
361 public:
362   dwarf2_section_info info {};
363   dwarf2_section_info abbrev {};
364   dwarf2_section_info line {};
365   dwarf2_section_info loc {};
366   dwarf2_section_info loclists {};
367   dwarf2_section_info macinfo {};
368   dwarf2_section_info macro {};
369   dwarf2_section_info str {};
370   dwarf2_section_info line_str {};
371   dwarf2_section_info ranges {};
372   dwarf2_section_info rnglists {};
373   dwarf2_section_info addr {};
374   dwarf2_section_info frame {};
375   dwarf2_section_info eh_frame {};
376   dwarf2_section_info gdb_index {};
377   dwarf2_section_info debug_names {};
378   dwarf2_section_info debug_aranges {};
379
380   VEC (dwarf2_section_info_def) *types = NULL;
381
382   /* Back link.  */
383   struct objfile *objfile = NULL;
384
385   /* Table of all the compilation units.  This is used to locate
386      the target compilation unit of a particular reference.  */
387   struct dwarf2_per_cu_data **all_comp_units = NULL;
388
389   /* The number of compilation units in ALL_COMP_UNITS.  */
390   int n_comp_units = 0;
391
392   /* The number of .debug_types-related CUs.  */
393   int n_type_units = 0;
394
395   /* The number of elements allocated in all_type_units.
396      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
397   int n_allocated_type_units = 0;
398
399   /* The .debug_types-related CUs (TUs).
400      This is stored in malloc space because we may realloc it.  */
401   struct signatured_type **all_type_units = NULL;
402
403   /* Table of struct type_unit_group objects.
404      The hash key is the DW_AT_stmt_list value.  */
405   htab_t type_unit_groups {};
406
407   /* A table mapping .debug_types signatures to its signatured_type entry.
408      This is NULL if the .debug_types section hasn't been read in yet.  */
409   htab_t signatured_types {};
410
411   /* Type unit statistics, to see how well the scaling improvements
412      are doing.  */
413   struct tu_stats tu_stats {};
414
415   /* A chain of compilation units that are currently read in, so that
416      they can be freed later.  */
417   dwarf2_per_cu_data *read_in_chain = NULL;
418
419   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
420      This is NULL if the table hasn't been allocated yet.  */
421   htab_t dwo_files {};
422
423   /* True if we've checked for whether there is a DWP file.  */
424   bool dwp_checked = false;
425
426   /* The DWP file if there is one, or NULL.  */
427   struct dwp_file *dwp_file = NULL;
428
429   /* The shared '.dwz' file, if one exists.  This is used when the
430      original data was compressed using 'dwz -m'.  */
431   struct dwz_file *dwz_file = NULL;
432
433   /* A flag indicating whether this objfile has a section loaded at a
434      VMA of 0.  */
435   bool has_section_at_zero = false;
436
437   /* True if we are using the mapped index,
438      or we are faking it for OBJF_READNOW's sake.  */
439   bool using_index = false;
440
441   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
442   mapped_index *index_table = NULL;
443
444   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
445   std::unique_ptr<mapped_debug_names> debug_names_table;
446
447   /* When using index_table, this keeps track of all quick_file_names entries.
448      TUs typically share line table entries with a CU, so we maintain a
449      separate table of all line table entries to support the sharing.
450      Note that while there can be way more TUs than CUs, we've already
451      sorted all the TUs into "type unit groups", grouped by their
452      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
453      CU and its associated TU group if there is one.  */
454   htab_t quick_file_names_table {};
455
456   /* Set during partial symbol reading, to prevent queueing of full
457      symbols.  */
458   bool reading_partial_symbols = false;
459
460   /* Table mapping type DIEs to their struct type *.
461      This is NULL if not allocated yet.
462      The mapping is done via (CU/TU + DIE offset) -> type.  */
463   htab_t die_type_hash {};
464
465   /* The CUs we recently read.  */
466   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
467
468   /* Table containing line_header indexed by offset and offset_in_dwz.  */
469   htab_t line_header_hash {};
470
471   /* Table containing all filenames.  This is an optional because the
472      table is lazily constructed on first access.  */
473   gdb::optional<filename_seen_cache> filenames_cache;
474 };
475
476 static struct dwarf2_per_objfile *dwarf2_per_objfile;
477
478 /* Default names of the debugging sections.  */
479
480 /* Note that if the debugging section has been compressed, it might
481    have a name like .zdebug_info.  */
482
483 static const struct dwarf2_debug_sections dwarf2_elf_names =
484 {
485   { ".debug_info", ".zdebug_info" },
486   { ".debug_abbrev", ".zdebug_abbrev" },
487   { ".debug_line", ".zdebug_line" },
488   { ".debug_loc", ".zdebug_loc" },
489   { ".debug_loclists", ".zdebug_loclists" },
490   { ".debug_macinfo", ".zdebug_macinfo" },
491   { ".debug_macro", ".zdebug_macro" },
492   { ".debug_str", ".zdebug_str" },
493   { ".debug_line_str", ".zdebug_line_str" },
494   { ".debug_ranges", ".zdebug_ranges" },
495   { ".debug_rnglists", ".zdebug_rnglists" },
496   { ".debug_types", ".zdebug_types" },
497   { ".debug_addr", ".zdebug_addr" },
498   { ".debug_frame", ".zdebug_frame" },
499   { ".eh_frame", NULL },
500   { ".gdb_index", ".zgdb_index" },
501   { ".debug_names", ".zdebug_names" },
502   { ".debug_aranges", ".zdebug_aranges" },
503   23
504 };
505
506 /* List of DWO/DWP sections.  */
507
508 static const struct dwop_section_names
509 {
510   struct dwarf2_section_names abbrev_dwo;
511   struct dwarf2_section_names info_dwo;
512   struct dwarf2_section_names line_dwo;
513   struct dwarf2_section_names loc_dwo;
514   struct dwarf2_section_names loclists_dwo;
515   struct dwarf2_section_names macinfo_dwo;
516   struct dwarf2_section_names macro_dwo;
517   struct dwarf2_section_names str_dwo;
518   struct dwarf2_section_names str_offsets_dwo;
519   struct dwarf2_section_names types_dwo;
520   struct dwarf2_section_names cu_index;
521   struct dwarf2_section_names tu_index;
522 }
523 dwop_section_names =
524 {
525   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
526   { ".debug_info.dwo", ".zdebug_info.dwo" },
527   { ".debug_line.dwo", ".zdebug_line.dwo" },
528   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
529   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
530   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
531   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
532   { ".debug_str.dwo", ".zdebug_str.dwo" },
533   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
534   { ".debug_types.dwo", ".zdebug_types.dwo" },
535   { ".debug_cu_index", ".zdebug_cu_index" },
536   { ".debug_tu_index", ".zdebug_tu_index" },
537 };
538
539 /* local data types */
540
541 /* The data in a compilation unit header, after target2host
542    translation, looks like this.  */
543 struct comp_unit_head
544 {
545   unsigned int length;
546   short version;
547   unsigned char addr_size;
548   unsigned char signed_addr_p;
549   sect_offset abbrev_sect_off;
550
551   /* Size of file offsets; either 4 or 8.  */
552   unsigned int offset_size;
553
554   /* Size of the length field; either 4 or 12.  */
555   unsigned int initial_length_size;
556
557   enum dwarf_unit_type unit_type;
558
559   /* Offset to the first byte of this compilation unit header in the
560      .debug_info section, for resolving relative reference dies.  */
561   sect_offset sect_off;
562
563   /* Offset to first die in this cu from the start of the cu.
564      This will be the first byte following the compilation unit header.  */
565   cu_offset first_die_cu_offset;
566
567   /* 64-bit signature of this type unit - it is valid only for
568      UNIT_TYPE DW_UT_type.  */
569   ULONGEST signature;
570
571   /* For types, offset in the type's DIE of the type defined by this TU.  */
572   cu_offset type_cu_offset_in_tu;
573 };
574
575 /* Type used for delaying computation of method physnames.
576    See comments for compute_delayed_physnames.  */
577 struct delayed_method_info
578 {
579   /* The type to which the method is attached, i.e., its parent class.  */
580   struct type *type;
581
582   /* The index of the method in the type's function fieldlists.  */
583   int fnfield_index;
584
585   /* The index of the method in the fieldlist.  */
586   int index;
587
588   /* The name of the DIE.  */
589   const char *name;
590
591   /*  The DIE associated with this method.  */
592   struct die_info *die;
593 };
594
595 typedef struct delayed_method_info delayed_method_info;
596 DEF_VEC_O (delayed_method_info);
597
598 /* Internal state when decoding a particular compilation unit.  */
599 struct dwarf2_cu
600 {
601   /* The objfile containing this compilation unit.  */
602   struct objfile *objfile;
603
604   /* The header of the compilation unit.  */
605   struct comp_unit_head header;
606
607   /* Base address of this compilation unit.  */
608   CORE_ADDR base_address;
609
610   /* Non-zero if base_address has been set.  */
611   int base_known;
612
613   /* The language we are debugging.  */
614   enum language language;
615   const struct language_defn *language_defn;
616
617   const char *producer;
618
619   /* The generic symbol table building routines have separate lists for
620      file scope symbols and all all other scopes (local scopes).  So
621      we need to select the right one to pass to add_symbol_to_list().
622      We do it by keeping a pointer to the correct list in list_in_scope.
623
624      FIXME: The original dwarf code just treated the file scope as the
625      first local scope, and all other local scopes as nested local
626      scopes, and worked fine.  Check to see if we really need to
627      distinguish these in buildsym.c.  */
628   struct pending **list_in_scope;
629
630   /* The abbrev table for this CU.
631      Normally this points to the abbrev table in the objfile.
632      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
633   struct abbrev_table *abbrev_table;
634
635   /* Hash table holding all the loaded partial DIEs
636      with partial_die->offset.SECT_OFF as hash.  */
637   htab_t partial_dies;
638
639   /* Storage for things with the same lifetime as this read-in compilation
640      unit, including partial DIEs.  */
641   struct obstack comp_unit_obstack;
642
643   /* When multiple dwarf2_cu structures are living in memory, this field
644      chains them all together, so that they can be released efficiently.
645      We will probably also want a generation counter so that most-recently-used
646      compilation units are cached...  */
647   struct dwarf2_per_cu_data *read_in_chain;
648
649   /* Backlink to our per_cu entry.  */
650   struct dwarf2_per_cu_data *per_cu;
651
652   /* How many compilation units ago was this CU last referenced?  */
653   int last_used;
654
655   /* A hash table of DIE cu_offset for following references with
656      die_info->offset.sect_off as hash.  */
657   htab_t die_hash;
658
659   /* Full DIEs if read in.  */
660   struct die_info *dies;
661
662   /* A set of pointers to dwarf2_per_cu_data objects for compilation
663      units referenced by this one.  Only set during full symbol processing;
664      partial symbol tables do not have dependencies.  */
665   htab_t dependencies;
666
667   /* Header data from the line table, during full symbol processing.  */
668   struct line_header *line_header;
669   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
670      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
671      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
672      to the line header as long as this DIE is being processed.  See
673      process_die_scope.  */
674   die_info *line_header_die_owner;
675
676   /* A list of methods which need to have physnames computed
677      after all type information has been read.  */
678   VEC (delayed_method_info) *method_list;
679
680   /* To be copied to symtab->call_site_htab.  */
681   htab_t call_site_htab;
682
683   /* Non-NULL if this CU came from a DWO file.
684      There is an invariant here that is important to remember:
685      Except for attributes copied from the top level DIE in the "main"
686      (or "stub") file in preparation for reading the DWO file
687      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
688      Either there isn't a DWO file (in which case this is NULL and the point
689      is moot), or there is and either we're not going to read it (in which
690      case this is NULL) or there is and we are reading it (in which case this
691      is non-NULL).  */
692   struct dwo_unit *dwo_unit;
693
694   /* The DW_AT_addr_base attribute if present, zero otherwise
695      (zero is a valid value though).
696      Note this value comes from the Fission stub CU/TU's DIE.  */
697   ULONGEST addr_base;
698
699   /* The DW_AT_ranges_base attribute if present, zero otherwise
700      (zero is a valid value though).
701      Note this value comes from the Fission stub CU/TU's DIE.
702      Also note that the value is zero in the non-DWO case so this value can
703      be used without needing to know whether DWO files are in use or not.
704      N.B. This does not apply to DW_AT_ranges appearing in
705      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
706      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
707      DW_AT_ranges_base *would* have to be applied, and we'd have to care
708      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
709   ULONGEST ranges_base;
710
711   /* Mark used when releasing cached dies.  */
712   unsigned int mark : 1;
713
714   /* This CU references .debug_loc.  See the symtab->locations_valid field.
715      This test is imperfect as there may exist optimized debug code not using
716      any location list and still facing inlining issues if handled as
717      unoptimized code.  For a future better test see GCC PR other/32998.  */
718   unsigned int has_loclist : 1;
719
720   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
721      if all the producer_is_* fields are valid.  This information is cached
722      because profiling CU expansion showed excessive time spent in
723      producer_is_gxx_lt_4_6.  */
724   unsigned int checked_producer : 1;
725   unsigned int producer_is_gxx_lt_4_6 : 1;
726   unsigned int producer_is_gcc_lt_4_3 : 1;
727   unsigned int producer_is_icc_lt_14 : 1;
728
729   /* When set, the file that we're processing is known to have
730      debugging info for C++ namespaces.  GCC 3.3.x did not produce
731      this information, but later versions do.  */
732
733   unsigned int processing_has_namespace_info : 1;
734 };
735
736 /* Persistent data held for a compilation unit, even when not
737    processing it.  We put a pointer to this structure in the
738    read_symtab_private field of the psymtab.  */
739
740 struct dwarf2_per_cu_data
741 {
742   /* The start offset and length of this compilation unit.
743      NOTE: Unlike comp_unit_head.length, this length includes
744      initial_length_size.
745      If the DIE refers to a DWO file, this is always of the original die,
746      not the DWO file.  */
747   sect_offset sect_off;
748   unsigned int length;
749
750   /* DWARF standard version this data has been read from (such as 4 or 5).  */
751   short dwarf_version;
752
753   /* Flag indicating this compilation unit will be read in before
754      any of the current compilation units are processed.  */
755   unsigned int queued : 1;
756
757   /* This flag will be set when reading partial DIEs if we need to load
758      absolutely all DIEs for this compilation unit, instead of just the ones
759      we think are interesting.  It gets set if we look for a DIE in the
760      hash table and don't find it.  */
761   unsigned int load_all_dies : 1;
762
763   /* Non-zero if this CU is from .debug_types.
764      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
765      this is non-zero.  */
766   unsigned int is_debug_types : 1;
767
768   /* Non-zero if this CU is from the .dwz file.  */
769   unsigned int is_dwz : 1;
770
771   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
772      This flag is only valid if is_debug_types is true.
773      We can't read a CU directly from a DWO file: There are required
774      attributes in the stub.  */
775   unsigned int reading_dwo_directly : 1;
776
777   /* Non-zero if the TU has been read.
778      This is used to assist the "Stay in DWO Optimization" for Fission:
779      When reading a DWO, it's faster to read TUs from the DWO instead of
780      fetching them from random other DWOs (due to comdat folding).
781      If the TU has already been read, the optimization is unnecessary
782      (and unwise - we don't want to change where gdb thinks the TU lives
783      "midflight").
784      This flag is only valid if is_debug_types is true.  */
785   unsigned int tu_read : 1;
786
787   /* The section this CU/TU lives in.
788      If the DIE refers to a DWO file, this is always the original die,
789      not the DWO file.  */
790   struct dwarf2_section_info *section;
791
792   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
793      of the CU cache it gets reset to NULL again.  This is left as NULL for
794      dummy CUs (a CU header, but nothing else).  */
795   struct dwarf2_cu *cu;
796
797   /* The corresponding objfile.
798      Normally we can get the objfile from dwarf2_per_objfile.
799      However we can enter this file with just a "per_cu" handle.  */
800   struct objfile *objfile;
801
802   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
803      is active.  Otherwise, the 'psymtab' field is active.  */
804   union
805   {
806     /* The partial symbol table associated with this compilation unit,
807        or NULL for unread partial units.  */
808     struct partial_symtab *psymtab;
809
810     /* Data needed by the "quick" functions.  */
811     struct dwarf2_per_cu_quick_data *quick;
812   } v;
813
814   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
815      while reading psymtabs, used to compute the psymtab dependencies,
816      and then cleared.  Then it is filled in again while reading full
817      symbols, and only deleted when the objfile is destroyed.
818
819      This is also used to work around a difference between the way gold
820      generates .gdb_index version <=7 and the way gdb does.  Arguably this
821      is a gold bug.  For symbols coming from TUs, gold records in the index
822      the CU that includes the TU instead of the TU itself.  This breaks
823      dw2_lookup_symbol: It assumes that if the index says symbol X lives
824      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
825      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
826      we need to look in TU Z to find X.  Fortunately, this is akin to
827      DW_TAG_imported_unit, so we just use the same mechanism: For
828      .gdb_index version <=7 this also records the TUs that the CU referred
829      to.  Concurrently with this change gdb was modified to emit version 8
830      indices so we only pay a price for gold generated indices.
831      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
832   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
833 };
834
835 /* Entry in the signatured_types hash table.  */
836
837 struct signatured_type
838 {
839   /* The "per_cu" object of this type.
840      This struct is used iff per_cu.is_debug_types.
841      N.B.: This is the first member so that it's easy to convert pointers
842      between them.  */
843   struct dwarf2_per_cu_data per_cu;
844
845   /* The type's signature.  */
846   ULONGEST signature;
847
848   /* Offset in the TU of the type's DIE, as read from the TU header.
849      If this TU is a DWO stub and the definition lives in a DWO file
850      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
851   cu_offset type_offset_in_tu;
852
853   /* Offset in the section of the type's DIE.
854      If the definition lives in a DWO file, this is the offset in the
855      .debug_types.dwo section.
856      The value is zero until the actual value is known.
857      Zero is otherwise not a valid section offset.  */
858   sect_offset type_offset_in_section;
859
860   /* Type units are grouped by their DW_AT_stmt_list entry so that they
861      can share them.  This points to the containing symtab.  */
862   struct type_unit_group *type_unit_group;
863
864   /* The type.
865      The first time we encounter this type we fully read it in and install it
866      in the symbol tables.  Subsequent times we only need the type.  */
867   struct type *type;
868
869   /* Containing DWO unit.
870      This field is valid iff per_cu.reading_dwo_directly.  */
871   struct dwo_unit *dwo_unit;
872 };
873
874 typedef struct signatured_type *sig_type_ptr;
875 DEF_VEC_P (sig_type_ptr);
876
877 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
878    This includes type_unit_group and quick_file_names.  */
879
880 struct stmt_list_hash
881 {
882   /* The DWO unit this table is from or NULL if there is none.  */
883   struct dwo_unit *dwo_unit;
884
885   /* Offset in .debug_line or .debug_line.dwo.  */
886   sect_offset line_sect_off;
887 };
888
889 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
890    an object of this type.  */
891
892 struct type_unit_group
893 {
894   /* dwarf2read.c's main "handle" on a TU symtab.
895      To simplify things we create an artificial CU that "includes" all the
896      type units using this stmt_list so that the rest of the code still has
897      a "per_cu" handle on the symtab.
898      This PER_CU is recognized by having no section.  */
899 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
900   struct dwarf2_per_cu_data per_cu;
901
902   /* The TUs that share this DW_AT_stmt_list entry.
903      This is added to while parsing type units to build partial symtabs,
904      and is deleted afterwards and not used again.  */
905   VEC (sig_type_ptr) *tus;
906
907   /* The compunit symtab.
908      Type units in a group needn't all be defined in the same source file,
909      so we create an essentially anonymous symtab as the compunit symtab.  */
910   struct compunit_symtab *compunit_symtab;
911
912   /* The data used to construct the hash key.  */
913   struct stmt_list_hash hash;
914
915   /* The number of symtabs from the line header.
916      The value here must match line_header.num_file_names.  */
917   unsigned int num_symtabs;
918
919   /* The symbol tables for this TU (obtained from the files listed in
920      DW_AT_stmt_list).
921      WARNING: The order of entries here must match the order of entries
922      in the line header.  After the first TU using this type_unit_group, the
923      line header for the subsequent TUs is recreated from this.  This is done
924      because we need to use the same symtabs for each TU using the same
925      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
926      there's no guarantee the line header doesn't have duplicate entries.  */
927   struct symtab **symtabs;
928 };
929
930 /* These sections are what may appear in a (real or virtual) DWO file.  */
931
932 struct dwo_sections
933 {
934   struct dwarf2_section_info abbrev;
935   struct dwarf2_section_info line;
936   struct dwarf2_section_info loc;
937   struct dwarf2_section_info loclists;
938   struct dwarf2_section_info macinfo;
939   struct dwarf2_section_info macro;
940   struct dwarf2_section_info str;
941   struct dwarf2_section_info str_offsets;
942   /* In the case of a virtual DWO file, these two are unused.  */
943   struct dwarf2_section_info info;
944   VEC (dwarf2_section_info_def) *types;
945 };
946
947 /* CUs/TUs in DWP/DWO files.  */
948
949 struct dwo_unit
950 {
951   /* Backlink to the containing struct dwo_file.  */
952   struct dwo_file *dwo_file;
953
954   /* The "id" that distinguishes this CU/TU.
955      .debug_info calls this "dwo_id", .debug_types calls this "signature".
956      Since signatures came first, we stick with it for consistency.  */
957   ULONGEST signature;
958
959   /* The section this CU/TU lives in, in the DWO file.  */
960   struct dwarf2_section_info *section;
961
962   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
963   sect_offset sect_off;
964   unsigned int length;
965
966   /* For types, offset in the type's DIE of the type defined by this TU.  */
967   cu_offset type_offset_in_tu;
968 };
969
970 /* include/dwarf2.h defines the DWP section codes.
971    It defines a max value but it doesn't define a min value, which we
972    use for error checking, so provide one.  */
973
974 enum dwp_v2_section_ids
975 {
976   DW_SECT_MIN = 1
977 };
978
979 /* Data for one DWO file.
980
981    This includes virtual DWO files (a virtual DWO file is a DWO file as it
982    appears in a DWP file).  DWP files don't really have DWO files per se -
983    comdat folding of types "loses" the DWO file they came from, and from
984    a high level view DWP files appear to contain a mass of random types.
985    However, to maintain consistency with the non-DWP case we pretend DWP
986    files contain virtual DWO files, and we assign each TU with one virtual
987    DWO file (generally based on the line and abbrev section offsets -
988    a heuristic that seems to work in practice).  */
989
990 struct dwo_file
991 {
992   /* The DW_AT_GNU_dwo_name attribute.
993      For virtual DWO files the name is constructed from the section offsets
994      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
995      from related CU+TUs.  */
996   const char *dwo_name;
997
998   /* The DW_AT_comp_dir attribute.  */
999   const char *comp_dir;
1000
1001   /* The bfd, when the file is open.  Otherwise this is NULL.
1002      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1003   bfd *dbfd;
1004
1005   /* The sections that make up this DWO file.
1006      Remember that for virtual DWO files in DWP V2, these are virtual
1007      sections (for lack of a better name).  */
1008   struct dwo_sections sections;
1009
1010   /* The CUs in the file.
1011      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1012      an extension to handle LLVM's Link Time Optimization output (where
1013      multiple source files may be compiled into a single object/dwo pair). */
1014   htab_t cus;
1015
1016   /* Table of TUs in the file.
1017      Each element is a struct dwo_unit.  */
1018   htab_t tus;
1019 };
1020
1021 /* These sections are what may appear in a DWP file.  */
1022
1023 struct dwp_sections
1024 {
1025   /* These are used by both DWP version 1 and 2.  */
1026   struct dwarf2_section_info str;
1027   struct dwarf2_section_info cu_index;
1028   struct dwarf2_section_info tu_index;
1029
1030   /* These are only used by DWP version 2 files.
1031      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1032      sections are referenced by section number, and are not recorded here.
1033      In DWP version 2 there is at most one copy of all these sections, each
1034      section being (effectively) comprised of the concatenation of all of the
1035      individual sections that exist in the version 1 format.
1036      To keep the code simple we treat each of these concatenated pieces as a
1037      section itself (a virtual section?).  */
1038   struct dwarf2_section_info abbrev;
1039   struct dwarf2_section_info info;
1040   struct dwarf2_section_info line;
1041   struct dwarf2_section_info loc;
1042   struct dwarf2_section_info macinfo;
1043   struct dwarf2_section_info macro;
1044   struct dwarf2_section_info str_offsets;
1045   struct dwarf2_section_info types;
1046 };
1047
1048 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1049    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1050
1051 struct virtual_v1_dwo_sections
1052 {
1053   struct dwarf2_section_info abbrev;
1054   struct dwarf2_section_info line;
1055   struct dwarf2_section_info loc;
1056   struct dwarf2_section_info macinfo;
1057   struct dwarf2_section_info macro;
1058   struct dwarf2_section_info str_offsets;
1059   /* Each DWP hash table entry records one CU or one TU.
1060      That is recorded here, and copied to dwo_unit.section.  */
1061   struct dwarf2_section_info info_or_types;
1062 };
1063
1064 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1065    In version 2, the sections of the DWO files are concatenated together
1066    and stored in one section of that name.  Thus each ELF section contains
1067    several "virtual" sections.  */
1068
1069 struct virtual_v2_dwo_sections
1070 {
1071   bfd_size_type abbrev_offset;
1072   bfd_size_type abbrev_size;
1073
1074   bfd_size_type line_offset;
1075   bfd_size_type line_size;
1076
1077   bfd_size_type loc_offset;
1078   bfd_size_type loc_size;
1079
1080   bfd_size_type macinfo_offset;
1081   bfd_size_type macinfo_size;
1082
1083   bfd_size_type macro_offset;
1084   bfd_size_type macro_size;
1085
1086   bfd_size_type str_offsets_offset;
1087   bfd_size_type str_offsets_size;
1088
1089   /* Each DWP hash table entry records one CU or one TU.
1090      That is recorded here, and copied to dwo_unit.section.  */
1091   bfd_size_type info_or_types_offset;
1092   bfd_size_type info_or_types_size;
1093 };
1094
1095 /* Contents of DWP hash tables.  */
1096
1097 struct dwp_hash_table
1098 {
1099   uint32_t version, nr_columns;
1100   uint32_t nr_units, nr_slots;
1101   const gdb_byte *hash_table, *unit_table;
1102   union
1103   {
1104     struct
1105     {
1106       const gdb_byte *indices;
1107     } v1;
1108     struct
1109     {
1110       /* This is indexed by column number and gives the id of the section
1111          in that column.  */
1112 #define MAX_NR_V2_DWO_SECTIONS \
1113   (1 /* .debug_info or .debug_types */ \
1114    + 1 /* .debug_abbrev */ \
1115    + 1 /* .debug_line */ \
1116    + 1 /* .debug_loc */ \
1117    + 1 /* .debug_str_offsets */ \
1118    + 1 /* .debug_macro or .debug_macinfo */)
1119       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1120       const gdb_byte *offsets;
1121       const gdb_byte *sizes;
1122     } v2;
1123   } section_pool;
1124 };
1125
1126 /* Data for one DWP file.  */
1127
1128 struct dwp_file
1129 {
1130   /* Name of the file.  */
1131   const char *name;
1132
1133   /* File format version.  */
1134   int version;
1135
1136   /* The bfd.  */
1137   bfd *dbfd;
1138
1139   /* Section info for this file.  */
1140   struct dwp_sections sections;
1141
1142   /* Table of CUs in the file.  */
1143   const struct dwp_hash_table *cus;
1144
1145   /* Table of TUs in the file.  */
1146   const struct dwp_hash_table *tus;
1147
1148   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1149   htab_t loaded_cus;
1150   htab_t loaded_tus;
1151
1152   /* Table to map ELF section numbers to their sections.
1153      This is only needed for the DWP V1 file format.  */
1154   unsigned int num_sections;
1155   asection **elf_sections;
1156 };
1157
1158 /* This represents a '.dwz' file.  */
1159
1160 struct dwz_file
1161 {
1162   /* A dwz file can only contain a few sections.  */
1163   struct dwarf2_section_info abbrev;
1164   struct dwarf2_section_info info;
1165   struct dwarf2_section_info str;
1166   struct dwarf2_section_info line;
1167   struct dwarf2_section_info macro;
1168   struct dwarf2_section_info gdb_index;
1169   struct dwarf2_section_info debug_names;
1170
1171   /* The dwz's BFD.  */
1172   bfd *dwz_bfd;
1173 };
1174
1175 /* Struct used to pass misc. parameters to read_die_and_children, et
1176    al.  which are used for both .debug_info and .debug_types dies.
1177    All parameters here are unchanging for the life of the call.  This
1178    struct exists to abstract away the constant parameters of die reading.  */
1179
1180 struct die_reader_specs
1181 {
1182   /* The bfd of die_section.  */
1183   bfd* abfd;
1184
1185   /* The CU of the DIE we are parsing.  */
1186   struct dwarf2_cu *cu;
1187
1188   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1189   struct dwo_file *dwo_file;
1190
1191   /* The section the die comes from.
1192      This is either .debug_info or .debug_types, or the .dwo variants.  */
1193   struct dwarf2_section_info *die_section;
1194
1195   /* die_section->buffer.  */
1196   const gdb_byte *buffer;
1197
1198   /* The end of the buffer.  */
1199   const gdb_byte *buffer_end;
1200
1201   /* The value of the DW_AT_comp_dir attribute.  */
1202   const char *comp_dir;
1203 };
1204
1205 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1206 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1207                                       const gdb_byte *info_ptr,
1208                                       struct die_info *comp_unit_die,
1209                                       int has_children,
1210                                       void *data);
1211
1212 /* A 1-based directory index.  This is a strong typedef to prevent
1213    accidentally using a directory index as a 0-based index into an
1214    array/vector.  */
1215 enum class dir_index : unsigned int {};
1216
1217 /* Likewise, a 1-based file name index.  */
1218 enum class file_name_index : unsigned int {};
1219
1220 struct file_entry
1221 {
1222   file_entry () = default;
1223
1224   file_entry (const char *name_, dir_index d_index_,
1225               unsigned int mod_time_, unsigned int length_)
1226     : name (name_),
1227       d_index (d_index_),
1228       mod_time (mod_time_),
1229       length (length_)
1230   {}
1231
1232   /* Return the include directory at D_INDEX stored in LH.  Returns
1233      NULL if D_INDEX is out of bounds.  */
1234   const char *include_dir (const line_header *lh) const;
1235
1236   /* The file name.  Note this is an observing pointer.  The memory is
1237      owned by debug_line_buffer.  */
1238   const char *name {};
1239
1240   /* The directory index (1-based).  */
1241   dir_index d_index {};
1242
1243   unsigned int mod_time {};
1244
1245   unsigned int length {};
1246
1247   /* True if referenced by the Line Number Program.  */
1248   bool included_p {};
1249
1250   /* The associated symbol table, if any.  */
1251   struct symtab *symtab {};
1252 };
1253
1254 /* The line number information for a compilation unit (found in the
1255    .debug_line section) begins with a "statement program header",
1256    which contains the following information.  */
1257 struct line_header
1258 {
1259   line_header ()
1260     : offset_in_dwz {}
1261   {}
1262
1263   /* Add an entry to the include directory table.  */
1264   void add_include_dir (const char *include_dir);
1265
1266   /* Add an entry to the file name table.  */
1267   void add_file_name (const char *name, dir_index d_index,
1268                       unsigned int mod_time, unsigned int length);
1269
1270   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1271      is out of bounds.  */
1272   const char *include_dir_at (dir_index index) const
1273   {
1274     /* Convert directory index number (1-based) to vector index
1275        (0-based).  */
1276     size_t vec_index = to_underlying (index) - 1;
1277
1278     if (vec_index >= include_dirs.size ())
1279       return NULL;
1280     return include_dirs[vec_index];
1281   }
1282
1283   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1284      is out of bounds.  */
1285   file_entry *file_name_at (file_name_index index)
1286   {
1287     /* Convert file name index number (1-based) to vector index
1288        (0-based).  */
1289     size_t vec_index = to_underlying (index) - 1;
1290
1291     if (vec_index >= file_names.size ())
1292       return NULL;
1293     return &file_names[vec_index];
1294   }
1295
1296   /* Const version of the above.  */
1297   const file_entry *file_name_at (unsigned int index) const
1298   {
1299     if (index >= file_names.size ())
1300       return NULL;
1301     return &file_names[index];
1302   }
1303
1304   /* Offset of line number information in .debug_line section.  */
1305   sect_offset sect_off {};
1306
1307   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1308   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1309
1310   unsigned int total_length {};
1311   unsigned short version {};
1312   unsigned int header_length {};
1313   unsigned char minimum_instruction_length {};
1314   unsigned char maximum_ops_per_instruction {};
1315   unsigned char default_is_stmt {};
1316   int line_base {};
1317   unsigned char line_range {};
1318   unsigned char opcode_base {};
1319
1320   /* standard_opcode_lengths[i] is the number of operands for the
1321      standard opcode whose value is i.  This means that
1322      standard_opcode_lengths[0] is unused, and the last meaningful
1323      element is standard_opcode_lengths[opcode_base - 1].  */
1324   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1325
1326   /* The include_directories table.  Note these are observing
1327      pointers.  The memory is owned by debug_line_buffer.  */
1328   std::vector<const char *> include_dirs;
1329
1330   /* The file_names table.  */
1331   std::vector<file_entry> file_names;
1332
1333   /* The start and end of the statement program following this
1334      header.  These point into dwarf2_per_objfile->line_buffer.  */
1335   const gdb_byte *statement_program_start {}, *statement_program_end {};
1336 };
1337
1338 typedef std::unique_ptr<line_header> line_header_up;
1339
1340 const char *
1341 file_entry::include_dir (const line_header *lh) const
1342 {
1343   return lh->include_dir_at (d_index);
1344 }
1345
1346 /* When we construct a partial symbol table entry we only
1347    need this much information.  */
1348 struct partial_die_info
1349   {
1350     /* Offset of this DIE.  */
1351     sect_offset sect_off;
1352
1353     /* DWARF-2 tag for this DIE.  */
1354     ENUM_BITFIELD(dwarf_tag) tag : 16;
1355
1356     /* Assorted flags describing the data found in this DIE.  */
1357     unsigned int has_children : 1;
1358     unsigned int is_external : 1;
1359     unsigned int is_declaration : 1;
1360     unsigned int has_type : 1;
1361     unsigned int has_specification : 1;
1362     unsigned int has_pc_info : 1;
1363     unsigned int may_be_inlined : 1;
1364
1365     /* This DIE has been marked DW_AT_main_subprogram.  */
1366     unsigned int main_subprogram : 1;
1367
1368     /* Flag set if the SCOPE field of this structure has been
1369        computed.  */
1370     unsigned int scope_set : 1;
1371
1372     /* Flag set if the DIE has a byte_size attribute.  */
1373     unsigned int has_byte_size : 1;
1374
1375     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1376     unsigned int has_const_value : 1;
1377
1378     /* Flag set if any of the DIE's children are template arguments.  */
1379     unsigned int has_template_arguments : 1;
1380
1381     /* Flag set if fixup_partial_die has been called on this die.  */
1382     unsigned int fixup_called : 1;
1383
1384     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1385     unsigned int is_dwz : 1;
1386
1387     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1388     unsigned int spec_is_dwz : 1;
1389
1390     /* The name of this DIE.  Normally the value of DW_AT_name, but
1391        sometimes a default name for unnamed DIEs.  */
1392     const char *name;
1393
1394     /* The linkage name, if present.  */
1395     const char *linkage_name;
1396
1397     /* The scope to prepend to our children.  This is generally
1398        allocated on the comp_unit_obstack, so will disappear
1399        when this compilation unit leaves the cache.  */
1400     const char *scope;
1401
1402     /* Some data associated with the partial DIE.  The tag determines
1403        which field is live.  */
1404     union
1405     {
1406       /* The location description associated with this DIE, if any.  */
1407       struct dwarf_block *locdesc;
1408       /* The offset of an import, for DW_TAG_imported_unit.  */
1409       sect_offset sect_off;
1410     } d;
1411
1412     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1413     CORE_ADDR lowpc;
1414     CORE_ADDR highpc;
1415
1416     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1417        DW_AT_sibling, if any.  */
1418     /* NOTE: This member isn't strictly necessary, read_partial_die could
1419        return DW_AT_sibling values to its caller load_partial_dies.  */
1420     const gdb_byte *sibling;
1421
1422     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1423        DW_AT_specification (or DW_AT_abstract_origin or
1424        DW_AT_extension).  */
1425     sect_offset spec_offset;
1426
1427     /* Pointers to this DIE's parent, first child, and next sibling,
1428        if any.  */
1429     struct partial_die_info *die_parent, *die_child, *die_sibling;
1430   };
1431
1432 /* This data structure holds the information of an abbrev.  */
1433 struct abbrev_info
1434   {
1435     unsigned int number;        /* number identifying abbrev */
1436     enum dwarf_tag tag;         /* dwarf tag */
1437     unsigned short has_children;                /* boolean */
1438     unsigned short num_attrs;   /* number of attributes */
1439     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1440     struct abbrev_info *next;   /* next in chain */
1441   };
1442
1443 struct attr_abbrev
1444   {
1445     ENUM_BITFIELD(dwarf_attribute) name : 16;
1446     ENUM_BITFIELD(dwarf_form) form : 16;
1447
1448     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1449     LONGEST implicit_const;
1450   };
1451
1452 /* Size of abbrev_table.abbrev_hash_table.  */
1453 #define ABBREV_HASH_SIZE 121
1454
1455 /* Top level data structure to contain an abbreviation table.  */
1456
1457 struct abbrev_table
1458 {
1459   /* Where the abbrev table came from.
1460      This is used as a sanity check when the table is used.  */
1461   sect_offset sect_off;
1462
1463   /* Storage for the abbrev table.  */
1464   struct obstack abbrev_obstack;
1465
1466   /* Hash table of abbrevs.
1467      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1468      It could be statically allocated, but the previous code didn't so we
1469      don't either.  */
1470   struct abbrev_info **abbrevs;
1471 };
1472
1473 /* Attributes have a name and a value.  */
1474 struct attribute
1475   {
1476     ENUM_BITFIELD(dwarf_attribute) name : 16;
1477     ENUM_BITFIELD(dwarf_form) form : 15;
1478
1479     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1480        field should be in u.str (existing only for DW_STRING) but it is kept
1481        here for better struct attribute alignment.  */
1482     unsigned int string_is_canonical : 1;
1483
1484     union
1485       {
1486         const char *str;
1487         struct dwarf_block *blk;
1488         ULONGEST unsnd;
1489         LONGEST snd;
1490         CORE_ADDR addr;
1491         ULONGEST signature;
1492       }
1493     u;
1494   };
1495
1496 /* This data structure holds a complete die structure.  */
1497 struct die_info
1498   {
1499     /* DWARF-2 tag for this DIE.  */
1500     ENUM_BITFIELD(dwarf_tag) tag : 16;
1501
1502     /* Number of attributes */
1503     unsigned char num_attrs;
1504
1505     /* True if we're presently building the full type name for the
1506        type derived from this DIE.  */
1507     unsigned char building_fullname : 1;
1508
1509     /* True if this die is in process.  PR 16581.  */
1510     unsigned char in_process : 1;
1511
1512     /* Abbrev number */
1513     unsigned int abbrev;
1514
1515     /* Offset in .debug_info or .debug_types section.  */
1516     sect_offset sect_off;
1517
1518     /* The dies in a compilation unit form an n-ary tree.  PARENT
1519        points to this die's parent; CHILD points to the first child of
1520        this node; and all the children of a given node are chained
1521        together via their SIBLING fields.  */
1522     struct die_info *child;     /* Its first child, if any.  */
1523     struct die_info *sibling;   /* Its next sibling, if any.  */
1524     struct die_info *parent;    /* Its parent, if any.  */
1525
1526     /* An array of attributes, with NUM_ATTRS elements.  There may be
1527        zero, but it's not common and zero-sized arrays are not
1528        sufficiently portable C.  */
1529     struct attribute attrs[1];
1530   };
1531
1532 /* Get at parts of an attribute structure.  */
1533
1534 #define DW_STRING(attr)    ((attr)->u.str)
1535 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1536 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1537 #define DW_BLOCK(attr)     ((attr)->u.blk)
1538 #define DW_SND(attr)       ((attr)->u.snd)
1539 #define DW_ADDR(attr)      ((attr)->u.addr)
1540 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1541
1542 /* Blocks are a bunch of untyped bytes.  */
1543 struct dwarf_block
1544   {
1545     size_t size;
1546
1547     /* Valid only if SIZE is not zero.  */
1548     const gdb_byte *data;
1549   };
1550
1551 #ifndef ATTR_ALLOC_CHUNK
1552 #define ATTR_ALLOC_CHUNK 4
1553 #endif
1554
1555 /* Allocate fields for structs, unions and enums in this size.  */
1556 #ifndef DW_FIELD_ALLOC_CHUNK
1557 #define DW_FIELD_ALLOC_CHUNK 4
1558 #endif
1559
1560 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1561    but this would require a corresponding change in unpack_field_as_long
1562    and friends.  */
1563 static int bits_per_byte = 8;
1564
1565 struct nextfield
1566 {
1567   struct nextfield *next;
1568   int accessibility;
1569   int virtuality;
1570   struct field field;
1571 };
1572
1573 struct nextfnfield
1574 {
1575   struct nextfnfield *next;
1576   struct fn_field fnfield;
1577 };
1578
1579 struct fnfieldlist
1580 {
1581   const char *name;
1582   int length;
1583   struct nextfnfield *head;
1584 };
1585
1586 struct decl_field_list
1587 {
1588   struct decl_field field;
1589   struct decl_field_list *next;
1590 };
1591
1592 /* The routines that read and process dies for a C struct or C++ class
1593    pass lists of data member fields and lists of member function fields
1594    in an instance of a field_info structure, as defined below.  */
1595 struct field_info
1596   {
1597     /* List of data member and baseclasses fields.  */
1598     struct nextfield *fields, *baseclasses;
1599
1600     /* Number of fields (including baseclasses).  */
1601     int nfields;
1602
1603     /* Number of baseclasses.  */
1604     int nbaseclasses;
1605
1606     /* Set if the accesibility of one of the fields is not public.  */
1607     int non_public_fields;
1608
1609     /* Member function fieldlist array, contains name of possibly overloaded
1610        member function, number of overloaded member functions and a pointer
1611        to the head of the member function field chain.  */
1612     struct fnfieldlist *fnfieldlists;
1613
1614     /* Number of entries in the fnfieldlists array.  */
1615     int nfnfields;
1616
1617     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1618        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1619     struct decl_field_list *typedef_field_list;
1620     unsigned typedef_field_list_count;
1621
1622     /* Nested types defined by this class and the number of elements in this
1623        list.  */
1624     struct decl_field_list *nested_types_list;
1625     unsigned nested_types_list_count;
1626   };
1627
1628 /* One item on the queue of compilation units to read in full symbols
1629    for.  */
1630 struct dwarf2_queue_item
1631 {
1632   struct dwarf2_per_cu_data *per_cu;
1633   enum language pretend_language;
1634   struct dwarf2_queue_item *next;
1635 };
1636
1637 /* The current queue.  */
1638 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1639
1640 /* Loaded secondary compilation units are kept in memory until they
1641    have not been referenced for the processing of this many
1642    compilation units.  Set this to zero to disable caching.  Cache
1643    sizes of up to at least twenty will improve startup time for
1644    typical inter-CU-reference binaries, at an obvious memory cost.  */
1645 static int dwarf_max_cache_age = 5;
1646 static void
1647 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1648                           struct cmd_list_element *c, const char *value)
1649 {
1650   fprintf_filtered (file, _("The upper bound on the age of cached "
1651                             "DWARF compilation units is %s.\n"),
1652                     value);
1653 }
1654 \f
1655 /* local function prototypes */
1656
1657 static const char *get_section_name (const struct dwarf2_section_info *);
1658
1659 static const char *get_section_file_name (const struct dwarf2_section_info *);
1660
1661 static void dwarf2_find_base_address (struct die_info *die,
1662                                       struct dwarf2_cu *cu);
1663
1664 static struct partial_symtab *create_partial_symtab
1665   (struct dwarf2_per_cu_data *per_cu, const char *name);
1666
1667 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1668                                         const gdb_byte *info_ptr,
1669                                         struct die_info *type_unit_die,
1670                                         int has_children, void *data);
1671
1672 static void dwarf2_build_psymtabs_hard (struct objfile *);
1673
1674 static void scan_partial_symbols (struct partial_die_info *,
1675                                   CORE_ADDR *, CORE_ADDR *,
1676                                   int, struct dwarf2_cu *);
1677
1678 static void add_partial_symbol (struct partial_die_info *,
1679                                 struct dwarf2_cu *);
1680
1681 static void add_partial_namespace (struct partial_die_info *pdi,
1682                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1683                                    int set_addrmap, struct dwarf2_cu *cu);
1684
1685 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1686                                 CORE_ADDR *highpc, int set_addrmap,
1687                                 struct dwarf2_cu *cu);
1688
1689 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1690                                      struct dwarf2_cu *cu);
1691
1692 static void add_partial_subprogram (struct partial_die_info *pdi,
1693                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1694                                     int need_pc, struct dwarf2_cu *cu);
1695
1696 static void dwarf2_read_symtab (struct partial_symtab *,
1697                                 struct objfile *);
1698
1699 static void psymtab_to_symtab_1 (struct partial_symtab *);
1700
1701 static struct abbrev_info *abbrev_table_lookup_abbrev
1702   (const struct abbrev_table *, unsigned int);
1703
1704 static struct abbrev_table *abbrev_table_read_table
1705   (struct dwarf2_section_info *, sect_offset);
1706
1707 static void abbrev_table_free (struct abbrev_table *);
1708
1709 static void abbrev_table_free_cleanup (void *);
1710
1711 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1712                                  struct dwarf2_section_info *);
1713
1714 static void dwarf2_free_abbrev_table (void *);
1715
1716 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1717
1718 static struct partial_die_info *load_partial_dies
1719   (const struct die_reader_specs *, const gdb_byte *, int);
1720
1721 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1722                                          struct partial_die_info *,
1723                                          struct abbrev_info *,
1724                                          unsigned int,
1725                                          const gdb_byte *);
1726
1727 static struct partial_die_info *find_partial_die (sect_offset, int,
1728                                                   struct dwarf2_cu *);
1729
1730 static void fixup_partial_die (struct partial_die_info *,
1731                                struct dwarf2_cu *);
1732
1733 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1734                                        struct attribute *, struct attr_abbrev *,
1735                                        const gdb_byte *);
1736
1737 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1738
1739 static int read_1_signed_byte (bfd *, const gdb_byte *);
1740
1741 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1742
1743 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1744
1745 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1746
1747 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1748                                unsigned int *);
1749
1750 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1751
1752 static LONGEST read_checked_initial_length_and_offset
1753   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1754    unsigned int *, unsigned int *);
1755
1756 static LONGEST read_offset (bfd *, const gdb_byte *,
1757                             const struct comp_unit_head *,
1758                             unsigned int *);
1759
1760 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1761
1762 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1763                                        sect_offset);
1764
1765 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1766
1767 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1768
1769 static const char *read_indirect_string (bfd *, const gdb_byte *,
1770                                          const struct comp_unit_head *,
1771                                          unsigned int *);
1772
1773 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1774                                               const struct comp_unit_head *,
1775                                               unsigned int *);
1776
1777 static const char *read_indirect_string_at_offset (bfd *abfd,
1778                                                    LONGEST str_offset);
1779
1780 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1781
1782 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1783
1784 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1785                                               const gdb_byte *,
1786                                               unsigned int *);
1787
1788 static const char *read_str_index (const struct die_reader_specs *reader,
1789                                    ULONGEST str_index);
1790
1791 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1792
1793 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1794                                       struct dwarf2_cu *);
1795
1796 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1797                                                 unsigned int);
1798
1799 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1800                                        struct dwarf2_cu *cu);
1801
1802 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1803                                struct dwarf2_cu *cu);
1804
1805 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1806
1807 static struct die_info *die_specification (struct die_info *die,
1808                                            struct dwarf2_cu **);
1809
1810 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1811                                                 struct dwarf2_cu *cu);
1812
1813 static void dwarf_decode_lines (struct line_header *, const char *,
1814                                 struct dwarf2_cu *, struct partial_symtab *,
1815                                 CORE_ADDR, int decode_mapping);
1816
1817 static void dwarf2_start_subfile (const char *, const char *);
1818
1819 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1820                                                     const char *, const char *,
1821                                                     CORE_ADDR);
1822
1823 static struct symbol *new_symbol (struct die_info *, struct type *,
1824                                   struct dwarf2_cu *);
1825
1826 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1827                                        struct dwarf2_cu *, struct symbol *);
1828
1829 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1830                                 struct dwarf2_cu *);
1831
1832 static void dwarf2_const_value_attr (const struct attribute *attr,
1833                                      struct type *type,
1834                                      const char *name,
1835                                      struct obstack *obstack,
1836                                      struct dwarf2_cu *cu, LONGEST *value,
1837                                      const gdb_byte **bytes,
1838                                      struct dwarf2_locexpr_baton **baton);
1839
1840 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1841
1842 static int need_gnat_info (struct dwarf2_cu *);
1843
1844 static struct type *die_descriptive_type (struct die_info *,
1845                                           struct dwarf2_cu *);
1846
1847 static void set_descriptive_type (struct type *, struct die_info *,
1848                                   struct dwarf2_cu *);
1849
1850 static struct type *die_containing_type (struct die_info *,
1851                                          struct dwarf2_cu *);
1852
1853 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1854                                      struct dwarf2_cu *);
1855
1856 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1857
1858 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1859
1860 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1861
1862 static char *typename_concat (struct obstack *obs, const char *prefix,
1863                               const char *suffix, int physname,
1864                               struct dwarf2_cu *cu);
1865
1866 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1867
1868 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1869
1870 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1871
1872 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1873
1874 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1875
1876 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1877
1878 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1879                                struct dwarf2_cu *, struct partial_symtab *);
1880
1881 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1882    values.  Keep the items ordered with increasing constraints compliance.  */
1883 enum pc_bounds_kind
1884 {
1885   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1886   PC_BOUNDS_NOT_PRESENT,
1887
1888   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1889      were present but they do not form a valid range of PC addresses.  */
1890   PC_BOUNDS_INVALID,
1891
1892   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1893   PC_BOUNDS_RANGES,
1894
1895   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1896   PC_BOUNDS_HIGH_LOW,
1897 };
1898
1899 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1900                                                  CORE_ADDR *, CORE_ADDR *,
1901                                                  struct dwarf2_cu *,
1902                                                  struct partial_symtab *);
1903
1904 static void get_scope_pc_bounds (struct die_info *,
1905                                  CORE_ADDR *, CORE_ADDR *,
1906                                  struct dwarf2_cu *);
1907
1908 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1909                                         CORE_ADDR, struct dwarf2_cu *);
1910
1911 static void dwarf2_add_field (struct field_info *, struct die_info *,
1912                               struct dwarf2_cu *);
1913
1914 static void dwarf2_attach_fields_to_type (struct field_info *,
1915                                           struct type *, struct dwarf2_cu *);
1916
1917 static void dwarf2_add_member_fn (struct field_info *,
1918                                   struct die_info *, struct type *,
1919                                   struct dwarf2_cu *);
1920
1921 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1922                                              struct type *,
1923                                              struct dwarf2_cu *);
1924
1925 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1926
1927 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1928
1929 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1930
1931 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1932
1933 static struct using_direct **using_directives (enum language);
1934
1935 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1936
1937 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1938
1939 static struct type *read_module_type (struct die_info *die,
1940                                       struct dwarf2_cu *cu);
1941
1942 static const char *namespace_name (struct die_info *die,
1943                                    int *is_anonymous, struct dwarf2_cu *);
1944
1945 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1946
1947 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1948
1949 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1950                                                        struct dwarf2_cu *);
1951
1952 static struct die_info *read_die_and_siblings_1
1953   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1954    struct die_info *);
1955
1956 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1957                                                const gdb_byte *info_ptr,
1958                                                const gdb_byte **new_info_ptr,
1959                                                struct die_info *parent);
1960
1961 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1962                                         struct die_info **, const gdb_byte *,
1963                                         int *, int);
1964
1965 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1966                                       struct die_info **, const gdb_byte *,
1967                                       int *);
1968
1969 static void process_die (struct die_info *, struct dwarf2_cu *);
1970
1971 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1972                                              struct obstack *);
1973
1974 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1975
1976 static const char *dwarf2_full_name (const char *name,
1977                                      struct die_info *die,
1978                                      struct dwarf2_cu *cu);
1979
1980 static const char *dwarf2_physname (const char *name, struct die_info *die,
1981                                     struct dwarf2_cu *cu);
1982
1983 static struct die_info *dwarf2_extension (struct die_info *die,
1984                                           struct dwarf2_cu **);
1985
1986 static const char *dwarf_tag_name (unsigned int);
1987
1988 static const char *dwarf_attr_name (unsigned int);
1989
1990 static const char *dwarf_form_name (unsigned int);
1991
1992 static const char *dwarf_bool_name (unsigned int);
1993
1994 static const char *dwarf_type_encoding_name (unsigned int);
1995
1996 static struct die_info *sibling_die (struct die_info *);
1997
1998 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1999
2000 static void dump_die_for_error (struct die_info *);
2001
2002 static void dump_die_1 (struct ui_file *, int level, int max_level,
2003                         struct die_info *);
2004
2005 /*static*/ void dump_die (struct die_info *, int max_level);
2006
2007 static void store_in_ref_table (struct die_info *,
2008                                 struct dwarf2_cu *);
2009
2010 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2011
2012 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2013
2014 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2015                                                const struct attribute *,
2016                                                struct dwarf2_cu **);
2017
2018 static struct die_info *follow_die_ref (struct die_info *,
2019                                         const struct attribute *,
2020                                         struct dwarf2_cu **);
2021
2022 static struct die_info *follow_die_sig (struct die_info *,
2023                                         const struct attribute *,
2024                                         struct dwarf2_cu **);
2025
2026 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2027                                          struct dwarf2_cu *);
2028
2029 static struct type *get_DW_AT_signature_type (struct die_info *,
2030                                               const struct attribute *,
2031                                               struct dwarf2_cu *);
2032
2033 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2034
2035 static void read_signatured_type (struct signatured_type *);
2036
2037 static int attr_to_dynamic_prop (const struct attribute *attr,
2038                                  struct die_info *die, struct dwarf2_cu *cu,
2039                                  struct dynamic_prop *prop);
2040
2041 /* memory allocation interface */
2042
2043 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2044
2045 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2046
2047 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2048
2049 static int attr_form_is_block (const struct attribute *);
2050
2051 static int attr_form_is_section_offset (const struct attribute *);
2052
2053 static int attr_form_is_constant (const struct attribute *);
2054
2055 static int attr_form_is_ref (const struct attribute *);
2056
2057 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2058                                    struct dwarf2_loclist_baton *baton,
2059                                    const struct attribute *attr);
2060
2061 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2062                                          struct symbol *sym,
2063                                          struct dwarf2_cu *cu,
2064                                          int is_block);
2065
2066 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2067                                      const gdb_byte *info_ptr,
2068                                      struct abbrev_info *abbrev);
2069
2070 static void free_stack_comp_unit (void *);
2071
2072 static hashval_t partial_die_hash (const void *item);
2073
2074 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2075
2076 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2077   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2078
2079 static void init_one_comp_unit (struct dwarf2_cu *cu,
2080                                 struct dwarf2_per_cu_data *per_cu);
2081
2082 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2083                                    struct die_info *comp_unit_die,
2084                                    enum language pretend_language);
2085
2086 static void free_heap_comp_unit (void *);
2087
2088 static void free_cached_comp_units (void *);
2089
2090 static void age_cached_comp_units (void);
2091
2092 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2093
2094 static struct type *set_die_type (struct die_info *, struct type *,
2095                                   struct dwarf2_cu *);
2096
2097 static void create_all_comp_units (struct objfile *);
2098
2099 static int create_all_type_units (struct objfile *);
2100
2101 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2102                                  enum language);
2103
2104 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2105                                     enum language);
2106
2107 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2108                                     enum language);
2109
2110 static void dwarf2_add_dependence (struct dwarf2_cu *,
2111                                    struct dwarf2_per_cu_data *);
2112
2113 static void dwarf2_mark (struct dwarf2_cu *);
2114
2115 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2116
2117 static struct type *get_die_type_at_offset (sect_offset,
2118                                             struct dwarf2_per_cu_data *);
2119
2120 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2121
2122 static void dwarf2_release_queue (void *dummy);
2123
2124 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2125                              enum language pretend_language);
2126
2127 static void process_queue (void);
2128
2129 /* The return type of find_file_and_directory.  Note, the enclosed
2130    string pointers are only valid while this object is valid.  */
2131
2132 struct file_and_directory
2133 {
2134   /* The filename.  This is never NULL.  */
2135   const char *name;
2136
2137   /* The compilation directory.  NULL if not known.  If we needed to
2138      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2139      points directly to the DW_AT_comp_dir string attribute owned by
2140      the obstack that owns the DIE.  */
2141   const char *comp_dir;
2142
2143   /* If we needed to build a new string for comp_dir, this is what
2144      owns the storage.  */
2145   std::string comp_dir_storage;
2146 };
2147
2148 static file_and_directory find_file_and_directory (struct die_info *die,
2149                                                    struct dwarf2_cu *cu);
2150
2151 static char *file_full_name (int file, struct line_header *lh,
2152                              const char *comp_dir);
2153
2154 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2155 enum class rcuh_kind { COMPILE, TYPE };
2156
2157 static const gdb_byte *read_and_check_comp_unit_head
2158   (struct comp_unit_head *header,
2159    struct dwarf2_section_info *section,
2160    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2161    rcuh_kind section_kind);
2162
2163 static void init_cutu_and_read_dies
2164   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2165    int use_existing_cu, int keep,
2166    die_reader_func_ftype *die_reader_func, void *data);
2167
2168 static void init_cutu_and_read_dies_simple
2169   (struct dwarf2_per_cu_data *this_cu,
2170    die_reader_func_ftype *die_reader_func, void *data);
2171
2172 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2173
2174 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2175
2176 static struct dwo_unit *lookup_dwo_unit_in_dwp
2177   (struct dwp_file *dwp_file, const char *comp_dir,
2178    ULONGEST signature, int is_debug_types);
2179
2180 static struct dwp_file *get_dwp_file (void);
2181
2182 static struct dwo_unit *lookup_dwo_comp_unit
2183   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2184
2185 static struct dwo_unit *lookup_dwo_type_unit
2186   (struct signatured_type *, const char *, const char *);
2187
2188 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2189
2190 static void free_dwo_file_cleanup (void *);
2191
2192 static void process_cu_includes (void);
2193
2194 static void check_producer (struct dwarf2_cu *cu);
2195
2196 static void free_line_header_voidp (void *arg);
2197 \f
2198 /* Various complaints about symbol reading that don't abort the process.  */
2199
2200 static void
2201 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2202 {
2203   complaint (&symfile_complaints,
2204              _("statement list doesn't fit in .debug_line section"));
2205 }
2206
2207 static void
2208 dwarf2_debug_line_missing_file_complaint (void)
2209 {
2210   complaint (&symfile_complaints,
2211              _(".debug_line section has line data without a file"));
2212 }
2213
2214 static void
2215 dwarf2_debug_line_missing_end_sequence_complaint (void)
2216 {
2217   complaint (&symfile_complaints,
2218              _(".debug_line section has line "
2219                "program sequence without an end"));
2220 }
2221
2222 static void
2223 dwarf2_complex_location_expr_complaint (void)
2224 {
2225   complaint (&symfile_complaints, _("location expression too complex"));
2226 }
2227
2228 static void
2229 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2230                                               int arg3)
2231 {
2232   complaint (&symfile_complaints,
2233              _("const value length mismatch for '%s', got %d, expected %d"),
2234              arg1, arg2, arg3);
2235 }
2236
2237 static void
2238 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2239 {
2240   complaint (&symfile_complaints,
2241              _("debug info runs off end of %s section"
2242                " [in module %s]"),
2243              get_section_name (section),
2244              get_section_file_name (section));
2245 }
2246
2247 static void
2248 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2249 {
2250   complaint (&symfile_complaints,
2251              _("macro debug info contains a "
2252                "malformed macro definition:\n`%s'"),
2253              arg1);
2254 }
2255
2256 static void
2257 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2258 {
2259   complaint (&symfile_complaints,
2260              _("invalid attribute class or form for '%s' in '%s'"),
2261              arg1, arg2);
2262 }
2263
2264 /* Hash function for line_header_hash.  */
2265
2266 static hashval_t
2267 line_header_hash (const struct line_header *ofs)
2268 {
2269   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2270 }
2271
2272 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2273
2274 static hashval_t
2275 line_header_hash_voidp (const void *item)
2276 {
2277   const struct line_header *ofs = (const struct line_header *) item;
2278
2279   return line_header_hash (ofs);
2280 }
2281
2282 /* Equality function for line_header_hash.  */
2283
2284 static int
2285 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2286 {
2287   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2288   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2289
2290   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2291           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2292 }
2293
2294 \f
2295
2296 /* Read the given attribute value as an address, taking the attribute's
2297    form into account.  */
2298
2299 static CORE_ADDR
2300 attr_value_as_address (struct attribute *attr)
2301 {
2302   CORE_ADDR addr;
2303
2304   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2305     {
2306       /* Aside from a few clearly defined exceptions, attributes that
2307          contain an address must always be in DW_FORM_addr form.
2308          Unfortunately, some compilers happen to be violating this
2309          requirement by encoding addresses using other forms, such
2310          as DW_FORM_data4 for example.  For those broken compilers,
2311          we try to do our best, without any guarantee of success,
2312          to interpret the address correctly.  It would also be nice
2313          to generate a complaint, but that would require us to maintain
2314          a list of legitimate cases where a non-address form is allowed,
2315          as well as update callers to pass in at least the CU's DWARF
2316          version.  This is more overhead than what we're willing to
2317          expand for a pretty rare case.  */
2318       addr = DW_UNSND (attr);
2319     }
2320   else
2321     addr = DW_ADDR (attr);
2322
2323   return addr;
2324 }
2325
2326 /* The suffix for an index file.  */
2327 #define INDEX4_SUFFIX ".gdb-index"
2328 #define INDEX5_SUFFIX ".debug_names"
2329 #define DEBUG_STR_SUFFIX ".debug_str"
2330
2331 /* See declaration.  */
2332
2333 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2334                                         const dwarf2_debug_sections *names)
2335   : objfile (objfile_)
2336 {
2337   if (names == NULL)
2338     names = &dwarf2_elf_names;
2339
2340   bfd *obfd = objfile->obfd;
2341
2342   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2343     locate_sections (obfd, sec, *names);
2344 }
2345
2346 dwarf2_per_objfile::~dwarf2_per_objfile ()
2347 {
2348   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2349   free_cached_comp_units ();
2350
2351   if (quick_file_names_table)
2352     htab_delete (quick_file_names_table);
2353
2354   if (line_header_hash)
2355     htab_delete (line_header_hash);
2356
2357   /* Everything else should be on the objfile obstack.  */
2358 }
2359
2360 /* See declaration.  */
2361
2362 void
2363 dwarf2_per_objfile::free_cached_comp_units ()
2364 {
2365   dwarf2_per_cu_data *per_cu = read_in_chain;
2366   dwarf2_per_cu_data **last_chain = &read_in_chain;
2367   while (per_cu != NULL)
2368     {
2369       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2370
2371       free_heap_comp_unit (per_cu->cu);
2372       *last_chain = next_cu;
2373       per_cu = next_cu;
2374     }
2375 }
2376
2377 /* Try to locate the sections we need for DWARF 2 debugging
2378    information and return true if we have enough to do something.
2379    NAMES points to the dwarf2 section names, or is NULL if the standard
2380    ELF names are used.  */
2381
2382 int
2383 dwarf2_has_info (struct objfile *objfile,
2384                  const struct dwarf2_debug_sections *names)
2385 {
2386   if (objfile->flags & OBJF_READNEVER)
2387     return 0;
2388
2389   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2390                         objfile_data (objfile, dwarf2_objfile_data_key));
2391   if (!dwarf2_per_objfile)
2392     {
2393       /* Initialize per-objfile state.  */
2394       struct dwarf2_per_objfile *data
2395         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2396
2397       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2398       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2399     }
2400   return (!dwarf2_per_objfile->info.is_virtual
2401           && dwarf2_per_objfile->info.s.section != NULL
2402           && !dwarf2_per_objfile->abbrev.is_virtual
2403           && dwarf2_per_objfile->abbrev.s.section != NULL);
2404 }
2405
2406 /* Return the containing section of virtual section SECTION.  */
2407
2408 static struct dwarf2_section_info *
2409 get_containing_section (const struct dwarf2_section_info *section)
2410 {
2411   gdb_assert (section->is_virtual);
2412   return section->s.containing_section;
2413 }
2414
2415 /* Return the bfd owner of SECTION.  */
2416
2417 static struct bfd *
2418 get_section_bfd_owner (const struct dwarf2_section_info *section)
2419 {
2420   if (section->is_virtual)
2421     {
2422       section = get_containing_section (section);
2423       gdb_assert (!section->is_virtual);
2424     }
2425   return section->s.section->owner;
2426 }
2427
2428 /* Return the bfd section of SECTION.
2429    Returns NULL if the section is not present.  */
2430
2431 static asection *
2432 get_section_bfd_section (const struct dwarf2_section_info *section)
2433 {
2434   if (section->is_virtual)
2435     {
2436       section = get_containing_section (section);
2437       gdb_assert (!section->is_virtual);
2438     }
2439   return section->s.section;
2440 }
2441
2442 /* Return the name of SECTION.  */
2443
2444 static const char *
2445 get_section_name (const struct dwarf2_section_info *section)
2446 {
2447   asection *sectp = get_section_bfd_section (section);
2448
2449   gdb_assert (sectp != NULL);
2450   return bfd_section_name (get_section_bfd_owner (section), sectp);
2451 }
2452
2453 /* Return the name of the file SECTION is in.  */
2454
2455 static const char *
2456 get_section_file_name (const struct dwarf2_section_info *section)
2457 {
2458   bfd *abfd = get_section_bfd_owner (section);
2459
2460   return bfd_get_filename (abfd);
2461 }
2462
2463 /* Return the id of SECTION.
2464    Returns 0 if SECTION doesn't exist.  */
2465
2466 static int
2467 get_section_id (const struct dwarf2_section_info *section)
2468 {
2469   asection *sectp = get_section_bfd_section (section);
2470
2471   if (sectp == NULL)
2472     return 0;
2473   return sectp->id;
2474 }
2475
2476 /* Return the flags of SECTION.
2477    SECTION (or containing section if this is a virtual section) must exist.  */
2478
2479 static int
2480 get_section_flags (const struct dwarf2_section_info *section)
2481 {
2482   asection *sectp = get_section_bfd_section (section);
2483
2484   gdb_assert (sectp != NULL);
2485   return bfd_get_section_flags (sectp->owner, sectp);
2486 }
2487
2488 /* When loading sections, we look either for uncompressed section or for
2489    compressed section names.  */
2490
2491 static int
2492 section_is_p (const char *section_name,
2493               const struct dwarf2_section_names *names)
2494 {
2495   if (names->normal != NULL
2496       && strcmp (section_name, names->normal) == 0)
2497     return 1;
2498   if (names->compressed != NULL
2499       && strcmp (section_name, names->compressed) == 0)
2500     return 1;
2501   return 0;
2502 }
2503
2504 /* See declaration.  */
2505
2506 void
2507 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2508                                      const dwarf2_debug_sections &names)
2509 {
2510   flagword aflag = bfd_get_section_flags (abfd, sectp);
2511
2512   if ((aflag & SEC_HAS_CONTENTS) == 0)
2513     {
2514     }
2515   else if (section_is_p (sectp->name, &names.info))
2516     {
2517       this->info.s.section = sectp;
2518       this->info.size = bfd_get_section_size (sectp);
2519     }
2520   else if (section_is_p (sectp->name, &names.abbrev))
2521     {
2522       this->abbrev.s.section = sectp;
2523       this->abbrev.size = bfd_get_section_size (sectp);
2524     }
2525   else if (section_is_p (sectp->name, &names.line))
2526     {
2527       this->line.s.section = sectp;
2528       this->line.size = bfd_get_section_size (sectp);
2529     }
2530   else if (section_is_p (sectp->name, &names.loc))
2531     {
2532       this->loc.s.section = sectp;
2533       this->loc.size = bfd_get_section_size (sectp);
2534     }
2535   else if (section_is_p (sectp->name, &names.loclists))
2536     {
2537       this->loclists.s.section = sectp;
2538       this->loclists.size = bfd_get_section_size (sectp);
2539     }
2540   else if (section_is_p (sectp->name, &names.macinfo))
2541     {
2542       this->macinfo.s.section = sectp;
2543       this->macinfo.size = bfd_get_section_size (sectp);
2544     }
2545   else if (section_is_p (sectp->name, &names.macro))
2546     {
2547       this->macro.s.section = sectp;
2548       this->macro.size = bfd_get_section_size (sectp);
2549     }
2550   else if (section_is_p (sectp->name, &names.str))
2551     {
2552       this->str.s.section = sectp;
2553       this->str.size = bfd_get_section_size (sectp);
2554     }
2555   else if (section_is_p (sectp->name, &names.line_str))
2556     {
2557       this->line_str.s.section = sectp;
2558       this->line_str.size = bfd_get_section_size (sectp);
2559     }
2560   else if (section_is_p (sectp->name, &names.addr))
2561     {
2562       this->addr.s.section = sectp;
2563       this->addr.size = bfd_get_section_size (sectp);
2564     }
2565   else if (section_is_p (sectp->name, &names.frame))
2566     {
2567       this->frame.s.section = sectp;
2568       this->frame.size = bfd_get_section_size (sectp);
2569     }
2570   else if (section_is_p (sectp->name, &names.eh_frame))
2571     {
2572       this->eh_frame.s.section = sectp;
2573       this->eh_frame.size = bfd_get_section_size (sectp);
2574     }
2575   else if (section_is_p (sectp->name, &names.ranges))
2576     {
2577       this->ranges.s.section = sectp;
2578       this->ranges.size = bfd_get_section_size (sectp);
2579     }
2580   else if (section_is_p (sectp->name, &names.rnglists))
2581     {
2582       this->rnglists.s.section = sectp;
2583       this->rnglists.size = bfd_get_section_size (sectp);
2584     }
2585   else if (section_is_p (sectp->name, &names.types))
2586     {
2587       struct dwarf2_section_info type_section;
2588
2589       memset (&type_section, 0, sizeof (type_section));
2590       type_section.s.section = sectp;
2591       type_section.size = bfd_get_section_size (sectp);
2592
2593       VEC_safe_push (dwarf2_section_info_def, this->types,
2594                      &type_section);
2595     }
2596   else if (section_is_p (sectp->name, &names.gdb_index))
2597     {
2598       this->gdb_index.s.section = sectp;
2599       this->gdb_index.size = bfd_get_section_size (sectp);
2600     }
2601   else if (section_is_p (sectp->name, &names.debug_names))
2602     {
2603       this->debug_names.s.section = sectp;
2604       this->debug_names.size = bfd_get_section_size (sectp);
2605     }
2606   else if (section_is_p (sectp->name, &names.debug_aranges))
2607     {
2608       this->debug_aranges.s.section = sectp;
2609       this->debug_aranges.size = bfd_get_section_size (sectp);
2610     }
2611
2612   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2613       && bfd_section_vma (abfd, sectp) == 0)
2614     this->has_section_at_zero = true;
2615 }
2616
2617 /* A helper function that decides whether a section is empty,
2618    or not present.  */
2619
2620 static int
2621 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2622 {
2623   if (section->is_virtual)
2624     return section->size == 0;
2625   return section->s.section == NULL || section->size == 0;
2626 }
2627
2628 /* Read the contents of the section INFO.
2629    OBJFILE is the main object file, but not necessarily the file where
2630    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2631    of the DWO file.
2632    If the section is compressed, uncompress it before returning.  */
2633
2634 static void
2635 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2636 {
2637   asection *sectp;
2638   bfd *abfd;
2639   gdb_byte *buf, *retbuf;
2640
2641   if (info->readin)
2642     return;
2643   info->buffer = NULL;
2644   info->readin = 1;
2645
2646   if (dwarf2_section_empty_p (info))
2647     return;
2648
2649   sectp = get_section_bfd_section (info);
2650
2651   /* If this is a virtual section we need to read in the real one first.  */
2652   if (info->is_virtual)
2653     {
2654       struct dwarf2_section_info *containing_section =
2655         get_containing_section (info);
2656
2657       gdb_assert (sectp != NULL);
2658       if ((sectp->flags & SEC_RELOC) != 0)
2659         {
2660           error (_("Dwarf Error: DWP format V2 with relocations is not"
2661                    " supported in section %s [in module %s]"),
2662                  get_section_name (info), get_section_file_name (info));
2663         }
2664       dwarf2_read_section (objfile, containing_section);
2665       /* Other code should have already caught virtual sections that don't
2666          fit.  */
2667       gdb_assert (info->virtual_offset + info->size
2668                   <= containing_section->size);
2669       /* If the real section is empty or there was a problem reading the
2670          section we shouldn't get here.  */
2671       gdb_assert (containing_section->buffer != NULL);
2672       info->buffer = containing_section->buffer + info->virtual_offset;
2673       return;
2674     }
2675
2676   /* If the section has relocations, we must read it ourselves.
2677      Otherwise we attach it to the BFD.  */
2678   if ((sectp->flags & SEC_RELOC) == 0)
2679     {
2680       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2681       return;
2682     }
2683
2684   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2685   info->buffer = buf;
2686
2687   /* When debugging .o files, we may need to apply relocations; see
2688      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2689      We never compress sections in .o files, so we only need to
2690      try this when the section is not compressed.  */
2691   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2692   if (retbuf != NULL)
2693     {
2694       info->buffer = retbuf;
2695       return;
2696     }
2697
2698   abfd = get_section_bfd_owner (info);
2699   gdb_assert (abfd != NULL);
2700
2701   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2702       || bfd_bread (buf, info->size, abfd) != info->size)
2703     {
2704       error (_("Dwarf Error: Can't read DWARF data"
2705                " in section %s [in module %s]"),
2706              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2707     }
2708 }
2709
2710 /* A helper function that returns the size of a section in a safe way.
2711    If you are positive that the section has been read before using the
2712    size, then it is safe to refer to the dwarf2_section_info object's
2713    "size" field directly.  In other cases, you must call this
2714    function, because for compressed sections the size field is not set
2715    correctly until the section has been read.  */
2716
2717 static bfd_size_type
2718 dwarf2_section_size (struct objfile *objfile,
2719                      struct dwarf2_section_info *info)
2720 {
2721   if (!info->readin)
2722     dwarf2_read_section (objfile, info);
2723   return info->size;
2724 }
2725
2726 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2727    SECTION_NAME.  */
2728
2729 void
2730 dwarf2_get_section_info (struct objfile *objfile,
2731                          enum dwarf2_section_enum sect,
2732                          asection **sectp, const gdb_byte **bufp,
2733                          bfd_size_type *sizep)
2734 {
2735   struct dwarf2_per_objfile *data
2736     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2737                                                   dwarf2_objfile_data_key);
2738   struct dwarf2_section_info *info;
2739
2740   /* We may see an objfile without any DWARF, in which case we just
2741      return nothing.  */
2742   if (data == NULL)
2743     {
2744       *sectp = NULL;
2745       *bufp = NULL;
2746       *sizep = 0;
2747       return;
2748     }
2749   switch (sect)
2750     {
2751     case DWARF2_DEBUG_FRAME:
2752       info = &data->frame;
2753       break;
2754     case DWARF2_EH_FRAME:
2755       info = &data->eh_frame;
2756       break;
2757     default:
2758       gdb_assert_not_reached ("unexpected section");
2759     }
2760
2761   dwarf2_read_section (objfile, info);
2762
2763   *sectp = get_section_bfd_section (info);
2764   *bufp = info->buffer;
2765   *sizep = info->size;
2766 }
2767
2768 /* A helper function to find the sections for a .dwz file.  */
2769
2770 static void
2771 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2772 {
2773   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2774
2775   /* Note that we only support the standard ELF names, because .dwz
2776      is ELF-only (at the time of writing).  */
2777   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2778     {
2779       dwz_file->abbrev.s.section = sectp;
2780       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2781     }
2782   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2783     {
2784       dwz_file->info.s.section = sectp;
2785       dwz_file->info.size = bfd_get_section_size (sectp);
2786     }
2787   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2788     {
2789       dwz_file->str.s.section = sectp;
2790       dwz_file->str.size = bfd_get_section_size (sectp);
2791     }
2792   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2793     {
2794       dwz_file->line.s.section = sectp;
2795       dwz_file->line.size = bfd_get_section_size (sectp);
2796     }
2797   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2798     {
2799       dwz_file->macro.s.section = sectp;
2800       dwz_file->macro.size = bfd_get_section_size (sectp);
2801     }
2802   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2803     {
2804       dwz_file->gdb_index.s.section = sectp;
2805       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2806     }
2807   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2808     {
2809       dwz_file->debug_names.s.section = sectp;
2810       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2811     }
2812 }
2813
2814 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2815    there is no .gnu_debugaltlink section in the file.  Error if there
2816    is such a section but the file cannot be found.  */
2817
2818 static struct dwz_file *
2819 dwarf2_get_dwz_file (void)
2820 {
2821   const char *filename;
2822   struct dwz_file *result;
2823   bfd_size_type buildid_len_arg;
2824   size_t buildid_len;
2825   bfd_byte *buildid;
2826
2827   if (dwarf2_per_objfile->dwz_file != NULL)
2828     return dwarf2_per_objfile->dwz_file;
2829
2830   bfd_set_error (bfd_error_no_error);
2831   gdb::unique_xmalloc_ptr<char> data
2832     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2833                                   &buildid_len_arg, &buildid));
2834   if (data == NULL)
2835     {
2836       if (bfd_get_error () == bfd_error_no_error)
2837         return NULL;
2838       error (_("could not read '.gnu_debugaltlink' section: %s"),
2839              bfd_errmsg (bfd_get_error ()));
2840     }
2841
2842   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2843
2844   buildid_len = (size_t) buildid_len_arg;
2845
2846   filename = data.get ();
2847
2848   std::string abs_storage;
2849   if (!IS_ABSOLUTE_PATH (filename))
2850     {
2851       gdb::unique_xmalloc_ptr<char> abs
2852         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2853
2854       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2855       filename = abs_storage.c_str ();
2856     }
2857
2858   /* First try the file name given in the section.  If that doesn't
2859      work, try to use the build-id instead.  */
2860   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2861   if (dwz_bfd != NULL)
2862     {
2863       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2864         dwz_bfd.release ();
2865     }
2866
2867   if (dwz_bfd == NULL)
2868     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2869
2870   if (dwz_bfd == NULL)
2871     error (_("could not find '.gnu_debugaltlink' file for %s"),
2872            objfile_name (dwarf2_per_objfile->objfile));
2873
2874   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2875                            struct dwz_file);
2876   result->dwz_bfd = dwz_bfd.release ();
2877
2878   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2879
2880   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2881   dwarf2_per_objfile->dwz_file = result;
2882   return result;
2883 }
2884 \f
2885 /* DWARF quick_symbols_functions support.  */
2886
2887 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2888    unique line tables, so we maintain a separate table of all .debug_line
2889    derived entries to support the sharing.
2890    All the quick functions need is the list of file names.  We discard the
2891    line_header when we're done and don't need to record it here.  */
2892 struct quick_file_names
2893 {
2894   /* The data used to construct the hash key.  */
2895   struct stmt_list_hash hash;
2896
2897   /* The number of entries in file_names, real_names.  */
2898   unsigned int num_file_names;
2899
2900   /* The file names from the line table, after being run through
2901      file_full_name.  */
2902   const char **file_names;
2903
2904   /* The file names from the line table after being run through
2905      gdb_realpath.  These are computed lazily.  */
2906   const char **real_names;
2907 };
2908
2909 /* When using the index (and thus not using psymtabs), each CU has an
2910    object of this type.  This is used to hold information needed by
2911    the various "quick" methods.  */
2912 struct dwarf2_per_cu_quick_data
2913 {
2914   /* The file table.  This can be NULL if there was no file table
2915      or it's currently not read in.
2916      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2917   struct quick_file_names *file_names;
2918
2919   /* The corresponding symbol table.  This is NULL if symbols for this
2920      CU have not yet been read.  */
2921   struct compunit_symtab *compunit_symtab;
2922
2923   /* A temporary mark bit used when iterating over all CUs in
2924      expand_symtabs_matching.  */
2925   unsigned int mark : 1;
2926
2927   /* True if we've tried to read the file table and found there isn't one.
2928      There will be no point in trying to read it again next time.  */
2929   unsigned int no_file_data : 1;
2930 };
2931
2932 /* Utility hash function for a stmt_list_hash.  */
2933
2934 static hashval_t
2935 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2936 {
2937   hashval_t v = 0;
2938
2939   if (stmt_list_hash->dwo_unit != NULL)
2940     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2941   v += to_underlying (stmt_list_hash->line_sect_off);
2942   return v;
2943 }
2944
2945 /* Utility equality function for a stmt_list_hash.  */
2946
2947 static int
2948 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2949                     const struct stmt_list_hash *rhs)
2950 {
2951   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2952     return 0;
2953   if (lhs->dwo_unit != NULL
2954       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2955     return 0;
2956
2957   return lhs->line_sect_off == rhs->line_sect_off;
2958 }
2959
2960 /* Hash function for a quick_file_names.  */
2961
2962 static hashval_t
2963 hash_file_name_entry (const void *e)
2964 {
2965   const struct quick_file_names *file_data
2966     = (const struct quick_file_names *) e;
2967
2968   return hash_stmt_list_entry (&file_data->hash);
2969 }
2970
2971 /* Equality function for a quick_file_names.  */
2972
2973 static int
2974 eq_file_name_entry (const void *a, const void *b)
2975 {
2976   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2977   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2978
2979   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2980 }
2981
2982 /* Delete function for a quick_file_names.  */
2983
2984 static void
2985 delete_file_name_entry (void *e)
2986 {
2987   struct quick_file_names *file_data = (struct quick_file_names *) e;
2988   int i;
2989
2990   for (i = 0; i < file_data->num_file_names; ++i)
2991     {
2992       xfree ((void*) file_data->file_names[i]);
2993       if (file_data->real_names)
2994         xfree ((void*) file_data->real_names[i]);
2995     }
2996
2997   /* The space for the struct itself lives on objfile_obstack,
2998      so we don't free it here.  */
2999 }
3000
3001 /* Create a quick_file_names hash table.  */
3002
3003 static htab_t
3004 create_quick_file_names_table (unsigned int nr_initial_entries)
3005 {
3006   return htab_create_alloc (nr_initial_entries,
3007                             hash_file_name_entry, eq_file_name_entry,
3008                             delete_file_name_entry, xcalloc, xfree);
3009 }
3010
3011 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3012    have to be created afterwards.  You should call age_cached_comp_units after
3013    processing PER_CU->CU.  dw2_setup must have been already called.  */
3014
3015 static void
3016 load_cu (struct dwarf2_per_cu_data *per_cu)
3017 {
3018   if (per_cu->is_debug_types)
3019     load_full_type_unit (per_cu);
3020   else
3021     load_full_comp_unit (per_cu, language_minimal);
3022
3023   if (per_cu->cu == NULL)
3024     return;  /* Dummy CU.  */
3025
3026   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3027 }
3028
3029 /* Read in the symbols for PER_CU.  */
3030
3031 static void
3032 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3033 {
3034   struct cleanup *back_to;
3035
3036   /* Skip type_unit_groups, reading the type units they contain
3037      is handled elsewhere.  */
3038   if (IS_TYPE_UNIT_GROUP (per_cu))
3039     return;
3040
3041   back_to = make_cleanup (dwarf2_release_queue, NULL);
3042
3043   if (dwarf2_per_objfile->using_index
3044       ? per_cu->v.quick->compunit_symtab == NULL
3045       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3046     {
3047       queue_comp_unit (per_cu, language_minimal);
3048       load_cu (per_cu);
3049
3050       /* If we just loaded a CU from a DWO, and we're working with an index
3051          that may badly handle TUs, load all the TUs in that DWO as well.
3052          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3053       if (!per_cu->is_debug_types
3054           && per_cu->cu != NULL
3055           && per_cu->cu->dwo_unit != NULL
3056           && dwarf2_per_objfile->index_table != NULL
3057           && dwarf2_per_objfile->index_table->version <= 7
3058           /* DWP files aren't supported yet.  */
3059           && get_dwp_file () == NULL)
3060         queue_and_load_all_dwo_tus (per_cu);
3061     }
3062
3063   process_queue ();
3064
3065   /* Age the cache, releasing compilation units that have not
3066      been used recently.  */
3067   age_cached_comp_units ();
3068
3069   do_cleanups (back_to);
3070 }
3071
3072 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3073    the objfile from which this CU came.  Returns the resulting symbol
3074    table.  */
3075
3076 static struct compunit_symtab *
3077 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3078 {
3079   gdb_assert (dwarf2_per_objfile->using_index);
3080   if (!per_cu->v.quick->compunit_symtab)
3081     {
3082       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
3083       scoped_restore decrementer = increment_reading_symtab ();
3084       dw2_do_instantiate_symtab (per_cu);
3085       process_cu_includes ();
3086       do_cleanups (back_to);
3087     }
3088
3089   return per_cu->v.quick->compunit_symtab;
3090 }
3091
3092 /* Return the CU/TU given its index.
3093
3094    This is intended for loops like:
3095
3096    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3097                     + dwarf2_per_objfile->n_type_units); ++i)
3098      {
3099        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3100
3101        ...;
3102      }
3103 */
3104
3105 static struct dwarf2_per_cu_data *
3106 dw2_get_cutu (int index)
3107 {
3108   if (index >= dwarf2_per_objfile->n_comp_units)
3109     {
3110       index -= dwarf2_per_objfile->n_comp_units;
3111       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3112       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3113     }
3114
3115   return dwarf2_per_objfile->all_comp_units[index];
3116 }
3117
3118 /* Return the CU given its index.
3119    This differs from dw2_get_cutu in that it's for when you know INDEX
3120    refers to a CU.  */
3121
3122 static struct dwarf2_per_cu_data *
3123 dw2_get_cu (int index)
3124 {
3125   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3126
3127   return dwarf2_per_objfile->all_comp_units[index];
3128 }
3129
3130 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3131    objfile_obstack, and constructed with the specified field
3132    values.  */
3133
3134 static dwarf2_per_cu_data *
3135 create_cu_from_index_list (struct objfile *objfile,
3136                           struct dwarf2_section_info *section,
3137                           int is_dwz,
3138                           sect_offset sect_off, ULONGEST length)
3139 {
3140   dwarf2_per_cu_data *the_cu
3141     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3142                      struct dwarf2_per_cu_data);
3143   the_cu->sect_off = sect_off;
3144   the_cu->length = length;
3145   the_cu->objfile = objfile;
3146   the_cu->section = section;
3147   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3148                                    struct dwarf2_per_cu_quick_data);
3149   the_cu->is_dwz = is_dwz;
3150   return the_cu;
3151 }
3152
3153 /* A helper for create_cus_from_index that handles a given list of
3154    CUs.  */
3155
3156 static void
3157 create_cus_from_index_list (struct objfile *objfile,
3158                             const gdb_byte *cu_list, offset_type n_elements,
3159                             struct dwarf2_section_info *section,
3160                             int is_dwz,
3161                             int base_offset)
3162 {
3163   offset_type i;
3164
3165   for (i = 0; i < n_elements; i += 2)
3166     {
3167       gdb_static_assert (sizeof (ULONGEST) >= 8);
3168
3169       sect_offset sect_off
3170         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3171       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3172       cu_list += 2 * 8;
3173
3174       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3175         = create_cu_from_index_list (objfile, section, is_dwz, sect_off, length);
3176     }
3177 }
3178
3179 /* Read the CU list from the mapped index, and use it to create all
3180    the CU objects for this objfile.  */
3181
3182 static void
3183 create_cus_from_index (struct objfile *objfile,
3184                        const gdb_byte *cu_list, offset_type cu_list_elements,
3185                        const gdb_byte *dwz_list, offset_type dwz_elements)
3186 {
3187   struct dwz_file *dwz;
3188
3189   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3190   dwarf2_per_objfile->all_comp_units =
3191     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3192                dwarf2_per_objfile->n_comp_units);
3193
3194   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3195                               &dwarf2_per_objfile->info, 0, 0);
3196
3197   if (dwz_elements == 0)
3198     return;
3199
3200   dwz = dwarf2_get_dwz_file ();
3201   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3202                               cu_list_elements / 2);
3203 }
3204
3205 /* Create the signatured type hash table from the index.  */
3206
3207 static void
3208 create_signatured_type_table_from_index (struct objfile *objfile,
3209                                          struct dwarf2_section_info *section,
3210                                          const gdb_byte *bytes,
3211                                          offset_type elements)
3212 {
3213   offset_type i;
3214   htab_t sig_types_hash;
3215
3216   dwarf2_per_objfile->n_type_units
3217     = dwarf2_per_objfile->n_allocated_type_units
3218     = elements / 3;
3219   dwarf2_per_objfile->all_type_units =
3220     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3221
3222   sig_types_hash = allocate_signatured_type_table (objfile);
3223
3224   for (i = 0; i < elements; i += 3)
3225     {
3226       struct signatured_type *sig_type;
3227       ULONGEST signature;
3228       void **slot;
3229       cu_offset type_offset_in_tu;
3230
3231       gdb_static_assert (sizeof (ULONGEST) >= 8);
3232       sect_offset sect_off
3233         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3234       type_offset_in_tu
3235         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3236                                                 BFD_ENDIAN_LITTLE);
3237       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3238       bytes += 3 * 8;
3239
3240       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3241                                  struct signatured_type);
3242       sig_type->signature = signature;
3243       sig_type->type_offset_in_tu = type_offset_in_tu;
3244       sig_type->per_cu.is_debug_types = 1;
3245       sig_type->per_cu.section = section;
3246       sig_type->per_cu.sect_off = sect_off;
3247       sig_type->per_cu.objfile = objfile;
3248       sig_type->per_cu.v.quick
3249         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3250                           struct dwarf2_per_cu_quick_data);
3251
3252       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3253       *slot = sig_type;
3254
3255       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3256     }
3257
3258   dwarf2_per_objfile->signatured_types = sig_types_hash;
3259 }
3260
3261 /* Create the signatured type hash table from .debug_names.  */
3262
3263 static void
3264 create_signatured_type_table_from_debug_names
3265   (struct objfile *objfile,
3266    const mapped_debug_names &map,
3267    struct dwarf2_section_info *section,
3268    struct dwarf2_section_info *abbrev_section)
3269 {
3270   dwarf2_read_section (objfile, section);
3271   dwarf2_read_section (objfile, abbrev_section);
3272
3273   dwarf2_per_objfile->n_type_units
3274     = dwarf2_per_objfile->n_allocated_type_units
3275     = map.tu_count;
3276   dwarf2_per_objfile->all_type_units
3277     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3278
3279   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3280
3281   for (uint32_t i = 0; i < map.tu_count; ++i)
3282     {
3283       struct signatured_type *sig_type;
3284       ULONGEST signature;
3285       void **slot;
3286       cu_offset type_offset_in_tu;
3287
3288       sect_offset sect_off
3289         = (sect_offset) (extract_unsigned_integer
3290                          (map.tu_table_reordered + i * map.offset_size,
3291                           map.offset_size,
3292                           map.dwarf5_byte_order));
3293
3294       comp_unit_head cu_header;
3295       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
3296                                      section->buffer + to_underlying (sect_off),
3297                                      rcuh_kind::TYPE);
3298
3299       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3300                                  struct signatured_type);
3301       sig_type->signature = cu_header.signature;
3302       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3303       sig_type->per_cu.is_debug_types = 1;
3304       sig_type->per_cu.section = section;
3305       sig_type->per_cu.sect_off = sect_off;
3306       sig_type->per_cu.objfile = objfile;
3307       sig_type->per_cu.v.quick
3308         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3309                           struct dwarf2_per_cu_quick_data);
3310
3311       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3312       *slot = sig_type;
3313
3314       dwarf2_per_objfile->all_type_units[i] = sig_type;
3315     }
3316
3317   dwarf2_per_objfile->signatured_types = sig_types_hash;
3318 }
3319
3320 /* Read the address map data from the mapped index, and use it to
3321    populate the objfile's psymtabs_addrmap.  */
3322
3323 static void
3324 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3325 {
3326   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3327   const gdb_byte *iter, *end;
3328   struct addrmap *mutable_map;
3329   CORE_ADDR baseaddr;
3330
3331   auto_obstack temp_obstack;
3332
3333   mutable_map = addrmap_create_mutable (&temp_obstack);
3334
3335   iter = index->address_table.data ();
3336   end = iter + index->address_table.size ();
3337
3338   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3339
3340   while (iter < end)
3341     {
3342       ULONGEST hi, lo, cu_index;
3343       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3344       iter += 8;
3345       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3346       iter += 8;
3347       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3348       iter += 4;
3349
3350       if (lo > hi)
3351         {
3352           complaint (&symfile_complaints,
3353                      _(".gdb_index address table has invalid range (%s - %s)"),
3354                      hex_string (lo), hex_string (hi));
3355           continue;
3356         }
3357
3358       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3359         {
3360           complaint (&symfile_complaints,
3361                      _(".gdb_index address table has invalid CU number %u"),
3362                      (unsigned) cu_index);
3363           continue;
3364         }
3365
3366       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3367       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3368       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3369     }
3370
3371   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3372                                                     &objfile->objfile_obstack);
3373 }
3374
3375 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3376    populate the objfile's psymtabs_addrmap.  */
3377
3378 static void
3379 create_addrmap_from_aranges (struct objfile *objfile,
3380                              struct dwarf2_section_info *section)
3381 {
3382   bfd *abfd = objfile->obfd;
3383   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3384   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3385                                        SECT_OFF_TEXT (objfile));
3386
3387   auto_obstack temp_obstack;
3388   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3389
3390   std::unordered_map<sect_offset,
3391                      dwarf2_per_cu_data *,
3392                      gdb::hash_enum<sect_offset>>
3393     debug_info_offset_to_per_cu;
3394   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3395     {
3396       dwarf2_per_cu_data *per_cu = dw2_get_cutu (cui);
3397       const auto insertpair
3398         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3399       if (!insertpair.second)
3400         {
3401           warning (_("Section .debug_aranges in %s has duplicate "
3402                      "debug_info_offset %u, ignoring .debug_aranges."),
3403                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3404           return;
3405         }
3406     }
3407
3408   dwarf2_read_section (objfile, section);
3409
3410   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3411
3412   const gdb_byte *addr = section->buffer;
3413
3414   while (addr < section->buffer + section->size)
3415     {
3416       const gdb_byte *const entry_addr = addr;
3417       unsigned int bytes_read;
3418
3419       const LONGEST entry_length = read_initial_length (abfd, addr,
3420                                                         &bytes_read);
3421       addr += bytes_read;
3422
3423       const gdb_byte *const entry_end = addr + entry_length;
3424       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3425       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3426       if (addr + entry_length > section->buffer + section->size)
3427         {
3428           warning (_("Section .debug_aranges in %s entry at offset %zu "
3429                      "length %s exceeds section length %s, "
3430                      "ignoring .debug_aranges."),
3431                    objfile_name (objfile), entry_addr - section->buffer,
3432                    plongest (bytes_read + entry_length),
3433                    pulongest (section->size));
3434           return;
3435         }
3436
3437       /* The version number.  */
3438       const uint16_t version = read_2_bytes (abfd, addr);
3439       addr += 2;
3440       if (version != 2)
3441         {
3442           warning (_("Section .debug_aranges in %s entry at offset %zu "
3443                      "has unsupported version %d, ignoring .debug_aranges."),
3444                    objfile_name (objfile), entry_addr - section->buffer,
3445                    version);
3446           return;
3447         }
3448
3449       const uint64_t debug_info_offset
3450         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3451       addr += offset_size;
3452       const auto per_cu_it
3453         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3454       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3455         {
3456           warning (_("Section .debug_aranges in %s entry at offset %zu "
3457                      "debug_info_offset %s does not exists, "
3458                      "ignoring .debug_aranges."),
3459                    objfile_name (objfile), entry_addr - section->buffer,
3460                    pulongest (debug_info_offset));
3461           return;
3462         }
3463       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3464
3465       const uint8_t address_size = *addr++;
3466       if (address_size < 1 || address_size > 8)
3467         {
3468           warning (_("Section .debug_aranges in %s entry at offset %zu "
3469                      "address_size %u is invalid, ignoring .debug_aranges."),
3470                    objfile_name (objfile), entry_addr - section->buffer,
3471                    address_size);
3472           return;
3473         }
3474
3475       const uint8_t segment_selector_size = *addr++;
3476       if (segment_selector_size != 0)
3477         {
3478           warning (_("Section .debug_aranges in %s entry at offset %zu "
3479                      "segment_selector_size %u is not supported, "
3480                      "ignoring .debug_aranges."),
3481                    objfile_name (objfile), entry_addr - section->buffer,
3482                    segment_selector_size);
3483           return;
3484         }
3485
3486       /* Must pad to an alignment boundary that is twice the address
3487          size.  It is undocumented by the DWARF standard but GCC does
3488          use it.  */
3489       for (size_t padding = ((-(addr - section->buffer))
3490                              & (2 * address_size - 1));
3491            padding > 0; padding--)
3492         if (*addr++ != 0)
3493           {
3494             warning (_("Section .debug_aranges in %s entry at offset %zu "
3495                        "padding is not zero, ignoring .debug_aranges."),
3496                      objfile_name (objfile), entry_addr - section->buffer);
3497             return;
3498           }
3499
3500       for (;;)
3501         {
3502           if (addr + 2 * address_size > entry_end)
3503             {
3504               warning (_("Section .debug_aranges in %s entry at offset %zu "
3505                          "address list is not properly terminated, "
3506                          "ignoring .debug_aranges."),
3507                        objfile_name (objfile), entry_addr - section->buffer);
3508               return;
3509             }
3510           ULONGEST start = extract_unsigned_integer (addr, address_size,
3511                                                      dwarf5_byte_order);
3512           addr += address_size;
3513           ULONGEST length = extract_unsigned_integer (addr, address_size,
3514                                                       dwarf5_byte_order);
3515           addr += address_size;
3516           if (start == 0 && length == 0)
3517             break;
3518           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3519             {
3520               /* Symbol was eliminated due to a COMDAT group.  */
3521               continue;
3522             }
3523           ULONGEST end = start + length;
3524           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3525           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3526           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3527         }
3528     }
3529
3530   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3531                                                     &objfile->objfile_obstack);
3532 }
3533
3534 /* The hash function for strings in the mapped index.  This is the same as
3535    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3536    implementation.  This is necessary because the hash function is tied to the
3537    format of the mapped index file.  The hash values do not have to match with
3538    SYMBOL_HASH_NEXT.
3539    
3540    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3541
3542 static hashval_t
3543 mapped_index_string_hash (int index_version, const void *p)
3544 {
3545   const unsigned char *str = (const unsigned char *) p;
3546   hashval_t r = 0;
3547   unsigned char c;
3548
3549   while ((c = *str++) != 0)
3550     {
3551       if (index_version >= 5)
3552         c = tolower (c);
3553       r = r * 67 + c - 113;
3554     }
3555
3556   return r;
3557 }
3558
3559 /* Find a slot in the mapped index INDEX for the object named NAME.
3560    If NAME is found, set *VEC_OUT to point to the CU vector in the
3561    constant pool and return true.  If NAME cannot be found, return
3562    false.  */
3563
3564 static bool
3565 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3566                           offset_type **vec_out)
3567 {
3568   offset_type hash;
3569   offset_type slot, step;
3570   int (*cmp) (const char *, const char *);
3571
3572   gdb::unique_xmalloc_ptr<char> without_params;
3573   if (current_language->la_language == language_cplus
3574       || current_language->la_language == language_fortran
3575       || current_language->la_language == language_d)
3576     {
3577       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3578          not contain any.  */
3579
3580       if (strchr (name, '(') != NULL)
3581         {
3582           without_params = cp_remove_params (name);
3583
3584           if (without_params != NULL)
3585             name = without_params.get ();
3586         }
3587     }
3588
3589   /* Index version 4 did not support case insensitive searches.  But the
3590      indices for case insensitive languages are built in lowercase, therefore
3591      simulate our NAME being searched is also lowercased.  */
3592   hash = mapped_index_string_hash ((index->version == 4
3593                                     && case_sensitivity == case_sensitive_off
3594                                     ? 5 : index->version),
3595                                    name);
3596
3597   slot = hash & (index->symbol_table.size () - 1);
3598   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3599   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3600
3601   for (;;)
3602     {
3603       const char *str;
3604
3605       const auto &bucket = index->symbol_table[slot];
3606       if (bucket.name == 0 && bucket.vec == 0)
3607         return false;
3608
3609       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3610       if (!cmp (name, str))
3611         {
3612           *vec_out = (offset_type *) (index->constant_pool
3613                                       + MAYBE_SWAP (bucket.vec));
3614           return true;
3615         }
3616
3617       slot = (slot + step) & (index->symbol_table.size () - 1);
3618     }
3619 }
3620
3621 /* A helper function that reads the .gdb_index from SECTION and fills
3622    in MAP.  FILENAME is the name of the file containing the section;
3623    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3624    ok to use deprecated sections.
3625
3626    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3627    out parameters that are filled in with information about the CU and
3628    TU lists in the section.
3629
3630    Returns 1 if all went well, 0 otherwise.  */
3631
3632 static int
3633 read_index_from_section (struct objfile *objfile,
3634                          const char *filename,
3635                          int deprecated_ok,
3636                          struct dwarf2_section_info *section,
3637                          struct mapped_index *map,
3638                          const gdb_byte **cu_list,
3639                          offset_type *cu_list_elements,
3640                          const gdb_byte **types_list,
3641                          offset_type *types_list_elements)
3642 {
3643   const gdb_byte *addr;
3644   offset_type version;
3645   offset_type *metadata;
3646   int i;
3647
3648   if (dwarf2_section_empty_p (section))
3649     return 0;
3650
3651   /* Older elfutils strip versions could keep the section in the main
3652      executable while splitting it for the separate debug info file.  */
3653   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3654     return 0;
3655
3656   dwarf2_read_section (objfile, section);
3657
3658   addr = section->buffer;
3659   /* Version check.  */
3660   version = MAYBE_SWAP (*(offset_type *) addr);
3661   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3662      causes the index to behave very poorly for certain requests.  Version 3
3663      contained incomplete addrmap.  So, it seems better to just ignore such
3664      indices.  */
3665   if (version < 4)
3666     {
3667       static int warning_printed = 0;
3668       if (!warning_printed)
3669         {
3670           warning (_("Skipping obsolete .gdb_index section in %s."),
3671                    filename);
3672           warning_printed = 1;
3673         }
3674       return 0;
3675     }
3676   /* Index version 4 uses a different hash function than index version
3677      5 and later.
3678
3679      Versions earlier than 6 did not emit psymbols for inlined
3680      functions.  Using these files will cause GDB not to be able to
3681      set breakpoints on inlined functions by name, so we ignore these
3682      indices unless the user has done
3683      "set use-deprecated-index-sections on".  */
3684   if (version < 6 && !deprecated_ok)
3685     {
3686       static int warning_printed = 0;
3687       if (!warning_printed)
3688         {
3689           warning (_("\
3690 Skipping deprecated .gdb_index section in %s.\n\
3691 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3692 to use the section anyway."),
3693                    filename);
3694           warning_printed = 1;
3695         }
3696       return 0;
3697     }
3698   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3699      of the TU (for symbols coming from TUs),
3700      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3701      Plus gold-generated indices can have duplicate entries for global symbols,
3702      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3703      These are just performance bugs, and we can't distinguish gdb-generated
3704      indices from gold-generated ones, so issue no warning here.  */
3705
3706   /* Indexes with higher version than the one supported by GDB may be no
3707      longer backward compatible.  */
3708   if (version > 8)
3709     return 0;
3710
3711   map->version = version;
3712   map->total_size = section->size;
3713
3714   metadata = (offset_type *) (addr + sizeof (offset_type));
3715
3716   i = 0;
3717   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3718   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3719                        / 8);
3720   ++i;
3721
3722   *types_list = addr + MAYBE_SWAP (metadata[i]);
3723   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3724                            - MAYBE_SWAP (metadata[i]))
3725                           / 8);
3726   ++i;
3727
3728   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3729   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3730   map->address_table
3731     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3732   ++i;
3733
3734   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3735   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3736   map->symbol_table
3737     = gdb::array_view<mapped_index::symbol_table_slot>
3738        ((mapped_index::symbol_table_slot *) symbol_table,
3739         (mapped_index::symbol_table_slot *) symbol_table_end);
3740
3741   ++i;
3742   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3743
3744   return 1;
3745 }
3746
3747 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3748    elements of all the CUs and return 1.  Otherwise, return 0.  */
3749
3750 static int
3751 dwarf2_read_index (struct objfile *objfile)
3752 {
3753   struct mapped_index local_map, *map;
3754   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3755   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3756   struct dwz_file *dwz;
3757
3758   if (!read_index_from_section (objfile, objfile_name (objfile),
3759                                 use_deprecated_index_sections,
3760                                 &dwarf2_per_objfile->gdb_index, &local_map,
3761                                 &cu_list, &cu_list_elements,
3762                                 &types_list, &types_list_elements))
3763     return 0;
3764
3765   /* Don't use the index if it's empty.  */
3766   if (local_map.symbol_table.empty ())
3767     return 0;
3768
3769   /* If there is a .dwz file, read it so we can get its CU list as
3770      well.  */
3771   dwz = dwarf2_get_dwz_file ();
3772   if (dwz != NULL)
3773     {
3774       struct mapped_index dwz_map;
3775       const gdb_byte *dwz_types_ignore;
3776       offset_type dwz_types_elements_ignore;
3777
3778       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3779                                     1,
3780                                     &dwz->gdb_index, &dwz_map,
3781                                     &dwz_list, &dwz_list_elements,
3782                                     &dwz_types_ignore,
3783                                     &dwz_types_elements_ignore))
3784         {
3785           warning (_("could not read '.gdb_index' section from %s; skipping"),
3786                    bfd_get_filename (dwz->dwz_bfd));
3787           return 0;
3788         }
3789     }
3790
3791   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3792                          dwz_list_elements);
3793
3794   if (types_list_elements)
3795     {
3796       struct dwarf2_section_info *section;
3797
3798       /* We can only handle a single .debug_types when we have an
3799          index.  */
3800       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3801         return 0;
3802
3803       section = VEC_index (dwarf2_section_info_def,
3804                            dwarf2_per_objfile->types, 0);
3805
3806       create_signatured_type_table_from_index (objfile, section, types_list,
3807                                                types_list_elements);
3808     }
3809
3810   create_addrmap_from_index (objfile, &local_map);
3811
3812   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3813   map = new (map) mapped_index ();
3814   *map = local_map;
3815
3816   dwarf2_per_objfile->index_table = map;
3817   dwarf2_per_objfile->using_index = 1;
3818   dwarf2_per_objfile->quick_file_names_table =
3819     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3820
3821   return 1;
3822 }
3823
3824 /* A helper for the "quick" functions which sets the global
3825    dwarf2_per_objfile according to OBJFILE.  */
3826
3827 static void
3828 dw2_setup (struct objfile *objfile)
3829 {
3830   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3831                         objfile_data (objfile, dwarf2_objfile_data_key));
3832   gdb_assert (dwarf2_per_objfile);
3833 }
3834
3835 /* die_reader_func for dw2_get_file_names.  */
3836
3837 static void
3838 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3839                            const gdb_byte *info_ptr,
3840                            struct die_info *comp_unit_die,
3841                            int has_children,
3842                            void *data)
3843 {
3844   struct dwarf2_cu *cu = reader->cu;
3845   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3846   struct objfile *objfile = dwarf2_per_objfile->objfile;
3847   struct dwarf2_per_cu_data *lh_cu;
3848   struct attribute *attr;
3849   int i;
3850   void **slot;
3851   struct quick_file_names *qfn;
3852
3853   gdb_assert (! this_cu->is_debug_types);
3854
3855   /* Our callers never want to match partial units -- instead they
3856      will match the enclosing full CU.  */
3857   if (comp_unit_die->tag == DW_TAG_partial_unit)
3858     {
3859       this_cu->v.quick->no_file_data = 1;
3860       return;
3861     }
3862
3863   lh_cu = this_cu;
3864   slot = NULL;
3865
3866   line_header_up lh;
3867   sect_offset line_offset {};
3868
3869   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3870   if (attr)
3871     {
3872       struct quick_file_names find_entry;
3873
3874       line_offset = (sect_offset) DW_UNSND (attr);
3875
3876       /* We may have already read in this line header (TU line header sharing).
3877          If we have we're done.  */
3878       find_entry.hash.dwo_unit = cu->dwo_unit;
3879       find_entry.hash.line_sect_off = line_offset;
3880       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3881                              &find_entry, INSERT);
3882       if (*slot != NULL)
3883         {
3884           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3885           return;
3886         }
3887
3888       lh = dwarf_decode_line_header (line_offset, cu);
3889     }
3890   if (lh == NULL)
3891     {
3892       lh_cu->v.quick->no_file_data = 1;
3893       return;
3894     }
3895
3896   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3897   qfn->hash.dwo_unit = cu->dwo_unit;
3898   qfn->hash.line_sect_off = line_offset;
3899   gdb_assert (slot != NULL);
3900   *slot = qfn;
3901
3902   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3903
3904   qfn->num_file_names = lh->file_names.size ();
3905   qfn->file_names =
3906     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3907   for (i = 0; i < lh->file_names.size (); ++i)
3908     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3909   qfn->real_names = NULL;
3910
3911   lh_cu->v.quick->file_names = qfn;
3912 }
3913
3914 /* A helper for the "quick" functions which attempts to read the line
3915    table for THIS_CU.  */
3916
3917 static struct quick_file_names *
3918 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3919 {
3920   /* This should never be called for TUs.  */
3921   gdb_assert (! this_cu->is_debug_types);
3922   /* Nor type unit groups.  */
3923   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3924
3925   if (this_cu->v.quick->file_names != NULL)
3926     return this_cu->v.quick->file_names;
3927   /* If we know there is no line data, no point in looking again.  */
3928   if (this_cu->v.quick->no_file_data)
3929     return NULL;
3930
3931   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3932
3933   if (this_cu->v.quick->no_file_data)
3934     return NULL;
3935   return this_cu->v.quick->file_names;
3936 }
3937
3938 /* A helper for the "quick" functions which computes and caches the
3939    real path for a given file name from the line table.  */
3940
3941 static const char *
3942 dw2_get_real_path (struct objfile *objfile,
3943                    struct quick_file_names *qfn, int index)
3944 {
3945   if (qfn->real_names == NULL)
3946     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3947                                       qfn->num_file_names, const char *);
3948
3949   if (qfn->real_names[index] == NULL)
3950     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3951
3952   return qfn->real_names[index];
3953 }
3954
3955 static struct symtab *
3956 dw2_find_last_source_symtab (struct objfile *objfile)
3957 {
3958   struct compunit_symtab *cust;
3959   int index;
3960
3961   dw2_setup (objfile);
3962   index = dwarf2_per_objfile->n_comp_units - 1;
3963   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3964   if (cust == NULL)
3965     return NULL;
3966   return compunit_primary_filetab (cust);
3967 }
3968
3969 /* Traversal function for dw2_forget_cached_source_info.  */
3970
3971 static int
3972 dw2_free_cached_file_names (void **slot, void *info)
3973 {
3974   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3975
3976   if (file_data->real_names)
3977     {
3978       int i;
3979
3980       for (i = 0; i < file_data->num_file_names; ++i)
3981         {
3982           xfree ((void*) file_data->real_names[i]);
3983           file_data->real_names[i] = NULL;
3984         }
3985     }
3986
3987   return 1;
3988 }
3989
3990 static void
3991 dw2_forget_cached_source_info (struct objfile *objfile)
3992 {
3993   dw2_setup (objfile);
3994
3995   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3996                           dw2_free_cached_file_names, NULL);
3997 }
3998
3999 /* Helper function for dw2_map_symtabs_matching_filename that expands
4000    the symtabs and calls the iterator.  */
4001
4002 static int
4003 dw2_map_expand_apply (struct objfile *objfile,
4004                       struct dwarf2_per_cu_data *per_cu,
4005                       const char *name, const char *real_path,
4006                       gdb::function_view<bool (symtab *)> callback)
4007 {
4008   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4009
4010   /* Don't visit already-expanded CUs.  */
4011   if (per_cu->v.quick->compunit_symtab)
4012     return 0;
4013
4014   /* This may expand more than one symtab, and we want to iterate over
4015      all of them.  */
4016   dw2_instantiate_symtab (per_cu);
4017
4018   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4019                                     last_made, callback);
4020 }
4021
4022 /* Implementation of the map_symtabs_matching_filename method.  */
4023
4024 static bool
4025 dw2_map_symtabs_matching_filename
4026   (struct objfile *objfile, const char *name, const char *real_path,
4027    gdb::function_view<bool (symtab *)> callback)
4028 {
4029   int i;
4030   const char *name_basename = lbasename (name);
4031
4032   dw2_setup (objfile);
4033
4034   /* The rule is CUs specify all the files, including those used by
4035      any TU, so there's no need to scan TUs here.  */
4036
4037   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4038     {
4039       int j;
4040       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4041       struct quick_file_names *file_data;
4042
4043       /* We only need to look at symtabs not already expanded.  */
4044       if (per_cu->v.quick->compunit_symtab)
4045         continue;
4046
4047       file_data = dw2_get_file_names (per_cu);
4048       if (file_data == NULL)
4049         continue;
4050
4051       for (j = 0; j < file_data->num_file_names; ++j)
4052         {
4053           const char *this_name = file_data->file_names[j];
4054           const char *this_real_name;
4055
4056           if (compare_filenames_for_search (this_name, name))
4057             {
4058               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4059                                         callback))
4060                 return true;
4061               continue;
4062             }
4063
4064           /* Before we invoke realpath, which can get expensive when many
4065              files are involved, do a quick comparison of the basenames.  */
4066           if (! basenames_may_differ
4067               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4068             continue;
4069
4070           this_real_name = dw2_get_real_path (objfile, file_data, j);
4071           if (compare_filenames_for_search (this_real_name, name))
4072             {
4073               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4074                                         callback))
4075                 return true;
4076               continue;
4077             }
4078
4079           if (real_path != NULL)
4080             {
4081               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4082               gdb_assert (IS_ABSOLUTE_PATH (name));
4083               if (this_real_name != NULL
4084                   && FILENAME_CMP (real_path, this_real_name) == 0)
4085                 {
4086                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4087                                             callback))
4088                     return true;
4089                   continue;
4090                 }
4091             }
4092         }
4093     }
4094
4095   return false;
4096 }
4097
4098 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4099
4100 struct dw2_symtab_iterator
4101 {
4102   /* The internalized form of .gdb_index.  */
4103   struct mapped_index *index;
4104   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4105   int want_specific_block;
4106   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4107      Unused if !WANT_SPECIFIC_BLOCK.  */
4108   int block_index;
4109   /* The kind of symbol we're looking for.  */
4110   domain_enum domain;
4111   /* The list of CUs from the index entry of the symbol,
4112      or NULL if not found.  */
4113   offset_type *vec;
4114   /* The next element in VEC to look at.  */
4115   int next;
4116   /* The number of elements in VEC, or zero if there is no match.  */
4117   int length;
4118   /* Have we seen a global version of the symbol?
4119      If so we can ignore all further global instances.
4120      This is to work around gold/15646, inefficient gold-generated
4121      indices.  */
4122   int global_seen;
4123 };
4124
4125 /* Initialize the index symtab iterator ITER.
4126    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4127    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4128
4129 static void
4130 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4131                       struct mapped_index *index,
4132                       int want_specific_block,
4133                       int block_index,
4134                       domain_enum domain,
4135                       const char *name)
4136 {
4137   iter->index = index;
4138   iter->want_specific_block = want_specific_block;
4139   iter->block_index = block_index;
4140   iter->domain = domain;
4141   iter->next = 0;
4142   iter->global_seen = 0;
4143
4144   if (find_slot_in_mapped_hash (index, name, &iter->vec))
4145     iter->length = MAYBE_SWAP (*iter->vec);
4146   else
4147     {
4148       iter->vec = NULL;
4149       iter->length = 0;
4150     }
4151 }
4152
4153 /* Return the next matching CU or NULL if there are no more.  */
4154
4155 static struct dwarf2_per_cu_data *
4156 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4157 {
4158   for ( ; iter->next < iter->length; ++iter->next)
4159     {
4160       offset_type cu_index_and_attrs =
4161         MAYBE_SWAP (iter->vec[iter->next + 1]);
4162       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4163       struct dwarf2_per_cu_data *per_cu;
4164       int want_static = iter->block_index != GLOBAL_BLOCK;
4165       /* This value is only valid for index versions >= 7.  */
4166       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4167       gdb_index_symbol_kind symbol_kind =
4168         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4169       /* Only check the symbol attributes if they're present.
4170          Indices prior to version 7 don't record them,
4171          and indices >= 7 may elide them for certain symbols
4172          (gold does this).  */
4173       int attrs_valid =
4174         (iter->index->version >= 7
4175          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4176
4177       /* Don't crash on bad data.  */
4178       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4179                        + dwarf2_per_objfile->n_type_units))
4180         {
4181           complaint (&symfile_complaints,
4182                      _(".gdb_index entry has bad CU index"
4183                        " [in module %s]"),
4184                      objfile_name (dwarf2_per_objfile->objfile));
4185           continue;
4186         }
4187
4188       per_cu = dw2_get_cutu (cu_index);
4189
4190       /* Skip if already read in.  */
4191       if (per_cu->v.quick->compunit_symtab)
4192         continue;
4193
4194       /* Check static vs global.  */
4195       if (attrs_valid)
4196         {
4197           if (iter->want_specific_block
4198               && want_static != is_static)
4199             continue;
4200           /* Work around gold/15646.  */
4201           if (!is_static && iter->global_seen)
4202             continue;
4203           if (!is_static)
4204             iter->global_seen = 1;
4205         }
4206
4207       /* Only check the symbol's kind if it has one.  */
4208       if (attrs_valid)
4209         {
4210           switch (iter->domain)
4211             {
4212             case VAR_DOMAIN:
4213               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4214                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4215                   /* Some types are also in VAR_DOMAIN.  */
4216                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4217                 continue;
4218               break;
4219             case STRUCT_DOMAIN:
4220               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4221                 continue;
4222               break;
4223             case LABEL_DOMAIN:
4224               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4225                 continue;
4226               break;
4227             default:
4228               break;
4229             }
4230         }
4231
4232       ++iter->next;
4233       return per_cu;
4234     }
4235
4236   return NULL;
4237 }
4238
4239 static struct compunit_symtab *
4240 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4241                    const char *name, domain_enum domain)
4242 {
4243   struct compunit_symtab *stab_best = NULL;
4244   struct mapped_index *index;
4245
4246   dw2_setup (objfile);
4247
4248   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4249
4250   index = dwarf2_per_objfile->index_table;
4251
4252   /* index is NULL if OBJF_READNOW.  */
4253   if (index)
4254     {
4255       struct dw2_symtab_iterator iter;
4256       struct dwarf2_per_cu_data *per_cu;
4257
4258       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
4259
4260       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4261         {
4262           struct symbol *sym, *with_opaque = NULL;
4263           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4264           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4265           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4266
4267           sym = block_find_symbol (block, name, domain,
4268                                    block_find_non_opaque_type_preferred,
4269                                    &with_opaque);
4270
4271           /* Some caution must be observed with overloaded functions
4272              and methods, since the index will not contain any overload
4273              information (but NAME might contain it).  */
4274
4275           if (sym != NULL
4276               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4277             return stab;
4278           if (with_opaque != NULL
4279               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4280             stab_best = stab;
4281
4282           /* Keep looking through other CUs.  */
4283         }
4284     }
4285
4286   return stab_best;
4287 }
4288
4289 static void
4290 dw2_print_stats (struct objfile *objfile)
4291 {
4292   int i, total, count;
4293
4294   dw2_setup (objfile);
4295   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4296   count = 0;
4297   for (i = 0; i < total; ++i)
4298     {
4299       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4300
4301       if (!per_cu->v.quick->compunit_symtab)
4302         ++count;
4303     }
4304   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4305   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4306 }
4307
4308 /* This dumps minimal information about the index.
4309    It is called via "mt print objfiles".
4310    One use is to verify .gdb_index has been loaded by the
4311    gdb.dwarf2/gdb-index.exp testcase.  */
4312
4313 static void
4314 dw2_dump (struct objfile *objfile)
4315 {
4316   dw2_setup (objfile);
4317   gdb_assert (dwarf2_per_objfile->using_index);
4318   printf_filtered (".gdb_index:");
4319   if (dwarf2_per_objfile->index_table != NULL)
4320     {
4321       printf_filtered (" version %d\n",
4322                        dwarf2_per_objfile->index_table->version);
4323     }
4324   else
4325     printf_filtered (" faked for \"readnow\"\n");
4326   printf_filtered ("\n");
4327 }
4328
4329 static void
4330 dw2_relocate (struct objfile *objfile,
4331               const struct section_offsets *new_offsets,
4332               const struct section_offsets *delta)
4333 {
4334   /* There's nothing to relocate here.  */
4335 }
4336
4337 static void
4338 dw2_expand_symtabs_for_function (struct objfile *objfile,
4339                                  const char *func_name)
4340 {
4341   struct mapped_index *index;
4342
4343   dw2_setup (objfile);
4344
4345   index = dwarf2_per_objfile->index_table;
4346
4347   /* index is NULL if OBJF_READNOW.  */
4348   if (index)
4349     {
4350       struct dw2_symtab_iterator iter;
4351       struct dwarf2_per_cu_data *per_cu;
4352
4353       /* Note: It doesn't matter what we pass for block_index here.  */
4354       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4355                             func_name);
4356
4357       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4358         dw2_instantiate_symtab (per_cu);
4359     }
4360 }
4361
4362 static void
4363 dw2_expand_all_symtabs (struct objfile *objfile)
4364 {
4365   int i;
4366
4367   dw2_setup (objfile);
4368
4369   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4370                    + dwarf2_per_objfile->n_type_units); ++i)
4371     {
4372       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4373
4374       dw2_instantiate_symtab (per_cu);
4375     }
4376 }
4377
4378 static void
4379 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4380                                   const char *fullname)
4381 {
4382   int i;
4383
4384   dw2_setup (objfile);
4385
4386   /* We don't need to consider type units here.
4387      This is only called for examining code, e.g. expand_line_sal.
4388      There can be an order of magnitude (or more) more type units
4389      than comp units, and we avoid them if we can.  */
4390
4391   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4392     {
4393       int j;
4394       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4395       struct quick_file_names *file_data;
4396
4397       /* We only need to look at symtabs not already expanded.  */
4398       if (per_cu->v.quick->compunit_symtab)
4399         continue;
4400
4401       file_data = dw2_get_file_names (per_cu);
4402       if (file_data == NULL)
4403         continue;
4404
4405       for (j = 0; j < file_data->num_file_names; ++j)
4406         {
4407           const char *this_fullname = file_data->file_names[j];
4408
4409           if (filename_cmp (this_fullname, fullname) == 0)
4410             {
4411               dw2_instantiate_symtab (per_cu);
4412               break;
4413             }
4414         }
4415     }
4416 }
4417
4418 static void
4419 dw2_map_matching_symbols (struct objfile *objfile,
4420                           const char * name, domain_enum domain,
4421                           int global,
4422                           int (*callback) (struct block *,
4423                                            struct symbol *, void *),
4424                           void *data, symbol_name_match_type match,
4425                           symbol_compare_ftype *ordered_compare)
4426 {
4427   /* Currently unimplemented; used for Ada.  The function can be called if the
4428      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4429      does not look for non-Ada symbols this function should just return.  */
4430 }
4431
4432 /* Symbol name matcher for .gdb_index names.
4433
4434    Symbol names in .gdb_index have a few particularities:
4435
4436    - There's no indication of which is the language of each symbol.
4437
4438      Since each language has its own symbol name matching algorithm,
4439      and we don't know which language is the right one, we must match
4440      each symbol against all languages.  This would be a potential
4441      performance problem if it were not mitigated by the
4442      mapped_index::name_components lookup table, which significantly
4443      reduces the number of times we need to call into this matcher,
4444      making it a non-issue.
4445
4446    - Symbol names in the index have no overload (parameter)
4447      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4448      appear as "foo" in the index, for example.
4449
4450      This means that the lookup names passed to the symbol name
4451      matcher functions must have no parameter information either
4452      because (e.g.) symbol search name "foo" does not match
4453      lookup-name "foo(int)" [while swapping search name for lookup
4454      name would match].
4455 */
4456 class gdb_index_symbol_name_matcher
4457 {
4458 public:
4459   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4460   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4461
4462   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4463      Returns true if any matcher matches.  */
4464   bool matches (const char *symbol_name);
4465
4466 private:
4467   /* A reference to the lookup name we're matching against.  */
4468   const lookup_name_info &m_lookup_name;
4469
4470   /* A vector holding all the different symbol name matchers, for all
4471      languages.  */
4472   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4473 };
4474
4475 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4476   (const lookup_name_info &lookup_name)
4477     : m_lookup_name (lookup_name)
4478 {
4479   /* Prepare the vector of comparison functions upfront, to avoid
4480      doing the same work for each symbol.  Care is taken to avoid
4481      matching with the same matcher more than once if/when multiple
4482      languages use the same matcher function.  */
4483   auto &matchers = m_symbol_name_matcher_funcs;
4484   matchers.reserve (nr_languages);
4485
4486   matchers.push_back (default_symbol_name_matcher);
4487
4488   for (int i = 0; i < nr_languages; i++)
4489     {
4490       const language_defn *lang = language_def ((enum language) i);
4491       if (lang->la_get_symbol_name_matcher != NULL)
4492         {
4493           symbol_name_matcher_ftype *name_matcher
4494             = lang->la_get_symbol_name_matcher (m_lookup_name);
4495
4496           /* Don't insert the same comparison routine more than once.
4497              Note that we do this linear walk instead of a cheaper
4498              sorted insert, or use a std::set or something like that,
4499              because relative order of function addresses is not
4500              stable.  This is not a problem in practice because the
4501              number of supported languages is low, and the cost here
4502              is tiny compared to the number of searches we'll do
4503              afterwards using this object.  */
4504           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4505               == matchers.end ())
4506             matchers.push_back (name_matcher);
4507         }
4508     }
4509 }
4510
4511 bool
4512 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4513 {
4514   for (auto matches_name : m_symbol_name_matcher_funcs)
4515     if (matches_name (symbol_name, m_lookup_name, NULL))
4516       return true;
4517
4518   return false;
4519 }
4520
4521 /* Starting from a search name, return the string that finds the upper
4522    bound of all strings that start with SEARCH_NAME in a sorted name
4523    list.  Returns the empty string to indicate that the upper bound is
4524    the end of the list.  */
4525
4526 static std::string
4527 make_sort_after_prefix_name (const char *search_name)
4528 {
4529   /* When looking to complete "func", we find the upper bound of all
4530      symbols that start with "func" by looking for where we'd insert
4531      the closest string that would follow "func" in lexicographical
4532      order.  Usually, that's "func"-with-last-character-incremented,
4533      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4534      will be UTF-8 multi-byte sequences, but we can't be certain.
4535      Especially mind the 0xff character, which is a valid character in
4536      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4537      rule out compilers allowing it in identifiers.  Note that
4538      conveniently, strcmp/strcasecmp are specified to compare
4539      characters interpreted as unsigned char.  So what we do is treat
4540      the whole string as a base 256 number composed of a sequence of
4541      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4542      to 0, and carries 1 to the following more-significant position.
4543      If the very first character in SEARCH_NAME ends up incremented
4544      and carries/overflows, then the upper bound is the end of the
4545      list.  The string after the empty string is also the empty
4546      string.
4547
4548      Some examples of this operation:
4549
4550        SEARCH_NAME  => "+1" RESULT
4551
4552        "abc"              => "abd"
4553        "ab\xff"           => "ac"
4554        "\xff" "a" "\xff"  => "\xff" "b"
4555        "\xff"             => ""
4556        "\xff\xff"         => ""
4557        ""                 => ""
4558
4559      Then, with these symbols for example:
4560
4561       func
4562       func1
4563       fund
4564
4565      completing "func" looks for symbols between "func" and
4566      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4567      which finds "func" and "func1", but not "fund".
4568
4569      And with:
4570
4571       funcÿ     (Latin1 'ÿ' [0xff])
4572       funcÿ1
4573       fund
4574
4575      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4576      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4577
4578      And with:
4579
4580       ÿÿ        (Latin1 'ÿ' [0xff])
4581       ÿÿ1
4582
4583      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4584      the end of the list.
4585   */
4586   std::string after = search_name;
4587   while (!after.empty () && (unsigned char) after.back () == 0xff)
4588     after.pop_back ();
4589   if (!after.empty ())
4590     after.back () = (unsigned char) after.back () + 1;
4591   return after;
4592 }
4593
4594 /* See declaration.  */
4595
4596 std::pair<std::vector<name_component>::const_iterator,
4597           std::vector<name_component>::const_iterator>
4598 mapped_index::find_name_components_bounds
4599   (const lookup_name_info &lookup_name_without_params) const
4600 {
4601   auto *name_cmp
4602     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4603
4604   const char *cplus
4605     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4606
4607   /* Comparison function object for lower_bound that matches against a
4608      given symbol name.  */
4609   auto lookup_compare_lower = [&] (const name_component &elem,
4610                                    const char *name)
4611     {
4612       const char *elem_qualified = this->symbol_name_at (elem.idx);
4613       const char *elem_name = elem_qualified + elem.name_offset;
4614       return name_cmp (elem_name, name) < 0;
4615     };
4616
4617   /* Comparison function object for upper_bound that matches against a
4618      given symbol name.  */
4619   auto lookup_compare_upper = [&] (const char *name,
4620                                    const name_component &elem)
4621     {
4622       const char *elem_qualified = this->symbol_name_at (elem.idx);
4623       const char *elem_name = elem_qualified + elem.name_offset;
4624       return name_cmp (name, elem_name) < 0;
4625     };
4626
4627   auto begin = this->name_components.begin ();
4628   auto end = this->name_components.end ();
4629
4630   /* Find the lower bound.  */
4631   auto lower = [&] ()
4632     {
4633       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4634         return begin;
4635       else
4636         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4637     } ();
4638
4639   /* Find the upper bound.  */
4640   auto upper = [&] ()
4641     {
4642       if (lookup_name_without_params.completion_mode ())
4643         {
4644           /* In completion mode, we want UPPER to point past all
4645              symbols names that have the same prefix.  I.e., with
4646              these symbols, and completing "func":
4647
4648               function        << lower bound
4649               function1
4650               other_function  << upper bound
4651
4652              We find the upper bound by looking for the insertion
4653              point of "func"-with-last-character-incremented,
4654              i.e. "fund".  */
4655           std::string after = make_sort_after_prefix_name (cplus);
4656           if (after.empty ())
4657             return end;
4658           return std::lower_bound (lower, end, after.c_str (),
4659                                    lookup_compare_lower);
4660         }
4661       else
4662         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4663     } ();
4664
4665   return {lower, upper};
4666 }
4667
4668 /* See declaration.  */
4669
4670 void
4671 mapped_index::build_name_components ()
4672 {
4673   if (!this->name_components.empty ())
4674     return;
4675
4676   this->name_components_casing = case_sensitivity;
4677   auto *name_cmp
4678     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4679
4680   /* The code below only knows how to break apart components of C++
4681      symbol names (and other languages that use '::' as
4682      namespace/module separator).  If we add support for wild matching
4683      to some language that uses some other operator (E.g., Ada, Go and
4684      D use '.'), then we'll need to try splitting the symbol name
4685      according to that language too.  Note that Ada does support wild
4686      matching, but doesn't currently support .gdb_index.  */
4687   for (offset_type idx = 0; idx < this->symbol_table.size (); ++idx)
4688     {
4689       auto &bucket = this->symbol_table[idx];
4690
4691       if (bucket.name == 0 && bucket.vec == 0)
4692         continue;
4693
4694       const char *name = this->symbol_name_at (idx);
4695
4696       /* Add each name component to the name component table.  */
4697       unsigned int previous_len = 0;
4698       for (unsigned int current_len = cp_find_first_component (name);
4699            name[current_len] != '\0';
4700            current_len += cp_find_first_component (name + current_len))
4701         {
4702           gdb_assert (name[current_len] == ':');
4703           this->name_components.push_back ({previous_len, idx});
4704           /* Skip the '::'.  */
4705           current_len += 2;
4706           previous_len = current_len;
4707         }
4708       this->name_components.push_back ({previous_len, idx});
4709     }
4710
4711   /* Sort name_components elements by name.  */
4712   auto name_comp_compare = [&] (const name_component &left,
4713                                 const name_component &right)
4714     {
4715       const char *left_qualified = this->symbol_name_at (left.idx);
4716       const char *right_qualified = this->symbol_name_at (right.idx);
4717
4718       const char *left_name = left_qualified + left.name_offset;
4719       const char *right_name = right_qualified + right.name_offset;
4720
4721       return name_cmp (left_name, right_name) < 0;
4722     };
4723
4724   std::sort (this->name_components.begin (),
4725              this->name_components.end (),
4726              name_comp_compare);
4727 }
4728
4729 /* Helper for dw2_expand_symtabs_matching that works with a
4730    mapped_index instead of the containing objfile.  This is split to a
4731    separate function in order to be able to unit test the
4732    name_components matching using a mock mapped_index.  For each
4733    symbol name that matches, calls MATCH_CALLBACK, passing it the
4734    symbol's index in the mapped_index symbol table.  */
4735
4736 static void
4737 dw2_expand_symtabs_matching_symbol
4738   (mapped_index &index,
4739    const lookup_name_info &lookup_name_in,
4740    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4741    enum search_domain kind,
4742    gdb::function_view<void (offset_type)> match_callback)
4743 {
4744   lookup_name_info lookup_name_without_params
4745     = lookup_name_in.make_ignore_params ();
4746   gdb_index_symbol_name_matcher lookup_name_matcher
4747     (lookup_name_without_params);
4748
4749   /* Build the symbol name component sorted vector, if we haven't
4750      yet.  */
4751   index.build_name_components ();
4752
4753   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4754
4755   /* Now for each symbol name in range, check to see if we have a name
4756      match, and if so, call the MATCH_CALLBACK callback.  */
4757
4758   /* The same symbol may appear more than once in the range though.
4759      E.g., if we're looking for symbols that complete "w", and we have
4760      a symbol named "w1::w2", we'll find the two name components for
4761      that same symbol in the range.  To be sure we only call the
4762      callback once per symbol, we first collect the symbol name
4763      indexes that matched in a temporary vector and ignore
4764      duplicates.  */
4765   std::vector<offset_type> matches;
4766   matches.reserve (std::distance (bounds.first, bounds.second));
4767
4768   for (; bounds.first != bounds.second; ++bounds.first)
4769     {
4770       const char *qualified = index.symbol_name_at (bounds.first->idx);
4771
4772       if (!lookup_name_matcher.matches (qualified)
4773           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4774         continue;
4775
4776       matches.push_back (bounds.first->idx);
4777     }
4778
4779   std::sort (matches.begin (), matches.end ());
4780
4781   /* Finally call the callback, once per match.  */
4782   ULONGEST prev = -1;
4783   for (offset_type idx : matches)
4784     {
4785       if (prev != idx)
4786         {
4787           match_callback (idx);
4788           prev = idx;
4789         }
4790     }
4791
4792   /* Above we use a type wider than idx's for 'prev', since 0 and
4793      (offset_type)-1 are both possible values.  */
4794   static_assert (sizeof (prev) > sizeof (offset_type), "");
4795 }
4796
4797 #if GDB_SELF_TEST
4798
4799 namespace selftests { namespace dw2_expand_symtabs_matching {
4800
4801 /* A wrapper around mapped_index that builds a mock mapped_index, from
4802    the symbol list passed as parameter to the constructor.  */
4803 class mock_mapped_index
4804 {
4805 public:
4806   template<size_t N>
4807   mock_mapped_index (const char *(&symbols)[N])
4808     : mock_mapped_index (symbols, N)
4809   {}
4810
4811   /* Access the built index.  */
4812   mapped_index &index ()
4813   { return m_index; }
4814
4815   /* Disable copy.  */
4816   mock_mapped_index(const mock_mapped_index &) = delete;
4817   void operator= (const mock_mapped_index &) = delete;
4818
4819 private:
4820   mock_mapped_index (const char **symbols, size_t symbols_size)
4821   {
4822     /* No string can live at offset zero.  Add a dummy entry.  */
4823     obstack_grow_str0 (&m_constant_pool, "");
4824
4825     for (size_t i = 0; i < symbols_size; i++)
4826       {
4827         const char *sym = symbols[i];
4828         size_t offset = obstack_object_size (&m_constant_pool);
4829         obstack_grow_str0 (&m_constant_pool, sym);
4830         m_symbol_table.push_back ({offset, 0});
4831       };
4832
4833     m_index.constant_pool = (const char *) obstack_base (&m_constant_pool);
4834     m_index.symbol_table = m_symbol_table;
4835   }
4836
4837 public:
4838   /* The built mapped_index.  */
4839   mapped_index m_index{};
4840
4841   /* The storage that the built mapped_index uses for symbol and
4842      constant pool tables.  */
4843   std::vector<mapped_index::symbol_table_slot> m_symbol_table;
4844   auto_obstack m_constant_pool;
4845 };
4846
4847 /* Convenience function that converts a NULL pointer to a "<null>"
4848    string, to pass to print routines.  */
4849
4850 static const char *
4851 string_or_null (const char *str)
4852 {
4853   return str != NULL ? str : "<null>";
4854 }
4855
4856 /* Check if a lookup_name_info built from
4857    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4858    index.  EXPECTED_LIST is the list of expected matches, in expected
4859    matching order.  If no match expected, then an empty list is
4860    specified.  Returns true on success.  On failure prints a warning
4861    indicating the file:line that failed, and returns false.  */
4862
4863 static bool
4864 check_match (const char *file, int line,
4865              mock_mapped_index &mock_index,
4866              const char *name, symbol_name_match_type match_type,
4867              bool completion_mode,
4868              std::initializer_list<const char *> expected_list)
4869 {
4870   lookup_name_info lookup_name (name, match_type, completion_mode);
4871
4872   bool matched = true;
4873
4874   auto mismatch = [&] (const char *expected_str,
4875                        const char *got)
4876   {
4877     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4878                "expected=\"%s\", got=\"%s\"\n"),
4879              file, line,
4880              (match_type == symbol_name_match_type::FULL
4881               ? "FULL" : "WILD"),
4882              name, string_or_null (expected_str), string_or_null (got));
4883     matched = false;
4884   };
4885
4886   auto expected_it = expected_list.begin ();
4887   auto expected_end = expected_list.end ();
4888
4889   dw2_expand_symtabs_matching_symbol (mock_index.index (), lookup_name,
4890                                       NULL, ALL_DOMAIN,
4891                                       [&] (offset_type idx)
4892   {
4893     const char *matched_name = mock_index.index ().symbol_name_at (idx);
4894     const char *expected_str
4895       = expected_it == expected_end ? NULL : *expected_it++;
4896
4897     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4898       mismatch (expected_str, matched_name);
4899   });
4900
4901   const char *expected_str
4902   = expected_it == expected_end ? NULL : *expected_it++;
4903   if (expected_str != NULL)
4904     mismatch (expected_str, NULL);
4905
4906   return matched;
4907 }
4908
4909 /* The symbols added to the mock mapped_index for testing (in
4910    canonical form).  */
4911 static const char *test_symbols[] = {
4912   "function",
4913   "std::bar",
4914   "std::zfunction",
4915   "std::zfunction2",
4916   "w1::w2",
4917   "ns::foo<char*>",
4918   "ns::foo<int>",
4919   "ns::foo<long>",
4920   "ns2::tmpl<int>::foo2",
4921   "(anonymous namespace)::A::B::C",
4922
4923   /* These are used to check that the increment-last-char in the
4924      matching algorithm for completion doesn't match "t1_fund" when
4925      completing "t1_func".  */
4926   "t1_func",
4927   "t1_func1",
4928   "t1_fund",
4929   "t1_fund1",
4930
4931   /* A UTF-8 name with multi-byte sequences to make sure that
4932      cp-name-parser understands this as a single identifier ("função"
4933      is "function" in PT).  */
4934   u8"u8função",
4935
4936   /* \377 (0xff) is Latin1 'ÿ'.  */
4937   "yfunc\377",
4938
4939   /* \377 (0xff) is Latin1 'ÿ'.  */
4940   "\377",
4941   "\377\377123",
4942
4943   /* A name with all sorts of complications.  Starts with "z" to make
4944      it easier for the completion tests below.  */
4945 #define Z_SYM_NAME \
4946   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4947     "::tuple<(anonymous namespace)::ui*, " \
4948     "std::default_delete<(anonymous namespace)::ui>, void>"
4949
4950   Z_SYM_NAME
4951 };
4952
4953 /* Returns true if the mapped_index::find_name_component_bounds method
4954    finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME, in
4955    completion mode.  */
4956
4957 static bool
4958 check_find_bounds_finds (mapped_index &index,
4959                          const char *search_name,
4960                          gdb::array_view<const char *> expected_syms)
4961 {
4962   lookup_name_info lookup_name (search_name,
4963                                 symbol_name_match_type::FULL, true);
4964
4965   auto bounds = index.find_name_components_bounds (lookup_name);
4966
4967   size_t distance = std::distance (bounds.first, bounds.second);
4968   if (distance != expected_syms.size ())
4969     return false;
4970
4971   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4972     {
4973       auto nc_elem = bounds.first + exp_elem;
4974       const char *qualified = index.symbol_name_at (nc_elem->idx);
4975       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4976         return false;
4977     }
4978
4979   return true;
4980 }
4981
4982 /* Test the lower-level mapped_index::find_name_component_bounds
4983    method.  */
4984
4985 static void
4986 test_mapped_index_find_name_component_bounds ()
4987 {
4988   mock_mapped_index mock_index (test_symbols);
4989
4990   mock_index.index ().build_name_components ();
4991
4992   /* Test the lower-level mapped_index::find_name_component_bounds
4993      method in completion mode.  */
4994   {
4995     static const char *expected_syms[] = {
4996       "t1_func",
4997       "t1_func1",
4998     };
4999
5000     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
5001                                          "t1_func", expected_syms));
5002   }
5003
5004   /* Check that the increment-last-char in the name matching algorithm
5005      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5006   {
5007     static const char *expected_syms1[] = {
5008       "\377",
5009       "\377\377123",
5010     };
5011     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
5012                                          "\377", expected_syms1));
5013
5014     static const char *expected_syms2[] = {
5015       "\377\377123",
5016     };
5017     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
5018                                          "\377\377", expected_syms2));
5019   }
5020 }
5021
5022 /* Test dw2_expand_symtabs_matching_symbol.  */
5023
5024 static void
5025 test_dw2_expand_symtabs_matching_symbol ()
5026 {
5027   mock_mapped_index mock_index (test_symbols);
5028
5029   /* We let all tests run until the end even if some fails, for debug
5030      convenience.  */
5031   bool any_mismatch = false;
5032
5033   /* Create the expected symbols list (an initializer_list).  Needed
5034      because lists have commas, and we need to pass them to CHECK,
5035      which is a macro.  */
5036 #define EXPECT(...) { __VA_ARGS__ }
5037
5038   /* Wrapper for check_match that passes down the current
5039      __FILE__/__LINE__.  */
5040 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5041   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5042                                 mock_index,                             \
5043                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5044                                 EXPECTED_LIST)
5045
5046   /* Identity checks.  */
5047   for (const char *sym : test_symbols)
5048     {
5049       /* Should be able to match all existing symbols.  */
5050       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5051                    EXPECT (sym));
5052
5053       /* Should be able to match all existing symbols with
5054          parameters.  */
5055       std::string with_params = std::string (sym) + "(int)";
5056       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5057                    EXPECT (sym));
5058
5059       /* Should be able to match all existing symbols with
5060          parameters and qualifiers.  */
5061       with_params = std::string (sym) + " ( int ) const";
5062       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5063                    EXPECT (sym));
5064
5065       /* This should really find sym, but cp-name-parser.y doesn't
5066          know about lvalue/rvalue qualifiers yet.  */
5067       with_params = std::string (sym) + " ( int ) &&";
5068       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5069                    {});
5070     }
5071
5072   /* Check that the name matching algorithm for completion doesn't get
5073      confused with Latin1 'ÿ' / 0xff.  */
5074   {
5075     static const char str[] = "\377";
5076     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5077                  EXPECT ("\377", "\377\377123"));
5078   }
5079
5080   /* Check that the increment-last-char in the matching algorithm for
5081      completion doesn't match "t1_fund" when completing "t1_func".  */
5082   {
5083     static const char str[] = "t1_func";
5084     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5085                  EXPECT ("t1_func", "t1_func1"));
5086   }
5087
5088   /* Check that completion mode works at each prefix of the expected
5089      symbol name.  */
5090   {
5091     static const char str[] = "function(int)";
5092     size_t len = strlen (str);
5093     std::string lookup;
5094
5095     for (size_t i = 1; i < len; i++)
5096       {
5097         lookup.assign (str, i);
5098         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5099                      EXPECT ("function"));
5100       }
5101   }
5102
5103   /* While "w" is a prefix of both components, the match function
5104      should still only be called once.  */
5105   {
5106     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5107                  EXPECT ("w1::w2"));
5108     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5109                  EXPECT ("w1::w2"));
5110   }
5111
5112   /* Same, with a "complicated" symbol.  */
5113   {
5114     static const char str[] = Z_SYM_NAME;
5115     size_t len = strlen (str);
5116     std::string lookup;
5117
5118     for (size_t i = 1; i < len; i++)
5119       {
5120         lookup.assign (str, i);
5121         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5122                      EXPECT (Z_SYM_NAME));
5123       }
5124   }
5125
5126   /* In FULL mode, an incomplete symbol doesn't match.  */
5127   {
5128     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5129                  {});
5130   }
5131
5132   /* A complete symbol with parameters matches any overload, since the
5133      index has no overload info.  */
5134   {
5135     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5136                  EXPECT ("std::zfunction", "std::zfunction2"));
5137     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5138                  EXPECT ("std::zfunction", "std::zfunction2"));
5139     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5140                  EXPECT ("std::zfunction", "std::zfunction2"));
5141   }
5142
5143   /* Check that whitespace is ignored appropriately.  A symbol with a
5144      template argument list. */
5145   {
5146     static const char expected[] = "ns::foo<int>";
5147     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5148                  EXPECT (expected));
5149     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5150                  EXPECT (expected));
5151   }
5152
5153   /* Check that whitespace is ignored appropriately.  A symbol with a
5154      template argument list that includes a pointer.  */
5155   {
5156     static const char expected[] = "ns::foo<char*>";
5157     /* Try both completion and non-completion modes.  */
5158     static const bool completion_mode[2] = {false, true};
5159     for (size_t i = 0; i < 2; i++)
5160       {
5161         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5162                      completion_mode[i], EXPECT (expected));
5163         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5164                      completion_mode[i], EXPECT (expected));
5165
5166         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5167                      completion_mode[i], EXPECT (expected));
5168         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5169                      completion_mode[i], EXPECT (expected));
5170       }
5171   }
5172
5173   {
5174     /* Check method qualifiers are ignored.  */
5175     static const char expected[] = "ns::foo<char*>";
5176     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5177                  symbol_name_match_type::FULL, true, EXPECT (expected));
5178     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5179                  symbol_name_match_type::FULL, true, EXPECT (expected));
5180     CHECK_MATCH ("foo < char * >  ( int ) const",
5181                  symbol_name_match_type::WILD, true, EXPECT (expected));
5182     CHECK_MATCH ("foo < char * >  ( int ) &&",
5183                  symbol_name_match_type::WILD, true, EXPECT (expected));
5184   }
5185
5186   /* Test lookup names that don't match anything.  */
5187   {
5188     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5189                  {});
5190
5191     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5192                  {});
5193   }
5194
5195   /* Some wild matching tests, exercising "(anonymous namespace)",
5196      which should not be confused with a parameter list.  */
5197   {
5198     static const char *syms[] = {
5199       "A::B::C",
5200       "B::C",
5201       "C",
5202       "A :: B :: C ( int )",
5203       "B :: C ( int )",
5204       "C ( int )",
5205     };
5206
5207     for (const char *s : syms)
5208       {
5209         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5210                      EXPECT ("(anonymous namespace)::A::B::C"));
5211       }
5212   }
5213
5214   {
5215     static const char expected[] = "ns2::tmpl<int>::foo2";
5216     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5217                  EXPECT (expected));
5218     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5219                  EXPECT (expected));
5220   }
5221
5222   SELF_CHECK (!any_mismatch);
5223
5224 #undef EXPECT
5225 #undef CHECK_MATCH
5226 }
5227
5228 static void
5229 run_test ()
5230 {
5231   test_mapped_index_find_name_component_bounds ();
5232   test_dw2_expand_symtabs_matching_symbol ();
5233 }
5234
5235 }} // namespace selftests::dw2_expand_symtabs_matching
5236
5237 #endif /* GDB_SELF_TEST */
5238
5239 /* If FILE_MATCHER is NULL or if PER_CU has
5240    dwarf2_per_cu_quick_data::MARK set (see
5241    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5242    EXPANSION_NOTIFY on it.  */
5243
5244 static void
5245 dw2_expand_symtabs_matching_one
5246   (struct dwarf2_per_cu_data *per_cu,
5247    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5248    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5249 {
5250   if (file_matcher == NULL || per_cu->v.quick->mark)
5251     {
5252       bool symtab_was_null
5253         = (per_cu->v.quick->compunit_symtab == NULL);
5254
5255       dw2_instantiate_symtab (per_cu);
5256
5257       if (expansion_notify != NULL
5258           && symtab_was_null
5259           && per_cu->v.quick->compunit_symtab != NULL)
5260         expansion_notify (per_cu->v.quick->compunit_symtab);
5261     }
5262 }
5263
5264 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5265    matched, to expand corresponding CUs that were marked.  IDX is the
5266    index of the symbol name that matched.  */
5267
5268 static void
5269 dw2_expand_marked_cus
5270   (mapped_index &index, offset_type idx,
5271    struct objfile *objfile,
5272    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5273    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5274    search_domain kind)
5275 {
5276   offset_type *vec, vec_len, vec_idx;
5277   bool global_seen = false;
5278
5279   vec = (offset_type *) (index.constant_pool
5280                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5281   vec_len = MAYBE_SWAP (vec[0]);
5282   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5283     {
5284       struct dwarf2_per_cu_data *per_cu;
5285       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5286       /* This value is only valid for index versions >= 7.  */
5287       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5288       gdb_index_symbol_kind symbol_kind =
5289         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5290       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5291       /* Only check the symbol attributes if they're present.
5292          Indices prior to version 7 don't record them,
5293          and indices >= 7 may elide them for certain symbols
5294          (gold does this).  */
5295       int attrs_valid =
5296         (index.version >= 7
5297          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5298
5299       /* Work around gold/15646.  */
5300       if (attrs_valid)
5301         {
5302           if (!is_static && global_seen)
5303             continue;
5304           if (!is_static)
5305             global_seen = true;
5306         }
5307
5308       /* Only check the symbol's kind if it has one.  */
5309       if (attrs_valid)
5310         {
5311           switch (kind)
5312             {
5313             case VARIABLES_DOMAIN:
5314               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5315                 continue;
5316               break;
5317             case FUNCTIONS_DOMAIN:
5318               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5319                 continue;
5320               break;
5321             case TYPES_DOMAIN:
5322               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5323                 continue;
5324               break;
5325             default:
5326               break;
5327             }
5328         }
5329
5330       /* Don't crash on bad data.  */
5331       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5332                        + dwarf2_per_objfile->n_type_units))
5333         {
5334           complaint (&symfile_complaints,
5335                      _(".gdb_index entry has bad CU index"
5336                        " [in module %s]"), objfile_name (objfile));
5337           continue;
5338         }
5339
5340       per_cu = dw2_get_cutu (cu_index);
5341       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5342                                        expansion_notify);
5343     }
5344 }
5345
5346 /* If FILE_MATCHER is non-NULL, set all the
5347    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5348    that match FILE_MATCHER.  */
5349
5350 static void
5351 dw_expand_symtabs_matching_file_matcher
5352   (gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5353 {
5354   if (file_matcher == NULL)
5355     return;
5356
5357   objfile *const objfile = dwarf2_per_objfile->objfile;
5358
5359   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5360                                             htab_eq_pointer,
5361                                             NULL, xcalloc, xfree));
5362   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5363                                                 htab_eq_pointer,
5364                                                 NULL, xcalloc, xfree));
5365
5366   /* The rule is CUs specify all the files, including those used by
5367      any TU, so there's no need to scan TUs here.  */
5368
5369   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5370     {
5371       int j;
5372       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5373       struct quick_file_names *file_data;
5374       void **slot;
5375
5376       QUIT;
5377
5378       per_cu->v.quick->mark = 0;
5379
5380       /* We only need to look at symtabs not already expanded.  */
5381       if (per_cu->v.quick->compunit_symtab)
5382         continue;
5383
5384       file_data = dw2_get_file_names (per_cu);
5385       if (file_data == NULL)
5386         continue;
5387
5388       if (htab_find (visited_not_found.get (), file_data) != NULL)
5389         continue;
5390       else if (htab_find (visited_found.get (), file_data) != NULL)
5391         {
5392           per_cu->v.quick->mark = 1;
5393           continue;
5394         }
5395
5396       for (j = 0; j < file_data->num_file_names; ++j)
5397         {
5398           const char *this_real_name;
5399
5400           if (file_matcher (file_data->file_names[j], false))
5401             {
5402               per_cu->v.quick->mark = 1;
5403               break;
5404             }
5405
5406           /* Before we invoke realpath, which can get expensive when many
5407              files are involved, do a quick comparison of the basenames.  */
5408           if (!basenames_may_differ
5409               && !file_matcher (lbasename (file_data->file_names[j]),
5410                                 true))
5411             continue;
5412
5413           this_real_name = dw2_get_real_path (objfile, file_data, j);
5414           if (file_matcher (this_real_name, false))
5415             {
5416               per_cu->v.quick->mark = 1;
5417               break;
5418             }
5419         }
5420
5421       slot = htab_find_slot (per_cu->v.quick->mark
5422                              ? visited_found.get ()
5423                              : visited_not_found.get (),
5424                              file_data, INSERT);
5425       *slot = file_data;
5426     }
5427 }
5428
5429 static void
5430 dw2_expand_symtabs_matching
5431   (struct objfile *objfile,
5432    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5433    const lookup_name_info &lookup_name,
5434    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5435    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5436    enum search_domain kind)
5437 {
5438   int i;
5439
5440   dw2_setup (objfile);
5441
5442   /* index_table is NULL if OBJF_READNOW.  */
5443   if (!dwarf2_per_objfile->index_table)
5444     return;
5445
5446   dw_expand_symtabs_matching_file_matcher (file_matcher);
5447
5448   mapped_index &index = *dwarf2_per_objfile->index_table;
5449
5450   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5451                                       symbol_matcher,
5452                                       kind, [&] (offset_type idx)
5453     {
5454       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
5455                              expansion_notify, kind);
5456     });
5457 }
5458
5459 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5460    symtab.  */
5461
5462 static struct compunit_symtab *
5463 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5464                                           CORE_ADDR pc)
5465 {
5466   int i;
5467
5468   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5469       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5470     return cust;
5471
5472   if (cust->includes == NULL)
5473     return NULL;
5474
5475   for (i = 0; cust->includes[i]; ++i)
5476     {
5477       struct compunit_symtab *s = cust->includes[i];
5478
5479       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5480       if (s != NULL)
5481         return s;
5482     }
5483
5484   return NULL;
5485 }
5486
5487 static struct compunit_symtab *
5488 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5489                                   struct bound_minimal_symbol msymbol,
5490                                   CORE_ADDR pc,
5491                                   struct obj_section *section,
5492                                   int warn_if_readin)
5493 {
5494   struct dwarf2_per_cu_data *data;
5495   struct compunit_symtab *result;
5496
5497   dw2_setup (objfile);
5498
5499   if (!objfile->psymtabs_addrmap)
5500     return NULL;
5501
5502   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5503                                                      pc);
5504   if (!data)
5505     return NULL;
5506
5507   if (warn_if_readin && data->v.quick->compunit_symtab)
5508     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5509              paddress (get_objfile_arch (objfile), pc));
5510
5511   result
5512     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5513                                                 pc);
5514   gdb_assert (result != NULL);
5515   return result;
5516 }
5517
5518 static void
5519 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5520                           void *data, int need_fullname)
5521 {
5522   dw2_setup (objfile);
5523
5524   if (!dwarf2_per_objfile->filenames_cache)
5525     {
5526       dwarf2_per_objfile->filenames_cache.emplace ();
5527
5528       htab_up visited (htab_create_alloc (10,
5529                                           htab_hash_pointer, htab_eq_pointer,
5530                                           NULL, xcalloc, xfree));
5531
5532       /* The rule is CUs specify all the files, including those used
5533          by any TU, so there's no need to scan TUs here.  We can
5534          ignore file names coming from already-expanded CUs.  */
5535
5536       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5537         {
5538           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5539
5540           if (per_cu->v.quick->compunit_symtab)
5541             {
5542               void **slot = htab_find_slot (visited.get (),
5543                                             per_cu->v.quick->file_names,
5544                                             INSERT);
5545
5546               *slot = per_cu->v.quick->file_names;
5547             }
5548         }
5549
5550       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5551         {
5552           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5553           struct quick_file_names *file_data;
5554           void **slot;
5555
5556           /* We only need to look at symtabs not already expanded.  */
5557           if (per_cu->v.quick->compunit_symtab)
5558             continue;
5559
5560           file_data = dw2_get_file_names (per_cu);
5561           if (file_data == NULL)
5562             continue;
5563
5564           slot = htab_find_slot (visited.get (), file_data, INSERT);
5565           if (*slot)
5566             {
5567               /* Already visited.  */
5568               continue;
5569             }
5570           *slot = file_data;
5571
5572           for (int j = 0; j < file_data->num_file_names; ++j)
5573             {
5574               const char *filename = file_data->file_names[j];
5575               dwarf2_per_objfile->filenames_cache->seen (filename);
5576             }
5577         }
5578     }
5579
5580   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5581     {
5582       gdb::unique_xmalloc_ptr<char> this_real_name;
5583
5584       if (need_fullname)
5585         this_real_name = gdb_realpath (filename);
5586       (*fun) (filename, this_real_name.get (), data);
5587     });
5588 }
5589
5590 static int
5591 dw2_has_symbols (struct objfile *objfile)
5592 {
5593   return 1;
5594 }
5595
5596 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5597 {
5598   dw2_has_symbols,
5599   dw2_find_last_source_symtab,
5600   dw2_forget_cached_source_info,
5601   dw2_map_symtabs_matching_filename,
5602   dw2_lookup_symbol,
5603   dw2_print_stats,
5604   dw2_dump,
5605   dw2_relocate,
5606   dw2_expand_symtabs_for_function,
5607   dw2_expand_all_symtabs,
5608   dw2_expand_symtabs_with_fullname,
5609   dw2_map_matching_symbols,
5610   dw2_expand_symtabs_matching,
5611   dw2_find_pc_sect_compunit_symtab,
5612   NULL,
5613   dw2_map_symbol_filenames
5614 };
5615
5616 /* DWARF-5 debug_names reader.  */
5617
5618 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5619 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5620
5621 /* A helper function that reads the .debug_names section in SECTION
5622    and fills in MAP.  FILENAME is the name of the file containing the
5623    section; it is used for error reporting.
5624
5625    Returns true if all went well, false otherwise.  */
5626
5627 static bool
5628 read_debug_names_from_section (struct objfile *objfile,
5629                                const char *filename,
5630                                struct dwarf2_section_info *section,
5631                                mapped_debug_names &map)
5632 {
5633   if (dwarf2_section_empty_p (section))
5634     return false;
5635
5636   /* Older elfutils strip versions could keep the section in the main
5637      executable while splitting it for the separate debug info file.  */
5638   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5639     return false;
5640
5641   dwarf2_read_section (objfile, section);
5642
5643   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5644
5645   const gdb_byte *addr = section->buffer;
5646
5647   bfd *const abfd = get_section_bfd_owner (section);
5648
5649   unsigned int bytes_read;
5650   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5651   addr += bytes_read;
5652
5653   map.dwarf5_is_dwarf64 = bytes_read != 4;
5654   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5655   if (bytes_read + length != section->size)
5656     {
5657       /* There may be multiple per-CU indices.  */
5658       warning (_("Section .debug_names in %s length %s does not match "
5659                  "section length %s, ignoring .debug_names."),
5660                filename, plongest (bytes_read + length),
5661                pulongest (section->size));
5662       return false;
5663     }
5664
5665   /* The version number.  */
5666   uint16_t version = read_2_bytes (abfd, addr);
5667   addr += 2;
5668   if (version != 5)
5669     {
5670       warning (_("Section .debug_names in %s has unsupported version %d, "
5671                  "ignoring .debug_names."),
5672                filename, version);
5673       return false;
5674     }
5675
5676   /* Padding.  */
5677   uint16_t padding = read_2_bytes (abfd, addr);
5678   addr += 2;
5679   if (padding != 0)
5680     {
5681       warning (_("Section .debug_names in %s has unsupported padding %d, "
5682                  "ignoring .debug_names."),
5683                filename, padding);
5684       return false;
5685     }
5686
5687   /* comp_unit_count - The number of CUs in the CU list.  */
5688   map.cu_count = read_4_bytes (abfd, addr);
5689   addr += 4;
5690
5691   /* local_type_unit_count - The number of TUs in the local TU
5692      list.  */
5693   map.tu_count = read_4_bytes (abfd, addr);
5694   addr += 4;
5695
5696   /* foreign_type_unit_count - The number of TUs in the foreign TU
5697      list.  */
5698   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5699   addr += 4;
5700   if (foreign_tu_count != 0)
5701     {
5702       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5703                  "ignoring .debug_names."),
5704                filename, static_cast<unsigned long> (foreign_tu_count));
5705       return false;
5706     }
5707
5708   /* bucket_count - The number of hash buckets in the hash lookup
5709      table.  */
5710   map.bucket_count = read_4_bytes (abfd, addr);
5711   addr += 4;
5712
5713   /* name_count - The number of unique names in the index.  */
5714   map.name_count = read_4_bytes (abfd, addr);
5715   addr += 4;
5716
5717   /* abbrev_table_size - The size in bytes of the abbreviations
5718      table.  */
5719   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5720   addr += 4;
5721
5722   /* augmentation_string_size - The size in bytes of the augmentation
5723      string.  This value is rounded up to a multiple of 4.  */
5724   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5725   addr += 4;
5726   map.augmentation_is_gdb = ((augmentation_string_size
5727                               == sizeof (dwarf5_augmentation))
5728                              && memcmp (addr, dwarf5_augmentation,
5729                                         sizeof (dwarf5_augmentation)) == 0);
5730   augmentation_string_size += (-augmentation_string_size) & 3;
5731   addr += augmentation_string_size;
5732
5733   /* List of CUs */
5734   map.cu_table_reordered = addr;
5735   addr += map.cu_count * map.offset_size;
5736
5737   /* List of Local TUs */
5738   map.tu_table_reordered = addr;
5739   addr += map.tu_count * map.offset_size;
5740
5741   /* Hash Lookup Table */
5742   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5743   addr += map.bucket_count * 4;
5744   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5745   addr += map.name_count * 4;
5746
5747   /* Name Table */
5748   map.name_table_string_offs_reordered = addr;
5749   addr += map.name_count * map.offset_size;
5750   map.name_table_entry_offs_reordered = addr;
5751   addr += map.name_count * map.offset_size;
5752
5753   const gdb_byte *abbrev_table_start = addr;
5754   for (;;)
5755     {
5756       unsigned int bytes_read;
5757       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5758       addr += bytes_read;
5759       if (index_num == 0)
5760         break;
5761
5762       const auto insertpair
5763         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5764       if (!insertpair.second)
5765         {
5766           warning (_("Section .debug_names in %s has duplicate index %s, "
5767                      "ignoring .debug_names."),
5768                    filename, pulongest (index_num));
5769           return false;
5770         }
5771       mapped_debug_names::index_val &indexval = insertpair.first->second;
5772       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5773       addr += bytes_read;
5774
5775       for (;;)
5776         {
5777           mapped_debug_names::index_val::attr attr;
5778           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5779           addr += bytes_read;
5780           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5781           addr += bytes_read;
5782           if (attr.form == DW_FORM_implicit_const)
5783             {
5784               attr.implicit_const = read_signed_leb128 (abfd, addr,
5785                                                         &bytes_read);
5786               addr += bytes_read;
5787             }
5788           if (attr.dw_idx == 0 && attr.form == 0)
5789             break;
5790           indexval.attr_vec.push_back (std::move (attr));
5791         }
5792     }
5793   if (addr != abbrev_table_start + abbrev_table_size)
5794     {
5795       warning (_("Section .debug_names in %s has abbreviation_table "
5796                  "of size %zu vs. written as %u, ignoring .debug_names."),
5797                filename, addr - abbrev_table_start, abbrev_table_size);
5798       return false;
5799     }
5800   map.entry_pool = addr;
5801
5802   return true;
5803 }
5804
5805 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5806    list.  */
5807
5808 static void
5809 create_cus_from_debug_names_list (struct objfile *objfile,
5810                                   const mapped_debug_names &map,
5811                                   dwarf2_section_info &section,
5812                                   bool is_dwz, int base_offset)
5813 {
5814   sect_offset sect_off_prev;
5815   for (uint32_t i = 0; i <= map.cu_count; ++i)
5816     {
5817       sect_offset sect_off_next;
5818       if (i < map.cu_count)
5819         {
5820           sect_off_next
5821             = (sect_offset) (extract_unsigned_integer
5822                              (map.cu_table_reordered + i * map.offset_size,
5823                               map.offset_size,
5824                               map.dwarf5_byte_order));
5825         }
5826       else
5827         sect_off_next = (sect_offset) section.size;
5828       if (i >= 1)
5829         {
5830           const ULONGEST length = sect_off_next - sect_off_prev;
5831           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5832             = create_cu_from_index_list (objfile, &section, is_dwz,
5833                                          sect_off_prev, length);
5834         }
5835       sect_off_prev = sect_off_next;
5836     }
5837 }
5838
5839 /* Read the CU list from the mapped index, and use it to create all
5840    the CU objects for this objfile.  */
5841
5842 static void
5843 create_cus_from_debug_names (struct objfile *objfile,
5844                              const mapped_debug_names &map,
5845                              const mapped_debug_names &dwz_map)
5846 {
5847
5848   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5849   dwarf2_per_objfile->all_comp_units
5850     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5851                  dwarf2_per_objfile->n_comp_units);
5852
5853   create_cus_from_debug_names_list (objfile, map, dwarf2_per_objfile->info,
5854                                     false /* is_dwz */,
5855                                     0 /* base_offset */);
5856
5857   if (dwz_map.cu_count == 0)
5858     return;
5859
5860   dwz_file *dwz = dwarf2_get_dwz_file ();
5861   create_cus_from_debug_names_list (objfile, dwz_map, dwz->info,
5862                                     true /* is_dwz */,
5863                                     map.cu_count /* base_offset */);
5864 }
5865
5866 /* Read .debug_names.  If everything went ok, initialize the "quick"
5867    elements of all the CUs and return true.  Otherwise, return false.  */
5868
5869 static bool
5870 dwarf2_read_debug_names (struct objfile *objfile)
5871 {
5872   mapped_debug_names local_map, dwz_map;
5873
5874   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5875                                       &dwarf2_per_objfile->debug_names,
5876                                       local_map))
5877     return false;
5878
5879   /* Don't use the index if it's empty.  */
5880   if (local_map.name_count == 0)
5881     return false;
5882
5883   /* If there is a .dwz file, read it so we can get its CU list as
5884      well.  */
5885   dwz_file *dwz = dwarf2_get_dwz_file ();
5886   if (dwz != NULL)
5887     {
5888       if (!read_debug_names_from_section (objfile,
5889                                           bfd_get_filename (dwz->dwz_bfd),
5890                                           &dwz->debug_names, dwz_map))
5891         {
5892           warning (_("could not read '.debug_names' section from %s; skipping"),
5893                    bfd_get_filename (dwz->dwz_bfd));
5894           return false;
5895         }
5896     }
5897
5898   create_cus_from_debug_names (objfile, local_map, dwz_map);
5899
5900   if (local_map.tu_count != 0)
5901     {
5902       /* We can only handle a single .debug_types when we have an
5903          index.  */
5904       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5905         return false;
5906
5907       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5908                                                 dwarf2_per_objfile->types, 0);
5909
5910       create_signatured_type_table_from_debug_names
5911         (objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5912     }
5913
5914   create_addrmap_from_aranges (objfile, &dwarf2_per_objfile->debug_aranges);
5915
5916   dwarf2_per_objfile->debug_names_table.reset (new mapped_debug_names);
5917   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5918   dwarf2_per_objfile->using_index = 1;
5919   dwarf2_per_objfile->quick_file_names_table =
5920     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5921
5922   return true;
5923 }
5924
5925 /* Symbol name hashing function as specified by DWARF-5.  */
5926
5927 static uint32_t
5928 dwarf5_djb_hash (const char *str_)
5929 {
5930   const unsigned char *str = (const unsigned char *) str_;
5931
5932   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
5933      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
5934
5935   uint32_t hash = 5381;
5936   while (int c = *str++)
5937     hash = hash * 33 + tolower (c);
5938   return hash;
5939 }
5940
5941 /* Type used to manage iterating over all CUs looking for a symbol for
5942    .debug_names.  */
5943
5944 class dw2_debug_names_iterator
5945 {
5946 public:
5947   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5948      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5949   dw2_debug_names_iterator (const mapped_debug_names &map,
5950                             bool want_specific_block,
5951                             block_enum block_index, domain_enum domain,
5952                             const char *name)
5953     : m_map (map), m_want_specific_block (want_specific_block),
5954       m_block_index (block_index), m_domain (domain),
5955       m_addr (find_vec_in_debug_names (map, name))
5956   {}
5957
5958   dw2_debug_names_iterator (const mapped_debug_names &map,
5959                             search_domain search, uint32_t namei)
5960     : m_map (map),
5961       m_search (search),
5962       m_addr (find_vec_in_debug_names (map, namei))
5963   {}
5964
5965   /* Return the next matching CU or NULL if there are no more.  */
5966   dwarf2_per_cu_data *next ();
5967
5968 private:
5969   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5970                                                   const char *name);
5971   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5972                                                   uint32_t namei);
5973
5974   /* The internalized form of .debug_names.  */
5975   const mapped_debug_names &m_map;
5976
5977   /* If true, only look for symbols that match BLOCK_INDEX.  */
5978   const bool m_want_specific_block = false;
5979
5980   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5981      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5982      value.  */
5983   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5984
5985   /* The kind of symbol we're looking for.  */
5986   const domain_enum m_domain = UNDEF_DOMAIN;
5987   const search_domain m_search = ALL_DOMAIN;
5988
5989   /* The list of CUs from the index entry of the symbol, or NULL if
5990      not found.  */
5991   const gdb_byte *m_addr;
5992 };
5993
5994 const char *
5995 mapped_debug_names::namei_to_name (uint32_t namei) const
5996 {
5997   const ULONGEST namei_string_offs
5998     = extract_unsigned_integer ((name_table_string_offs_reordered
5999                                  + namei * offset_size),
6000                                 offset_size,
6001                                 dwarf5_byte_order);
6002   return read_indirect_string_at_offset
6003     (dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6004 }
6005
6006 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6007    found, return pointer to its pool data.  If NAME cannot be found,
6008    return NULL.  */
6009
6010 const gdb_byte *
6011 dw2_debug_names_iterator::find_vec_in_debug_names
6012   (const mapped_debug_names &map, const char *name)
6013 {
6014   int (*cmp) (const char *, const char *);
6015
6016   if (current_language->la_language == language_cplus
6017       || current_language->la_language == language_fortran
6018       || current_language->la_language == language_d)
6019     {
6020       /* NAME is already canonical.  Drop any qualifiers as
6021          .debug_names does not contain any.  */
6022
6023       if (strchr (name, '(') != NULL)
6024         {
6025           gdb::unique_xmalloc_ptr<char> without_params
6026             = cp_remove_params (name);
6027
6028           if (without_params != NULL)
6029             {
6030               name = without_params.get();
6031             }
6032         }
6033     }
6034
6035   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6036
6037   const uint32_t full_hash = dwarf5_djb_hash (name);
6038   uint32_t namei
6039     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6040                                 (map.bucket_table_reordered
6041                                  + (full_hash % map.bucket_count)), 4,
6042                                 map.dwarf5_byte_order);
6043   if (namei == 0)
6044     return NULL;
6045   --namei;
6046   if (namei >= map.name_count)
6047     {
6048       complaint (&symfile_complaints,
6049                  _("Wrong .debug_names with name index %u but name_count=%u "
6050                    "[in module %s]"),
6051                  namei, map.name_count,
6052                  objfile_name (dwarf2_per_objfile->objfile));
6053       return NULL;
6054     }
6055
6056   for (;;)
6057     {
6058       const uint32_t namei_full_hash
6059         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6060                                     (map.hash_table_reordered + namei), 4,
6061                                     map.dwarf5_byte_order);
6062       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6063         return NULL;
6064
6065       if (full_hash == namei_full_hash)
6066         {
6067           const char *const namei_string = map.namei_to_name (namei);
6068
6069 #if 0 /* An expensive sanity check.  */
6070           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6071             {
6072               complaint (&symfile_complaints,
6073                          _("Wrong .debug_names hash for string at index %u "
6074                            "[in module %s]"),
6075                          namei, objfile_name (dwarf2_per_objfile->objfile));
6076               return NULL;
6077             }
6078 #endif
6079
6080           if (cmp (namei_string, name) == 0)
6081             {
6082               const ULONGEST namei_entry_offs
6083                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6084                                              + namei * map.offset_size),
6085                                             map.offset_size, map.dwarf5_byte_order);
6086               return map.entry_pool + namei_entry_offs;
6087             }
6088         }
6089
6090       ++namei;
6091       if (namei >= map.name_count)
6092         return NULL;
6093     }
6094 }
6095
6096 const gdb_byte *
6097 dw2_debug_names_iterator::find_vec_in_debug_names
6098   (const mapped_debug_names &map, uint32_t namei)
6099 {
6100   if (namei >= map.name_count)
6101     {
6102       complaint (&symfile_complaints,
6103                  _("Wrong .debug_names with name index %u but name_count=%u "
6104                    "[in module %s]"),
6105                  namei, map.name_count,
6106                  objfile_name (dwarf2_per_objfile->objfile));
6107       return NULL;
6108     }
6109
6110   const ULONGEST namei_entry_offs
6111     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6112                                  + namei * map.offset_size),
6113                                 map.offset_size, map.dwarf5_byte_order);
6114   return map.entry_pool + namei_entry_offs;
6115 }
6116
6117 /* See dw2_debug_names_iterator.  */
6118
6119 dwarf2_per_cu_data *
6120 dw2_debug_names_iterator::next ()
6121 {
6122   if (m_addr == NULL)
6123     return NULL;
6124
6125   bfd *const abfd = dwarf2_per_objfile->objfile->obfd;
6126
6127  again:
6128
6129   unsigned int bytes_read;
6130   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6131   m_addr += bytes_read;
6132   if (abbrev == 0)
6133     return NULL;
6134
6135   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6136   if (indexval_it == m_map.abbrev_map.cend ())
6137     {
6138       complaint (&symfile_complaints,
6139                  _("Wrong .debug_names undefined abbrev code %s "
6140                    "[in module %s]"),
6141                  pulongest (abbrev), objfile_name (dwarf2_per_objfile->objfile));
6142       return NULL;
6143     }
6144   const mapped_debug_names::index_val &indexval = indexval_it->second;
6145   bool have_is_static = false;
6146   bool is_static;
6147   dwarf2_per_cu_data *per_cu = NULL;
6148   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6149     {
6150       ULONGEST ull;
6151       switch (attr.form)
6152         {
6153         case DW_FORM_implicit_const:
6154           ull = attr.implicit_const;
6155           break;
6156         case DW_FORM_flag_present:
6157           ull = 1;
6158           break;
6159         case DW_FORM_udata:
6160           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6161           m_addr += bytes_read;
6162           break;
6163         default:
6164           complaint (&symfile_complaints,
6165                      _("Unsupported .debug_names form %s [in module %s]"),
6166                      dwarf_form_name (attr.form),
6167                      objfile_name (dwarf2_per_objfile->objfile));
6168           return NULL;
6169         }
6170       switch (attr.dw_idx)
6171         {
6172         case DW_IDX_compile_unit:
6173           /* Don't crash on bad data.  */
6174           if (ull >= (dwarf2_per_objfile->n_comp_units
6175                       + dwarf2_per_objfile->n_type_units))
6176             {
6177               complaint (&symfile_complaints,
6178                          _(".debug_names entry has bad CU index %s"
6179                            " [in module %s]"),
6180                          pulongest (ull),
6181                          objfile_name (dwarf2_per_objfile->objfile));
6182               continue;
6183             }
6184           per_cu = dw2_get_cutu (ull);
6185           break;
6186         case DW_IDX_GNU_internal:
6187           if (!m_map.augmentation_is_gdb)
6188             break;
6189           have_is_static = true;
6190           is_static = true;
6191           break;
6192         case DW_IDX_GNU_external:
6193           if (!m_map.augmentation_is_gdb)
6194             break;
6195           have_is_static = true;
6196           is_static = false;
6197           break;
6198         }
6199     }
6200
6201   /* Skip if already read in.  */
6202   if (per_cu->v.quick->compunit_symtab)
6203     goto again;
6204
6205   /* Check static vs global.  */
6206   if (have_is_static)
6207     {
6208       const bool want_static = m_block_index != GLOBAL_BLOCK;
6209       if (m_want_specific_block && want_static != is_static)
6210         goto again;
6211     }
6212
6213   /* Match dw2_symtab_iter_next, symbol_kind
6214      and debug_names::psymbol_tag.  */
6215   switch (m_domain)
6216     {
6217     case VAR_DOMAIN:
6218       switch (indexval.dwarf_tag)
6219         {
6220         case DW_TAG_variable:
6221         case DW_TAG_subprogram:
6222         /* Some types are also in VAR_DOMAIN.  */
6223         case DW_TAG_typedef:
6224         case DW_TAG_structure_type:
6225           break;
6226         default:
6227           goto again;
6228         }
6229       break;
6230     case STRUCT_DOMAIN:
6231       switch (indexval.dwarf_tag)
6232         {
6233         case DW_TAG_typedef:
6234         case DW_TAG_structure_type:
6235           break;
6236         default:
6237           goto again;
6238         }
6239       break;
6240     case LABEL_DOMAIN:
6241       switch (indexval.dwarf_tag)
6242         {
6243         case 0:
6244         case DW_TAG_variable:
6245           break;
6246         default:
6247           goto again;
6248         }
6249       break;
6250     default:
6251       break;
6252     }
6253
6254   /* Match dw2_expand_symtabs_matching, symbol_kind and
6255      debug_names::psymbol_tag.  */
6256   switch (m_search)
6257     {
6258     case VARIABLES_DOMAIN:
6259       switch (indexval.dwarf_tag)
6260         {
6261         case DW_TAG_variable:
6262           break;
6263         default:
6264           goto again;
6265         }
6266       break;
6267     case FUNCTIONS_DOMAIN:
6268       switch (indexval.dwarf_tag)
6269         {
6270         case DW_TAG_subprogram:
6271           break;
6272         default:
6273           goto again;
6274         }
6275       break;
6276     case TYPES_DOMAIN:
6277       switch (indexval.dwarf_tag)
6278         {
6279         case DW_TAG_typedef:
6280         case DW_TAG_structure_type:
6281           break;
6282         default:
6283           goto again;
6284         }
6285       break;
6286     default:
6287       break;
6288     }
6289
6290   return per_cu;
6291 }
6292
6293 static struct compunit_symtab *
6294 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6295                                const char *name, domain_enum domain)
6296 {
6297   const block_enum block_index = static_cast<block_enum> (block_index_int);
6298   dw2_setup (objfile);
6299
6300   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6301   if (!mapp)
6302     {
6303       /* index is NULL if OBJF_READNOW.  */
6304       return NULL;
6305     }
6306   const auto &map = *mapp;
6307
6308   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6309                                  block_index, domain, name);
6310
6311   struct compunit_symtab *stab_best = NULL;
6312   struct dwarf2_per_cu_data *per_cu;
6313   while ((per_cu = iter.next ()) != NULL)
6314     {
6315       struct symbol *sym, *with_opaque = NULL;
6316       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6317       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6318       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6319
6320       sym = block_find_symbol (block, name, domain,
6321                                block_find_non_opaque_type_preferred,
6322                                &with_opaque);
6323
6324       /* Some caution must be observed with overloaded functions and
6325          methods, since the index will not contain any overload
6326          information (but NAME might contain it).  */
6327
6328       if (sym != NULL
6329           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6330         return stab;
6331       if (with_opaque != NULL
6332           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6333         stab_best = stab;
6334
6335       /* Keep looking through other CUs.  */
6336     }
6337
6338   return stab_best;
6339 }
6340
6341 /* This dumps minimal information about .debug_names.  It is called
6342    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6343    uses this to verify that .debug_names has been loaded.  */
6344
6345 static void
6346 dw2_debug_names_dump (struct objfile *objfile)
6347 {
6348   dw2_setup (objfile);
6349   gdb_assert (dwarf2_per_objfile->using_index);
6350   printf_filtered (".debug_names:");
6351   if (dwarf2_per_objfile->debug_names_table)
6352     printf_filtered (" exists\n");
6353   else
6354     printf_filtered (" faked for \"readnow\"\n");
6355   printf_filtered ("\n");
6356 }
6357
6358 static void
6359 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6360                                              const char *func_name)
6361 {
6362   dw2_setup (objfile);
6363
6364   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6365   if (dwarf2_per_objfile->debug_names_table)
6366     {
6367       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6368
6369       /* Note: It doesn't matter what we pass for block_index here.  */
6370       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6371                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6372
6373       struct dwarf2_per_cu_data *per_cu;
6374       while ((per_cu = iter.next ()) != NULL)
6375         dw2_instantiate_symtab (per_cu);
6376     }
6377 }
6378
6379 static void
6380 dw2_debug_names_expand_symtabs_matching
6381   (struct objfile *objfile,
6382    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6383    const lookup_name_info &lookup_name,
6384    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6385    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6386    enum search_domain kind)
6387 {
6388   dw2_setup (objfile);
6389
6390   /* debug_names_table is NULL if OBJF_READNOW.  */
6391   if (!dwarf2_per_objfile->debug_names_table)
6392     return;
6393
6394   dw_expand_symtabs_matching_file_matcher (file_matcher);
6395
6396   const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6397
6398   for (uint32_t namei = 0; namei < map.name_count; ++namei)
6399     {
6400       QUIT;
6401
6402       const char *const namei_string = map.namei_to_name (namei);
6403       if (symbol_matcher != NULL && !symbol_matcher (namei_string))
6404         continue;
6405
6406       /* The name was matched, now expand corresponding CUs that were
6407          marked.  */
6408       dw2_debug_names_iterator iter (map, kind, namei);
6409
6410       struct dwarf2_per_cu_data *per_cu;
6411       while ((per_cu = iter.next ()) != NULL)
6412         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6413                                          expansion_notify);
6414     }
6415 }
6416
6417 const struct quick_symbol_functions dwarf2_debug_names_functions =
6418 {
6419   dw2_has_symbols,
6420   dw2_find_last_source_symtab,
6421   dw2_forget_cached_source_info,
6422   dw2_map_symtabs_matching_filename,
6423   dw2_debug_names_lookup_symbol,
6424   dw2_print_stats,
6425   dw2_debug_names_dump,
6426   dw2_relocate,
6427   dw2_debug_names_expand_symtabs_for_function,
6428   dw2_expand_all_symtabs,
6429   dw2_expand_symtabs_with_fullname,
6430   dw2_map_matching_symbols,
6431   dw2_debug_names_expand_symtabs_matching,
6432   dw2_find_pc_sect_compunit_symtab,
6433   NULL,
6434   dw2_map_symbol_filenames
6435 };
6436
6437 /* Initialize for reading DWARF for this objfile.  Return 0 if this
6438    file will use psymtabs, or 1 if using the GNU index.  */
6439
6440 const sym_fns &
6441 dwarf2_initialize_objfile (struct objfile *objfile)
6442 {
6443   /* If we're about to read full symbols, don't bother with the
6444      indices.  In this case we also don't care if some other debug
6445      format is making psymtabs, because they are all about to be
6446      expanded anyway.  */
6447   if ((objfile->flags & OBJF_READNOW))
6448     {
6449       int i;
6450
6451       dwarf2_per_objfile->using_index = 1;
6452       create_all_comp_units (objfile);
6453       create_all_type_units (objfile);
6454       dwarf2_per_objfile->quick_file_names_table =
6455         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6456
6457       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6458                        + dwarf2_per_objfile->n_type_units); ++i)
6459         {
6460           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6461
6462           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6463                                             struct dwarf2_per_cu_quick_data);
6464         }
6465
6466       /* Return 1 so that gdb sees the "quick" functions.  However,
6467          these functions will be no-ops because we will have expanded
6468          all symtabs.  */
6469       return elf_sym_fns_gdb_index;
6470     }
6471
6472   if (dwarf2_read_debug_names (objfile))
6473     return elf_sym_fns_debug_names;
6474
6475   if (dwarf2_read_index (objfile))
6476     return elf_sym_fns_gdb_index;
6477
6478   return elf_sym_fns_lazy_psyms;
6479 }
6480
6481 \f
6482
6483 /* Build a partial symbol table.  */
6484
6485 void
6486 dwarf2_build_psymtabs (struct objfile *objfile)
6487 {
6488
6489   if (objfile->global_psymbols.capacity () == 0
6490       && objfile->static_psymbols.capacity () == 0)
6491     init_psymbol_list (objfile, 1024);
6492
6493   TRY
6494     {
6495       /* This isn't really ideal: all the data we allocate on the
6496          objfile's obstack is still uselessly kept around.  However,
6497          freeing it seems unsafe.  */
6498       psymtab_discarder psymtabs (objfile);
6499       dwarf2_build_psymtabs_hard (objfile);
6500       psymtabs.keep ();
6501     }
6502   CATCH (except, RETURN_MASK_ERROR)
6503     {
6504       exception_print (gdb_stderr, except);
6505     }
6506   END_CATCH
6507 }
6508
6509 /* Return the total length of the CU described by HEADER.  */
6510
6511 static unsigned int
6512 get_cu_length (const struct comp_unit_head *header)
6513 {
6514   return header->initial_length_size + header->length;
6515 }
6516
6517 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6518
6519 static inline bool
6520 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6521 {
6522   sect_offset bottom = cu_header->sect_off;
6523   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6524
6525   return sect_off >= bottom && sect_off < top;
6526 }
6527
6528 /* Find the base address of the compilation unit for range lists and
6529    location lists.  It will normally be specified by DW_AT_low_pc.
6530    In DWARF-3 draft 4, the base address could be overridden by
6531    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6532    compilation units with discontinuous ranges.  */
6533
6534 static void
6535 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6536 {
6537   struct attribute *attr;
6538
6539   cu->base_known = 0;
6540   cu->base_address = 0;
6541
6542   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6543   if (attr)
6544     {
6545       cu->base_address = attr_value_as_address (attr);
6546       cu->base_known = 1;
6547     }
6548   else
6549     {
6550       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6551       if (attr)
6552         {
6553           cu->base_address = attr_value_as_address (attr);
6554           cu->base_known = 1;
6555         }
6556     }
6557 }
6558
6559 /* Read in the comp unit header information from the debug_info at info_ptr.
6560    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6561    NOTE: This leaves members offset, first_die_offset to be filled in
6562    by the caller.  */
6563
6564 static const gdb_byte *
6565 read_comp_unit_head (struct comp_unit_head *cu_header,
6566                      const gdb_byte *info_ptr,
6567                      struct dwarf2_section_info *section,
6568                      rcuh_kind section_kind)
6569 {
6570   int signed_addr;
6571   unsigned int bytes_read;
6572   const char *filename = get_section_file_name (section);
6573   bfd *abfd = get_section_bfd_owner (section);
6574
6575   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6576   cu_header->initial_length_size = bytes_read;
6577   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6578   info_ptr += bytes_read;
6579   cu_header->version = read_2_bytes (abfd, info_ptr);
6580   info_ptr += 2;
6581   if (cu_header->version < 5)
6582     switch (section_kind)
6583       {
6584       case rcuh_kind::COMPILE:
6585         cu_header->unit_type = DW_UT_compile;
6586         break;
6587       case rcuh_kind::TYPE:
6588         cu_header->unit_type = DW_UT_type;
6589         break;
6590       default:
6591         internal_error (__FILE__, __LINE__,
6592                         _("read_comp_unit_head: invalid section_kind"));
6593       }
6594   else
6595     {
6596       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6597                                                  (read_1_byte (abfd, info_ptr));
6598       info_ptr += 1;
6599       switch (cu_header->unit_type)
6600         {
6601         case DW_UT_compile:
6602           if (section_kind != rcuh_kind::COMPILE)
6603             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6604                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6605                    filename);
6606           break;
6607         case DW_UT_type:
6608           section_kind = rcuh_kind::TYPE;
6609           break;
6610         default:
6611           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6612                  "(is %d, should be %d or %d) [in module %s]"),
6613                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6614         }
6615
6616       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6617       info_ptr += 1;
6618     }
6619   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6620                                                           cu_header,
6621                                                           &bytes_read);
6622   info_ptr += bytes_read;
6623   if (cu_header->version < 5)
6624     {
6625       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6626       info_ptr += 1;
6627     }
6628   signed_addr = bfd_get_sign_extend_vma (abfd);
6629   if (signed_addr < 0)
6630     internal_error (__FILE__, __LINE__,
6631                     _("read_comp_unit_head: dwarf from non elf file"));
6632   cu_header->signed_addr_p = signed_addr;
6633
6634   if (section_kind == rcuh_kind::TYPE)
6635     {
6636       LONGEST type_offset;
6637
6638       cu_header->signature = read_8_bytes (abfd, info_ptr);
6639       info_ptr += 8;
6640
6641       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6642       info_ptr += bytes_read;
6643       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6644       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6645         error (_("Dwarf Error: Too big type_offset in compilation unit "
6646                "header (is %s) [in module %s]"), plongest (type_offset),
6647                filename);
6648     }
6649
6650   return info_ptr;
6651 }
6652
6653 /* Helper function that returns the proper abbrev section for
6654    THIS_CU.  */
6655
6656 static struct dwarf2_section_info *
6657 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6658 {
6659   struct dwarf2_section_info *abbrev;
6660
6661   if (this_cu->is_dwz)
6662     abbrev = &dwarf2_get_dwz_file ()->abbrev;
6663   else
6664     abbrev = &dwarf2_per_objfile->abbrev;
6665
6666   return abbrev;
6667 }
6668
6669 /* Subroutine of read_and_check_comp_unit_head and
6670    read_and_check_type_unit_head to simplify them.
6671    Perform various error checking on the header.  */
6672
6673 static void
6674 error_check_comp_unit_head (struct comp_unit_head *header,
6675                             struct dwarf2_section_info *section,
6676                             struct dwarf2_section_info *abbrev_section)
6677 {
6678   const char *filename = get_section_file_name (section);
6679
6680   if (header->version < 2 || header->version > 5)
6681     error (_("Dwarf Error: wrong version in compilation unit header "
6682            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6683            filename);
6684
6685   if (to_underlying (header->abbrev_sect_off)
6686       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6687     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6688            "(offset 0x%x + 6) [in module %s]"),
6689            to_underlying (header->abbrev_sect_off),
6690            to_underlying (header->sect_off),
6691            filename);
6692
6693   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6694      avoid potential 32-bit overflow.  */
6695   if (((ULONGEST) header->sect_off + get_cu_length (header))
6696       > section->size)
6697     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6698            "(offset 0x%x + 0) [in module %s]"),
6699            header->length, to_underlying (header->sect_off),
6700            filename);
6701 }
6702
6703 /* Read in a CU/TU header and perform some basic error checking.
6704    The contents of the header are stored in HEADER.
6705    The result is a pointer to the start of the first DIE.  */
6706
6707 static const gdb_byte *
6708 read_and_check_comp_unit_head (struct comp_unit_head *header,
6709                                struct dwarf2_section_info *section,
6710                                struct dwarf2_section_info *abbrev_section,
6711                                const gdb_byte *info_ptr,
6712                                rcuh_kind section_kind)
6713 {
6714   const gdb_byte *beg_of_comp_unit = info_ptr;
6715
6716   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6717
6718   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6719
6720   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6721
6722   error_check_comp_unit_head (header, section, abbrev_section);
6723
6724   return info_ptr;
6725 }
6726
6727 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6728
6729 static sect_offset
6730 read_abbrev_offset (struct dwarf2_section_info *section,
6731                     sect_offset sect_off)
6732 {
6733   bfd *abfd = get_section_bfd_owner (section);
6734   const gdb_byte *info_ptr;
6735   unsigned int initial_length_size, offset_size;
6736   uint16_t version;
6737
6738   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6739   info_ptr = section->buffer + to_underlying (sect_off);
6740   read_initial_length (abfd, info_ptr, &initial_length_size);
6741   offset_size = initial_length_size == 4 ? 4 : 8;
6742   info_ptr += initial_length_size;
6743
6744   version = read_2_bytes (abfd, info_ptr);
6745   info_ptr += 2;
6746   if (version >= 5)
6747     {
6748       /* Skip unit type and address size.  */
6749       info_ptr += 2;
6750     }
6751
6752   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6753 }
6754
6755 /* Allocate a new partial symtab for file named NAME and mark this new
6756    partial symtab as being an include of PST.  */
6757
6758 static void
6759 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6760                                struct objfile *objfile)
6761 {
6762   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6763
6764   if (!IS_ABSOLUTE_PATH (subpst->filename))
6765     {
6766       /* It shares objfile->objfile_obstack.  */
6767       subpst->dirname = pst->dirname;
6768     }
6769
6770   subpst->textlow = 0;
6771   subpst->texthigh = 0;
6772
6773   subpst->dependencies
6774     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6775   subpst->dependencies[0] = pst;
6776   subpst->number_of_dependencies = 1;
6777
6778   subpst->globals_offset = 0;
6779   subpst->n_global_syms = 0;
6780   subpst->statics_offset = 0;
6781   subpst->n_static_syms = 0;
6782   subpst->compunit_symtab = NULL;
6783   subpst->read_symtab = pst->read_symtab;
6784   subpst->readin = 0;
6785
6786   /* No private part is necessary for include psymtabs.  This property
6787      can be used to differentiate between such include psymtabs and
6788      the regular ones.  */
6789   subpst->read_symtab_private = NULL;
6790 }
6791
6792 /* Read the Line Number Program data and extract the list of files
6793    included by the source file represented by PST.  Build an include
6794    partial symtab for each of these included files.  */
6795
6796 static void
6797 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6798                                struct die_info *die,
6799                                struct partial_symtab *pst)
6800 {
6801   line_header_up lh;
6802   struct attribute *attr;
6803
6804   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6805   if (attr)
6806     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6807   if (lh == NULL)
6808     return;  /* No linetable, so no includes.  */
6809
6810   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6811   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6812 }
6813
6814 static hashval_t
6815 hash_signatured_type (const void *item)
6816 {
6817   const struct signatured_type *sig_type
6818     = (const struct signatured_type *) item;
6819
6820   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6821   return sig_type->signature;
6822 }
6823
6824 static int
6825 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6826 {
6827   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6828   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6829
6830   return lhs->signature == rhs->signature;
6831 }
6832
6833 /* Allocate a hash table for signatured types.  */
6834
6835 static htab_t
6836 allocate_signatured_type_table (struct objfile *objfile)
6837 {
6838   return htab_create_alloc_ex (41,
6839                                hash_signatured_type,
6840                                eq_signatured_type,
6841                                NULL,
6842                                &objfile->objfile_obstack,
6843                                hashtab_obstack_allocate,
6844                                dummy_obstack_deallocate);
6845 }
6846
6847 /* A helper function to add a signatured type CU to a table.  */
6848
6849 static int
6850 add_signatured_type_cu_to_table (void **slot, void *datum)
6851 {
6852   struct signatured_type *sigt = (struct signatured_type *) *slot;
6853   struct signatured_type ***datap = (struct signatured_type ***) datum;
6854
6855   **datap = sigt;
6856   ++*datap;
6857
6858   return 1;
6859 }
6860
6861 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6862    and fill them into TYPES_HTAB.  It will process only type units,
6863    therefore DW_UT_type.  */
6864
6865 static void
6866 create_debug_type_hash_table (struct dwo_file *dwo_file,
6867                               dwarf2_section_info *section, htab_t &types_htab,
6868                               rcuh_kind section_kind)
6869 {
6870   struct objfile *objfile = dwarf2_per_objfile->objfile;
6871   struct dwarf2_section_info *abbrev_section;
6872   bfd *abfd;
6873   const gdb_byte *info_ptr, *end_ptr;
6874
6875   abbrev_section = (dwo_file != NULL
6876                     ? &dwo_file->sections.abbrev
6877                     : &dwarf2_per_objfile->abbrev);
6878
6879   if (dwarf_read_debug)
6880     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6881                         get_section_name (section),
6882                         get_section_file_name (abbrev_section));
6883
6884   dwarf2_read_section (objfile, section);
6885   info_ptr = section->buffer;
6886
6887   if (info_ptr == NULL)
6888     return;
6889
6890   /* We can't set abfd until now because the section may be empty or
6891      not present, in which case the bfd is unknown.  */
6892   abfd = get_section_bfd_owner (section);
6893
6894   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6895      because we don't need to read any dies: the signature is in the
6896      header.  */
6897
6898   end_ptr = info_ptr + section->size;
6899   while (info_ptr < end_ptr)
6900     {
6901       struct signatured_type *sig_type;
6902       struct dwo_unit *dwo_tu;
6903       void **slot;
6904       const gdb_byte *ptr = info_ptr;
6905       struct comp_unit_head header;
6906       unsigned int length;
6907
6908       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6909
6910       /* Initialize it due to a false compiler warning.  */
6911       header.signature = -1;
6912       header.type_cu_offset_in_tu = (cu_offset) -1;
6913
6914       /* We need to read the type's signature in order to build the hash
6915          table, but we don't need anything else just yet.  */
6916
6917       ptr = read_and_check_comp_unit_head (&header, section,
6918                                            abbrev_section, ptr, section_kind);
6919
6920       length = get_cu_length (&header);
6921
6922       /* Skip dummy type units.  */
6923       if (ptr >= info_ptr + length
6924           || peek_abbrev_code (abfd, ptr) == 0
6925           || header.unit_type != DW_UT_type)
6926         {
6927           info_ptr += length;
6928           continue;
6929         }
6930
6931       if (types_htab == NULL)
6932         {
6933           if (dwo_file)
6934             types_htab = allocate_dwo_unit_table (objfile);
6935           else
6936             types_htab = allocate_signatured_type_table (objfile);
6937         }
6938
6939       if (dwo_file)
6940         {
6941           sig_type = NULL;
6942           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6943                                    struct dwo_unit);
6944           dwo_tu->dwo_file = dwo_file;
6945           dwo_tu->signature = header.signature;
6946           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6947           dwo_tu->section = section;
6948           dwo_tu->sect_off = sect_off;
6949           dwo_tu->length = length;
6950         }
6951       else
6952         {
6953           /* N.B.: type_offset is not usable if this type uses a DWO file.
6954              The real type_offset is in the DWO file.  */
6955           dwo_tu = NULL;
6956           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6957                                      struct signatured_type);
6958           sig_type->signature = header.signature;
6959           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6960           sig_type->per_cu.objfile = objfile;
6961           sig_type->per_cu.is_debug_types = 1;
6962           sig_type->per_cu.section = section;
6963           sig_type->per_cu.sect_off = sect_off;
6964           sig_type->per_cu.length = length;
6965         }
6966
6967       slot = htab_find_slot (types_htab,
6968                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6969                              INSERT);
6970       gdb_assert (slot != NULL);
6971       if (*slot != NULL)
6972         {
6973           sect_offset dup_sect_off;
6974
6975           if (dwo_file)
6976             {
6977               const struct dwo_unit *dup_tu
6978                 = (const struct dwo_unit *) *slot;
6979
6980               dup_sect_off = dup_tu->sect_off;
6981             }
6982           else
6983             {
6984               const struct signatured_type *dup_tu
6985                 = (const struct signatured_type *) *slot;
6986
6987               dup_sect_off = dup_tu->per_cu.sect_off;
6988             }
6989
6990           complaint (&symfile_complaints,
6991                      _("debug type entry at offset 0x%x is duplicate to"
6992                        " the entry at offset 0x%x, signature %s"),
6993                      to_underlying (sect_off), to_underlying (dup_sect_off),
6994                      hex_string (header.signature));
6995         }
6996       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6997
6998       if (dwarf_read_debug > 1)
6999         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7000                             to_underlying (sect_off),
7001                             hex_string (header.signature));
7002
7003       info_ptr += length;
7004     }
7005 }
7006
7007 /* Create the hash table of all entries in the .debug_types
7008    (or .debug_types.dwo) section(s).
7009    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7010    otherwise it is NULL.
7011
7012    The result is a pointer to the hash table or NULL if there are no types.
7013
7014    Note: This function processes DWO files only, not DWP files.  */
7015
7016 static void
7017 create_debug_types_hash_table (struct dwo_file *dwo_file,
7018                                VEC (dwarf2_section_info_def) *types,
7019                                htab_t &types_htab)
7020 {
7021   int ix;
7022   struct dwarf2_section_info *section;
7023
7024   if (VEC_empty (dwarf2_section_info_def, types))
7025     return;
7026
7027   for (ix = 0;
7028        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7029        ++ix)
7030     create_debug_type_hash_table (dwo_file, section, types_htab,
7031                                   rcuh_kind::TYPE);
7032 }
7033
7034 /* Create the hash table of all entries in the .debug_types section,
7035    and initialize all_type_units.
7036    The result is zero if there is an error (e.g. missing .debug_types section),
7037    otherwise non-zero.  */
7038
7039 static int
7040 create_all_type_units (struct objfile *objfile)
7041 {
7042   htab_t types_htab = NULL;
7043   struct signatured_type **iter;
7044
7045   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
7046                                 rcuh_kind::COMPILE);
7047   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
7048   if (types_htab == NULL)
7049     {
7050       dwarf2_per_objfile->signatured_types = NULL;
7051       return 0;
7052     }
7053
7054   dwarf2_per_objfile->signatured_types = types_htab;
7055
7056   dwarf2_per_objfile->n_type_units
7057     = dwarf2_per_objfile->n_allocated_type_units
7058     = htab_elements (types_htab);
7059   dwarf2_per_objfile->all_type_units =
7060     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7061   iter = &dwarf2_per_objfile->all_type_units[0];
7062   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7063   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7064               == dwarf2_per_objfile->n_type_units);
7065
7066   return 1;
7067 }
7068
7069 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7070    If SLOT is non-NULL, it is the entry to use in the hash table.
7071    Otherwise we find one.  */
7072
7073 static struct signatured_type *
7074 add_type_unit (ULONGEST sig, void **slot)
7075 {
7076   struct objfile *objfile = dwarf2_per_objfile->objfile;
7077   int n_type_units = dwarf2_per_objfile->n_type_units;
7078   struct signatured_type *sig_type;
7079
7080   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7081   ++n_type_units;
7082   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7083     {
7084       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7085         dwarf2_per_objfile->n_allocated_type_units = 1;
7086       dwarf2_per_objfile->n_allocated_type_units *= 2;
7087       dwarf2_per_objfile->all_type_units
7088         = XRESIZEVEC (struct signatured_type *,
7089                       dwarf2_per_objfile->all_type_units,
7090                       dwarf2_per_objfile->n_allocated_type_units);
7091       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7092     }
7093   dwarf2_per_objfile->n_type_units = n_type_units;
7094
7095   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7096                              struct signatured_type);
7097   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7098   sig_type->signature = sig;
7099   sig_type->per_cu.is_debug_types = 1;
7100   if (dwarf2_per_objfile->using_index)
7101     {
7102       sig_type->per_cu.v.quick =
7103         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7104                         struct dwarf2_per_cu_quick_data);
7105     }
7106
7107   if (slot == NULL)
7108     {
7109       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7110                              sig_type, INSERT);
7111     }
7112   gdb_assert (*slot == NULL);
7113   *slot = sig_type;
7114   /* The rest of sig_type must be filled in by the caller.  */
7115   return sig_type;
7116 }
7117
7118 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7119    Fill in SIG_ENTRY with DWO_ENTRY.  */
7120
7121 static void
7122 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
7123                                   struct signatured_type *sig_entry,
7124                                   struct dwo_unit *dwo_entry)
7125 {
7126   /* Make sure we're not clobbering something we don't expect to.  */
7127   gdb_assert (! sig_entry->per_cu.queued);
7128   gdb_assert (sig_entry->per_cu.cu == NULL);
7129   if (dwarf2_per_objfile->using_index)
7130     {
7131       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7132       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7133     }
7134   else
7135       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7136   gdb_assert (sig_entry->signature == dwo_entry->signature);
7137   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7138   gdb_assert (sig_entry->type_unit_group == NULL);
7139   gdb_assert (sig_entry->dwo_unit == NULL);
7140
7141   sig_entry->per_cu.section = dwo_entry->section;
7142   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7143   sig_entry->per_cu.length = dwo_entry->length;
7144   sig_entry->per_cu.reading_dwo_directly = 1;
7145   sig_entry->per_cu.objfile = objfile;
7146   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7147   sig_entry->dwo_unit = dwo_entry;
7148 }
7149
7150 /* Subroutine of lookup_signatured_type.
7151    If we haven't read the TU yet, create the signatured_type data structure
7152    for a TU to be read in directly from a DWO file, bypassing the stub.
7153    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7154    using .gdb_index, then when reading a CU we want to stay in the DWO file
7155    containing that CU.  Otherwise we could end up reading several other DWO
7156    files (due to comdat folding) to process the transitive closure of all the
7157    mentioned TUs, and that can be slow.  The current DWO file will have every
7158    type signature that it needs.
7159    We only do this for .gdb_index because in the psymtab case we already have
7160    to read all the DWOs to build the type unit groups.  */
7161
7162 static struct signatured_type *
7163 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7164 {
7165   struct objfile *objfile = dwarf2_per_objfile->objfile;
7166   struct dwo_file *dwo_file;
7167   struct dwo_unit find_dwo_entry, *dwo_entry;
7168   struct signatured_type find_sig_entry, *sig_entry;
7169   void **slot;
7170
7171   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7172
7173   /* If TU skeletons have been removed then we may not have read in any
7174      TUs yet.  */
7175   if (dwarf2_per_objfile->signatured_types == NULL)
7176     {
7177       dwarf2_per_objfile->signatured_types
7178         = allocate_signatured_type_table (objfile);
7179     }
7180
7181   /* We only ever need to read in one copy of a signatured type.
7182      Use the global signatured_types array to do our own comdat-folding
7183      of types.  If this is the first time we're reading this TU, and
7184      the TU has an entry in .gdb_index, replace the recorded data from
7185      .gdb_index with this TU.  */
7186
7187   find_sig_entry.signature = sig;
7188   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7189                          &find_sig_entry, INSERT);
7190   sig_entry = (struct signatured_type *) *slot;
7191
7192   /* We can get here with the TU already read, *or* in the process of being
7193      read.  Don't reassign the global entry to point to this DWO if that's
7194      the case.  Also note that if the TU is already being read, it may not
7195      have come from a DWO, the program may be a mix of Fission-compiled
7196      code and non-Fission-compiled code.  */
7197
7198   /* Have we already tried to read this TU?
7199      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7200      needn't exist in the global table yet).  */
7201   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7202     return sig_entry;
7203
7204   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7205      dwo_unit of the TU itself.  */
7206   dwo_file = cu->dwo_unit->dwo_file;
7207
7208   /* Ok, this is the first time we're reading this TU.  */
7209   if (dwo_file->tus == NULL)
7210     return NULL;
7211   find_dwo_entry.signature = sig;
7212   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7213   if (dwo_entry == NULL)
7214     return NULL;
7215
7216   /* If the global table doesn't have an entry for this TU, add one.  */
7217   if (sig_entry == NULL)
7218     sig_entry = add_type_unit (sig, slot);
7219
7220   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7221   sig_entry->per_cu.tu_read = 1;
7222   return sig_entry;
7223 }
7224
7225 /* Subroutine of lookup_signatured_type.
7226    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7227    then try the DWP file.  If the TU stub (skeleton) has been removed then
7228    it won't be in .gdb_index.  */
7229
7230 static struct signatured_type *
7231 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7232 {
7233   struct objfile *objfile = dwarf2_per_objfile->objfile;
7234   struct dwp_file *dwp_file = get_dwp_file ();
7235   struct dwo_unit *dwo_entry;
7236   struct signatured_type find_sig_entry, *sig_entry;
7237   void **slot;
7238
7239   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7240   gdb_assert (dwp_file != NULL);
7241
7242   /* If TU skeletons have been removed then we may not have read in any
7243      TUs yet.  */
7244   if (dwarf2_per_objfile->signatured_types == NULL)
7245     {
7246       dwarf2_per_objfile->signatured_types
7247         = allocate_signatured_type_table (objfile);
7248     }
7249
7250   find_sig_entry.signature = sig;
7251   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7252                          &find_sig_entry, INSERT);
7253   sig_entry = (struct signatured_type *) *slot;
7254
7255   /* Have we already tried to read this TU?
7256      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7257      needn't exist in the global table yet).  */
7258   if (sig_entry != NULL)
7259     return sig_entry;
7260
7261   if (dwp_file->tus == NULL)
7262     return NULL;
7263   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
7264                                       sig, 1 /* is_debug_types */);
7265   if (dwo_entry == NULL)
7266     return NULL;
7267
7268   sig_entry = add_type_unit (sig, slot);
7269   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
7270
7271   return sig_entry;
7272 }
7273
7274 /* Lookup a signature based type for DW_FORM_ref_sig8.
7275    Returns NULL if signature SIG is not present in the table.
7276    It is up to the caller to complain about this.  */
7277
7278 static struct signatured_type *
7279 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7280 {
7281   if (cu->dwo_unit
7282       && dwarf2_per_objfile->using_index)
7283     {
7284       /* We're in a DWO/DWP file, and we're using .gdb_index.
7285          These cases require special processing.  */
7286       if (get_dwp_file () == NULL)
7287         return lookup_dwo_signatured_type (cu, sig);
7288       else
7289         return lookup_dwp_signatured_type (cu, sig);
7290     }
7291   else
7292     {
7293       struct signatured_type find_entry, *entry;
7294
7295       if (dwarf2_per_objfile->signatured_types == NULL)
7296         return NULL;
7297       find_entry.signature = sig;
7298       entry = ((struct signatured_type *)
7299                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7300       return entry;
7301     }
7302 }
7303 \f
7304 /* Low level DIE reading support.  */
7305
7306 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7307
7308 static void
7309 init_cu_die_reader (struct die_reader_specs *reader,
7310                     struct dwarf2_cu *cu,
7311                     struct dwarf2_section_info *section,
7312                     struct dwo_file *dwo_file)
7313 {
7314   gdb_assert (section->readin && section->buffer != NULL);
7315   reader->abfd = get_section_bfd_owner (section);
7316   reader->cu = cu;
7317   reader->dwo_file = dwo_file;
7318   reader->die_section = section;
7319   reader->buffer = section->buffer;
7320   reader->buffer_end = section->buffer + section->size;
7321   reader->comp_dir = NULL;
7322 }
7323
7324 /* Subroutine of init_cutu_and_read_dies to simplify it.
7325    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7326    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7327    already.
7328
7329    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7330    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7331    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7332    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7333    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7334    STUB_COMP_DIR may be non-NULL.
7335    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7336    are filled in with the info of the DIE from the DWO file.
7337    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
7338    provided an abbrev table to use.
7339    The result is non-zero if a valid (non-dummy) DIE was found.  */
7340
7341 static int
7342 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7343                         struct dwo_unit *dwo_unit,
7344                         int abbrev_table_provided,
7345                         struct die_info *stub_comp_unit_die,
7346                         const char *stub_comp_dir,
7347                         struct die_reader_specs *result_reader,
7348                         const gdb_byte **result_info_ptr,
7349                         struct die_info **result_comp_unit_die,
7350                         int *result_has_children)
7351 {
7352   struct objfile *objfile = dwarf2_per_objfile->objfile;
7353   struct dwarf2_cu *cu = this_cu->cu;
7354   struct dwarf2_section_info *section;
7355   bfd *abfd;
7356   const gdb_byte *begin_info_ptr, *info_ptr;
7357   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7358   int i,num_extra_attrs;
7359   struct dwarf2_section_info *dwo_abbrev_section;
7360   struct attribute *attr;
7361   struct die_info *comp_unit_die;
7362
7363   /* At most one of these may be provided.  */
7364   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7365
7366   /* These attributes aren't processed until later:
7367      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7368      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7369      referenced later.  However, these attributes are found in the stub
7370      which we won't have later.  In order to not impose this complication
7371      on the rest of the code, we read them here and copy them to the
7372      DWO CU/TU die.  */
7373
7374   stmt_list = NULL;
7375   low_pc = NULL;
7376   high_pc = NULL;
7377   ranges = NULL;
7378   comp_dir = NULL;
7379
7380   if (stub_comp_unit_die != NULL)
7381     {
7382       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7383          DWO file.  */
7384       if (! this_cu->is_debug_types)
7385         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7386       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7387       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7388       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7389       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7390
7391       /* There should be a DW_AT_addr_base attribute here (if needed).
7392          We need the value before we can process DW_FORM_GNU_addr_index.  */
7393       cu->addr_base = 0;
7394       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7395       if (attr)
7396         cu->addr_base = DW_UNSND (attr);
7397
7398       /* There should be a DW_AT_ranges_base attribute here (if needed).
7399          We need the value before we can process DW_AT_ranges.  */
7400       cu->ranges_base = 0;
7401       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7402       if (attr)
7403         cu->ranges_base = DW_UNSND (attr);
7404     }
7405   else if (stub_comp_dir != NULL)
7406     {
7407       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7408       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7409       comp_dir->name = DW_AT_comp_dir;
7410       comp_dir->form = DW_FORM_string;
7411       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7412       DW_STRING (comp_dir) = stub_comp_dir;
7413     }
7414
7415   /* Set up for reading the DWO CU/TU.  */
7416   cu->dwo_unit = dwo_unit;
7417   section = dwo_unit->section;
7418   dwarf2_read_section (objfile, section);
7419   abfd = get_section_bfd_owner (section);
7420   begin_info_ptr = info_ptr = (section->buffer
7421                                + to_underlying (dwo_unit->sect_off));
7422   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7423   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
7424
7425   if (this_cu->is_debug_types)
7426     {
7427       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7428
7429       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7430                                                 dwo_abbrev_section,
7431                                                 info_ptr, rcuh_kind::TYPE);
7432       /* This is not an assert because it can be caused by bad debug info.  */
7433       if (sig_type->signature != cu->header.signature)
7434         {
7435           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7436                    " TU at offset 0x%x [in module %s]"),
7437                  hex_string (sig_type->signature),
7438                  hex_string (cu->header.signature),
7439                  to_underlying (dwo_unit->sect_off),
7440                  bfd_get_filename (abfd));
7441         }
7442       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7443       /* For DWOs coming from DWP files, we don't know the CU length
7444          nor the type's offset in the TU until now.  */
7445       dwo_unit->length = get_cu_length (&cu->header);
7446       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7447
7448       /* Establish the type offset that can be used to lookup the type.
7449          For DWO files, we don't know it until now.  */
7450       sig_type->type_offset_in_section
7451         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7452     }
7453   else
7454     {
7455       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7456                                                 dwo_abbrev_section,
7457                                                 info_ptr, rcuh_kind::COMPILE);
7458       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7459       /* For DWOs coming from DWP files, we don't know the CU length
7460          until now.  */
7461       dwo_unit->length = get_cu_length (&cu->header);
7462     }
7463
7464   /* Replace the CU's original abbrev table with the DWO's.
7465      Reminder: We can't read the abbrev table until we've read the header.  */
7466   if (abbrev_table_provided)
7467     {
7468       /* Don't free the provided abbrev table, the caller of
7469          init_cutu_and_read_dies owns it.  */
7470       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7471       /* Ensure the DWO abbrev table gets freed.  */
7472       make_cleanup (dwarf2_free_abbrev_table, cu);
7473     }
7474   else
7475     {
7476       dwarf2_free_abbrev_table (cu);
7477       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7478       /* Leave any existing abbrev table cleanup as is.  */
7479     }
7480
7481   /* Read in the die, but leave space to copy over the attributes
7482      from the stub.  This has the benefit of simplifying the rest of
7483      the code - all the work to maintain the illusion of a single
7484      DW_TAG_{compile,type}_unit DIE is done here.  */
7485   num_extra_attrs = ((stmt_list != NULL)
7486                      + (low_pc != NULL)
7487                      + (high_pc != NULL)
7488                      + (ranges != NULL)
7489                      + (comp_dir != NULL));
7490   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7491                               result_has_children, num_extra_attrs);
7492
7493   /* Copy over the attributes from the stub to the DIE we just read in.  */
7494   comp_unit_die = *result_comp_unit_die;
7495   i = comp_unit_die->num_attrs;
7496   if (stmt_list != NULL)
7497     comp_unit_die->attrs[i++] = *stmt_list;
7498   if (low_pc != NULL)
7499     comp_unit_die->attrs[i++] = *low_pc;
7500   if (high_pc != NULL)
7501     comp_unit_die->attrs[i++] = *high_pc;
7502   if (ranges != NULL)
7503     comp_unit_die->attrs[i++] = *ranges;
7504   if (comp_dir != NULL)
7505     comp_unit_die->attrs[i++] = *comp_dir;
7506   comp_unit_die->num_attrs += num_extra_attrs;
7507
7508   if (dwarf_die_debug)
7509     {
7510       fprintf_unfiltered (gdb_stdlog,
7511                           "Read die from %s@0x%x of %s:\n",
7512                           get_section_name (section),
7513                           (unsigned) (begin_info_ptr - section->buffer),
7514                           bfd_get_filename (abfd));
7515       dump_die (comp_unit_die, dwarf_die_debug);
7516     }
7517
7518   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7519      TUs by skipping the stub and going directly to the entry in the DWO file.
7520      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7521      to get it via circuitous means.  Blech.  */
7522   if (comp_dir != NULL)
7523     result_reader->comp_dir = DW_STRING (comp_dir);
7524
7525   /* Skip dummy compilation units.  */
7526   if (info_ptr >= begin_info_ptr + dwo_unit->length
7527       || peek_abbrev_code (abfd, info_ptr) == 0)
7528     return 0;
7529
7530   *result_info_ptr = info_ptr;
7531   return 1;
7532 }
7533
7534 /* Subroutine of init_cutu_and_read_dies to simplify it.
7535    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7536    Returns NULL if the specified DWO unit cannot be found.  */
7537
7538 static struct dwo_unit *
7539 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7540                  struct die_info *comp_unit_die)
7541 {
7542   struct dwarf2_cu *cu = this_cu->cu;
7543   ULONGEST signature;
7544   struct dwo_unit *dwo_unit;
7545   const char *comp_dir, *dwo_name;
7546
7547   gdb_assert (cu != NULL);
7548
7549   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7550   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7551   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7552
7553   if (this_cu->is_debug_types)
7554     {
7555       struct signatured_type *sig_type;
7556
7557       /* Since this_cu is the first member of struct signatured_type,
7558          we can go from a pointer to one to a pointer to the other.  */
7559       sig_type = (struct signatured_type *) this_cu;
7560       signature = sig_type->signature;
7561       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7562     }
7563   else
7564     {
7565       struct attribute *attr;
7566
7567       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7568       if (! attr)
7569         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7570                  " [in module %s]"),
7571                dwo_name, objfile_name (this_cu->objfile));
7572       signature = DW_UNSND (attr);
7573       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7574                                        signature);
7575     }
7576
7577   return dwo_unit;
7578 }
7579
7580 /* Subroutine of init_cutu_and_read_dies to simplify it.
7581    See it for a description of the parameters.
7582    Read a TU directly from a DWO file, bypassing the stub.
7583
7584    Note: This function could be a little bit simpler if we shared cleanups
7585    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
7586    to do, so we keep this function self-contained.  Or we could move this
7587    into our caller, but it's complex enough already.  */
7588
7589 static void
7590 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7591                            int use_existing_cu, int keep,
7592                            die_reader_func_ftype *die_reader_func,
7593                            void *data)
7594 {
7595   struct dwarf2_cu *cu;
7596   struct signatured_type *sig_type;
7597   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7598   struct die_reader_specs reader;
7599   const gdb_byte *info_ptr;
7600   struct die_info *comp_unit_die;
7601   int has_children;
7602
7603   /* Verify we can do the following downcast, and that we have the
7604      data we need.  */
7605   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7606   sig_type = (struct signatured_type *) this_cu;
7607   gdb_assert (sig_type->dwo_unit != NULL);
7608
7609   cleanups = make_cleanup (null_cleanup, NULL);
7610
7611   if (use_existing_cu && this_cu->cu != NULL)
7612     {
7613       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7614       cu = this_cu->cu;
7615       /* There's no need to do the rereading_dwo_cu handling that
7616          init_cutu_and_read_dies does since we don't read the stub.  */
7617     }
7618   else
7619     {
7620       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7621       gdb_assert (this_cu->cu == NULL);
7622       cu = XNEW (struct dwarf2_cu);
7623       init_one_comp_unit (cu, this_cu);
7624       /* If an error occurs while loading, release our storage.  */
7625       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7626     }
7627
7628   /* A future optimization, if needed, would be to use an existing
7629      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7630      could share abbrev tables.  */
7631
7632   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7633                               0 /* abbrev_table_provided */,
7634                               NULL /* stub_comp_unit_die */,
7635                               sig_type->dwo_unit->dwo_file->comp_dir,
7636                               &reader, &info_ptr,
7637                               &comp_unit_die, &has_children) == 0)
7638     {
7639       /* Dummy die.  */
7640       do_cleanups (cleanups);
7641       return;
7642     }
7643
7644   /* All the "real" work is done here.  */
7645   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7646
7647   /* This duplicates the code in init_cutu_and_read_dies,
7648      but the alternative is making the latter more complex.
7649      This function is only for the special case of using DWO files directly:
7650      no point in overly complicating the general case just to handle this.  */
7651   if (free_cu_cleanup != NULL)
7652     {
7653       if (keep)
7654         {
7655           /* We've successfully allocated this compilation unit.  Let our
7656              caller clean it up when finished with it.  */
7657           discard_cleanups (free_cu_cleanup);
7658
7659           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7660              So we have to manually free the abbrev table.  */
7661           dwarf2_free_abbrev_table (cu);
7662
7663           /* Link this CU into read_in_chain.  */
7664           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7665           dwarf2_per_objfile->read_in_chain = this_cu;
7666         }
7667       else
7668         do_cleanups (free_cu_cleanup);
7669     }
7670
7671   do_cleanups (cleanups);
7672 }
7673
7674 /* Initialize a CU (or TU) and read its DIEs.
7675    If the CU defers to a DWO file, read the DWO file as well.
7676
7677    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7678    Otherwise the table specified in the comp unit header is read in and used.
7679    This is an optimization for when we already have the abbrev table.
7680
7681    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7682    Otherwise, a new CU is allocated with xmalloc.
7683
7684    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7685    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7686
7687    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7688    linker) then DIE_READER_FUNC will not get called.  */
7689
7690 static void
7691 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7692                          struct abbrev_table *abbrev_table,
7693                          int use_existing_cu, int keep,
7694                          die_reader_func_ftype *die_reader_func,
7695                          void *data)
7696 {
7697   struct objfile *objfile = dwarf2_per_objfile->objfile;
7698   struct dwarf2_section_info *section = this_cu->section;
7699   bfd *abfd = get_section_bfd_owner (section);
7700   struct dwarf2_cu *cu;
7701   const gdb_byte *begin_info_ptr, *info_ptr;
7702   struct die_reader_specs reader;
7703   struct die_info *comp_unit_die;
7704   int has_children;
7705   struct attribute *attr;
7706   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7707   struct signatured_type *sig_type = NULL;
7708   struct dwarf2_section_info *abbrev_section;
7709   /* Non-zero if CU currently points to a DWO file and we need to
7710      reread it.  When this happens we need to reread the skeleton die
7711      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7712   int rereading_dwo_cu = 0;
7713
7714   if (dwarf_die_debug)
7715     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7716                         this_cu->is_debug_types ? "type" : "comp",
7717                         to_underlying (this_cu->sect_off));
7718
7719   if (use_existing_cu)
7720     gdb_assert (keep);
7721
7722   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7723      file (instead of going through the stub), short-circuit all of this.  */
7724   if (this_cu->reading_dwo_directly)
7725     {
7726       /* Narrow down the scope of possibilities to have to understand.  */
7727       gdb_assert (this_cu->is_debug_types);
7728       gdb_assert (abbrev_table == NULL);
7729       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7730                                  die_reader_func, data);
7731       return;
7732     }
7733
7734   cleanups = make_cleanup (null_cleanup, NULL);
7735
7736   /* This is cheap if the section is already read in.  */
7737   dwarf2_read_section (objfile, section);
7738
7739   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7740
7741   abbrev_section = get_abbrev_section_for_cu (this_cu);
7742
7743   if (use_existing_cu && this_cu->cu != NULL)
7744     {
7745       cu = this_cu->cu;
7746       /* If this CU is from a DWO file we need to start over, we need to
7747          refetch the attributes from the skeleton CU.
7748          This could be optimized by retrieving those attributes from when we
7749          were here the first time: the previous comp_unit_die was stored in
7750          comp_unit_obstack.  But there's no data yet that we need this
7751          optimization.  */
7752       if (cu->dwo_unit != NULL)
7753         rereading_dwo_cu = 1;
7754     }
7755   else
7756     {
7757       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7758       gdb_assert (this_cu->cu == NULL);
7759       cu = XNEW (struct dwarf2_cu);
7760       init_one_comp_unit (cu, this_cu);
7761       /* If an error occurs while loading, release our storage.  */
7762       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7763     }
7764
7765   /* Get the header.  */
7766   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7767     {
7768       /* We already have the header, there's no need to read it in again.  */
7769       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7770     }
7771   else
7772     {
7773       if (this_cu->is_debug_types)
7774         {
7775           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7776                                                     abbrev_section, info_ptr,
7777                                                     rcuh_kind::TYPE);
7778
7779           /* Since per_cu is the first member of struct signatured_type,
7780              we can go from a pointer to one to a pointer to the other.  */
7781           sig_type = (struct signatured_type *) this_cu;
7782           gdb_assert (sig_type->signature == cu->header.signature);
7783           gdb_assert (sig_type->type_offset_in_tu
7784                       == cu->header.type_cu_offset_in_tu);
7785           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7786
7787           /* LENGTH has not been set yet for type units if we're
7788              using .gdb_index.  */
7789           this_cu->length = get_cu_length (&cu->header);
7790
7791           /* Establish the type offset that can be used to lookup the type.  */
7792           sig_type->type_offset_in_section =
7793             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7794
7795           this_cu->dwarf_version = cu->header.version;
7796         }
7797       else
7798         {
7799           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
7800                                                     abbrev_section,
7801                                                     info_ptr,
7802                                                     rcuh_kind::COMPILE);
7803
7804           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7805           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7806           this_cu->dwarf_version = cu->header.version;
7807         }
7808     }
7809
7810   /* Skip dummy compilation units.  */
7811   if (info_ptr >= begin_info_ptr + this_cu->length
7812       || peek_abbrev_code (abfd, info_ptr) == 0)
7813     {
7814       do_cleanups (cleanups);
7815       return;
7816     }
7817
7818   /* If we don't have them yet, read the abbrevs for this compilation unit.
7819      And if we need to read them now, make sure they're freed when we're
7820      done.  Note that it's important that if the CU had an abbrev table
7821      on entry we don't free it when we're done: Somewhere up the call stack
7822      it may be in use.  */
7823   if (abbrev_table != NULL)
7824     {
7825       gdb_assert (cu->abbrev_table == NULL);
7826       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7827       cu->abbrev_table = abbrev_table;
7828     }
7829   else if (cu->abbrev_table == NULL)
7830     {
7831       dwarf2_read_abbrevs (cu, abbrev_section);
7832       make_cleanup (dwarf2_free_abbrev_table, cu);
7833     }
7834   else if (rereading_dwo_cu)
7835     {
7836       dwarf2_free_abbrev_table (cu);
7837       dwarf2_read_abbrevs (cu, abbrev_section);
7838     }
7839
7840   /* Read the top level CU/TU die.  */
7841   init_cu_die_reader (&reader, cu, section, NULL);
7842   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7843
7844   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7845      from the DWO file.
7846      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7847      DWO CU, that this test will fail (the attribute will not be present).  */
7848   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7849   if (attr)
7850     {
7851       struct dwo_unit *dwo_unit;
7852       struct die_info *dwo_comp_unit_die;
7853
7854       if (has_children)
7855         {
7856           complaint (&symfile_complaints,
7857                      _("compilation unit with DW_AT_GNU_dwo_name"
7858                        " has children (offset 0x%x) [in module %s]"),
7859                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7860         }
7861       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7862       if (dwo_unit != NULL)
7863         {
7864           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7865                                       abbrev_table != NULL,
7866                                       comp_unit_die, NULL,
7867                                       &reader, &info_ptr,
7868                                       &dwo_comp_unit_die, &has_children) == 0)
7869             {
7870               /* Dummy die.  */
7871               do_cleanups (cleanups);
7872               return;
7873             }
7874           comp_unit_die = dwo_comp_unit_die;
7875         }
7876       else
7877         {
7878           /* Yikes, we couldn't find the rest of the DIE, we only have
7879              the stub.  A complaint has already been logged.  There's
7880              not much more we can do except pass on the stub DIE to
7881              die_reader_func.  We don't want to throw an error on bad
7882              debug info.  */
7883         }
7884     }
7885
7886   /* All of the above is setup for this call.  Yikes.  */
7887   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7888
7889   /* Done, clean up.  */
7890   if (free_cu_cleanup != NULL)
7891     {
7892       if (keep)
7893         {
7894           /* We've successfully allocated this compilation unit.  Let our
7895              caller clean it up when finished with it.  */
7896           discard_cleanups (free_cu_cleanup);
7897
7898           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7899              So we have to manually free the abbrev table.  */
7900           dwarf2_free_abbrev_table (cu);
7901
7902           /* Link this CU into read_in_chain.  */
7903           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7904           dwarf2_per_objfile->read_in_chain = this_cu;
7905         }
7906       else
7907         do_cleanups (free_cu_cleanup);
7908     }
7909
7910   do_cleanups (cleanups);
7911 }
7912
7913 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7914    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7915    to have already done the lookup to find the DWO file).
7916
7917    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7918    THIS_CU->is_debug_types, but nothing else.
7919
7920    We fill in THIS_CU->length.
7921
7922    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7923    linker) then DIE_READER_FUNC will not get called.
7924
7925    THIS_CU->cu is always freed when done.
7926    This is done in order to not leave THIS_CU->cu in a state where we have
7927    to care whether it refers to the "main" CU or the DWO CU.  */
7928
7929 static void
7930 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7931                                    struct dwo_file *dwo_file,
7932                                    die_reader_func_ftype *die_reader_func,
7933                                    void *data)
7934 {
7935   struct objfile *objfile = dwarf2_per_objfile->objfile;
7936   struct dwarf2_section_info *section = this_cu->section;
7937   bfd *abfd = get_section_bfd_owner (section);
7938   struct dwarf2_section_info *abbrev_section;
7939   struct dwarf2_cu cu;
7940   const gdb_byte *begin_info_ptr, *info_ptr;
7941   struct die_reader_specs reader;
7942   struct cleanup *cleanups;
7943   struct die_info *comp_unit_die;
7944   int has_children;
7945
7946   if (dwarf_die_debug)
7947     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7948                         this_cu->is_debug_types ? "type" : "comp",
7949                         to_underlying (this_cu->sect_off));
7950
7951   gdb_assert (this_cu->cu == NULL);
7952
7953   abbrev_section = (dwo_file != NULL
7954                     ? &dwo_file->sections.abbrev
7955                     : get_abbrev_section_for_cu (this_cu));
7956
7957   /* This is cheap if the section is already read in.  */
7958   dwarf2_read_section (objfile, section);
7959
7960   init_one_comp_unit (&cu, this_cu);
7961
7962   cleanups = make_cleanup (free_stack_comp_unit, &cu);
7963
7964   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7965   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
7966                                             abbrev_section, info_ptr,
7967                                             (this_cu->is_debug_types
7968                                              ? rcuh_kind::TYPE
7969                                              : rcuh_kind::COMPILE));
7970
7971   this_cu->length = get_cu_length (&cu.header);
7972
7973   /* Skip dummy compilation units.  */
7974   if (info_ptr >= begin_info_ptr + this_cu->length
7975       || peek_abbrev_code (abfd, info_ptr) == 0)
7976     {
7977       do_cleanups (cleanups);
7978       return;
7979     }
7980
7981   dwarf2_read_abbrevs (&cu, abbrev_section);
7982   make_cleanup (dwarf2_free_abbrev_table, &cu);
7983
7984   init_cu_die_reader (&reader, &cu, section, dwo_file);
7985   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7986
7987   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7988
7989   do_cleanups (cleanups);
7990 }
7991
7992 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7993    does not lookup the specified DWO file.
7994    This cannot be used to read DWO files.
7995
7996    THIS_CU->cu is always freed when done.
7997    This is done in order to not leave THIS_CU->cu in a state where we have
7998    to care whether it refers to the "main" CU or the DWO CU.
7999    We can revisit this if the data shows there's a performance issue.  */
8000
8001 static void
8002 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8003                                 die_reader_func_ftype *die_reader_func,
8004                                 void *data)
8005 {
8006   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8007 }
8008 \f
8009 /* Type Unit Groups.
8010
8011    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8012    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8013    so that all types coming from the same compilation (.o file) are grouped
8014    together.  A future step could be to put the types in the same symtab as
8015    the CU the types ultimately came from.  */
8016
8017 static hashval_t
8018 hash_type_unit_group (const void *item)
8019 {
8020   const struct type_unit_group *tu_group
8021     = (const struct type_unit_group *) item;
8022
8023   return hash_stmt_list_entry (&tu_group->hash);
8024 }
8025
8026 static int
8027 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8028 {
8029   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8030   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8031
8032   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8033 }
8034
8035 /* Allocate a hash table for type unit groups.  */
8036
8037 static htab_t
8038 allocate_type_unit_groups_table (void)
8039 {
8040   return htab_create_alloc_ex (3,
8041                                hash_type_unit_group,
8042                                eq_type_unit_group,
8043                                NULL,
8044                                &dwarf2_per_objfile->objfile->objfile_obstack,
8045                                hashtab_obstack_allocate,
8046                                dummy_obstack_deallocate);
8047 }
8048
8049 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8050    partial symtabs.  We combine several TUs per psymtab to not let the size
8051    of any one psymtab grow too big.  */
8052 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8053 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8054
8055 /* Helper routine for get_type_unit_group.
8056    Create the type_unit_group object used to hold one or more TUs.  */
8057
8058 static struct type_unit_group *
8059 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8060 {
8061   struct objfile *objfile = dwarf2_per_objfile->objfile;
8062   struct dwarf2_per_cu_data *per_cu;
8063   struct type_unit_group *tu_group;
8064
8065   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8066                              struct type_unit_group);
8067   per_cu = &tu_group->per_cu;
8068   per_cu->objfile = objfile;
8069
8070   if (dwarf2_per_objfile->using_index)
8071     {
8072       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8073                                         struct dwarf2_per_cu_quick_data);
8074     }
8075   else
8076     {
8077       unsigned int line_offset = to_underlying (line_offset_struct);
8078       struct partial_symtab *pst;
8079       char *name;
8080
8081       /* Give the symtab a useful name for debug purposes.  */
8082       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8083         name = xstrprintf ("<type_units_%d>",
8084                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8085       else
8086         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8087
8088       pst = create_partial_symtab (per_cu, name);
8089       pst->anonymous = 1;
8090
8091       xfree (name);
8092     }
8093
8094   tu_group->hash.dwo_unit = cu->dwo_unit;
8095   tu_group->hash.line_sect_off = line_offset_struct;
8096
8097   return tu_group;
8098 }
8099
8100 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8101    STMT_LIST is a DW_AT_stmt_list attribute.  */
8102
8103 static struct type_unit_group *
8104 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8105 {
8106   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8107   struct type_unit_group *tu_group;
8108   void **slot;
8109   unsigned int line_offset;
8110   struct type_unit_group type_unit_group_for_lookup;
8111
8112   if (dwarf2_per_objfile->type_unit_groups == NULL)
8113     {
8114       dwarf2_per_objfile->type_unit_groups =
8115         allocate_type_unit_groups_table ();
8116     }
8117
8118   /* Do we need to create a new group, or can we use an existing one?  */
8119
8120   if (stmt_list)
8121     {
8122       line_offset = DW_UNSND (stmt_list);
8123       ++tu_stats->nr_symtab_sharers;
8124     }
8125   else
8126     {
8127       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8128          We can do various things here like create one group per TU or
8129          spread them over multiple groups to split up the expansion work.
8130          To avoid worst case scenarios (too many groups or too large groups)
8131          we, umm, group them in bunches.  */
8132       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8133                      | (tu_stats->nr_stmt_less_type_units
8134                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8135       ++tu_stats->nr_stmt_less_type_units;
8136     }
8137
8138   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8139   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8140   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8141                          &type_unit_group_for_lookup, INSERT);
8142   if (*slot != NULL)
8143     {
8144       tu_group = (struct type_unit_group *) *slot;
8145       gdb_assert (tu_group != NULL);
8146     }
8147   else
8148     {
8149       sect_offset line_offset_struct = (sect_offset) line_offset;
8150       tu_group = create_type_unit_group (cu, line_offset_struct);
8151       *slot = tu_group;
8152       ++tu_stats->nr_symtabs;
8153     }
8154
8155   return tu_group;
8156 }
8157 \f
8158 /* Partial symbol tables.  */
8159
8160 /* Create a psymtab named NAME and assign it to PER_CU.
8161
8162    The caller must fill in the following details:
8163    dirname, textlow, texthigh.  */
8164
8165 static struct partial_symtab *
8166 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8167 {
8168   struct objfile *objfile = per_cu->objfile;
8169   struct partial_symtab *pst;
8170
8171   pst = start_psymtab_common (objfile, name, 0,
8172                               objfile->global_psymbols,
8173                               objfile->static_psymbols);
8174
8175   pst->psymtabs_addrmap_supported = 1;
8176
8177   /* This is the glue that links PST into GDB's symbol API.  */
8178   pst->read_symtab_private = per_cu;
8179   pst->read_symtab = dwarf2_read_symtab;
8180   per_cu->v.psymtab = pst;
8181
8182   return pst;
8183 }
8184
8185 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8186    type.  */
8187
8188 struct process_psymtab_comp_unit_data
8189 {
8190   /* True if we are reading a DW_TAG_partial_unit.  */
8191
8192   int want_partial_unit;
8193
8194   /* The "pretend" language that is used if the CU doesn't declare a
8195      language.  */
8196
8197   enum language pretend_language;
8198 };
8199
8200 /* die_reader_func for process_psymtab_comp_unit.  */
8201
8202 static void
8203 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8204                                   const gdb_byte *info_ptr,
8205                                   struct die_info *comp_unit_die,
8206                                   int has_children,
8207                                   void *data)
8208 {
8209   struct dwarf2_cu *cu = reader->cu;
8210   struct objfile *objfile = cu->objfile;
8211   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8212   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8213   CORE_ADDR baseaddr;
8214   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8215   struct partial_symtab *pst;
8216   enum pc_bounds_kind cu_bounds_kind;
8217   const char *filename;
8218   struct process_psymtab_comp_unit_data *info
8219     = (struct process_psymtab_comp_unit_data *) data;
8220
8221   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8222     return;
8223
8224   gdb_assert (! per_cu->is_debug_types);
8225
8226   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8227
8228   cu->list_in_scope = &file_symbols;
8229
8230   /* Allocate a new partial symbol table structure.  */
8231   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8232   if (filename == NULL)
8233     filename = "";
8234
8235   pst = create_partial_symtab (per_cu, filename);
8236
8237   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8238   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8239
8240   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8241
8242   dwarf2_find_base_address (comp_unit_die, cu);
8243
8244   /* Possibly set the default values of LOWPC and HIGHPC from
8245      `DW_AT_ranges'.  */
8246   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8247                                          &best_highpc, cu, pst);
8248   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8249     /* Store the contiguous range if it is not empty; it can be empty for
8250        CUs with no code.  */
8251     addrmap_set_empty (objfile->psymtabs_addrmap,
8252                        gdbarch_adjust_dwarf2_addr (gdbarch,
8253                                                    best_lowpc + baseaddr),
8254                        gdbarch_adjust_dwarf2_addr (gdbarch,
8255                                                    best_highpc + baseaddr) - 1,
8256                        pst);
8257
8258   /* Check if comp unit has_children.
8259      If so, read the rest of the partial symbols from this comp unit.
8260      If not, there's no more debug_info for this comp unit.  */
8261   if (has_children)
8262     {
8263       struct partial_die_info *first_die;
8264       CORE_ADDR lowpc, highpc;
8265
8266       lowpc = ((CORE_ADDR) -1);
8267       highpc = ((CORE_ADDR) 0);
8268
8269       first_die = load_partial_dies (reader, info_ptr, 1);
8270
8271       scan_partial_symbols (first_die, &lowpc, &highpc,
8272                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8273
8274       /* If we didn't find a lowpc, set it to highpc to avoid
8275          complaints from `maint check'.  */
8276       if (lowpc == ((CORE_ADDR) -1))
8277         lowpc = highpc;
8278
8279       /* If the compilation unit didn't have an explicit address range,
8280          then use the information extracted from its child dies.  */
8281       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8282         {
8283           best_lowpc = lowpc;
8284           best_highpc = highpc;
8285         }
8286     }
8287   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8288   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8289
8290   end_psymtab_common (objfile, pst);
8291
8292   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8293     {
8294       int i;
8295       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8296       struct dwarf2_per_cu_data *iter;
8297
8298       /* Fill in 'dependencies' here; we fill in 'users' in a
8299          post-pass.  */
8300       pst->number_of_dependencies = len;
8301       pst->dependencies =
8302         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8303       for (i = 0;
8304            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8305                         i, iter);
8306            ++i)
8307         pst->dependencies[i] = iter->v.psymtab;
8308
8309       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8310     }
8311
8312   /* Get the list of files included in the current compilation unit,
8313      and build a psymtab for each of them.  */
8314   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8315
8316   if (dwarf_read_debug)
8317     {
8318       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8319
8320       fprintf_unfiltered (gdb_stdlog,
8321                           "Psymtab for %s unit @0x%x: %s - %s"
8322                           ", %d global, %d static syms\n",
8323                           per_cu->is_debug_types ? "type" : "comp",
8324                           to_underlying (per_cu->sect_off),
8325                           paddress (gdbarch, pst->textlow),
8326                           paddress (gdbarch, pst->texthigh),
8327                           pst->n_global_syms, pst->n_static_syms);
8328     }
8329 }
8330
8331 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8332    Process compilation unit THIS_CU for a psymtab.  */
8333
8334 static void
8335 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8336                            int want_partial_unit,
8337                            enum language pretend_language)
8338 {
8339   /* If this compilation unit was already read in, free the
8340      cached copy in order to read it in again.  This is
8341      necessary because we skipped some symbols when we first
8342      read in the compilation unit (see load_partial_dies).
8343      This problem could be avoided, but the benefit is unclear.  */
8344   if (this_cu->cu != NULL)
8345     free_one_cached_comp_unit (this_cu);
8346
8347   if (this_cu->is_debug_types)
8348     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8349                              NULL);
8350   else
8351     {
8352       process_psymtab_comp_unit_data info;
8353       info.want_partial_unit = want_partial_unit;
8354       info.pretend_language = pretend_language;
8355       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8356                                process_psymtab_comp_unit_reader, &info);
8357     }
8358
8359   /* Age out any secondary CUs.  */
8360   age_cached_comp_units ();
8361 }
8362
8363 /* Reader function for build_type_psymtabs.  */
8364
8365 static void
8366 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8367                             const gdb_byte *info_ptr,
8368                             struct die_info *type_unit_die,
8369                             int has_children,
8370                             void *data)
8371 {
8372   struct objfile *objfile = dwarf2_per_objfile->objfile;
8373   struct dwarf2_cu *cu = reader->cu;
8374   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8375   struct signatured_type *sig_type;
8376   struct type_unit_group *tu_group;
8377   struct attribute *attr;
8378   struct partial_die_info *first_die;
8379   CORE_ADDR lowpc, highpc;
8380   struct partial_symtab *pst;
8381
8382   gdb_assert (data == NULL);
8383   gdb_assert (per_cu->is_debug_types);
8384   sig_type = (struct signatured_type *) per_cu;
8385
8386   if (! has_children)
8387     return;
8388
8389   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8390   tu_group = get_type_unit_group (cu, attr);
8391
8392   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8393
8394   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8395   cu->list_in_scope = &file_symbols;
8396   pst = create_partial_symtab (per_cu, "");
8397   pst->anonymous = 1;
8398
8399   first_die = load_partial_dies (reader, info_ptr, 1);
8400
8401   lowpc = (CORE_ADDR) -1;
8402   highpc = (CORE_ADDR) 0;
8403   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8404
8405   end_psymtab_common (objfile, pst);
8406 }
8407
8408 /* Struct used to sort TUs by their abbreviation table offset.  */
8409
8410 struct tu_abbrev_offset
8411 {
8412   struct signatured_type *sig_type;
8413   sect_offset abbrev_offset;
8414 };
8415
8416 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8417
8418 static int
8419 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8420 {
8421   const struct tu_abbrev_offset * const *a
8422     = (const struct tu_abbrev_offset * const*) ap;
8423   const struct tu_abbrev_offset * const *b
8424     = (const struct tu_abbrev_offset * const*) bp;
8425   sect_offset aoff = (*a)->abbrev_offset;
8426   sect_offset boff = (*b)->abbrev_offset;
8427
8428   return (aoff > boff) - (aoff < boff);
8429 }
8430
8431 /* Efficiently read all the type units.
8432    This does the bulk of the work for build_type_psymtabs.
8433
8434    The efficiency is because we sort TUs by the abbrev table they use and
8435    only read each abbrev table once.  In one program there are 200K TUs
8436    sharing 8K abbrev tables.
8437
8438    The main purpose of this function is to support building the
8439    dwarf2_per_objfile->type_unit_groups table.
8440    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8441    can collapse the search space by grouping them by stmt_list.
8442    The savings can be significant, in the same program from above the 200K TUs
8443    share 8K stmt_list tables.
8444
8445    FUNC is expected to call get_type_unit_group, which will create the
8446    struct type_unit_group if necessary and add it to
8447    dwarf2_per_objfile->type_unit_groups.  */
8448
8449 static void
8450 build_type_psymtabs_1 (void)
8451 {
8452   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8453   struct cleanup *cleanups;
8454   struct abbrev_table *abbrev_table;
8455   sect_offset abbrev_offset;
8456   struct tu_abbrev_offset *sorted_by_abbrev;
8457   int i;
8458
8459   /* It's up to the caller to not call us multiple times.  */
8460   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8461
8462   if (dwarf2_per_objfile->n_type_units == 0)
8463     return;
8464
8465   /* TUs typically share abbrev tables, and there can be way more TUs than
8466      abbrev tables.  Sort by abbrev table to reduce the number of times we
8467      read each abbrev table in.
8468      Alternatives are to punt or to maintain a cache of abbrev tables.
8469      This is simpler and efficient enough for now.
8470
8471      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8472      symtab to use).  Typically TUs with the same abbrev offset have the same
8473      stmt_list value too so in practice this should work well.
8474
8475      The basic algorithm here is:
8476
8477       sort TUs by abbrev table
8478       for each TU with same abbrev table:
8479         read abbrev table if first user
8480         read TU top level DIE
8481           [IWBN if DWO skeletons had DW_AT_stmt_list]
8482         call FUNC  */
8483
8484   if (dwarf_read_debug)
8485     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8486
8487   /* Sort in a separate table to maintain the order of all_type_units
8488      for .gdb_index: TU indices directly index all_type_units.  */
8489   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8490                               dwarf2_per_objfile->n_type_units);
8491   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8492     {
8493       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8494
8495       sorted_by_abbrev[i].sig_type = sig_type;
8496       sorted_by_abbrev[i].abbrev_offset =
8497         read_abbrev_offset (sig_type->per_cu.section,
8498                             sig_type->per_cu.sect_off);
8499     }
8500   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8501   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8502          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8503
8504   abbrev_offset = (sect_offset) ~(unsigned) 0;
8505   abbrev_table = NULL;
8506   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
8507
8508   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8509     {
8510       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8511
8512       /* Switch to the next abbrev table if necessary.  */
8513       if (abbrev_table == NULL
8514           || tu->abbrev_offset != abbrev_offset)
8515         {
8516           if (abbrev_table != NULL)
8517             {
8518               abbrev_table_free (abbrev_table);
8519               /* Reset to NULL in case abbrev_table_read_table throws
8520                  an error: abbrev_table_free_cleanup will get called.  */
8521               abbrev_table = NULL;
8522             }
8523           abbrev_offset = tu->abbrev_offset;
8524           abbrev_table =
8525             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
8526                                      abbrev_offset);
8527           ++tu_stats->nr_uniq_abbrev_tables;
8528         }
8529
8530       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
8531                                build_type_psymtabs_reader, NULL);
8532     }
8533
8534   do_cleanups (cleanups);
8535 }
8536
8537 /* Print collected type unit statistics.  */
8538
8539 static void
8540 print_tu_stats (void)
8541 {
8542   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8543
8544   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8545   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8546                       dwarf2_per_objfile->n_type_units);
8547   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8548                       tu_stats->nr_uniq_abbrev_tables);
8549   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8550                       tu_stats->nr_symtabs);
8551   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8552                       tu_stats->nr_symtab_sharers);
8553   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8554                       tu_stats->nr_stmt_less_type_units);
8555   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8556                       tu_stats->nr_all_type_units_reallocs);
8557 }
8558
8559 /* Traversal function for build_type_psymtabs.  */
8560
8561 static int
8562 build_type_psymtab_dependencies (void **slot, void *info)
8563 {
8564   struct objfile *objfile = dwarf2_per_objfile->objfile;
8565   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8566   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8567   struct partial_symtab *pst = per_cu->v.psymtab;
8568   int len = VEC_length (sig_type_ptr, tu_group->tus);
8569   struct signatured_type *iter;
8570   int i;
8571
8572   gdb_assert (len > 0);
8573   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8574
8575   pst->number_of_dependencies = len;
8576   pst->dependencies =
8577     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8578   for (i = 0;
8579        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8580        ++i)
8581     {
8582       gdb_assert (iter->per_cu.is_debug_types);
8583       pst->dependencies[i] = iter->per_cu.v.psymtab;
8584       iter->type_unit_group = tu_group;
8585     }
8586
8587   VEC_free (sig_type_ptr, tu_group->tus);
8588
8589   return 1;
8590 }
8591
8592 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8593    Build partial symbol tables for the .debug_types comp-units.  */
8594
8595 static void
8596 build_type_psymtabs (struct objfile *objfile)
8597 {
8598   if (! create_all_type_units (objfile))
8599     return;
8600
8601   build_type_psymtabs_1 ();
8602 }
8603
8604 /* Traversal function for process_skeletonless_type_unit.
8605    Read a TU in a DWO file and build partial symbols for it.  */
8606
8607 static int
8608 process_skeletonless_type_unit (void **slot, void *info)
8609 {
8610   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8611   struct objfile *objfile = (struct objfile *) info;
8612   struct signatured_type find_entry, *entry;
8613
8614   /* If this TU doesn't exist in the global table, add it and read it in.  */
8615
8616   if (dwarf2_per_objfile->signatured_types == NULL)
8617     {
8618       dwarf2_per_objfile->signatured_types
8619         = allocate_signatured_type_table (objfile);
8620     }
8621
8622   find_entry.signature = dwo_unit->signature;
8623   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8624                          INSERT);
8625   /* If we've already seen this type there's nothing to do.  What's happening
8626      is we're doing our own version of comdat-folding here.  */
8627   if (*slot != NULL)
8628     return 1;
8629
8630   /* This does the job that create_all_type_units would have done for
8631      this TU.  */
8632   entry = add_type_unit (dwo_unit->signature, slot);
8633   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
8634   *slot = entry;
8635
8636   /* This does the job that build_type_psymtabs_1 would have done.  */
8637   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8638                            build_type_psymtabs_reader, NULL);
8639
8640   return 1;
8641 }
8642
8643 /* Traversal function for process_skeletonless_type_units.  */
8644
8645 static int
8646 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8647 {
8648   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8649
8650   if (dwo_file->tus != NULL)
8651     {
8652       htab_traverse_noresize (dwo_file->tus,
8653                               process_skeletonless_type_unit, info);
8654     }
8655
8656   return 1;
8657 }
8658
8659 /* Scan all TUs of DWO files, verifying we've processed them.
8660    This is needed in case a TU was emitted without its skeleton.
8661    Note: This can't be done until we know what all the DWO files are.  */
8662
8663 static void
8664 process_skeletonless_type_units (struct objfile *objfile)
8665 {
8666   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8667   if (get_dwp_file () == NULL
8668       && dwarf2_per_objfile->dwo_files != NULL)
8669     {
8670       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8671                               process_dwo_file_for_skeletonless_type_units,
8672                               objfile);
8673     }
8674 }
8675
8676 /* Compute the 'user' field for each psymtab in OBJFILE.  */
8677
8678 static void
8679 set_partial_user (struct objfile *objfile)
8680 {
8681   int i;
8682
8683   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8684     {
8685       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8686       struct partial_symtab *pst = per_cu->v.psymtab;
8687       int j;
8688
8689       if (pst == NULL)
8690         continue;
8691
8692       for (j = 0; j < pst->number_of_dependencies; ++j)
8693         {
8694           /* Set the 'user' field only if it is not already set.  */
8695           if (pst->dependencies[j]->user == NULL)
8696             pst->dependencies[j]->user = pst;
8697         }
8698     }
8699 }
8700
8701 /* Build the partial symbol table by doing a quick pass through the
8702    .debug_info and .debug_abbrev sections.  */
8703
8704 static void
8705 dwarf2_build_psymtabs_hard (struct objfile *objfile)
8706 {
8707   struct cleanup *back_to;
8708   int i;
8709
8710   if (dwarf_read_debug)
8711     {
8712       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8713                           objfile_name (objfile));
8714     }
8715
8716   dwarf2_per_objfile->reading_partial_symbols = 1;
8717
8718   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8719
8720   /* Any cached compilation units will be linked by the per-objfile
8721      read_in_chain.  Make sure to free them when we're done.  */
8722   back_to = make_cleanup (free_cached_comp_units, NULL);
8723
8724   build_type_psymtabs (objfile);
8725
8726   create_all_comp_units (objfile);
8727
8728   /* Create a temporary address map on a temporary obstack.  We later
8729      copy this to the final obstack.  */
8730   auto_obstack temp_obstack;
8731
8732   scoped_restore save_psymtabs_addrmap
8733     = make_scoped_restore (&objfile->psymtabs_addrmap,
8734                            addrmap_create_mutable (&temp_obstack));
8735
8736   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8737     {
8738       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
8739
8740       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8741     }
8742
8743   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8744   process_skeletonless_type_units (objfile);
8745
8746   /* Now that all TUs have been processed we can fill in the dependencies.  */
8747   if (dwarf2_per_objfile->type_unit_groups != NULL)
8748     {
8749       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8750                               build_type_psymtab_dependencies, NULL);
8751     }
8752
8753   if (dwarf_read_debug)
8754     print_tu_stats ();
8755
8756   set_partial_user (objfile);
8757
8758   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8759                                                     &objfile->objfile_obstack);
8760   /* At this point we want to keep the address map.  */
8761   save_psymtabs_addrmap.release ();
8762
8763   do_cleanups (back_to);
8764
8765   if (dwarf_read_debug)
8766     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8767                         objfile_name (objfile));
8768 }
8769
8770 /* die_reader_func for load_partial_comp_unit.  */
8771
8772 static void
8773 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8774                                const gdb_byte *info_ptr,
8775                                struct die_info *comp_unit_die,
8776                                int has_children,
8777                                void *data)
8778 {
8779   struct dwarf2_cu *cu = reader->cu;
8780
8781   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8782
8783   /* Check if comp unit has_children.
8784      If so, read the rest of the partial symbols from this comp unit.
8785      If not, there's no more debug_info for this comp unit.  */
8786   if (has_children)
8787     load_partial_dies (reader, info_ptr, 0);
8788 }
8789
8790 /* Load the partial DIEs for a secondary CU into memory.
8791    This is also used when rereading a primary CU with load_all_dies.  */
8792
8793 static void
8794 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8795 {
8796   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8797                            load_partial_comp_unit_reader, NULL);
8798 }
8799
8800 static void
8801 read_comp_units_from_section (struct objfile *objfile,
8802                               struct dwarf2_section_info *section,
8803                               struct dwarf2_section_info *abbrev_section,
8804                               unsigned int is_dwz,
8805                               int *n_allocated,
8806                               int *n_comp_units,
8807                               struct dwarf2_per_cu_data ***all_comp_units)
8808 {
8809   const gdb_byte *info_ptr;
8810
8811   if (dwarf_read_debug)
8812     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8813                         get_section_name (section),
8814                         get_section_file_name (section));
8815
8816   dwarf2_read_section (objfile, section);
8817
8818   info_ptr = section->buffer;
8819
8820   while (info_ptr < section->buffer + section->size)
8821     {
8822       struct dwarf2_per_cu_data *this_cu;
8823
8824       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8825
8826       comp_unit_head cu_header;
8827       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
8828                                      info_ptr, rcuh_kind::COMPILE);
8829
8830       /* Save the compilation unit for later lookup.  */
8831       if (cu_header.unit_type != DW_UT_type)
8832         {
8833           this_cu = XOBNEW (&objfile->objfile_obstack,
8834                             struct dwarf2_per_cu_data);
8835           memset (this_cu, 0, sizeof (*this_cu));
8836         }
8837       else
8838         {
8839           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8840                                   struct signatured_type);
8841           memset (sig_type, 0, sizeof (*sig_type));
8842           sig_type->signature = cu_header.signature;
8843           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8844           this_cu = &sig_type->per_cu;
8845         }
8846       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8847       this_cu->sect_off = sect_off;
8848       this_cu->length = cu_header.length + cu_header.initial_length_size;
8849       this_cu->is_dwz = is_dwz;
8850       this_cu->objfile = objfile;
8851       this_cu->section = section;
8852
8853       if (*n_comp_units == *n_allocated)
8854         {
8855           *n_allocated *= 2;
8856           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8857                                         *all_comp_units, *n_allocated);
8858         }
8859       (*all_comp_units)[*n_comp_units] = this_cu;
8860       ++*n_comp_units;
8861
8862       info_ptr = info_ptr + this_cu->length;
8863     }
8864 }
8865
8866 /* Create a list of all compilation units in OBJFILE.
8867    This is only done for -readnow and building partial symtabs.  */
8868
8869 static void
8870 create_all_comp_units (struct objfile *objfile)
8871 {
8872   int n_allocated;
8873   int n_comp_units;
8874   struct dwarf2_per_cu_data **all_comp_units;
8875   struct dwz_file *dwz;
8876
8877   n_comp_units = 0;
8878   n_allocated = 10;
8879   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
8880
8881   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
8882                                 &dwarf2_per_objfile->abbrev, 0,
8883                                 &n_allocated, &n_comp_units, &all_comp_units);
8884
8885   dwz = dwarf2_get_dwz_file ();
8886   if (dwz != NULL)
8887     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
8888                                   &n_allocated, &n_comp_units,
8889                                   &all_comp_units);
8890
8891   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
8892                                                   struct dwarf2_per_cu_data *,
8893                                                   n_comp_units);
8894   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
8895           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
8896   xfree (all_comp_units);
8897   dwarf2_per_objfile->n_comp_units = n_comp_units;
8898 }
8899
8900 /* Process all loaded DIEs for compilation unit CU, starting at
8901    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8902    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8903    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8904    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8905
8906 static void
8907 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8908                       CORE_ADDR *highpc, int set_addrmap,
8909                       struct dwarf2_cu *cu)
8910 {
8911   struct partial_die_info *pdi;
8912
8913   /* Now, march along the PDI's, descending into ones which have
8914      interesting children but skipping the children of the other ones,
8915      until we reach the end of the compilation unit.  */
8916
8917   pdi = first_die;
8918
8919   while (pdi != NULL)
8920     {
8921       fixup_partial_die (pdi, cu);
8922
8923       /* Anonymous namespaces or modules have no name but have interesting
8924          children, so we need to look at them.  Ditto for anonymous
8925          enums.  */
8926
8927       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8928           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8929           || pdi->tag == DW_TAG_imported_unit)
8930         {
8931           switch (pdi->tag)
8932             {
8933             case DW_TAG_subprogram:
8934               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8935               break;
8936             case DW_TAG_constant:
8937             case DW_TAG_variable:
8938             case DW_TAG_typedef:
8939             case DW_TAG_union_type:
8940               if (!pdi->is_declaration)
8941                 {
8942                   add_partial_symbol (pdi, cu);
8943                 }
8944               break;
8945             case DW_TAG_class_type:
8946             case DW_TAG_interface_type:
8947             case DW_TAG_structure_type:
8948               if (!pdi->is_declaration)
8949                 {
8950                   add_partial_symbol (pdi, cu);
8951                 }
8952               if (cu->language == language_rust && pdi->has_children)
8953                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8954                                       set_addrmap, cu);
8955               break;
8956             case DW_TAG_enumeration_type:
8957               if (!pdi->is_declaration)
8958                 add_partial_enumeration (pdi, cu);
8959               break;
8960             case DW_TAG_base_type:
8961             case DW_TAG_subrange_type:
8962               /* File scope base type definitions are added to the partial
8963                  symbol table.  */
8964               add_partial_symbol (pdi, cu);
8965               break;
8966             case DW_TAG_namespace:
8967               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8968               break;
8969             case DW_TAG_module:
8970               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8971               break;
8972             case DW_TAG_imported_unit:
8973               {
8974                 struct dwarf2_per_cu_data *per_cu;
8975
8976                 /* For now we don't handle imported units in type units.  */
8977                 if (cu->per_cu->is_debug_types)
8978                   {
8979                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8980                              " supported in type units [in module %s]"),
8981                            objfile_name (cu->objfile));
8982                   }
8983
8984                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
8985                                                            pdi->is_dwz,
8986                                                            cu->objfile);
8987
8988                 /* Go read the partial unit, if needed.  */
8989                 if (per_cu->v.psymtab == NULL)
8990                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8991
8992                 VEC_safe_push (dwarf2_per_cu_ptr,
8993                                cu->per_cu->imported_symtabs, per_cu);
8994               }
8995               break;
8996             case DW_TAG_imported_declaration:
8997               add_partial_symbol (pdi, cu);
8998               break;
8999             default:
9000               break;
9001             }
9002         }
9003
9004       /* If the die has a sibling, skip to the sibling.  */
9005
9006       pdi = pdi->die_sibling;
9007     }
9008 }
9009
9010 /* Functions used to compute the fully scoped name of a partial DIE.
9011
9012    Normally, this is simple.  For C++, the parent DIE's fully scoped
9013    name is concatenated with "::" and the partial DIE's name.
9014    Enumerators are an exception; they use the scope of their parent
9015    enumeration type, i.e. the name of the enumeration type is not
9016    prepended to the enumerator.
9017
9018    There are two complexities.  One is DW_AT_specification; in this
9019    case "parent" means the parent of the target of the specification,
9020    instead of the direct parent of the DIE.  The other is compilers
9021    which do not emit DW_TAG_namespace; in this case we try to guess
9022    the fully qualified name of structure types from their members'
9023    linkage names.  This must be done using the DIE's children rather
9024    than the children of any DW_AT_specification target.  We only need
9025    to do this for structures at the top level, i.e. if the target of
9026    any DW_AT_specification (if any; otherwise the DIE itself) does not
9027    have a parent.  */
9028
9029 /* Compute the scope prefix associated with PDI's parent, in
9030    compilation unit CU.  The result will be allocated on CU's
9031    comp_unit_obstack, or a copy of the already allocated PDI->NAME
9032    field.  NULL is returned if no prefix is necessary.  */
9033 static const char *
9034 partial_die_parent_scope (struct partial_die_info *pdi,
9035                           struct dwarf2_cu *cu)
9036 {
9037   const char *grandparent_scope;
9038   struct partial_die_info *parent, *real_pdi;
9039
9040   /* We need to look at our parent DIE; if we have a DW_AT_specification,
9041      then this means the parent of the specification DIE.  */
9042
9043   real_pdi = pdi;
9044   while (real_pdi->has_specification)
9045     real_pdi = find_partial_die (real_pdi->spec_offset,
9046                                  real_pdi->spec_is_dwz, cu);
9047
9048   parent = real_pdi->die_parent;
9049   if (parent == NULL)
9050     return NULL;
9051
9052   if (parent->scope_set)
9053     return parent->scope;
9054
9055   fixup_partial_die (parent, cu);
9056
9057   grandparent_scope = partial_die_parent_scope (parent, cu);
9058
9059   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
9060      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
9061      Work around this problem here.  */
9062   if (cu->language == language_cplus
9063       && parent->tag == DW_TAG_namespace
9064       && strcmp (parent->name, "::") == 0
9065       && grandparent_scope == NULL)
9066     {
9067       parent->scope = NULL;
9068       parent->scope_set = 1;
9069       return NULL;
9070     }
9071
9072   if (pdi->tag == DW_TAG_enumerator)
9073     /* Enumerators should not get the name of the enumeration as a prefix.  */
9074     parent->scope = grandparent_scope;
9075   else if (parent->tag == DW_TAG_namespace
9076       || parent->tag == DW_TAG_module
9077       || parent->tag == DW_TAG_structure_type
9078       || parent->tag == DW_TAG_class_type
9079       || parent->tag == DW_TAG_interface_type
9080       || parent->tag == DW_TAG_union_type
9081       || parent->tag == DW_TAG_enumeration_type)
9082     {
9083       if (grandparent_scope == NULL)
9084         parent->scope = parent->name;
9085       else
9086         parent->scope = typename_concat (&cu->comp_unit_obstack,
9087                                          grandparent_scope,
9088                                          parent->name, 0, cu);
9089     }
9090   else
9091     {
9092       /* FIXME drow/2004-04-01: What should we be doing with
9093          function-local names?  For partial symbols, we should probably be
9094          ignoring them.  */
9095       complaint (&symfile_complaints,
9096                  _("unhandled containing DIE tag %d for DIE at %d"),
9097                  parent->tag, to_underlying (pdi->sect_off));
9098       parent->scope = grandparent_scope;
9099     }
9100
9101   parent->scope_set = 1;
9102   return parent->scope;
9103 }
9104
9105 /* Return the fully scoped name associated with PDI, from compilation unit
9106    CU.  The result will be allocated with malloc.  */
9107
9108 static char *
9109 partial_die_full_name (struct partial_die_info *pdi,
9110                        struct dwarf2_cu *cu)
9111 {
9112   const char *parent_scope;
9113
9114   /* If this is a template instantiation, we can not work out the
9115      template arguments from partial DIEs.  So, unfortunately, we have
9116      to go through the full DIEs.  At least any work we do building
9117      types here will be reused if full symbols are loaded later.  */
9118   if (pdi->has_template_arguments)
9119     {
9120       fixup_partial_die (pdi, cu);
9121
9122       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
9123         {
9124           struct die_info *die;
9125           struct attribute attr;
9126           struct dwarf2_cu *ref_cu = cu;
9127
9128           /* DW_FORM_ref_addr is using section offset.  */
9129           attr.name = (enum dwarf_attribute) 0;
9130           attr.form = DW_FORM_ref_addr;
9131           attr.u.unsnd = to_underlying (pdi->sect_off);
9132           die = follow_die_ref (NULL, &attr, &ref_cu);
9133
9134           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
9135         }
9136     }
9137
9138   parent_scope = partial_die_parent_scope (pdi, cu);
9139   if (parent_scope == NULL)
9140     return NULL;
9141   else
9142     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
9143 }
9144
9145 static void
9146 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
9147 {
9148   struct objfile *objfile = cu->objfile;
9149   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9150   CORE_ADDR addr = 0;
9151   const char *actual_name = NULL;
9152   CORE_ADDR baseaddr;
9153   char *built_actual_name;
9154
9155   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9156
9157   built_actual_name = partial_die_full_name (pdi, cu);
9158   if (built_actual_name != NULL)
9159     actual_name = built_actual_name;
9160
9161   if (actual_name == NULL)
9162     actual_name = pdi->name;
9163
9164   switch (pdi->tag)
9165     {
9166     case DW_TAG_subprogram:
9167       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9168       if (pdi->is_external || cu->language == language_ada)
9169         {
9170           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9171              of the global scope.  But in Ada, we want to be able to access
9172              nested procedures globally.  So all Ada subprograms are stored
9173              in the global scope.  */
9174           add_psymbol_to_list (actual_name, strlen (actual_name),
9175                                built_actual_name != NULL,
9176                                VAR_DOMAIN, LOC_BLOCK,
9177                                &objfile->global_psymbols,
9178                                addr, cu->language, objfile);
9179         }
9180       else
9181         {
9182           add_psymbol_to_list (actual_name, strlen (actual_name),
9183                                built_actual_name != NULL,
9184                                VAR_DOMAIN, LOC_BLOCK,
9185                                &objfile->static_psymbols,
9186                                addr, cu->language, objfile);
9187         }
9188
9189       if (pdi->main_subprogram && actual_name != NULL)
9190         set_objfile_main_name (objfile, actual_name, cu->language);
9191       break;
9192     case DW_TAG_constant:
9193       {
9194         std::vector<partial_symbol *> *list;
9195
9196         if (pdi->is_external)
9197           list = &objfile->global_psymbols;
9198         else
9199           list = &objfile->static_psymbols;
9200         add_psymbol_to_list (actual_name, strlen (actual_name),
9201                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9202                              list, 0, cu->language, objfile);
9203       }
9204       break;
9205     case DW_TAG_variable:
9206       if (pdi->d.locdesc)
9207         addr = decode_locdesc (pdi->d.locdesc, cu);
9208
9209       if (pdi->d.locdesc
9210           && addr == 0
9211           && !dwarf2_per_objfile->has_section_at_zero)
9212         {
9213           /* A global or static variable may also have been stripped
9214              out by the linker if unused, in which case its address
9215              will be nullified; do not add such variables into partial
9216              symbol table then.  */
9217         }
9218       else if (pdi->is_external)
9219         {
9220           /* Global Variable.
9221              Don't enter into the minimal symbol tables as there is
9222              a minimal symbol table entry from the ELF symbols already.
9223              Enter into partial symbol table if it has a location
9224              descriptor or a type.
9225              If the location descriptor is missing, new_symbol will create
9226              a LOC_UNRESOLVED symbol, the address of the variable will then
9227              be determined from the minimal symbol table whenever the variable
9228              is referenced.
9229              The address for the partial symbol table entry is not
9230              used by GDB, but it comes in handy for debugging partial symbol
9231              table building.  */
9232
9233           if (pdi->d.locdesc || pdi->has_type)
9234             add_psymbol_to_list (actual_name, strlen (actual_name),
9235                                  built_actual_name != NULL,
9236                                  VAR_DOMAIN, LOC_STATIC,
9237                                  &objfile->global_psymbols,
9238                                  addr + baseaddr,
9239                                  cu->language, objfile);
9240         }
9241       else
9242         {
9243           int has_loc = pdi->d.locdesc != NULL;
9244
9245           /* Static Variable.  Skip symbols whose value we cannot know (those
9246              without location descriptors or constant values).  */
9247           if (!has_loc && !pdi->has_const_value)
9248             {
9249               xfree (built_actual_name);
9250               return;
9251             }
9252
9253           add_psymbol_to_list (actual_name, strlen (actual_name),
9254                                built_actual_name != NULL,
9255                                VAR_DOMAIN, LOC_STATIC,
9256                                &objfile->static_psymbols,
9257                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9258                                cu->language, objfile);
9259         }
9260       break;
9261     case DW_TAG_typedef:
9262     case DW_TAG_base_type:
9263     case DW_TAG_subrange_type:
9264       add_psymbol_to_list (actual_name, strlen (actual_name),
9265                            built_actual_name != NULL,
9266                            VAR_DOMAIN, LOC_TYPEDEF,
9267                            &objfile->static_psymbols,
9268                            0, cu->language, objfile);
9269       break;
9270     case DW_TAG_imported_declaration:
9271     case DW_TAG_namespace:
9272       add_psymbol_to_list (actual_name, strlen (actual_name),
9273                            built_actual_name != NULL,
9274                            VAR_DOMAIN, LOC_TYPEDEF,
9275                            &objfile->global_psymbols,
9276                            0, cu->language, objfile);
9277       break;
9278     case DW_TAG_module:
9279       add_psymbol_to_list (actual_name, strlen (actual_name),
9280                            built_actual_name != NULL,
9281                            MODULE_DOMAIN, LOC_TYPEDEF,
9282                            &objfile->global_psymbols,
9283                            0, cu->language, objfile);
9284       break;
9285     case DW_TAG_class_type:
9286     case DW_TAG_interface_type:
9287     case DW_TAG_structure_type:
9288     case DW_TAG_union_type:
9289     case DW_TAG_enumeration_type:
9290       /* Skip external references.  The DWARF standard says in the section
9291          about "Structure, Union, and Class Type Entries": "An incomplete
9292          structure, union or class type is represented by a structure,
9293          union or class entry that does not have a byte size attribute
9294          and that has a DW_AT_declaration attribute."  */
9295       if (!pdi->has_byte_size && pdi->is_declaration)
9296         {
9297           xfree (built_actual_name);
9298           return;
9299         }
9300
9301       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9302          static vs. global.  */
9303       add_psymbol_to_list (actual_name, strlen (actual_name),
9304                            built_actual_name != NULL,
9305                            STRUCT_DOMAIN, LOC_TYPEDEF,
9306                            cu->language == language_cplus
9307                            ? &objfile->global_psymbols
9308                            : &objfile->static_psymbols,
9309                            0, cu->language, objfile);
9310
9311       break;
9312     case DW_TAG_enumerator:
9313       add_psymbol_to_list (actual_name, strlen (actual_name),
9314                            built_actual_name != NULL,
9315                            VAR_DOMAIN, LOC_CONST,
9316                            cu->language == language_cplus
9317                            ? &objfile->global_psymbols
9318                            : &objfile->static_psymbols,
9319                            0, cu->language, objfile);
9320       break;
9321     default:
9322       break;
9323     }
9324
9325   xfree (built_actual_name);
9326 }
9327
9328 /* Read a partial die corresponding to a namespace; also, add a symbol
9329    corresponding to that namespace to the symbol table.  NAMESPACE is
9330    the name of the enclosing namespace.  */
9331
9332 static void
9333 add_partial_namespace (struct partial_die_info *pdi,
9334                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9335                        int set_addrmap, struct dwarf2_cu *cu)
9336 {
9337   /* Add a symbol for the namespace.  */
9338
9339   add_partial_symbol (pdi, cu);
9340
9341   /* Now scan partial symbols in that namespace.  */
9342
9343   if (pdi->has_children)
9344     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9345 }
9346
9347 /* Read a partial die corresponding to a Fortran module.  */
9348
9349 static void
9350 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9351                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9352 {
9353   /* Add a symbol for the namespace.  */
9354
9355   add_partial_symbol (pdi, cu);
9356
9357   /* Now scan partial symbols in that module.  */
9358
9359   if (pdi->has_children)
9360     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9361 }
9362
9363 /* Read a partial die corresponding to a subprogram and create a partial
9364    symbol for that subprogram.  When the CU language allows it, this
9365    routine also defines a partial symbol for each nested subprogram
9366    that this subprogram contains.  If SET_ADDRMAP is true, record the
9367    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
9368    and highest PC values found in PDI.
9369
9370    PDI may also be a lexical block, in which case we simply search
9371    recursively for subprograms defined inside that lexical block.
9372    Again, this is only performed when the CU language allows this
9373    type of definitions.  */
9374
9375 static void
9376 add_partial_subprogram (struct partial_die_info *pdi,
9377                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9378                         int set_addrmap, struct dwarf2_cu *cu)
9379 {
9380   if (pdi->tag == DW_TAG_subprogram)
9381     {
9382       if (pdi->has_pc_info)
9383         {
9384           if (pdi->lowpc < *lowpc)
9385             *lowpc = pdi->lowpc;
9386           if (pdi->highpc > *highpc)
9387             *highpc = pdi->highpc;
9388           if (set_addrmap)
9389             {
9390               struct objfile *objfile = cu->objfile;
9391               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9392               CORE_ADDR baseaddr;
9393               CORE_ADDR highpc;
9394               CORE_ADDR lowpc;
9395
9396               baseaddr = ANOFFSET (objfile->section_offsets,
9397                                    SECT_OFF_TEXT (objfile));
9398               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9399                                                   pdi->lowpc + baseaddr);
9400               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9401                                                    pdi->highpc + baseaddr);
9402               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9403                                  cu->per_cu->v.psymtab);
9404             }
9405         }
9406
9407       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9408         {
9409           if (!pdi->is_declaration)
9410             /* Ignore subprogram DIEs that do not have a name, they are
9411                illegal.  Do not emit a complaint at this point, we will
9412                do so when we convert this psymtab into a symtab.  */
9413             if (pdi->name)
9414               add_partial_symbol (pdi, cu);
9415         }
9416     }
9417
9418   if (! pdi->has_children)
9419     return;
9420
9421   if (cu->language == language_ada)
9422     {
9423       pdi = pdi->die_child;
9424       while (pdi != NULL)
9425         {
9426           fixup_partial_die (pdi, cu);
9427           if (pdi->tag == DW_TAG_subprogram
9428               || pdi->tag == DW_TAG_lexical_block)
9429             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9430           pdi = pdi->die_sibling;
9431         }
9432     }
9433 }
9434
9435 /* Read a partial die corresponding to an enumeration type.  */
9436
9437 static void
9438 add_partial_enumeration (struct partial_die_info *enum_pdi,
9439                          struct dwarf2_cu *cu)
9440 {
9441   struct partial_die_info *pdi;
9442
9443   if (enum_pdi->name != NULL)
9444     add_partial_symbol (enum_pdi, cu);
9445
9446   pdi = enum_pdi->die_child;
9447   while (pdi)
9448     {
9449       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9450         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9451       else
9452         add_partial_symbol (pdi, cu);
9453       pdi = pdi->die_sibling;
9454     }
9455 }
9456
9457 /* Return the initial uleb128 in the die at INFO_PTR.  */
9458
9459 static unsigned int
9460 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9461 {
9462   unsigned int bytes_read;
9463
9464   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9465 }
9466
9467 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
9468    Return the corresponding abbrev, or NULL if the number is zero (indicating
9469    an empty DIE).  In either case *BYTES_READ will be set to the length of
9470    the initial number.  */
9471
9472 static struct abbrev_info *
9473 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
9474                  struct dwarf2_cu *cu)
9475 {
9476   bfd *abfd = cu->objfile->obfd;
9477   unsigned int abbrev_number;
9478   struct abbrev_info *abbrev;
9479
9480   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9481
9482   if (abbrev_number == 0)
9483     return NULL;
9484
9485   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
9486   if (!abbrev)
9487     {
9488       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9489                " at offset 0x%x [in module %s]"),
9490              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9491              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9492     }
9493
9494   return abbrev;
9495 }
9496
9497 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9498    Returns a pointer to the end of a series of DIEs, terminated by an empty
9499    DIE.  Any children of the skipped DIEs will also be skipped.  */
9500
9501 static const gdb_byte *
9502 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9503 {
9504   struct dwarf2_cu *cu = reader->cu;
9505   struct abbrev_info *abbrev;
9506   unsigned int bytes_read;
9507
9508   while (1)
9509     {
9510       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
9511       if (abbrev == NULL)
9512         return info_ptr + bytes_read;
9513       else
9514         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9515     }
9516 }
9517
9518 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9519    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9520    abbrev corresponding to that skipped uleb128 should be passed in
9521    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9522    children.  */
9523
9524 static const gdb_byte *
9525 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9526               struct abbrev_info *abbrev)
9527 {
9528   unsigned int bytes_read;
9529   struct attribute attr;
9530   bfd *abfd = reader->abfd;
9531   struct dwarf2_cu *cu = reader->cu;
9532   const gdb_byte *buffer = reader->buffer;
9533   const gdb_byte *buffer_end = reader->buffer_end;
9534   unsigned int form, i;
9535
9536   for (i = 0; i < abbrev->num_attrs; i++)
9537     {
9538       /* The only abbrev we care about is DW_AT_sibling.  */
9539       if (abbrev->attrs[i].name == DW_AT_sibling)
9540         {
9541           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9542           if (attr.form == DW_FORM_ref_addr)
9543             complaint (&symfile_complaints,
9544                        _("ignoring absolute DW_AT_sibling"));
9545           else
9546             {
9547               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9548               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9549
9550               if (sibling_ptr < info_ptr)
9551                 complaint (&symfile_complaints,
9552                            _("DW_AT_sibling points backwards"));
9553               else if (sibling_ptr > reader->buffer_end)
9554                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9555               else
9556                 return sibling_ptr;
9557             }
9558         }
9559
9560       /* If it isn't DW_AT_sibling, skip this attribute.  */
9561       form = abbrev->attrs[i].form;
9562     skip_attribute:
9563       switch (form)
9564         {
9565         case DW_FORM_ref_addr:
9566           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9567              and later it is offset sized.  */
9568           if (cu->header.version == 2)
9569             info_ptr += cu->header.addr_size;
9570           else
9571             info_ptr += cu->header.offset_size;
9572           break;
9573         case DW_FORM_GNU_ref_alt:
9574           info_ptr += cu->header.offset_size;
9575           break;
9576         case DW_FORM_addr:
9577           info_ptr += cu->header.addr_size;
9578           break;
9579         case DW_FORM_data1:
9580         case DW_FORM_ref1:
9581         case DW_FORM_flag:
9582           info_ptr += 1;
9583           break;
9584         case DW_FORM_flag_present:
9585         case DW_FORM_implicit_const:
9586           break;
9587         case DW_FORM_data2:
9588         case DW_FORM_ref2:
9589           info_ptr += 2;
9590           break;
9591         case DW_FORM_data4:
9592         case DW_FORM_ref4:
9593           info_ptr += 4;
9594           break;
9595         case DW_FORM_data8:
9596         case DW_FORM_ref8:
9597         case DW_FORM_ref_sig8:
9598           info_ptr += 8;
9599           break;
9600         case DW_FORM_data16:
9601           info_ptr += 16;
9602           break;
9603         case DW_FORM_string:
9604           read_direct_string (abfd, info_ptr, &bytes_read);
9605           info_ptr += bytes_read;
9606           break;
9607         case DW_FORM_sec_offset:
9608         case DW_FORM_strp:
9609         case DW_FORM_GNU_strp_alt:
9610           info_ptr += cu->header.offset_size;
9611           break;
9612         case DW_FORM_exprloc:
9613         case DW_FORM_block:
9614           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9615           info_ptr += bytes_read;
9616           break;
9617         case DW_FORM_block1:
9618           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9619           break;
9620         case DW_FORM_block2:
9621           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9622           break;
9623         case DW_FORM_block4:
9624           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9625           break;
9626         case DW_FORM_sdata:
9627         case DW_FORM_udata:
9628         case DW_FORM_ref_udata:
9629         case DW_FORM_GNU_addr_index:
9630         case DW_FORM_GNU_str_index:
9631           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9632           break;
9633         case DW_FORM_indirect:
9634           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9635           info_ptr += bytes_read;
9636           /* We need to continue parsing from here, so just go back to
9637              the top.  */
9638           goto skip_attribute;
9639
9640         default:
9641           error (_("Dwarf Error: Cannot handle %s "
9642                    "in DWARF reader [in module %s]"),
9643                  dwarf_form_name (form),
9644                  bfd_get_filename (abfd));
9645         }
9646     }
9647
9648   if (abbrev->has_children)
9649     return skip_children (reader, info_ptr);
9650   else
9651     return info_ptr;
9652 }
9653
9654 /* Locate ORIG_PDI's sibling.
9655    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9656
9657 static const gdb_byte *
9658 locate_pdi_sibling (const struct die_reader_specs *reader,
9659                     struct partial_die_info *orig_pdi,
9660                     const gdb_byte *info_ptr)
9661 {
9662   /* Do we know the sibling already?  */
9663
9664   if (orig_pdi->sibling)
9665     return orig_pdi->sibling;
9666
9667   /* Are there any children to deal with?  */
9668
9669   if (!orig_pdi->has_children)
9670     return info_ptr;
9671
9672   /* Skip the children the long way.  */
9673
9674   return skip_children (reader, info_ptr);
9675 }
9676
9677 /* Expand this partial symbol table into a full symbol table.  SELF is
9678    not NULL.  */
9679
9680 static void
9681 dwarf2_read_symtab (struct partial_symtab *self,
9682                     struct objfile *objfile)
9683 {
9684   if (self->readin)
9685     {
9686       warning (_("bug: psymtab for %s is already read in."),
9687                self->filename);
9688     }
9689   else
9690     {
9691       if (info_verbose)
9692         {
9693           printf_filtered (_("Reading in symbols for %s..."),
9694                            self->filename);
9695           gdb_flush (gdb_stdout);
9696         }
9697
9698       /* Restore our global data.  */
9699       dwarf2_per_objfile
9700         = (struct dwarf2_per_objfile *) objfile_data (objfile,
9701                                                       dwarf2_objfile_data_key);
9702
9703       /* If this psymtab is constructed from a debug-only objfile, the
9704          has_section_at_zero flag will not necessarily be correct.  We
9705          can get the correct value for this flag by looking at the data
9706          associated with the (presumably stripped) associated objfile.  */
9707       if (objfile->separate_debug_objfile_backlink)
9708         {
9709           struct dwarf2_per_objfile *dpo_backlink
9710             = ((struct dwarf2_per_objfile *)
9711                objfile_data (objfile->separate_debug_objfile_backlink,
9712                              dwarf2_objfile_data_key));
9713
9714           dwarf2_per_objfile->has_section_at_zero
9715             = dpo_backlink->has_section_at_zero;
9716         }
9717
9718       dwarf2_per_objfile->reading_partial_symbols = 0;
9719
9720       psymtab_to_symtab_1 (self);
9721
9722       /* Finish up the debug error message.  */
9723       if (info_verbose)
9724         printf_filtered (_("done.\n"));
9725     }
9726
9727   process_cu_includes ();
9728 }
9729 \f
9730 /* Reading in full CUs.  */
9731
9732 /* Add PER_CU to the queue.  */
9733
9734 static void
9735 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9736                  enum language pretend_language)
9737 {
9738   struct dwarf2_queue_item *item;
9739
9740   per_cu->queued = 1;
9741   item = XNEW (struct dwarf2_queue_item);
9742   item->per_cu = per_cu;
9743   item->pretend_language = pretend_language;
9744   item->next = NULL;
9745
9746   if (dwarf2_queue == NULL)
9747     dwarf2_queue = item;
9748   else
9749     dwarf2_queue_tail->next = item;
9750
9751   dwarf2_queue_tail = item;
9752 }
9753
9754 /* If PER_CU is not yet queued, add it to the queue.
9755    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9756    dependency.
9757    The result is non-zero if PER_CU was queued, otherwise the result is zero
9758    meaning either PER_CU is already queued or it is already loaded.
9759
9760    N.B. There is an invariant here that if a CU is queued then it is loaded.
9761    The caller is required to load PER_CU if we return non-zero.  */
9762
9763 static int
9764 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9765                        struct dwarf2_per_cu_data *per_cu,
9766                        enum language pretend_language)
9767 {
9768   /* We may arrive here during partial symbol reading, if we need full
9769      DIEs to process an unusual case (e.g. template arguments).  Do
9770      not queue PER_CU, just tell our caller to load its DIEs.  */
9771   if (dwarf2_per_objfile->reading_partial_symbols)
9772     {
9773       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9774         return 1;
9775       return 0;
9776     }
9777
9778   /* Mark the dependence relation so that we don't flush PER_CU
9779      too early.  */
9780   if (dependent_cu != NULL)
9781     dwarf2_add_dependence (dependent_cu, per_cu);
9782
9783   /* If it's already on the queue, we have nothing to do.  */
9784   if (per_cu->queued)
9785     return 0;
9786
9787   /* If the compilation unit is already loaded, just mark it as
9788      used.  */
9789   if (per_cu->cu != NULL)
9790     {
9791       per_cu->cu->last_used = 0;
9792       return 0;
9793     }
9794
9795   /* Add it to the queue.  */
9796   queue_comp_unit (per_cu, pretend_language);
9797
9798   return 1;
9799 }
9800
9801 /* Process the queue.  */
9802
9803 static void
9804 process_queue (void)
9805 {
9806   struct dwarf2_queue_item *item, *next_item;
9807
9808   if (dwarf_read_debug)
9809     {
9810       fprintf_unfiltered (gdb_stdlog,
9811                           "Expanding one or more symtabs of objfile %s ...\n",
9812                           objfile_name (dwarf2_per_objfile->objfile));
9813     }
9814
9815   /* The queue starts out with one item, but following a DIE reference
9816      may load a new CU, adding it to the end of the queue.  */
9817   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9818     {
9819       if ((dwarf2_per_objfile->using_index
9820            ? !item->per_cu->v.quick->compunit_symtab
9821            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9822           /* Skip dummy CUs.  */
9823           && item->per_cu->cu != NULL)
9824         {
9825           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9826           unsigned int debug_print_threshold;
9827           char buf[100];
9828
9829           if (per_cu->is_debug_types)
9830             {
9831               struct signatured_type *sig_type =
9832                 (struct signatured_type *) per_cu;
9833
9834               sprintf (buf, "TU %s at offset 0x%x",
9835                        hex_string (sig_type->signature),
9836                        to_underlying (per_cu->sect_off));
9837               /* There can be 100s of TUs.
9838                  Only print them in verbose mode.  */
9839               debug_print_threshold = 2;
9840             }
9841           else
9842             {
9843               sprintf (buf, "CU at offset 0x%x",
9844                        to_underlying (per_cu->sect_off));
9845               debug_print_threshold = 1;
9846             }
9847
9848           if (dwarf_read_debug >= debug_print_threshold)
9849             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9850
9851           if (per_cu->is_debug_types)
9852             process_full_type_unit (per_cu, item->pretend_language);
9853           else
9854             process_full_comp_unit (per_cu, item->pretend_language);
9855
9856           if (dwarf_read_debug >= debug_print_threshold)
9857             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9858         }
9859
9860       item->per_cu->queued = 0;
9861       next_item = item->next;
9862       xfree (item);
9863     }
9864
9865   dwarf2_queue_tail = NULL;
9866
9867   if (dwarf_read_debug)
9868     {
9869       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9870                           objfile_name (dwarf2_per_objfile->objfile));
9871     }
9872 }
9873
9874 /* Free all allocated queue entries.  This function only releases anything if
9875    an error was thrown; if the queue was processed then it would have been
9876    freed as we went along.  */
9877
9878 static void
9879 dwarf2_release_queue (void *dummy)
9880 {
9881   struct dwarf2_queue_item *item, *last;
9882
9883   item = dwarf2_queue;
9884   while (item)
9885     {
9886       /* Anything still marked queued is likely to be in an
9887          inconsistent state, so discard it.  */
9888       if (item->per_cu->queued)
9889         {
9890           if (item->per_cu->cu != NULL)
9891             free_one_cached_comp_unit (item->per_cu);
9892           item->per_cu->queued = 0;
9893         }
9894
9895       last = item;
9896       item = item->next;
9897       xfree (last);
9898     }
9899
9900   dwarf2_queue = dwarf2_queue_tail = NULL;
9901 }
9902
9903 /* Read in full symbols for PST, and anything it depends on.  */
9904
9905 static void
9906 psymtab_to_symtab_1 (struct partial_symtab *pst)
9907 {
9908   struct dwarf2_per_cu_data *per_cu;
9909   int i;
9910
9911   if (pst->readin)
9912     return;
9913
9914   for (i = 0; i < pst->number_of_dependencies; i++)
9915     if (!pst->dependencies[i]->readin
9916         && pst->dependencies[i]->user == NULL)
9917       {
9918         /* Inform about additional files that need to be read in.  */
9919         if (info_verbose)
9920           {
9921             /* FIXME: i18n: Need to make this a single string.  */
9922             fputs_filtered (" ", gdb_stdout);
9923             wrap_here ("");
9924             fputs_filtered ("and ", gdb_stdout);
9925             wrap_here ("");
9926             printf_filtered ("%s...", pst->dependencies[i]->filename);
9927             wrap_here ("");     /* Flush output.  */
9928             gdb_flush (gdb_stdout);
9929           }
9930         psymtab_to_symtab_1 (pst->dependencies[i]);
9931       }
9932
9933   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9934
9935   if (per_cu == NULL)
9936     {
9937       /* It's an include file, no symbols to read for it.
9938          Everything is in the parent symtab.  */
9939       pst->readin = 1;
9940       return;
9941     }
9942
9943   dw2_do_instantiate_symtab (per_cu);
9944 }
9945
9946 /* Trivial hash function for die_info: the hash value of a DIE
9947    is its offset in .debug_info for this objfile.  */
9948
9949 static hashval_t
9950 die_hash (const void *item)
9951 {
9952   const struct die_info *die = (const struct die_info *) item;
9953
9954   return to_underlying (die->sect_off);
9955 }
9956
9957 /* Trivial comparison function for die_info structures: two DIEs
9958    are equal if they have the same offset.  */
9959
9960 static int
9961 die_eq (const void *item_lhs, const void *item_rhs)
9962 {
9963   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9964   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9965
9966   return die_lhs->sect_off == die_rhs->sect_off;
9967 }
9968
9969 /* die_reader_func for load_full_comp_unit.
9970    This is identical to read_signatured_type_reader,
9971    but is kept separate for now.  */
9972
9973 static void
9974 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9975                             const gdb_byte *info_ptr,
9976                             struct die_info *comp_unit_die,
9977                             int has_children,
9978                             void *data)
9979 {
9980   struct dwarf2_cu *cu = reader->cu;
9981   enum language *language_ptr = (enum language *) data;
9982
9983   gdb_assert (cu->die_hash == NULL);
9984   cu->die_hash =
9985     htab_create_alloc_ex (cu->header.length / 12,
9986                           die_hash,
9987                           die_eq,
9988                           NULL,
9989                           &cu->comp_unit_obstack,
9990                           hashtab_obstack_allocate,
9991                           dummy_obstack_deallocate);
9992
9993   if (has_children)
9994     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9995                                                   &info_ptr, comp_unit_die);
9996   cu->dies = comp_unit_die;
9997   /* comp_unit_die is not stored in die_hash, no need.  */
9998
9999   /* We try not to read any attributes in this function, because not
10000      all CUs needed for references have been loaded yet, and symbol
10001      table processing isn't initialized.  But we have to set the CU language,
10002      or we won't be able to build types correctly.
10003      Similarly, if we do not read the producer, we can not apply
10004      producer-specific interpretation.  */
10005   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10006 }
10007
10008 /* Load the DIEs associated with PER_CU into memory.  */
10009
10010 static void
10011 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10012                      enum language pretend_language)
10013 {
10014   gdb_assert (! this_cu->is_debug_types);
10015
10016   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10017                            load_full_comp_unit_reader, &pretend_language);
10018 }
10019
10020 /* Add a DIE to the delayed physname list.  */
10021
10022 static void
10023 add_to_method_list (struct type *type, int fnfield_index, int index,
10024                     const char *name, struct die_info *die,
10025                     struct dwarf2_cu *cu)
10026 {
10027   struct delayed_method_info mi;
10028   mi.type = type;
10029   mi.fnfield_index = fnfield_index;
10030   mi.index = index;
10031   mi.name = name;
10032   mi.die = die;
10033   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
10034 }
10035
10036 /* A cleanup for freeing the delayed method list.  */
10037
10038 static void
10039 free_delayed_list (void *ptr)
10040 {
10041   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
10042   if (cu->method_list != NULL)
10043     {
10044       VEC_free (delayed_method_info, cu->method_list);
10045       cu->method_list = NULL;
10046     }
10047 }
10048
10049 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10050    "const" / "volatile".  If so, decrements LEN by the length of the
10051    modifier and return true.  Otherwise return false.  */
10052
10053 template<size_t N>
10054 static bool
10055 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10056 {
10057   size_t mod_len = sizeof (mod) - 1;
10058   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10059     {
10060       len -= mod_len;
10061       return true;
10062     }
10063   return false;
10064 }
10065
10066 /* Compute the physnames of any methods on the CU's method list.
10067
10068    The computation of method physnames is delayed in order to avoid the
10069    (bad) condition that one of the method's formal parameters is of an as yet
10070    incomplete type.  */
10071
10072 static void
10073 compute_delayed_physnames (struct dwarf2_cu *cu)
10074 {
10075   int i;
10076   struct delayed_method_info *mi;
10077
10078   /* Only C++ delays computing physnames.  */
10079   if (VEC_empty (delayed_method_info, cu->method_list))
10080     return;
10081   gdb_assert (cu->language == language_cplus);
10082
10083   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
10084     {
10085       const char *physname;
10086       struct fn_fieldlist *fn_flp
10087         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
10088       physname = dwarf2_physname (mi->name, mi->die, cu);
10089       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
10090         = physname ? physname : "";
10091
10092       /* Since there's no tag to indicate whether a method is a
10093          const/volatile overload, extract that information out of the
10094          demangled name.  */
10095       if (physname != NULL)
10096         {
10097           size_t len = strlen (physname);
10098
10099           while (1)
10100             {
10101               if (physname[len] == ')') /* shortcut */
10102                 break;
10103               else if (check_modifier (physname, len, " const"))
10104                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
10105               else if (check_modifier (physname, len, " volatile"))
10106                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
10107               else
10108                 break;
10109             }
10110         }
10111     }
10112 }
10113
10114 /* Go objects should be embedded in a DW_TAG_module DIE,
10115    and it's not clear if/how imported objects will appear.
10116    To keep Go support simple until that's worked out,
10117    go back through what we've read and create something usable.
10118    We could do this while processing each DIE, and feels kinda cleaner,
10119    but that way is more invasive.
10120    This is to, for example, allow the user to type "p var" or "b main"
10121    without having to specify the package name, and allow lookups
10122    of module.object to work in contexts that use the expression
10123    parser.  */
10124
10125 static void
10126 fixup_go_packaging (struct dwarf2_cu *cu)
10127 {
10128   char *package_name = NULL;
10129   struct pending *list;
10130   int i;
10131
10132   for (list = global_symbols; list != NULL; list = list->next)
10133     {
10134       for (i = 0; i < list->nsyms; ++i)
10135         {
10136           struct symbol *sym = list->symbol[i];
10137
10138           if (SYMBOL_LANGUAGE (sym) == language_go
10139               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10140             {
10141               char *this_package_name = go_symbol_package_name (sym);
10142
10143               if (this_package_name == NULL)
10144                 continue;
10145               if (package_name == NULL)
10146                 package_name = this_package_name;
10147               else
10148                 {
10149                   if (strcmp (package_name, this_package_name) != 0)
10150                     complaint (&symfile_complaints,
10151                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10152                                (symbol_symtab (sym) != NULL
10153                                 ? symtab_to_filename_for_display
10154                                     (symbol_symtab (sym))
10155                                 : objfile_name (cu->objfile)),
10156                                this_package_name, package_name);
10157                   xfree (this_package_name);
10158                 }
10159             }
10160         }
10161     }
10162
10163   if (package_name != NULL)
10164     {
10165       struct objfile *objfile = cu->objfile;
10166       const char *saved_package_name
10167         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10168                                         package_name,
10169                                         strlen (package_name));
10170       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10171                                      saved_package_name);
10172       struct symbol *sym;
10173
10174       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10175
10176       sym = allocate_symbol (objfile);
10177       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10178       SYMBOL_SET_NAMES (sym, saved_package_name,
10179                         strlen (saved_package_name), 0, objfile);
10180       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10181          e.g., "main" finds the "main" module and not C's main().  */
10182       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10183       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10184       SYMBOL_TYPE (sym) = type;
10185
10186       add_symbol_to_list (sym, &global_symbols);
10187
10188       xfree (package_name);
10189     }
10190 }
10191
10192 /* Return the symtab for PER_CU.  This works properly regardless of
10193    whether we're using the index or psymtabs.  */
10194
10195 static struct compunit_symtab *
10196 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10197 {
10198   return (dwarf2_per_objfile->using_index
10199           ? per_cu->v.quick->compunit_symtab
10200           : per_cu->v.psymtab->compunit_symtab);
10201 }
10202
10203 /* A helper function for computing the list of all symbol tables
10204    included by PER_CU.  */
10205
10206 static void
10207 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10208                                 htab_t all_children, htab_t all_type_symtabs,
10209                                 struct dwarf2_per_cu_data *per_cu,
10210                                 struct compunit_symtab *immediate_parent)
10211 {
10212   void **slot;
10213   int ix;
10214   struct compunit_symtab *cust;
10215   struct dwarf2_per_cu_data *iter;
10216
10217   slot = htab_find_slot (all_children, per_cu, INSERT);
10218   if (*slot != NULL)
10219     {
10220       /* This inclusion and its children have been processed.  */
10221       return;
10222     }
10223
10224   *slot = per_cu;
10225   /* Only add a CU if it has a symbol table.  */
10226   cust = get_compunit_symtab (per_cu);
10227   if (cust != NULL)
10228     {
10229       /* If this is a type unit only add its symbol table if we haven't
10230          seen it yet (type unit per_cu's can share symtabs).  */
10231       if (per_cu->is_debug_types)
10232         {
10233           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10234           if (*slot == NULL)
10235             {
10236               *slot = cust;
10237               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10238               if (cust->user == NULL)
10239                 cust->user = immediate_parent;
10240             }
10241         }
10242       else
10243         {
10244           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10245           if (cust->user == NULL)
10246             cust->user = immediate_parent;
10247         }
10248     }
10249
10250   for (ix = 0;
10251        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10252        ++ix)
10253     {
10254       recursively_compute_inclusions (result, all_children,
10255                                       all_type_symtabs, iter, cust);
10256     }
10257 }
10258
10259 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10260    PER_CU.  */
10261
10262 static void
10263 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10264 {
10265   gdb_assert (! per_cu->is_debug_types);
10266
10267   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10268     {
10269       int ix, len;
10270       struct dwarf2_per_cu_data *per_cu_iter;
10271       struct compunit_symtab *compunit_symtab_iter;
10272       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10273       htab_t all_children, all_type_symtabs;
10274       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10275
10276       /* If we don't have a symtab, we can just skip this case.  */
10277       if (cust == NULL)
10278         return;
10279
10280       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10281                                         NULL, xcalloc, xfree);
10282       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10283                                             NULL, xcalloc, xfree);
10284
10285       for (ix = 0;
10286            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10287                         ix, per_cu_iter);
10288            ++ix)
10289         {
10290           recursively_compute_inclusions (&result_symtabs, all_children,
10291                                           all_type_symtabs, per_cu_iter,
10292                                           cust);
10293         }
10294
10295       /* Now we have a transitive closure of all the included symtabs.  */
10296       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10297       cust->includes
10298         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
10299                      struct compunit_symtab *, len + 1);
10300       for (ix = 0;
10301            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10302                         compunit_symtab_iter);
10303            ++ix)
10304         cust->includes[ix] = compunit_symtab_iter;
10305       cust->includes[len] = NULL;
10306
10307       VEC_free (compunit_symtab_ptr, result_symtabs);
10308       htab_delete (all_children);
10309       htab_delete (all_type_symtabs);
10310     }
10311 }
10312
10313 /* Compute the 'includes' field for the symtabs of all the CUs we just
10314    read.  */
10315
10316 static void
10317 process_cu_includes (void)
10318 {
10319   int ix;
10320   struct dwarf2_per_cu_data *iter;
10321
10322   for (ix = 0;
10323        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10324                     ix, iter);
10325        ++ix)
10326     {
10327       if (! iter->is_debug_types)
10328         compute_compunit_symtab_includes (iter);
10329     }
10330
10331   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10332 }
10333
10334 /* Generate full symbol information for PER_CU, whose DIEs have
10335    already been loaded into memory.  */
10336
10337 static void
10338 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10339                         enum language pretend_language)
10340 {
10341   struct dwarf2_cu *cu = per_cu->cu;
10342   struct objfile *objfile = per_cu->objfile;
10343   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10344   CORE_ADDR lowpc, highpc;
10345   struct compunit_symtab *cust;
10346   struct cleanup *delayed_list_cleanup;
10347   CORE_ADDR baseaddr;
10348   struct block *static_block;
10349   CORE_ADDR addr;
10350
10351   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10352
10353   buildsym_init ();
10354   scoped_free_pendings free_pending;
10355   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10356
10357   cu->list_in_scope = &file_symbols;
10358
10359   cu->language = pretend_language;
10360   cu->language_defn = language_def (cu->language);
10361
10362   /* Do line number decoding in read_file_scope () */
10363   process_die (cu->dies, cu);
10364
10365   /* For now fudge the Go package.  */
10366   if (cu->language == language_go)
10367     fixup_go_packaging (cu);
10368
10369   /* Now that we have processed all the DIEs in the CU, all the types 
10370      should be complete, and it should now be safe to compute all of the
10371      physnames.  */
10372   compute_delayed_physnames (cu);
10373   do_cleanups (delayed_list_cleanup);
10374
10375   /* Some compilers don't define a DW_AT_high_pc attribute for the
10376      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10377      it, by scanning the DIE's below the compilation unit.  */
10378   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10379
10380   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10381   static_block = end_symtab_get_static_block (addr, 0, 1);
10382
10383   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10384      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10385      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10386      addrmap to help ensure it has an accurate map of pc values belonging to
10387      this comp unit.  */
10388   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10389
10390   cust = end_symtab_from_static_block (static_block,
10391                                        SECT_OFF_TEXT (objfile), 0);
10392
10393   if (cust != NULL)
10394     {
10395       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10396
10397       /* Set symtab language to language from DW_AT_language.  If the
10398          compilation is from a C file generated by language preprocessors, do
10399          not set the language if it was already deduced by start_subfile.  */
10400       if (!(cu->language == language_c
10401             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10402         COMPUNIT_FILETABS (cust)->language = cu->language;
10403
10404       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10405          produce DW_AT_location with location lists but it can be possibly
10406          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10407          there were bugs in prologue debug info, fixed later in GCC-4.5
10408          by "unwind info for epilogues" patch (which is not directly related).
10409
10410          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10411          needed, it would be wrong due to missing DW_AT_producer there.
10412
10413          Still one can confuse GDB by using non-standard GCC compilation
10414          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10415          */ 
10416       if (cu->has_loclist && gcc_4_minor >= 5)
10417         cust->locations_valid = 1;
10418
10419       if (gcc_4_minor >= 5)
10420         cust->epilogue_unwind_valid = 1;
10421
10422       cust->call_site_htab = cu->call_site_htab;
10423     }
10424
10425   if (dwarf2_per_objfile->using_index)
10426     per_cu->v.quick->compunit_symtab = cust;
10427   else
10428     {
10429       struct partial_symtab *pst = per_cu->v.psymtab;
10430       pst->compunit_symtab = cust;
10431       pst->readin = 1;
10432     }
10433
10434   /* Push it for inclusion processing later.  */
10435   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10436 }
10437
10438 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10439    already been loaded into memory.  */
10440
10441 static void
10442 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10443                         enum language pretend_language)
10444 {
10445   struct dwarf2_cu *cu = per_cu->cu;
10446   struct objfile *objfile = per_cu->objfile;
10447   struct compunit_symtab *cust;
10448   struct cleanup *delayed_list_cleanup;
10449   struct signatured_type *sig_type;
10450
10451   gdb_assert (per_cu->is_debug_types);
10452   sig_type = (struct signatured_type *) per_cu;
10453
10454   buildsym_init ();
10455   scoped_free_pendings free_pending;
10456   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10457
10458   cu->list_in_scope = &file_symbols;
10459
10460   cu->language = pretend_language;
10461   cu->language_defn = language_def (cu->language);
10462
10463   /* The symbol tables are set up in read_type_unit_scope.  */
10464   process_die (cu->dies, cu);
10465
10466   /* For now fudge the Go package.  */
10467   if (cu->language == language_go)
10468     fixup_go_packaging (cu);
10469
10470   /* Now that we have processed all the DIEs in the CU, all the types 
10471      should be complete, and it should now be safe to compute all of the
10472      physnames.  */
10473   compute_delayed_physnames (cu);
10474   do_cleanups (delayed_list_cleanup);
10475
10476   /* TUs share symbol tables.
10477      If this is the first TU to use this symtab, complete the construction
10478      of it with end_expandable_symtab.  Otherwise, complete the addition of
10479      this TU's symbols to the existing symtab.  */
10480   if (sig_type->type_unit_group->compunit_symtab == NULL)
10481     {
10482       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10483       sig_type->type_unit_group->compunit_symtab = cust;
10484
10485       if (cust != NULL)
10486         {
10487           /* Set symtab language to language from DW_AT_language.  If the
10488              compilation is from a C file generated by language preprocessors,
10489              do not set the language if it was already deduced by
10490              start_subfile.  */
10491           if (!(cu->language == language_c
10492                 && COMPUNIT_FILETABS (cust)->language != language_c))
10493             COMPUNIT_FILETABS (cust)->language = cu->language;
10494         }
10495     }
10496   else
10497     {
10498       augment_type_symtab ();
10499       cust = sig_type->type_unit_group->compunit_symtab;
10500     }
10501
10502   if (dwarf2_per_objfile->using_index)
10503     per_cu->v.quick->compunit_symtab = cust;
10504   else
10505     {
10506       struct partial_symtab *pst = per_cu->v.psymtab;
10507       pst->compunit_symtab = cust;
10508       pst->readin = 1;
10509     }
10510 }
10511
10512 /* Process an imported unit DIE.  */
10513
10514 static void
10515 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10516 {
10517   struct attribute *attr;
10518
10519   /* For now we don't handle imported units in type units.  */
10520   if (cu->per_cu->is_debug_types)
10521     {
10522       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10523                " supported in type units [in module %s]"),
10524              objfile_name (cu->objfile));
10525     }
10526
10527   attr = dwarf2_attr (die, DW_AT_import, cu);
10528   if (attr != NULL)
10529     {
10530       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10531       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10532       dwarf2_per_cu_data *per_cu
10533         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
10534
10535       /* If necessary, add it to the queue and load its DIEs.  */
10536       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10537         load_full_comp_unit (per_cu, cu->language);
10538
10539       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10540                      per_cu);
10541     }
10542 }
10543
10544 /* RAII object that represents a process_die scope: i.e.,
10545    starts/finishes processing a DIE.  */
10546 class process_die_scope
10547 {
10548 public:
10549   process_die_scope (die_info *die, dwarf2_cu *cu)
10550     : m_die (die), m_cu (cu)
10551   {
10552     /* We should only be processing DIEs not already in process.  */
10553     gdb_assert (!m_die->in_process);
10554     m_die->in_process = true;
10555   }
10556
10557   ~process_die_scope ()
10558   {
10559     m_die->in_process = false;
10560
10561     /* If we're done processing the DIE for the CU that owns the line
10562        header, we don't need the line header anymore.  */
10563     if (m_cu->line_header_die_owner == m_die)
10564       {
10565         delete m_cu->line_header;
10566         m_cu->line_header = NULL;
10567         m_cu->line_header_die_owner = NULL;
10568       }
10569   }
10570
10571 private:
10572   die_info *m_die;
10573   dwarf2_cu *m_cu;
10574 };
10575
10576 /* Process a die and its children.  */
10577
10578 static void
10579 process_die (struct die_info *die, struct dwarf2_cu *cu)
10580 {
10581   process_die_scope scope (die, cu);
10582
10583   switch (die->tag)
10584     {
10585     case DW_TAG_padding:
10586       break;
10587     case DW_TAG_compile_unit:
10588     case DW_TAG_partial_unit:
10589       read_file_scope (die, cu);
10590       break;
10591     case DW_TAG_type_unit:
10592       read_type_unit_scope (die, cu);
10593       break;
10594     case DW_TAG_subprogram:
10595     case DW_TAG_inlined_subroutine:
10596       read_func_scope (die, cu);
10597       break;
10598     case DW_TAG_lexical_block:
10599     case DW_TAG_try_block:
10600     case DW_TAG_catch_block:
10601       read_lexical_block_scope (die, cu);
10602       break;
10603     case DW_TAG_call_site:
10604     case DW_TAG_GNU_call_site:
10605       read_call_site_scope (die, cu);
10606       break;
10607     case DW_TAG_class_type:
10608     case DW_TAG_interface_type:
10609     case DW_TAG_structure_type:
10610     case DW_TAG_union_type:
10611       process_structure_scope (die, cu);
10612       break;
10613     case DW_TAG_enumeration_type:
10614       process_enumeration_scope (die, cu);
10615       break;
10616
10617     /* These dies have a type, but processing them does not create
10618        a symbol or recurse to process the children.  Therefore we can
10619        read them on-demand through read_type_die.  */
10620     case DW_TAG_subroutine_type:
10621     case DW_TAG_set_type:
10622     case DW_TAG_array_type:
10623     case DW_TAG_pointer_type:
10624     case DW_TAG_ptr_to_member_type:
10625     case DW_TAG_reference_type:
10626     case DW_TAG_rvalue_reference_type:
10627     case DW_TAG_string_type:
10628       break;
10629
10630     case DW_TAG_base_type:
10631     case DW_TAG_subrange_type:
10632     case DW_TAG_typedef:
10633       /* Add a typedef symbol for the type definition, if it has a
10634          DW_AT_name.  */
10635       new_symbol (die, read_type_die (die, cu), cu);
10636       break;
10637     case DW_TAG_common_block:
10638       read_common_block (die, cu);
10639       break;
10640     case DW_TAG_common_inclusion:
10641       break;
10642     case DW_TAG_namespace:
10643       cu->processing_has_namespace_info = 1;
10644       read_namespace (die, cu);
10645       break;
10646     case DW_TAG_module:
10647       cu->processing_has_namespace_info = 1;
10648       read_module (die, cu);
10649       break;
10650     case DW_TAG_imported_declaration:
10651       cu->processing_has_namespace_info = 1;
10652       if (read_namespace_alias (die, cu))
10653         break;
10654       /* The declaration is not a global namespace alias: fall through.  */
10655     case DW_TAG_imported_module:
10656       cu->processing_has_namespace_info = 1;
10657       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10658                                  || cu->language != language_fortran))
10659         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10660                    dwarf_tag_name (die->tag));
10661       read_import_statement (die, cu);
10662       break;
10663
10664     case DW_TAG_imported_unit:
10665       process_imported_unit_die (die, cu);
10666       break;
10667
10668     case DW_TAG_variable:
10669       read_variable (die, cu);
10670       break;
10671
10672     default:
10673       new_symbol (die, NULL, cu);
10674       break;
10675     }
10676 }
10677 \f
10678 /* DWARF name computation.  */
10679
10680 /* A helper function for dwarf2_compute_name which determines whether DIE
10681    needs to have the name of the scope prepended to the name listed in the
10682    die.  */
10683
10684 static int
10685 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10686 {
10687   struct attribute *attr;
10688
10689   switch (die->tag)
10690     {
10691     case DW_TAG_namespace:
10692     case DW_TAG_typedef:
10693     case DW_TAG_class_type:
10694     case DW_TAG_interface_type:
10695     case DW_TAG_structure_type:
10696     case DW_TAG_union_type:
10697     case DW_TAG_enumeration_type:
10698     case DW_TAG_enumerator:
10699     case DW_TAG_subprogram:
10700     case DW_TAG_inlined_subroutine:
10701     case DW_TAG_member:
10702     case DW_TAG_imported_declaration:
10703       return 1;
10704
10705     case DW_TAG_variable:
10706     case DW_TAG_constant:
10707       /* We only need to prefix "globally" visible variables.  These include
10708          any variable marked with DW_AT_external or any variable that
10709          lives in a namespace.  [Variables in anonymous namespaces
10710          require prefixing, but they are not DW_AT_external.]  */
10711
10712       if (dwarf2_attr (die, DW_AT_specification, cu))
10713         {
10714           struct dwarf2_cu *spec_cu = cu;
10715
10716           return die_needs_namespace (die_specification (die, &spec_cu),
10717                                       spec_cu);
10718         }
10719
10720       attr = dwarf2_attr (die, DW_AT_external, cu);
10721       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10722           && die->parent->tag != DW_TAG_module)
10723         return 0;
10724       /* A variable in a lexical block of some kind does not need a
10725          namespace, even though in C++ such variables may be external
10726          and have a mangled name.  */
10727       if (die->parent->tag ==  DW_TAG_lexical_block
10728           || die->parent->tag ==  DW_TAG_try_block
10729           || die->parent->tag ==  DW_TAG_catch_block
10730           || die->parent->tag == DW_TAG_subprogram)
10731         return 0;
10732       return 1;
10733
10734     default:
10735       return 0;
10736     }
10737 }
10738
10739 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10740    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10741    defined for the given DIE.  */
10742
10743 static struct attribute *
10744 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10745 {
10746   struct attribute *attr;
10747
10748   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10749   if (attr == NULL)
10750     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10751
10752   return attr;
10753 }
10754
10755 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10756    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10757    defined for the given DIE.  */
10758
10759 static const char *
10760 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10761 {
10762   const char *linkage_name;
10763
10764   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10765   if (linkage_name == NULL)
10766     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10767
10768   return linkage_name;
10769 }
10770
10771 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10772    compute the physname for the object, which include a method's:
10773    - formal parameters (C++),
10774    - receiver type (Go),
10775
10776    The term "physname" is a bit confusing.
10777    For C++, for example, it is the demangled name.
10778    For Go, for example, it's the mangled name.
10779
10780    For Ada, return the DIE's linkage name rather than the fully qualified
10781    name.  PHYSNAME is ignored..
10782
10783    The result is allocated on the objfile_obstack and canonicalized.  */
10784
10785 static const char *
10786 dwarf2_compute_name (const char *name,
10787                      struct die_info *die, struct dwarf2_cu *cu,
10788                      int physname)
10789 {
10790   struct objfile *objfile = cu->objfile;
10791
10792   if (name == NULL)
10793     name = dwarf2_name (die, cu);
10794
10795   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10796      but otherwise compute it by typename_concat inside GDB.
10797      FIXME: Actually this is not really true, or at least not always true.
10798      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10799      Fortran names because there is no mangling standard.  So new_symbol_full
10800      will set the demangled name to the result of dwarf2_full_name, and it is
10801      the demangled name that GDB uses if it exists.  */
10802   if (cu->language == language_ada
10803       || (cu->language == language_fortran && physname))
10804     {
10805       /* For Ada unit, we prefer the linkage name over the name, as
10806          the former contains the exported name, which the user expects
10807          to be able to reference.  Ideally, we want the user to be able
10808          to reference this entity using either natural or linkage name,
10809          but we haven't started looking at this enhancement yet.  */
10810       const char *linkage_name = dw2_linkage_name (die, cu);
10811
10812       if (linkage_name != NULL)
10813         return linkage_name;
10814     }
10815
10816   /* These are the only languages we know how to qualify names in.  */
10817   if (name != NULL
10818       && (cu->language == language_cplus
10819           || cu->language == language_fortran || cu->language == language_d
10820           || cu->language == language_rust))
10821     {
10822       if (die_needs_namespace (die, cu))
10823         {
10824           const char *prefix;
10825           const char *canonical_name = NULL;
10826
10827           string_file buf;
10828
10829           prefix = determine_prefix (die, cu);
10830           if (*prefix != '\0')
10831             {
10832               char *prefixed_name = typename_concat (NULL, prefix, name,
10833                                                      physname, cu);
10834
10835               buf.puts (prefixed_name);
10836               xfree (prefixed_name);
10837             }
10838           else
10839             buf.puts (name);
10840
10841           /* Template parameters may be specified in the DIE's DW_AT_name, or
10842              as children with DW_TAG_template_type_param or
10843              DW_TAG_value_type_param.  If the latter, add them to the name
10844              here.  If the name already has template parameters, then
10845              skip this step; some versions of GCC emit both, and
10846              it is more efficient to use the pre-computed name.
10847
10848              Something to keep in mind about this process: it is very
10849              unlikely, or in some cases downright impossible, to produce
10850              something that will match the mangled name of a function.
10851              If the definition of the function has the same debug info,
10852              we should be able to match up with it anyway.  But fallbacks
10853              using the minimal symbol, for instance to find a method
10854              implemented in a stripped copy of libstdc++, will not work.
10855              If we do not have debug info for the definition, we will have to
10856              match them up some other way.
10857
10858              When we do name matching there is a related problem with function
10859              templates; two instantiated function templates are allowed to
10860              differ only by their return types, which we do not add here.  */
10861
10862           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10863             {
10864               struct attribute *attr;
10865               struct die_info *child;
10866               int first = 1;
10867
10868               die->building_fullname = 1;
10869
10870               for (child = die->child; child != NULL; child = child->sibling)
10871                 {
10872                   struct type *type;
10873                   LONGEST value;
10874                   const gdb_byte *bytes;
10875                   struct dwarf2_locexpr_baton *baton;
10876                   struct value *v;
10877
10878                   if (child->tag != DW_TAG_template_type_param
10879                       && child->tag != DW_TAG_template_value_param)
10880                     continue;
10881
10882                   if (first)
10883                     {
10884                       buf.puts ("<");
10885                       first = 0;
10886                     }
10887                   else
10888                     buf.puts (", ");
10889
10890                   attr = dwarf2_attr (child, DW_AT_type, cu);
10891                   if (attr == NULL)
10892                     {
10893                       complaint (&symfile_complaints,
10894                                  _("template parameter missing DW_AT_type"));
10895                       buf.puts ("UNKNOWN_TYPE");
10896                       continue;
10897                     }
10898                   type = die_type (child, cu);
10899
10900                   if (child->tag == DW_TAG_template_type_param)
10901                     {
10902                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
10903                       continue;
10904                     }
10905
10906                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10907                   if (attr == NULL)
10908                     {
10909                       complaint (&symfile_complaints,
10910                                  _("template parameter missing "
10911                                    "DW_AT_const_value"));
10912                       buf.puts ("UNKNOWN_VALUE");
10913                       continue;
10914                     }
10915
10916                   dwarf2_const_value_attr (attr, type, name,
10917                                            &cu->comp_unit_obstack, cu,
10918                                            &value, &bytes, &baton);
10919
10920                   if (TYPE_NOSIGN (type))
10921                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10922                        changed, this can use value_print instead.  */
10923                     c_printchar (value, type, &buf);
10924                   else
10925                     {
10926                       struct value_print_options opts;
10927
10928                       if (baton != NULL)
10929                         v = dwarf2_evaluate_loc_desc (type, NULL,
10930                                                       baton->data,
10931                                                       baton->size,
10932                                                       baton->per_cu);
10933                       else if (bytes != NULL)
10934                         {
10935                           v = allocate_value (type);
10936                           memcpy (value_contents_writeable (v), bytes,
10937                                   TYPE_LENGTH (type));
10938                         }
10939                       else
10940                         v = value_from_longest (type, value);
10941
10942                       /* Specify decimal so that we do not depend on
10943                          the radix.  */
10944                       get_formatted_print_options (&opts, 'd');
10945                       opts.raw = 1;
10946                       value_print (v, &buf, &opts);
10947                       release_value (v);
10948                       value_free (v);
10949                     }
10950                 }
10951
10952               die->building_fullname = 0;
10953
10954               if (!first)
10955                 {
10956                   /* Close the argument list, with a space if necessary
10957                      (nested templates).  */
10958                   if (!buf.empty () && buf.string ().back () == '>')
10959                     buf.puts (" >");
10960                   else
10961                     buf.puts (">");
10962                 }
10963             }
10964
10965           /* For C++ methods, append formal parameter type
10966              information, if PHYSNAME.  */
10967
10968           if (physname && die->tag == DW_TAG_subprogram
10969               && cu->language == language_cplus)
10970             {
10971               struct type *type = read_type_die (die, cu);
10972
10973               c_type_print_args (type, &buf, 1, cu->language,
10974                                  &type_print_raw_options);
10975
10976               if (cu->language == language_cplus)
10977                 {
10978                   /* Assume that an artificial first parameter is
10979                      "this", but do not crash if it is not.  RealView
10980                      marks unnamed (and thus unused) parameters as
10981                      artificial; there is no way to differentiate
10982                      the two cases.  */
10983                   if (TYPE_NFIELDS (type) > 0
10984                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10985                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10986                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10987                                                                         0))))
10988                     buf.puts (" const");
10989                 }
10990             }
10991
10992           const std::string &intermediate_name = buf.string ();
10993
10994           if (cu->language == language_cplus)
10995             canonical_name
10996               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10997                                           &objfile->per_bfd->storage_obstack);
10998
10999           /* If we only computed INTERMEDIATE_NAME, or if
11000              INTERMEDIATE_NAME is already canonical, then we need to
11001              copy it to the appropriate obstack.  */
11002           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11003             name = ((const char *)
11004                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11005                                    intermediate_name.c_str (),
11006                                    intermediate_name.length ()));
11007           else
11008             name = canonical_name;
11009         }
11010     }
11011
11012   return name;
11013 }
11014
11015 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11016    If scope qualifiers are appropriate they will be added.  The result
11017    will be allocated on the storage_obstack, or NULL if the DIE does
11018    not have a name.  NAME may either be from a previous call to
11019    dwarf2_name or NULL.
11020
11021    The output string will be canonicalized (if C++).  */
11022
11023 static const char *
11024 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11025 {
11026   return dwarf2_compute_name (name, die, cu, 0);
11027 }
11028
11029 /* Construct a physname for the given DIE in CU.  NAME may either be
11030    from a previous call to dwarf2_name or NULL.  The result will be
11031    allocated on the objfile_objstack or NULL if the DIE does not have a
11032    name.
11033
11034    The output string will be canonicalized (if C++).  */
11035
11036 static const char *
11037 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11038 {
11039   struct objfile *objfile = cu->objfile;
11040   const char *retval, *mangled = NULL, *canon = NULL;
11041   int need_copy = 1;
11042
11043   /* In this case dwarf2_compute_name is just a shortcut not building anything
11044      on its own.  */
11045   if (!die_needs_namespace (die, cu))
11046     return dwarf2_compute_name (name, die, cu, 1);
11047
11048   mangled = dw2_linkage_name (die, cu);
11049
11050   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11051      See https://github.com/rust-lang/rust/issues/32925.  */
11052   if (cu->language == language_rust && mangled != NULL
11053       && strchr (mangled, '{') != NULL)
11054     mangled = NULL;
11055
11056   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11057      has computed.  */
11058   gdb::unique_xmalloc_ptr<char> demangled;
11059   if (mangled != NULL)
11060     {
11061       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11062          type.  It is easier for GDB users to search for such functions as
11063          `name(params)' than `long name(params)'.  In such case the minimal
11064          symbol names do not match the full symbol names but for template
11065          functions there is never a need to look up their definition from their
11066          declaration so the only disadvantage remains the minimal symbol
11067          variant `long name(params)' does not have the proper inferior type.
11068          */
11069
11070       if (cu->language == language_go)
11071         {
11072           /* This is a lie, but we already lie to the caller new_symbol_full.
11073              new_symbol_full assumes we return the mangled name.
11074              This just undoes that lie until things are cleaned up.  */
11075         }
11076       else
11077         {
11078           demangled.reset (gdb_demangle (mangled,
11079                                          (DMGL_PARAMS | DMGL_ANSI
11080                                           | DMGL_RET_DROP)));
11081         }
11082       if (demangled)
11083         canon = demangled.get ();
11084       else
11085         {
11086           canon = mangled;
11087           need_copy = 0;
11088         }
11089     }
11090
11091   if (canon == NULL || check_physname)
11092     {
11093       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11094
11095       if (canon != NULL && strcmp (physname, canon) != 0)
11096         {
11097           /* It may not mean a bug in GDB.  The compiler could also
11098              compute DW_AT_linkage_name incorrectly.  But in such case
11099              GDB would need to be bug-to-bug compatible.  */
11100
11101           complaint (&symfile_complaints,
11102                      _("Computed physname <%s> does not match demangled <%s> "
11103                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11104                      physname, canon, mangled, to_underlying (die->sect_off),
11105                      objfile_name (objfile));
11106
11107           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11108              is available here - over computed PHYSNAME.  It is safer
11109              against both buggy GDB and buggy compilers.  */
11110
11111           retval = canon;
11112         }
11113       else
11114         {
11115           retval = physname;
11116           need_copy = 0;
11117         }
11118     }
11119   else
11120     retval = canon;
11121
11122   if (need_copy)
11123     retval = ((const char *)
11124               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11125                              retval, strlen (retval)));
11126
11127   return retval;
11128 }
11129
11130 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11131    a new symbol for it.
11132
11133    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11134
11135 static int
11136 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11137 {
11138   struct attribute *attr;
11139
11140   /* If the die does not have a name, this is not a namespace
11141      alias.  */
11142   attr = dwarf2_attr (die, DW_AT_name, cu);
11143   if (attr != NULL)
11144     {
11145       int num;
11146       struct die_info *d = die;
11147       struct dwarf2_cu *imported_cu = cu;
11148
11149       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11150          keep inspecting DIEs until we hit the underlying import.  */
11151 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11152       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11153         {
11154           attr = dwarf2_attr (d, DW_AT_import, cu);
11155           if (attr == NULL)
11156             break;
11157
11158           d = follow_die_ref (d, attr, &imported_cu);
11159           if (d->tag != DW_TAG_imported_declaration)
11160             break;
11161         }
11162
11163       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11164         {
11165           complaint (&symfile_complaints,
11166                      _("DIE at 0x%x has too many recursively imported "
11167                        "declarations"), to_underlying (d->sect_off));
11168           return 0;
11169         }
11170
11171       if (attr != NULL)
11172         {
11173           struct type *type;
11174           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11175
11176           type = get_die_type_at_offset (sect_off, cu->per_cu);
11177           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11178             {
11179               /* This declaration is a global namespace alias.  Add
11180                  a symbol for it whose type is the aliased namespace.  */
11181               new_symbol (die, type, cu);
11182               return 1;
11183             }
11184         }
11185     }
11186
11187   return 0;
11188 }
11189
11190 /* Return the using directives repository (global or local?) to use in the
11191    current context for LANGUAGE.
11192
11193    For Ada, imported declarations can materialize renamings, which *may* be
11194    global.  However it is impossible (for now?) in DWARF to distinguish
11195    "external" imported declarations and "static" ones.  As all imported
11196    declarations seem to be static in all other languages, make them all CU-wide
11197    global only in Ada.  */
11198
11199 static struct using_direct **
11200 using_directives (enum language language)
11201 {
11202   if (language == language_ada && context_stack_depth == 0)
11203     return &global_using_directives;
11204   else
11205     return &local_using_directives;
11206 }
11207
11208 /* Read the import statement specified by the given die and record it.  */
11209
11210 static void
11211 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11212 {
11213   struct objfile *objfile = cu->objfile;
11214   struct attribute *import_attr;
11215   struct die_info *imported_die, *child_die;
11216   struct dwarf2_cu *imported_cu;
11217   const char *imported_name;
11218   const char *imported_name_prefix;
11219   const char *canonical_name;
11220   const char *import_alias;
11221   const char *imported_declaration = NULL;
11222   const char *import_prefix;
11223   std::vector<const char *> excludes;
11224
11225   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11226   if (import_attr == NULL)
11227     {
11228       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11229                  dwarf_tag_name (die->tag));
11230       return;
11231     }
11232
11233   imported_cu = cu;
11234   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11235   imported_name = dwarf2_name (imported_die, imported_cu);
11236   if (imported_name == NULL)
11237     {
11238       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11239
11240         The import in the following code:
11241         namespace A
11242           {
11243             typedef int B;
11244           }
11245
11246         int main ()
11247           {
11248             using A::B;
11249             B b;
11250             return b;
11251           }
11252
11253         ...
11254          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11255             <52>   DW_AT_decl_file   : 1
11256             <53>   DW_AT_decl_line   : 6
11257             <54>   DW_AT_import      : <0x75>
11258          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11259             <59>   DW_AT_name        : B
11260             <5b>   DW_AT_decl_file   : 1
11261             <5c>   DW_AT_decl_line   : 2
11262             <5d>   DW_AT_type        : <0x6e>
11263         ...
11264          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11265             <76>   DW_AT_byte_size   : 4
11266             <77>   DW_AT_encoding    : 5        (signed)
11267
11268         imports the wrong die ( 0x75 instead of 0x58 ).
11269         This case will be ignored until the gcc bug is fixed.  */
11270       return;
11271     }
11272
11273   /* Figure out the local name after import.  */
11274   import_alias = dwarf2_name (die, cu);
11275
11276   /* Figure out where the statement is being imported to.  */
11277   import_prefix = determine_prefix (die, cu);
11278
11279   /* Figure out what the scope of the imported die is and prepend it
11280      to the name of the imported die.  */
11281   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11282
11283   if (imported_die->tag != DW_TAG_namespace
11284       && imported_die->tag != DW_TAG_module)
11285     {
11286       imported_declaration = imported_name;
11287       canonical_name = imported_name_prefix;
11288     }
11289   else if (strlen (imported_name_prefix) > 0)
11290     canonical_name = obconcat (&objfile->objfile_obstack,
11291                                imported_name_prefix,
11292                                (cu->language == language_d ? "." : "::"),
11293                                imported_name, (char *) NULL);
11294   else
11295     canonical_name = imported_name;
11296
11297   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11298     for (child_die = die->child; child_die && child_die->tag;
11299          child_die = sibling_die (child_die))
11300       {
11301         /* DWARF-4: A Fortran use statement with a “rename list” may be
11302            represented by an imported module entry with an import attribute
11303            referring to the module and owned entries corresponding to those
11304            entities that are renamed as part of being imported.  */
11305
11306         if (child_die->tag != DW_TAG_imported_declaration)
11307           {
11308             complaint (&symfile_complaints,
11309                        _("child DW_TAG_imported_declaration expected "
11310                          "- DIE at 0x%x [in module %s]"),
11311                        to_underlying (child_die->sect_off), objfile_name (objfile));
11312             continue;
11313           }
11314
11315         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11316         if (import_attr == NULL)
11317           {
11318             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11319                        dwarf_tag_name (child_die->tag));
11320             continue;
11321           }
11322
11323         imported_cu = cu;
11324         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11325                                               &imported_cu);
11326         imported_name = dwarf2_name (imported_die, imported_cu);
11327         if (imported_name == NULL)
11328           {
11329             complaint (&symfile_complaints,
11330                        _("child DW_TAG_imported_declaration has unknown "
11331                          "imported name - DIE at 0x%x [in module %s]"),
11332                        to_underlying (child_die->sect_off), objfile_name (objfile));
11333             continue;
11334           }
11335
11336         excludes.push_back (imported_name);
11337
11338         process_die (child_die, cu);
11339       }
11340
11341   add_using_directive (using_directives (cu->language),
11342                        import_prefix,
11343                        canonical_name,
11344                        import_alias,
11345                        imported_declaration,
11346                        excludes,
11347                        0,
11348                        &objfile->objfile_obstack);
11349 }
11350
11351 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11352    types, but gives them a size of zero.  Starting with version 14,
11353    ICC is compatible with GCC.  */
11354
11355 static int
11356 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11357 {
11358   if (!cu->checked_producer)
11359     check_producer (cu);
11360
11361   return cu->producer_is_icc_lt_14;
11362 }
11363
11364 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11365    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11366    this, it was first present in GCC release 4.3.0.  */
11367
11368 static int
11369 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11370 {
11371   if (!cu->checked_producer)
11372     check_producer (cu);
11373
11374   return cu->producer_is_gcc_lt_4_3;
11375 }
11376
11377 static file_and_directory
11378 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11379 {
11380   file_and_directory res;
11381
11382   /* Find the filename.  Do not use dwarf2_name here, since the filename
11383      is not a source language identifier.  */
11384   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11385   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11386
11387   if (res.comp_dir == NULL
11388       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11389       && IS_ABSOLUTE_PATH (res.name))
11390     {
11391       res.comp_dir_storage = ldirname (res.name);
11392       if (!res.comp_dir_storage.empty ())
11393         res.comp_dir = res.comp_dir_storage.c_str ();
11394     }
11395   if (res.comp_dir != NULL)
11396     {
11397       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11398          directory, get rid of it.  */
11399       const char *cp = strchr (res.comp_dir, ':');
11400
11401       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11402         res.comp_dir = cp + 1;
11403     }
11404
11405   if (res.name == NULL)
11406     res.name = "<unknown>";
11407
11408   return res;
11409 }
11410
11411 /* Handle DW_AT_stmt_list for a compilation unit.
11412    DIE is the DW_TAG_compile_unit die for CU.
11413    COMP_DIR is the compilation directory.  LOWPC is passed to
11414    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11415
11416 static void
11417 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11418                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11419 {
11420   struct objfile *objfile = dwarf2_per_objfile->objfile;
11421   struct attribute *attr;
11422   struct line_header line_header_local;
11423   hashval_t line_header_local_hash;
11424   void **slot;
11425   int decode_mapping;
11426
11427   gdb_assert (! cu->per_cu->is_debug_types);
11428
11429   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11430   if (attr == NULL)
11431     return;
11432
11433   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11434
11435   /* The line header hash table is only created if needed (it exists to
11436      prevent redundant reading of the line table for partial_units).
11437      If we're given a partial_unit, we'll need it.  If we're given a
11438      compile_unit, then use the line header hash table if it's already
11439      created, but don't create one just yet.  */
11440
11441   if (dwarf2_per_objfile->line_header_hash == NULL
11442       && die->tag == DW_TAG_partial_unit)
11443     {
11444       dwarf2_per_objfile->line_header_hash
11445         = htab_create_alloc_ex (127, line_header_hash_voidp,
11446                                 line_header_eq_voidp,
11447                                 free_line_header_voidp,
11448                                 &objfile->objfile_obstack,
11449                                 hashtab_obstack_allocate,
11450                                 dummy_obstack_deallocate);
11451     }
11452
11453   line_header_local.sect_off = line_offset;
11454   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11455   line_header_local_hash = line_header_hash (&line_header_local);
11456   if (dwarf2_per_objfile->line_header_hash != NULL)
11457     {
11458       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11459                                        &line_header_local,
11460                                        line_header_local_hash, NO_INSERT);
11461
11462       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11463          is not present in *SLOT (since if there is something in *SLOT then
11464          it will be for a partial_unit).  */
11465       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11466         {
11467           gdb_assert (*slot != NULL);
11468           cu->line_header = (struct line_header *) *slot;
11469           return;
11470         }
11471     }
11472
11473   /* dwarf_decode_line_header does not yet provide sufficient information.
11474      We always have to call also dwarf_decode_lines for it.  */
11475   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11476   if (lh == NULL)
11477     return;
11478
11479   cu->line_header = lh.release ();
11480   cu->line_header_die_owner = die;
11481
11482   if (dwarf2_per_objfile->line_header_hash == NULL)
11483     slot = NULL;
11484   else
11485     {
11486       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11487                                        &line_header_local,
11488                                        line_header_local_hash, INSERT);
11489       gdb_assert (slot != NULL);
11490     }
11491   if (slot != NULL && *slot == NULL)
11492     {
11493       /* This newly decoded line number information unit will be owned
11494          by line_header_hash hash table.  */
11495       *slot = cu->line_header;
11496       cu->line_header_die_owner = NULL;
11497     }
11498   else
11499     {
11500       /* We cannot free any current entry in (*slot) as that struct line_header
11501          may be already used by multiple CUs.  Create only temporary decoded
11502          line_header for this CU - it may happen at most once for each line
11503          number information unit.  And if we're not using line_header_hash
11504          then this is what we want as well.  */
11505       gdb_assert (die->tag != DW_TAG_partial_unit);
11506     }
11507   decode_mapping = (die->tag != DW_TAG_partial_unit);
11508   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11509                       decode_mapping);
11510
11511 }
11512
11513 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11514
11515 static void
11516 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11517 {
11518   struct objfile *objfile = dwarf2_per_objfile->objfile;
11519   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11520   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11521   CORE_ADDR highpc = ((CORE_ADDR) 0);
11522   struct attribute *attr;
11523   struct die_info *child_die;
11524   CORE_ADDR baseaddr;
11525
11526   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11527
11528   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11529
11530   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11531      from finish_block.  */
11532   if (lowpc == ((CORE_ADDR) -1))
11533     lowpc = highpc;
11534   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11535
11536   file_and_directory fnd = find_file_and_directory (die, cu);
11537
11538   prepare_one_comp_unit (cu, die, cu->language);
11539
11540   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11541      standardised yet.  As a workaround for the language detection we fall
11542      back to the DW_AT_producer string.  */
11543   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11544     cu->language = language_opencl;
11545
11546   /* Similar hack for Go.  */
11547   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11548     set_cu_language (DW_LANG_Go, cu);
11549
11550   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11551
11552   /* Decode line number information if present.  We do this before
11553      processing child DIEs, so that the line header table is available
11554      for DW_AT_decl_file.  */
11555   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11556
11557   /* Process all dies in compilation unit.  */
11558   if (die->child != NULL)
11559     {
11560       child_die = die->child;
11561       while (child_die && child_die->tag)
11562         {
11563           process_die (child_die, cu);
11564           child_die = sibling_die (child_die);
11565         }
11566     }
11567
11568   /* Decode macro information, if present.  Dwarf 2 macro information
11569      refers to information in the line number info statement program
11570      header, so we can only read it if we've read the header
11571      successfully.  */
11572   attr = dwarf2_attr (die, DW_AT_macros, cu);
11573   if (attr == NULL)
11574     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11575   if (attr && cu->line_header)
11576     {
11577       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11578         complaint (&symfile_complaints,
11579                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11580
11581       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11582     }
11583   else
11584     {
11585       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11586       if (attr && cu->line_header)
11587         {
11588           unsigned int macro_offset = DW_UNSND (attr);
11589
11590           dwarf_decode_macros (cu, macro_offset, 0);
11591         }
11592     }
11593 }
11594
11595 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11596    Create the set of symtabs used by this TU, or if this TU is sharing
11597    symtabs with another TU and the symtabs have already been created
11598    then restore those symtabs in the line header.
11599    We don't need the pc/line-number mapping for type units.  */
11600
11601 static void
11602 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11603 {
11604   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11605   struct type_unit_group *tu_group;
11606   int first_time;
11607   struct attribute *attr;
11608   unsigned int i;
11609   struct signatured_type *sig_type;
11610
11611   gdb_assert (per_cu->is_debug_types);
11612   sig_type = (struct signatured_type *) per_cu;
11613
11614   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11615
11616   /* If we're using .gdb_index (includes -readnow) then
11617      per_cu->type_unit_group may not have been set up yet.  */
11618   if (sig_type->type_unit_group == NULL)
11619     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11620   tu_group = sig_type->type_unit_group;
11621
11622   /* If we've already processed this stmt_list there's no real need to
11623      do it again, we could fake it and just recreate the part we need
11624      (file name,index -> symtab mapping).  If data shows this optimization
11625      is useful we can do it then.  */
11626   first_time = tu_group->compunit_symtab == NULL;
11627
11628   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11629      debug info.  */
11630   line_header_up lh;
11631   if (attr != NULL)
11632     {
11633       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11634       lh = dwarf_decode_line_header (line_offset, cu);
11635     }
11636   if (lh == NULL)
11637     {
11638       if (first_time)
11639         dwarf2_start_symtab (cu, "", NULL, 0);
11640       else
11641         {
11642           gdb_assert (tu_group->symtabs == NULL);
11643           restart_symtab (tu_group->compunit_symtab, "", 0);
11644         }
11645       return;
11646     }
11647
11648   cu->line_header = lh.release ();
11649   cu->line_header_die_owner = die;
11650
11651   if (first_time)
11652     {
11653       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11654
11655       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11656          still initializing it, and our caller (a few levels up)
11657          process_full_type_unit still needs to know if this is the first
11658          time.  */
11659
11660       tu_group->num_symtabs = cu->line_header->file_names.size ();
11661       tu_group->symtabs = XNEWVEC (struct symtab *,
11662                                    cu->line_header->file_names.size ());
11663
11664       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11665         {
11666           file_entry &fe = cu->line_header->file_names[i];
11667
11668           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11669
11670           if (current_subfile->symtab == NULL)
11671             {
11672               /* NOTE: start_subfile will recognize when it's been
11673                  passed a file it has already seen.  So we can't
11674                  assume there's a simple mapping from
11675                  cu->line_header->file_names to subfiles, plus
11676                  cu->line_header->file_names may contain dups.  */
11677               current_subfile->symtab
11678                 = allocate_symtab (cust, current_subfile->name);
11679             }
11680
11681           fe.symtab = current_subfile->symtab;
11682           tu_group->symtabs[i] = fe.symtab;
11683         }
11684     }
11685   else
11686     {
11687       restart_symtab (tu_group->compunit_symtab, "", 0);
11688
11689       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11690         {
11691           file_entry &fe = cu->line_header->file_names[i];
11692
11693           fe.symtab = tu_group->symtabs[i];
11694         }
11695     }
11696
11697   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11698      so they don't have a "real" (so to speak) symtab anyway.
11699      There is later code that will assign the main symtab to all symbols
11700      that don't have one.  We need to handle the case of a symbol with a
11701      missing symtab (DW_AT_decl_file) anyway.  */
11702 }
11703
11704 /* Process DW_TAG_type_unit.
11705    For TUs we want to skip the first top level sibling if it's not the
11706    actual type being defined by this TU.  In this case the first top
11707    level sibling is there to provide context only.  */
11708
11709 static void
11710 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11711 {
11712   struct die_info *child_die;
11713
11714   prepare_one_comp_unit (cu, die, language_minimal);
11715
11716   /* Initialize (or reinitialize) the machinery for building symtabs.
11717      We do this before processing child DIEs, so that the line header table
11718      is available for DW_AT_decl_file.  */
11719   setup_type_unit_groups (die, cu);
11720
11721   if (die->child != NULL)
11722     {
11723       child_die = die->child;
11724       while (child_die && child_die->tag)
11725         {
11726           process_die (child_die, cu);
11727           child_die = sibling_die (child_die);
11728         }
11729     }
11730 }
11731 \f
11732 /* DWO/DWP files.
11733
11734    http://gcc.gnu.org/wiki/DebugFission
11735    http://gcc.gnu.org/wiki/DebugFissionDWP
11736
11737    To simplify handling of both DWO files ("object" files with the DWARF info)
11738    and DWP files (a file with the DWOs packaged up into one file), we treat
11739    DWP files as having a collection of virtual DWO files.  */
11740
11741 static hashval_t
11742 hash_dwo_file (const void *item)
11743 {
11744   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11745   hashval_t hash;
11746
11747   hash = htab_hash_string (dwo_file->dwo_name);
11748   if (dwo_file->comp_dir != NULL)
11749     hash += htab_hash_string (dwo_file->comp_dir);
11750   return hash;
11751 }
11752
11753 static int
11754 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11755 {
11756   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11757   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11758
11759   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11760     return 0;
11761   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11762     return lhs->comp_dir == rhs->comp_dir;
11763   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11764 }
11765
11766 /* Allocate a hash table for DWO files.  */
11767
11768 static htab_t
11769 allocate_dwo_file_hash_table (void)
11770 {
11771   struct objfile *objfile = dwarf2_per_objfile->objfile;
11772
11773   return htab_create_alloc_ex (41,
11774                                hash_dwo_file,
11775                                eq_dwo_file,
11776                                NULL,
11777                                &objfile->objfile_obstack,
11778                                hashtab_obstack_allocate,
11779                                dummy_obstack_deallocate);
11780 }
11781
11782 /* Lookup DWO file DWO_NAME.  */
11783
11784 static void **
11785 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
11786 {
11787   struct dwo_file find_entry;
11788   void **slot;
11789
11790   if (dwarf2_per_objfile->dwo_files == NULL)
11791     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
11792
11793   memset (&find_entry, 0, sizeof (find_entry));
11794   find_entry.dwo_name = dwo_name;
11795   find_entry.comp_dir = comp_dir;
11796   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11797
11798   return slot;
11799 }
11800
11801 static hashval_t
11802 hash_dwo_unit (const void *item)
11803 {
11804   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11805
11806   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11807   return dwo_unit->signature;
11808 }
11809
11810 static int
11811 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11812 {
11813   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11814   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11815
11816   /* The signature is assumed to be unique within the DWO file.
11817      So while object file CU dwo_id's always have the value zero,
11818      that's OK, assuming each object file DWO file has only one CU,
11819      and that's the rule for now.  */
11820   return lhs->signature == rhs->signature;
11821 }
11822
11823 /* Allocate a hash table for DWO CUs,TUs.
11824    There is one of these tables for each of CUs,TUs for each DWO file.  */
11825
11826 static htab_t
11827 allocate_dwo_unit_table (struct objfile *objfile)
11828 {
11829   /* Start out with a pretty small number.
11830      Generally DWO files contain only one CU and maybe some TUs.  */
11831   return htab_create_alloc_ex (3,
11832                                hash_dwo_unit,
11833                                eq_dwo_unit,
11834                                NULL,
11835                                &objfile->objfile_obstack,
11836                                hashtab_obstack_allocate,
11837                                dummy_obstack_deallocate);
11838 }
11839
11840 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11841
11842 struct create_dwo_cu_data
11843 {
11844   struct dwo_file *dwo_file;
11845   struct dwo_unit dwo_unit;
11846 };
11847
11848 /* die_reader_func for create_dwo_cu.  */
11849
11850 static void
11851 create_dwo_cu_reader (const struct die_reader_specs *reader,
11852                       const gdb_byte *info_ptr,
11853                       struct die_info *comp_unit_die,
11854                       int has_children,
11855                       void *datap)
11856 {
11857   struct dwarf2_cu *cu = reader->cu;
11858   sect_offset sect_off = cu->per_cu->sect_off;
11859   struct dwarf2_section_info *section = cu->per_cu->section;
11860   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11861   struct dwo_file *dwo_file = data->dwo_file;
11862   struct dwo_unit *dwo_unit = &data->dwo_unit;
11863   struct attribute *attr;
11864
11865   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11866   if (attr == NULL)
11867     {
11868       complaint (&symfile_complaints,
11869                  _("Dwarf Error: debug entry at offset 0x%x is missing"
11870                    " its dwo_id [in module %s]"),
11871                  to_underlying (sect_off), dwo_file->dwo_name);
11872       return;
11873     }
11874
11875   dwo_unit->dwo_file = dwo_file;
11876   dwo_unit->signature = DW_UNSND (attr);
11877   dwo_unit->section = section;
11878   dwo_unit->sect_off = sect_off;
11879   dwo_unit->length = cu->per_cu->length;
11880
11881   if (dwarf_read_debug)
11882     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
11883                         to_underlying (sect_off),
11884                         hex_string (dwo_unit->signature));
11885 }
11886
11887 /* Create the dwo_units for the CUs in a DWO_FILE.
11888    Note: This function processes DWO files only, not DWP files.  */
11889
11890 static void
11891 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
11892                        htab_t &cus_htab)
11893 {
11894   struct objfile *objfile = dwarf2_per_objfile->objfile;
11895   const gdb_byte *info_ptr, *end_ptr;
11896
11897   dwarf2_read_section (objfile, &section);
11898   info_ptr = section.buffer;
11899
11900   if (info_ptr == NULL)
11901     return;
11902
11903   if (dwarf_read_debug)
11904     {
11905       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11906                           get_section_name (&section),
11907                           get_section_file_name (&section));
11908     }
11909
11910   end_ptr = info_ptr + section.size;
11911   while (info_ptr < end_ptr)
11912     {
11913       struct dwarf2_per_cu_data per_cu;
11914       struct create_dwo_cu_data create_dwo_cu_data;
11915       struct dwo_unit *dwo_unit;
11916       void **slot;
11917       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11918
11919       memset (&create_dwo_cu_data.dwo_unit, 0,
11920               sizeof (create_dwo_cu_data.dwo_unit));
11921       memset (&per_cu, 0, sizeof (per_cu));
11922       per_cu.objfile = objfile;
11923       per_cu.is_debug_types = 0;
11924       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11925       per_cu.section = &section;
11926       create_dwo_cu_data.dwo_file = &dwo_file;
11927
11928       init_cutu_and_read_dies_no_follow (
11929           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11930       info_ptr += per_cu.length;
11931
11932       // If the unit could not be parsed, skip it.
11933       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11934         continue;
11935
11936       if (cus_htab == NULL)
11937         cus_htab = allocate_dwo_unit_table (objfile);
11938
11939       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11940       *dwo_unit = create_dwo_cu_data.dwo_unit;
11941       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11942       gdb_assert (slot != NULL);
11943       if (*slot != NULL)
11944         {
11945           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11946           sect_offset dup_sect_off = dup_cu->sect_off;
11947
11948           complaint (&symfile_complaints,
11949                      _("debug cu entry at offset 0x%x is duplicate to"
11950                        " the entry at offset 0x%x, signature %s"),
11951                      to_underlying (sect_off), to_underlying (dup_sect_off),
11952                      hex_string (dwo_unit->signature));
11953         }
11954       *slot = (void *)dwo_unit;
11955     }
11956 }
11957
11958 /* DWP file .debug_{cu,tu}_index section format:
11959    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11960
11961    DWP Version 1:
11962
11963    Both index sections have the same format, and serve to map a 64-bit
11964    signature to a set of section numbers.  Each section begins with a header,
11965    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11966    indexes, and a pool of 32-bit section numbers.  The index sections will be
11967    aligned at 8-byte boundaries in the file.
11968
11969    The index section header consists of:
11970
11971     V, 32 bit version number
11972     -, 32 bits unused
11973     N, 32 bit number of compilation units or type units in the index
11974     M, 32 bit number of slots in the hash table
11975
11976    Numbers are recorded using the byte order of the application binary.
11977
11978    The hash table begins at offset 16 in the section, and consists of an array
11979    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11980    order of the application binary).  Unused slots in the hash table are 0.
11981    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11982
11983    The parallel table begins immediately after the hash table
11984    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11985    array of 32-bit indexes (using the byte order of the application binary),
11986    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11987    table contains a 32-bit index into the pool of section numbers.  For unused
11988    hash table slots, the corresponding entry in the parallel table will be 0.
11989
11990    The pool of section numbers begins immediately following the hash table
11991    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11992    section numbers consists of an array of 32-bit words (using the byte order
11993    of the application binary).  Each item in the array is indexed starting
11994    from 0.  The hash table entry provides the index of the first section
11995    number in the set.  Additional section numbers in the set follow, and the
11996    set is terminated by a 0 entry (section number 0 is not used in ELF).
11997
11998    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11999    section must be the first entry in the set, and the .debug_abbrev.dwo must
12000    be the second entry. Other members of the set may follow in any order.
12001
12002    ---
12003
12004    DWP Version 2:
12005
12006    DWP Version 2 combines all the .debug_info, etc. sections into one,
12007    and the entries in the index tables are now offsets into these sections.
12008    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12009    section.
12010
12011    Index Section Contents:
12012     Header
12013     Hash Table of Signatures   dwp_hash_table.hash_table
12014     Parallel Table of Indices  dwp_hash_table.unit_table
12015     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12016     Table of Section Sizes     dwp_hash_table.v2.sizes
12017
12018    The index section header consists of:
12019
12020     V, 32 bit version number
12021     L, 32 bit number of columns in the table of section offsets
12022     N, 32 bit number of compilation units or type units in the index
12023     M, 32 bit number of slots in the hash table
12024
12025    Numbers are recorded using the byte order of the application binary.
12026
12027    The hash table has the same format as version 1.
12028    The parallel table of indices has the same format as version 1,
12029    except that the entries are origin-1 indices into the table of sections
12030    offsets and the table of section sizes.
12031
12032    The table of offsets begins immediately following the parallel table
12033    (at offset 16 + 12 * M from the beginning of the section).  The table is
12034    a two-dimensional array of 32-bit words (using the byte order of the
12035    application binary), with L columns and N+1 rows, in row-major order.
12036    Each row in the array is indexed starting from 0.  The first row provides
12037    a key to the remaining rows: each column in this row provides an identifier
12038    for a debug section, and the offsets in the same column of subsequent rows
12039    refer to that section.  The section identifiers are:
12040
12041     DW_SECT_INFO         1  .debug_info.dwo
12042     DW_SECT_TYPES        2  .debug_types.dwo
12043     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12044     DW_SECT_LINE         4  .debug_line.dwo
12045     DW_SECT_LOC          5  .debug_loc.dwo
12046     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12047     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12048     DW_SECT_MACRO        8  .debug_macro.dwo
12049
12050    The offsets provided by the CU and TU index sections are the base offsets
12051    for the contributions made by each CU or TU to the corresponding section
12052    in the package file.  Each CU and TU header contains an abbrev_offset
12053    field, used to find the abbreviations table for that CU or TU within the
12054    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12055    be interpreted as relative to the base offset given in the index section.
12056    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12057    should be interpreted as relative to the base offset for .debug_line.dwo,
12058    and offsets into other debug sections obtained from DWARF attributes should
12059    also be interpreted as relative to the corresponding base offset.
12060
12061    The table of sizes begins immediately following the table of offsets.
12062    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12063    with L columns and N rows, in row-major order.  Each row in the array is
12064    indexed starting from 1 (row 0 is shared by the two tables).
12065
12066    ---
12067
12068    Hash table lookup is handled the same in version 1 and 2:
12069
12070    We assume that N and M will not exceed 2^32 - 1.
12071    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12072
12073    Given a 64-bit compilation unit signature or a type signature S, an entry
12074    in the hash table is located as follows:
12075
12076    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12077       the low-order k bits all set to 1.
12078
12079    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12080
12081    3) If the hash table entry at index H matches the signature, use that
12082       entry.  If the hash table entry at index H is unused (all zeroes),
12083       terminate the search: the signature is not present in the table.
12084
12085    4) Let H = (H + H') modulo M. Repeat at Step 3.
12086
12087    Because M > N and H' and M are relatively prime, the search is guaranteed
12088    to stop at an unused slot or find the match.  */
12089
12090 /* Create a hash table to map DWO IDs to their CU/TU entry in
12091    .debug_{info,types}.dwo in DWP_FILE.
12092    Returns NULL if there isn't one.
12093    Note: This function processes DWP files only, not DWO files.  */
12094
12095 static struct dwp_hash_table *
12096 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
12097 {
12098   struct objfile *objfile = dwarf2_per_objfile->objfile;
12099   bfd *dbfd = dwp_file->dbfd;
12100   const gdb_byte *index_ptr, *index_end;
12101   struct dwarf2_section_info *index;
12102   uint32_t version, nr_columns, nr_units, nr_slots;
12103   struct dwp_hash_table *htab;
12104
12105   if (is_debug_types)
12106     index = &dwp_file->sections.tu_index;
12107   else
12108     index = &dwp_file->sections.cu_index;
12109
12110   if (dwarf2_section_empty_p (index))
12111     return NULL;
12112   dwarf2_read_section (objfile, index);
12113
12114   index_ptr = index->buffer;
12115   index_end = index_ptr + index->size;
12116
12117   version = read_4_bytes (dbfd, index_ptr);
12118   index_ptr += 4;
12119   if (version == 2)
12120     nr_columns = read_4_bytes (dbfd, index_ptr);
12121   else
12122     nr_columns = 0;
12123   index_ptr += 4;
12124   nr_units = read_4_bytes (dbfd, index_ptr);
12125   index_ptr += 4;
12126   nr_slots = read_4_bytes (dbfd, index_ptr);
12127   index_ptr += 4;
12128
12129   if (version != 1 && version != 2)
12130     {
12131       error (_("Dwarf Error: unsupported DWP file version (%s)"
12132                " [in module %s]"),
12133              pulongest (version), dwp_file->name);
12134     }
12135   if (nr_slots != (nr_slots & -nr_slots))
12136     {
12137       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12138                " is not power of 2 [in module %s]"),
12139              pulongest (nr_slots), dwp_file->name);
12140     }
12141
12142   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12143   htab->version = version;
12144   htab->nr_columns = nr_columns;
12145   htab->nr_units = nr_units;
12146   htab->nr_slots = nr_slots;
12147   htab->hash_table = index_ptr;
12148   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12149
12150   /* Exit early if the table is empty.  */
12151   if (nr_slots == 0 || nr_units == 0
12152       || (version == 2 && nr_columns == 0))
12153     {
12154       /* All must be zero.  */
12155       if (nr_slots != 0 || nr_units != 0
12156           || (version == 2 && nr_columns != 0))
12157         {
12158           complaint (&symfile_complaints,
12159                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12160                        " all zero [in modules %s]"),
12161                      dwp_file->name);
12162         }
12163       return htab;
12164     }
12165
12166   if (version == 1)
12167     {
12168       htab->section_pool.v1.indices =
12169         htab->unit_table + sizeof (uint32_t) * nr_slots;
12170       /* It's harder to decide whether the section is too small in v1.
12171          V1 is deprecated anyway so we punt.  */
12172     }
12173   else
12174     {
12175       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12176       int *ids = htab->section_pool.v2.section_ids;
12177       /* Reverse map for error checking.  */
12178       int ids_seen[DW_SECT_MAX + 1];
12179       int i;
12180
12181       if (nr_columns < 2)
12182         {
12183           error (_("Dwarf Error: bad DWP hash table, too few columns"
12184                    " in section table [in module %s]"),
12185                  dwp_file->name);
12186         }
12187       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12188         {
12189           error (_("Dwarf Error: bad DWP hash table, too many columns"
12190                    " in section table [in module %s]"),
12191                  dwp_file->name);
12192         }
12193       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12194       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12195       for (i = 0; i < nr_columns; ++i)
12196         {
12197           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12198
12199           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12200             {
12201               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12202                        " in section table [in module %s]"),
12203                      id, dwp_file->name);
12204             }
12205           if (ids_seen[id] != -1)
12206             {
12207               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12208                        " id %d in section table [in module %s]"),
12209                      id, dwp_file->name);
12210             }
12211           ids_seen[id] = i;
12212           ids[i] = id;
12213         }
12214       /* Must have exactly one info or types section.  */
12215       if (((ids_seen[DW_SECT_INFO] != -1)
12216            + (ids_seen[DW_SECT_TYPES] != -1))
12217           != 1)
12218         {
12219           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12220                    " DWO info/types section [in module %s]"),
12221                  dwp_file->name);
12222         }
12223       /* Must have an abbrev section.  */
12224       if (ids_seen[DW_SECT_ABBREV] == -1)
12225         {
12226           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12227                    " section [in module %s]"),
12228                  dwp_file->name);
12229         }
12230       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12231       htab->section_pool.v2.sizes =
12232         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12233                                          * nr_units * nr_columns);
12234       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12235                                           * nr_units * nr_columns))
12236           > index_end)
12237         {
12238           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12239                    " [in module %s]"),
12240                  dwp_file->name);
12241         }
12242     }
12243
12244   return htab;
12245 }
12246
12247 /* Update SECTIONS with the data from SECTP.
12248
12249    This function is like the other "locate" section routines that are
12250    passed to bfd_map_over_sections, but in this context the sections to
12251    read comes from the DWP V1 hash table, not the full ELF section table.
12252
12253    The result is non-zero for success, or zero if an error was found.  */
12254
12255 static int
12256 locate_v1_virtual_dwo_sections (asection *sectp,
12257                                 struct virtual_v1_dwo_sections *sections)
12258 {
12259   const struct dwop_section_names *names = &dwop_section_names;
12260
12261   if (section_is_p (sectp->name, &names->abbrev_dwo))
12262     {
12263       /* There can be only one.  */
12264       if (sections->abbrev.s.section != NULL)
12265         return 0;
12266       sections->abbrev.s.section = sectp;
12267       sections->abbrev.size = bfd_get_section_size (sectp);
12268     }
12269   else if (section_is_p (sectp->name, &names->info_dwo)
12270            || section_is_p (sectp->name, &names->types_dwo))
12271     {
12272       /* There can be only one.  */
12273       if (sections->info_or_types.s.section != NULL)
12274         return 0;
12275       sections->info_or_types.s.section = sectp;
12276       sections->info_or_types.size = bfd_get_section_size (sectp);
12277     }
12278   else if (section_is_p (sectp->name, &names->line_dwo))
12279     {
12280       /* There can be only one.  */
12281       if (sections->line.s.section != NULL)
12282         return 0;
12283       sections->line.s.section = sectp;
12284       sections->line.size = bfd_get_section_size (sectp);
12285     }
12286   else if (section_is_p (sectp->name, &names->loc_dwo))
12287     {
12288       /* There can be only one.  */
12289       if (sections->loc.s.section != NULL)
12290         return 0;
12291       sections->loc.s.section = sectp;
12292       sections->loc.size = bfd_get_section_size (sectp);
12293     }
12294   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12295     {
12296       /* There can be only one.  */
12297       if (sections->macinfo.s.section != NULL)
12298         return 0;
12299       sections->macinfo.s.section = sectp;
12300       sections->macinfo.size = bfd_get_section_size (sectp);
12301     }
12302   else if (section_is_p (sectp->name, &names->macro_dwo))
12303     {
12304       /* There can be only one.  */
12305       if (sections->macro.s.section != NULL)
12306         return 0;
12307       sections->macro.s.section = sectp;
12308       sections->macro.size = bfd_get_section_size (sectp);
12309     }
12310   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12311     {
12312       /* There can be only one.  */
12313       if (sections->str_offsets.s.section != NULL)
12314         return 0;
12315       sections->str_offsets.s.section = sectp;
12316       sections->str_offsets.size = bfd_get_section_size (sectp);
12317     }
12318   else
12319     {
12320       /* No other kind of section is valid.  */
12321       return 0;
12322     }
12323
12324   return 1;
12325 }
12326
12327 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12328    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12329    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12330    This is for DWP version 1 files.  */
12331
12332 static struct dwo_unit *
12333 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
12334                            uint32_t unit_index,
12335                            const char *comp_dir,
12336                            ULONGEST signature, int is_debug_types)
12337 {
12338   struct objfile *objfile = dwarf2_per_objfile->objfile;
12339   const struct dwp_hash_table *dwp_htab =
12340     is_debug_types ? dwp_file->tus : dwp_file->cus;
12341   bfd *dbfd = dwp_file->dbfd;
12342   const char *kind = is_debug_types ? "TU" : "CU";
12343   struct dwo_file *dwo_file;
12344   struct dwo_unit *dwo_unit;
12345   struct virtual_v1_dwo_sections sections;
12346   void **dwo_file_slot;
12347   int i;
12348
12349   gdb_assert (dwp_file->version == 1);
12350
12351   if (dwarf_read_debug)
12352     {
12353       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12354                           kind,
12355                           pulongest (unit_index), hex_string (signature),
12356                           dwp_file->name);
12357     }
12358
12359   /* Fetch the sections of this DWO unit.
12360      Put a limit on the number of sections we look for so that bad data
12361      doesn't cause us to loop forever.  */
12362
12363 #define MAX_NR_V1_DWO_SECTIONS \
12364   (1 /* .debug_info or .debug_types */ \
12365    + 1 /* .debug_abbrev */ \
12366    + 1 /* .debug_line */ \
12367    + 1 /* .debug_loc */ \
12368    + 1 /* .debug_str_offsets */ \
12369    + 1 /* .debug_macro or .debug_macinfo */ \
12370    + 1 /* trailing zero */)
12371
12372   memset (&sections, 0, sizeof (sections));
12373
12374   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12375     {
12376       asection *sectp;
12377       uint32_t section_nr =
12378         read_4_bytes (dbfd,
12379                       dwp_htab->section_pool.v1.indices
12380                       + (unit_index + i) * sizeof (uint32_t));
12381
12382       if (section_nr == 0)
12383         break;
12384       if (section_nr >= dwp_file->num_sections)
12385         {
12386           error (_("Dwarf Error: bad DWP hash table, section number too large"
12387                    " [in module %s]"),
12388                  dwp_file->name);
12389         }
12390
12391       sectp = dwp_file->elf_sections[section_nr];
12392       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12393         {
12394           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12395                    " [in module %s]"),
12396                  dwp_file->name);
12397         }
12398     }
12399
12400   if (i < 2
12401       || dwarf2_section_empty_p (&sections.info_or_types)
12402       || dwarf2_section_empty_p (&sections.abbrev))
12403     {
12404       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12405                " [in module %s]"),
12406              dwp_file->name);
12407     }
12408   if (i == MAX_NR_V1_DWO_SECTIONS)
12409     {
12410       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12411                " [in module %s]"),
12412              dwp_file->name);
12413     }
12414
12415   /* It's easier for the rest of the code if we fake a struct dwo_file and
12416      have dwo_unit "live" in that.  At least for now.
12417
12418      The DWP file can be made up of a random collection of CUs and TUs.
12419      However, for each CU + set of TUs that came from the same original DWO
12420      file, we can combine them back into a virtual DWO file to save space
12421      (fewer struct dwo_file objects to allocate).  Remember that for really
12422      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12423
12424   std::string virtual_dwo_name =
12425     string_printf ("virtual-dwo/%d-%d-%d-%d",
12426                    get_section_id (&sections.abbrev),
12427                    get_section_id (&sections.line),
12428                    get_section_id (&sections.loc),
12429                    get_section_id (&sections.str_offsets));
12430   /* Can we use an existing virtual DWO file?  */
12431   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12432   /* Create one if necessary.  */
12433   if (*dwo_file_slot == NULL)
12434     {
12435       if (dwarf_read_debug)
12436         {
12437           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12438                               virtual_dwo_name.c_str ());
12439         }
12440       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12441       dwo_file->dwo_name
12442         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12443                                         virtual_dwo_name.c_str (),
12444                                         virtual_dwo_name.size ());
12445       dwo_file->comp_dir = comp_dir;
12446       dwo_file->sections.abbrev = sections.abbrev;
12447       dwo_file->sections.line = sections.line;
12448       dwo_file->sections.loc = sections.loc;
12449       dwo_file->sections.macinfo = sections.macinfo;
12450       dwo_file->sections.macro = sections.macro;
12451       dwo_file->sections.str_offsets = sections.str_offsets;
12452       /* The "str" section is global to the entire DWP file.  */
12453       dwo_file->sections.str = dwp_file->sections.str;
12454       /* The info or types section is assigned below to dwo_unit,
12455          there's no need to record it in dwo_file.
12456          Also, we can't simply record type sections in dwo_file because
12457          we record a pointer into the vector in dwo_unit.  As we collect more
12458          types we'll grow the vector and eventually have to reallocate space
12459          for it, invalidating all copies of pointers into the previous
12460          contents.  */
12461       *dwo_file_slot = dwo_file;
12462     }
12463   else
12464     {
12465       if (dwarf_read_debug)
12466         {
12467           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12468                               virtual_dwo_name.c_str ());
12469         }
12470       dwo_file = (struct dwo_file *) *dwo_file_slot;
12471     }
12472
12473   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12474   dwo_unit->dwo_file = dwo_file;
12475   dwo_unit->signature = signature;
12476   dwo_unit->section =
12477     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12478   *dwo_unit->section = sections.info_or_types;
12479   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12480
12481   return dwo_unit;
12482 }
12483
12484 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12485    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12486    piece within that section used by a TU/CU, return a virtual section
12487    of just that piece.  */
12488
12489 static struct dwarf2_section_info
12490 create_dwp_v2_section (struct dwarf2_section_info *section,
12491                        bfd_size_type offset, bfd_size_type size)
12492 {
12493   struct dwarf2_section_info result;
12494   asection *sectp;
12495
12496   gdb_assert (section != NULL);
12497   gdb_assert (!section->is_virtual);
12498
12499   memset (&result, 0, sizeof (result));
12500   result.s.containing_section = section;
12501   result.is_virtual = 1;
12502
12503   if (size == 0)
12504     return result;
12505
12506   sectp = get_section_bfd_section (section);
12507
12508   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12509      bounds of the real section.  This is a pretty-rare event, so just
12510      flag an error (easier) instead of a warning and trying to cope.  */
12511   if (sectp == NULL
12512       || offset + size > bfd_get_section_size (sectp))
12513     {
12514       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12515                " in section %s [in module %s]"),
12516              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12517              objfile_name (dwarf2_per_objfile->objfile));
12518     }
12519
12520   result.virtual_offset = offset;
12521   result.size = size;
12522   return result;
12523 }
12524
12525 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12526    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12527    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12528    This is for DWP version 2 files.  */
12529
12530 static struct dwo_unit *
12531 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
12532                            uint32_t unit_index,
12533                            const char *comp_dir,
12534                            ULONGEST signature, int is_debug_types)
12535 {
12536   struct objfile *objfile = dwarf2_per_objfile->objfile;
12537   const struct dwp_hash_table *dwp_htab =
12538     is_debug_types ? dwp_file->tus : dwp_file->cus;
12539   bfd *dbfd = dwp_file->dbfd;
12540   const char *kind = is_debug_types ? "TU" : "CU";
12541   struct dwo_file *dwo_file;
12542   struct dwo_unit *dwo_unit;
12543   struct virtual_v2_dwo_sections sections;
12544   void **dwo_file_slot;
12545   int i;
12546
12547   gdb_assert (dwp_file->version == 2);
12548
12549   if (dwarf_read_debug)
12550     {
12551       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12552                           kind,
12553                           pulongest (unit_index), hex_string (signature),
12554                           dwp_file->name);
12555     }
12556
12557   /* Fetch the section offsets of this DWO unit.  */
12558
12559   memset (&sections, 0, sizeof (sections));
12560
12561   for (i = 0; i < dwp_htab->nr_columns; ++i)
12562     {
12563       uint32_t offset = read_4_bytes (dbfd,
12564                                       dwp_htab->section_pool.v2.offsets
12565                                       + (((unit_index - 1) * dwp_htab->nr_columns
12566                                           + i)
12567                                          * sizeof (uint32_t)));
12568       uint32_t size = read_4_bytes (dbfd,
12569                                     dwp_htab->section_pool.v2.sizes
12570                                     + (((unit_index - 1) * dwp_htab->nr_columns
12571                                         + i)
12572                                        * sizeof (uint32_t)));
12573
12574       switch (dwp_htab->section_pool.v2.section_ids[i])
12575         {
12576         case DW_SECT_INFO:
12577         case DW_SECT_TYPES:
12578           sections.info_or_types_offset = offset;
12579           sections.info_or_types_size = size;
12580           break;
12581         case DW_SECT_ABBREV:
12582           sections.abbrev_offset = offset;
12583           sections.abbrev_size = size;
12584           break;
12585         case DW_SECT_LINE:
12586           sections.line_offset = offset;
12587           sections.line_size = size;
12588           break;
12589         case DW_SECT_LOC:
12590           sections.loc_offset = offset;
12591           sections.loc_size = size;
12592           break;
12593         case DW_SECT_STR_OFFSETS:
12594           sections.str_offsets_offset = offset;
12595           sections.str_offsets_size = size;
12596           break;
12597         case DW_SECT_MACINFO:
12598           sections.macinfo_offset = offset;
12599           sections.macinfo_size = size;
12600           break;
12601         case DW_SECT_MACRO:
12602           sections.macro_offset = offset;
12603           sections.macro_size = size;
12604           break;
12605         }
12606     }
12607
12608   /* It's easier for the rest of the code if we fake a struct dwo_file and
12609      have dwo_unit "live" in that.  At least for now.
12610
12611      The DWP file can be made up of a random collection of CUs and TUs.
12612      However, for each CU + set of TUs that came from the same original DWO
12613      file, we can combine them back into a virtual DWO file to save space
12614      (fewer struct dwo_file objects to allocate).  Remember that for really
12615      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12616
12617   std::string virtual_dwo_name =
12618     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12619                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12620                    (long) (sections.line_size ? sections.line_offset : 0),
12621                    (long) (sections.loc_size ? sections.loc_offset : 0),
12622                    (long) (sections.str_offsets_size
12623                            ? sections.str_offsets_offset : 0));
12624   /* Can we use an existing virtual DWO file?  */
12625   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
12626   /* Create one if necessary.  */
12627   if (*dwo_file_slot == NULL)
12628     {
12629       if (dwarf_read_debug)
12630         {
12631           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12632                               virtual_dwo_name.c_str ());
12633         }
12634       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12635       dwo_file->dwo_name
12636         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12637                                         virtual_dwo_name.c_str (),
12638                                         virtual_dwo_name.size ());
12639       dwo_file->comp_dir = comp_dir;
12640       dwo_file->sections.abbrev =
12641         create_dwp_v2_section (&dwp_file->sections.abbrev,
12642                                sections.abbrev_offset, sections.abbrev_size);
12643       dwo_file->sections.line =
12644         create_dwp_v2_section (&dwp_file->sections.line,
12645                                sections.line_offset, sections.line_size);
12646       dwo_file->sections.loc =
12647         create_dwp_v2_section (&dwp_file->sections.loc,
12648                                sections.loc_offset, sections.loc_size);
12649       dwo_file->sections.macinfo =
12650         create_dwp_v2_section (&dwp_file->sections.macinfo,
12651                                sections.macinfo_offset, sections.macinfo_size);
12652       dwo_file->sections.macro =
12653         create_dwp_v2_section (&dwp_file->sections.macro,
12654                                sections.macro_offset, sections.macro_size);
12655       dwo_file->sections.str_offsets =
12656         create_dwp_v2_section (&dwp_file->sections.str_offsets,
12657                                sections.str_offsets_offset,
12658                                sections.str_offsets_size);
12659       /* The "str" section is global to the entire DWP file.  */
12660       dwo_file->sections.str = dwp_file->sections.str;
12661       /* The info or types section is assigned below to dwo_unit,
12662          there's no need to record it in dwo_file.
12663          Also, we can't simply record type sections in dwo_file because
12664          we record a pointer into the vector in dwo_unit.  As we collect more
12665          types we'll grow the vector and eventually have to reallocate space
12666          for it, invalidating all copies of pointers into the previous
12667          contents.  */
12668       *dwo_file_slot = dwo_file;
12669     }
12670   else
12671     {
12672       if (dwarf_read_debug)
12673         {
12674           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12675                               virtual_dwo_name.c_str ());
12676         }
12677       dwo_file = (struct dwo_file *) *dwo_file_slot;
12678     }
12679
12680   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12681   dwo_unit->dwo_file = dwo_file;
12682   dwo_unit->signature = signature;
12683   dwo_unit->section =
12684     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12685   *dwo_unit->section = create_dwp_v2_section (is_debug_types
12686                                               ? &dwp_file->sections.types
12687                                               : &dwp_file->sections.info,
12688                                               sections.info_or_types_offset,
12689                                               sections.info_or_types_size);
12690   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12691
12692   return dwo_unit;
12693 }
12694
12695 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12696    Returns NULL if the signature isn't found.  */
12697
12698 static struct dwo_unit *
12699 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
12700                         ULONGEST signature, int is_debug_types)
12701 {
12702   const struct dwp_hash_table *dwp_htab =
12703     is_debug_types ? dwp_file->tus : dwp_file->cus;
12704   bfd *dbfd = dwp_file->dbfd;
12705   uint32_t mask = dwp_htab->nr_slots - 1;
12706   uint32_t hash = signature & mask;
12707   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12708   unsigned int i;
12709   void **slot;
12710   struct dwo_unit find_dwo_cu;
12711
12712   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12713   find_dwo_cu.signature = signature;
12714   slot = htab_find_slot (is_debug_types
12715                          ? dwp_file->loaded_tus
12716                          : dwp_file->loaded_cus,
12717                          &find_dwo_cu, INSERT);
12718
12719   if (*slot != NULL)
12720     return (struct dwo_unit *) *slot;
12721
12722   /* Use a for loop so that we don't loop forever on bad debug info.  */
12723   for (i = 0; i < dwp_htab->nr_slots; ++i)
12724     {
12725       ULONGEST signature_in_table;
12726
12727       signature_in_table =
12728         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12729       if (signature_in_table == signature)
12730         {
12731           uint32_t unit_index =
12732             read_4_bytes (dbfd,
12733                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12734
12735           if (dwp_file->version == 1)
12736             {
12737               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
12738                                                  comp_dir, signature,
12739                                                  is_debug_types);
12740             }
12741           else
12742             {
12743               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
12744                                                  comp_dir, signature,
12745                                                  is_debug_types);
12746             }
12747           return (struct dwo_unit *) *slot;
12748         }
12749       if (signature_in_table == 0)
12750         return NULL;
12751       hash = (hash + hash2) & mask;
12752     }
12753
12754   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12755            " [in module %s]"),
12756          dwp_file->name);
12757 }
12758
12759 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12760    Open the file specified by FILE_NAME and hand it off to BFD for
12761    preliminary analysis.  Return a newly initialized bfd *, which
12762    includes a canonicalized copy of FILE_NAME.
12763    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12764    SEARCH_CWD is true if the current directory is to be searched.
12765    It will be searched before debug-file-directory.
12766    If successful, the file is added to the bfd include table of the
12767    objfile's bfd (see gdb_bfd_record_inclusion).
12768    If unable to find/open the file, return NULL.
12769    NOTE: This function is derived from symfile_bfd_open.  */
12770
12771 static gdb_bfd_ref_ptr
12772 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
12773 {
12774   int desc, flags;
12775   char *absolute_name;
12776   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12777      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12778      to debug_file_directory.  */
12779   char *search_path;
12780   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12781
12782   if (search_cwd)
12783     {
12784       if (*debug_file_directory != '\0')
12785         search_path = concat (".", dirname_separator_string,
12786                               debug_file_directory, (char *) NULL);
12787       else
12788         search_path = xstrdup (".");
12789     }
12790   else
12791     search_path = xstrdup (debug_file_directory);
12792
12793   flags = OPF_RETURN_REALPATH;
12794   if (is_dwp)
12795     flags |= OPF_SEARCH_IN_PATH;
12796   desc = openp (search_path, flags, file_name,
12797                 O_RDONLY | O_BINARY, &absolute_name);
12798   xfree (search_path);
12799   if (desc < 0)
12800     return NULL;
12801
12802   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12803   xfree (absolute_name);
12804   if (sym_bfd == NULL)
12805     return NULL;
12806   bfd_set_cacheable (sym_bfd.get (), 1);
12807
12808   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12809     return NULL;
12810
12811   /* Success.  Record the bfd as having been included by the objfile's bfd.
12812      This is important because things like demangled_names_hash lives in the
12813      objfile's per_bfd space and may have references to things like symbol
12814      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12815   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12816
12817   return sym_bfd;
12818 }
12819
12820 /* Try to open DWO file FILE_NAME.
12821    COMP_DIR is the DW_AT_comp_dir attribute.
12822    The result is the bfd handle of the file.
12823    If there is a problem finding or opening the file, return NULL.
12824    Upon success, the canonicalized path of the file is stored in the bfd,
12825    same as symfile_bfd_open.  */
12826
12827 static gdb_bfd_ref_ptr
12828 open_dwo_file (const char *file_name, const char *comp_dir)
12829 {
12830   if (IS_ABSOLUTE_PATH (file_name))
12831     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
12832
12833   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12834
12835   if (comp_dir != NULL)
12836     {
12837       char *path_to_try = concat (comp_dir, SLASH_STRING,
12838                                   file_name, (char *) NULL);
12839
12840       /* NOTE: If comp_dir is a relative path, this will also try the
12841          search path, which seems useful.  */
12842       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
12843                                                 1 /*search_cwd*/));
12844       xfree (path_to_try);
12845       if (abfd != NULL)
12846         return abfd;
12847     }
12848
12849   /* That didn't work, try debug-file-directory, which, despite its name,
12850      is a list of paths.  */
12851
12852   if (*debug_file_directory == '\0')
12853     return NULL;
12854
12855   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
12856 }
12857
12858 /* This function is mapped across the sections and remembers the offset and
12859    size of each of the DWO debugging sections we are interested in.  */
12860
12861 static void
12862 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12863 {
12864   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12865   const struct dwop_section_names *names = &dwop_section_names;
12866
12867   if (section_is_p (sectp->name, &names->abbrev_dwo))
12868     {
12869       dwo_sections->abbrev.s.section = sectp;
12870       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12871     }
12872   else if (section_is_p (sectp->name, &names->info_dwo))
12873     {
12874       dwo_sections->info.s.section = sectp;
12875       dwo_sections->info.size = bfd_get_section_size (sectp);
12876     }
12877   else if (section_is_p (sectp->name, &names->line_dwo))
12878     {
12879       dwo_sections->line.s.section = sectp;
12880       dwo_sections->line.size = bfd_get_section_size (sectp);
12881     }
12882   else if (section_is_p (sectp->name, &names->loc_dwo))
12883     {
12884       dwo_sections->loc.s.section = sectp;
12885       dwo_sections->loc.size = bfd_get_section_size (sectp);
12886     }
12887   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12888     {
12889       dwo_sections->macinfo.s.section = sectp;
12890       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12891     }
12892   else if (section_is_p (sectp->name, &names->macro_dwo))
12893     {
12894       dwo_sections->macro.s.section = sectp;
12895       dwo_sections->macro.size = bfd_get_section_size (sectp);
12896     }
12897   else if (section_is_p (sectp->name, &names->str_dwo))
12898     {
12899       dwo_sections->str.s.section = sectp;
12900       dwo_sections->str.size = bfd_get_section_size (sectp);
12901     }
12902   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12903     {
12904       dwo_sections->str_offsets.s.section = sectp;
12905       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12906     }
12907   else if (section_is_p (sectp->name, &names->types_dwo))
12908     {
12909       struct dwarf2_section_info type_section;
12910
12911       memset (&type_section, 0, sizeof (type_section));
12912       type_section.s.section = sectp;
12913       type_section.size = bfd_get_section_size (sectp);
12914       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12915                      &type_section);
12916     }
12917 }
12918
12919 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12920    by PER_CU.  This is for the non-DWP case.
12921    The result is NULL if DWO_NAME can't be found.  */
12922
12923 static struct dwo_file *
12924 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12925                         const char *dwo_name, const char *comp_dir)
12926 {
12927   struct objfile *objfile = dwarf2_per_objfile->objfile;
12928   struct dwo_file *dwo_file;
12929   struct cleanup *cleanups;
12930
12931   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
12932   if (dbfd == NULL)
12933     {
12934       if (dwarf_read_debug)
12935         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12936       return NULL;
12937     }
12938   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12939   dwo_file->dwo_name = dwo_name;
12940   dwo_file->comp_dir = comp_dir;
12941   dwo_file->dbfd = dbfd.release ();
12942
12943   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
12944
12945   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12946                          &dwo_file->sections);
12947
12948   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
12949
12950   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
12951                                  dwo_file->tus);
12952
12953   discard_cleanups (cleanups);
12954
12955   if (dwarf_read_debug)
12956     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12957
12958   return dwo_file;
12959 }
12960
12961 /* This function is mapped across the sections and remembers the offset and
12962    size of each of the DWP debugging sections common to version 1 and 2 that
12963    we are interested in.  */
12964
12965 static void
12966 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12967                                    void *dwp_file_ptr)
12968 {
12969   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12970   const struct dwop_section_names *names = &dwop_section_names;
12971   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12972
12973   /* Record the ELF section number for later lookup: this is what the
12974      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12975   gdb_assert (elf_section_nr < dwp_file->num_sections);
12976   dwp_file->elf_sections[elf_section_nr] = sectp;
12977
12978   /* Look for specific sections that we need.  */
12979   if (section_is_p (sectp->name, &names->str_dwo))
12980     {
12981       dwp_file->sections.str.s.section = sectp;
12982       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12983     }
12984   else if (section_is_p (sectp->name, &names->cu_index))
12985     {
12986       dwp_file->sections.cu_index.s.section = sectp;
12987       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12988     }
12989   else if (section_is_p (sectp->name, &names->tu_index))
12990     {
12991       dwp_file->sections.tu_index.s.section = sectp;
12992       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12993     }
12994 }
12995
12996 /* This function is mapped across the sections and remembers the offset and
12997    size of each of the DWP version 2 debugging sections that we are interested
12998    in.  This is split into a separate function because we don't know if we
12999    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13000
13001 static void
13002 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13003 {
13004   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13005   const struct dwop_section_names *names = &dwop_section_names;
13006   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13007
13008   /* Record the ELF section number for later lookup: this is what the
13009      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13010   gdb_assert (elf_section_nr < dwp_file->num_sections);
13011   dwp_file->elf_sections[elf_section_nr] = sectp;
13012
13013   /* Look for specific sections that we need.  */
13014   if (section_is_p (sectp->name, &names->abbrev_dwo))
13015     {
13016       dwp_file->sections.abbrev.s.section = sectp;
13017       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13018     }
13019   else if (section_is_p (sectp->name, &names->info_dwo))
13020     {
13021       dwp_file->sections.info.s.section = sectp;
13022       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13023     }
13024   else if (section_is_p (sectp->name, &names->line_dwo))
13025     {
13026       dwp_file->sections.line.s.section = sectp;
13027       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13028     }
13029   else if (section_is_p (sectp->name, &names->loc_dwo))
13030     {
13031       dwp_file->sections.loc.s.section = sectp;
13032       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13033     }
13034   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13035     {
13036       dwp_file->sections.macinfo.s.section = sectp;
13037       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13038     }
13039   else if (section_is_p (sectp->name, &names->macro_dwo))
13040     {
13041       dwp_file->sections.macro.s.section = sectp;
13042       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13043     }
13044   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13045     {
13046       dwp_file->sections.str_offsets.s.section = sectp;
13047       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13048     }
13049   else if (section_is_p (sectp->name, &names->types_dwo))
13050     {
13051       dwp_file->sections.types.s.section = sectp;
13052       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13053     }
13054 }
13055
13056 /* Hash function for dwp_file loaded CUs/TUs.  */
13057
13058 static hashval_t
13059 hash_dwp_loaded_cutus (const void *item)
13060 {
13061   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13062
13063   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13064   return dwo_unit->signature;
13065 }
13066
13067 /* Equality function for dwp_file loaded CUs/TUs.  */
13068
13069 static int
13070 eq_dwp_loaded_cutus (const void *a, const void *b)
13071 {
13072   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13073   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13074
13075   return dua->signature == dub->signature;
13076 }
13077
13078 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13079
13080 static htab_t
13081 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13082 {
13083   return htab_create_alloc_ex (3,
13084                                hash_dwp_loaded_cutus,
13085                                eq_dwp_loaded_cutus,
13086                                NULL,
13087                                &objfile->objfile_obstack,
13088                                hashtab_obstack_allocate,
13089                                dummy_obstack_deallocate);
13090 }
13091
13092 /* Try to open DWP file FILE_NAME.
13093    The result is the bfd handle of the file.
13094    If there is a problem finding or opening the file, return NULL.
13095    Upon success, the canonicalized path of the file is stored in the bfd,
13096    same as symfile_bfd_open.  */
13097
13098 static gdb_bfd_ref_ptr
13099 open_dwp_file (const char *file_name)
13100 {
13101   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
13102                                             1 /*search_cwd*/));
13103   if (abfd != NULL)
13104     return abfd;
13105
13106   /* Work around upstream bug 15652.
13107      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13108      [Whether that's a "bug" is debatable, but it is getting in our way.]
13109      We have no real idea where the dwp file is, because gdb's realpath-ing
13110      of the executable's path may have discarded the needed info.
13111      [IWBN if the dwp file name was recorded in the executable, akin to
13112      .gnu_debuglink, but that doesn't exist yet.]
13113      Strip the directory from FILE_NAME and search again.  */
13114   if (*debug_file_directory != '\0')
13115     {
13116       /* Don't implicitly search the current directory here.
13117          If the user wants to search "." to handle this case,
13118          it must be added to debug-file-directory.  */
13119       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
13120                                  0 /*search_cwd*/);
13121     }
13122
13123   return NULL;
13124 }
13125
13126 /* Initialize the use of the DWP file for the current objfile.
13127    By convention the name of the DWP file is ${objfile}.dwp.
13128    The result is NULL if it can't be found.  */
13129
13130 static struct dwp_file *
13131 open_and_init_dwp_file (void)
13132 {
13133   struct objfile *objfile = dwarf2_per_objfile->objfile;
13134   struct dwp_file *dwp_file;
13135
13136   /* Try to find first .dwp for the binary file before any symbolic links
13137      resolving.  */
13138
13139   /* If the objfile is a debug file, find the name of the real binary
13140      file and get the name of dwp file from there.  */
13141   std::string dwp_name;
13142   if (objfile->separate_debug_objfile_backlink != NULL)
13143     {
13144       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13145       const char *backlink_basename = lbasename (backlink->original_name);
13146
13147       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13148     }
13149   else
13150     dwp_name = objfile->original_name;
13151
13152   dwp_name += ".dwp";
13153
13154   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
13155   if (dbfd == NULL
13156       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13157     {
13158       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13159       dwp_name = objfile_name (objfile);
13160       dwp_name += ".dwp";
13161       dbfd = open_dwp_file (dwp_name.c_str ());
13162     }
13163
13164   if (dbfd == NULL)
13165     {
13166       if (dwarf_read_debug)
13167         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13168       return NULL;
13169     }
13170   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13171   dwp_file->name = bfd_get_filename (dbfd.get ());
13172   dwp_file->dbfd = dbfd.release ();
13173
13174   /* +1: section 0 is unused */
13175   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13176   dwp_file->elf_sections =
13177     OBSTACK_CALLOC (&objfile->objfile_obstack,
13178                     dwp_file->num_sections, asection *);
13179
13180   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13181                          dwp_file);
13182
13183   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
13184
13185   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
13186
13187   /* The DWP file version is stored in the hash table.  Oh well.  */
13188   if (dwp_file->cus && dwp_file->tus
13189       && dwp_file->cus->version != dwp_file->tus->version)
13190     {
13191       /* Technically speaking, we should try to limp along, but this is
13192          pretty bizarre.  We use pulongest here because that's the established
13193          portability solution (e.g, we cannot use %u for uint32_t).  */
13194       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13195                " TU version %s [in DWP file %s]"),
13196              pulongest (dwp_file->cus->version),
13197              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13198     }
13199
13200   if (dwp_file->cus)
13201     dwp_file->version = dwp_file->cus->version;
13202   else if (dwp_file->tus)
13203     dwp_file->version = dwp_file->tus->version;
13204   else
13205     dwp_file->version = 2;
13206
13207   if (dwp_file->version == 2)
13208     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13209                            dwp_file);
13210
13211   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13212   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13213
13214   if (dwarf_read_debug)
13215     {
13216       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13217       fprintf_unfiltered (gdb_stdlog,
13218                           "    %s CUs, %s TUs\n",
13219                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13220                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13221     }
13222
13223   return dwp_file;
13224 }
13225
13226 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13227
13228 static struct dwp_file *
13229 get_dwp_file (void)
13230 {
13231   if (! dwarf2_per_objfile->dwp_checked)
13232     {
13233       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
13234       dwarf2_per_objfile->dwp_checked = 1;
13235     }
13236   return dwarf2_per_objfile->dwp_file;
13237 }
13238
13239 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13240    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13241    or in the DWP file for the objfile, referenced by THIS_UNIT.
13242    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13243    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13244
13245    This is called, for example, when wanting to read a variable with a
13246    complex location.  Therefore we don't want to do file i/o for every call.
13247    Therefore we don't want to look for a DWO file on every call.
13248    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13249    then we check if we've already seen DWO_NAME, and only THEN do we check
13250    for a DWO file.
13251
13252    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13253    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13254
13255 static struct dwo_unit *
13256 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13257                  const char *dwo_name, const char *comp_dir,
13258                  ULONGEST signature, int is_debug_types)
13259 {
13260   struct objfile *objfile = dwarf2_per_objfile->objfile;
13261   const char *kind = is_debug_types ? "TU" : "CU";
13262   void **dwo_file_slot;
13263   struct dwo_file *dwo_file;
13264   struct dwp_file *dwp_file;
13265
13266   /* First see if there's a DWP file.
13267      If we have a DWP file but didn't find the DWO inside it, don't
13268      look for the original DWO file.  It makes gdb behave differently
13269      depending on whether one is debugging in the build tree.  */
13270
13271   dwp_file = get_dwp_file ();
13272   if (dwp_file != NULL)
13273     {
13274       const struct dwp_hash_table *dwp_htab =
13275         is_debug_types ? dwp_file->tus : dwp_file->cus;
13276
13277       if (dwp_htab != NULL)
13278         {
13279           struct dwo_unit *dwo_cutu =
13280             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
13281                                     signature, is_debug_types);
13282
13283           if (dwo_cutu != NULL)
13284             {
13285               if (dwarf_read_debug)
13286                 {
13287                   fprintf_unfiltered (gdb_stdlog,
13288                                       "Virtual DWO %s %s found: @%s\n",
13289                                       kind, hex_string (signature),
13290                                       host_address_to_string (dwo_cutu));
13291                 }
13292               return dwo_cutu;
13293             }
13294         }
13295     }
13296   else
13297     {
13298       /* No DWP file, look for the DWO file.  */
13299
13300       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
13301       if (*dwo_file_slot == NULL)
13302         {
13303           /* Read in the file and build a table of the CUs/TUs it contains.  */
13304           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13305         }
13306       /* NOTE: This will be NULL if unable to open the file.  */
13307       dwo_file = (struct dwo_file *) *dwo_file_slot;
13308
13309       if (dwo_file != NULL)
13310         {
13311           struct dwo_unit *dwo_cutu = NULL;
13312
13313           if (is_debug_types && dwo_file->tus)
13314             {
13315               struct dwo_unit find_dwo_cutu;
13316
13317               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13318               find_dwo_cutu.signature = signature;
13319               dwo_cutu
13320                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13321             }
13322           else if (!is_debug_types && dwo_file->cus)
13323             {
13324               struct dwo_unit find_dwo_cutu;
13325
13326               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13327               find_dwo_cutu.signature = signature;
13328               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13329                                                        &find_dwo_cutu);
13330             }
13331
13332           if (dwo_cutu != NULL)
13333             {
13334               if (dwarf_read_debug)
13335                 {
13336                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13337                                       kind, dwo_name, hex_string (signature),
13338                                       host_address_to_string (dwo_cutu));
13339                 }
13340               return dwo_cutu;
13341             }
13342         }
13343     }
13344
13345   /* We didn't find it.  This could mean a dwo_id mismatch, or
13346      someone deleted the DWO/DWP file, or the search path isn't set up
13347      correctly to find the file.  */
13348
13349   if (dwarf_read_debug)
13350     {
13351       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13352                           kind, dwo_name, hex_string (signature));
13353     }
13354
13355   /* This is a warning and not a complaint because it can be caused by
13356      pilot error (e.g., user accidentally deleting the DWO).  */
13357   {
13358     /* Print the name of the DWP file if we looked there, helps the user
13359        better diagnose the problem.  */
13360     std::string dwp_text;
13361
13362     if (dwp_file != NULL)
13363       dwp_text = string_printf (" [in DWP file %s]",
13364                                 lbasename (dwp_file->name));
13365
13366     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13367                " [in module %s]"),
13368              kind, dwo_name, hex_string (signature),
13369              dwp_text.c_str (),
13370              this_unit->is_debug_types ? "TU" : "CU",
13371              to_underlying (this_unit->sect_off), objfile_name (objfile));
13372   }
13373   return NULL;
13374 }
13375
13376 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13377    See lookup_dwo_cutu_unit for details.  */
13378
13379 static struct dwo_unit *
13380 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13381                       const char *dwo_name, const char *comp_dir,
13382                       ULONGEST signature)
13383 {
13384   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13385 }
13386
13387 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13388    See lookup_dwo_cutu_unit for details.  */
13389
13390 static struct dwo_unit *
13391 lookup_dwo_type_unit (struct signatured_type *this_tu,
13392                       const char *dwo_name, const char *comp_dir)
13393 {
13394   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13395 }
13396
13397 /* Traversal function for queue_and_load_all_dwo_tus.  */
13398
13399 static int
13400 queue_and_load_dwo_tu (void **slot, void *info)
13401 {
13402   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13403   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13404   ULONGEST signature = dwo_unit->signature;
13405   struct signatured_type *sig_type =
13406     lookup_dwo_signatured_type (per_cu->cu, signature);
13407
13408   if (sig_type != NULL)
13409     {
13410       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13411
13412       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13413          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13414          while processing PER_CU.  */
13415       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13416         load_full_type_unit (sig_cu);
13417       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13418     }
13419
13420   return 1;
13421 }
13422
13423 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13424    The DWO may have the only definition of the type, though it may not be
13425    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13426    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13427
13428 static void
13429 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13430 {
13431   struct dwo_unit *dwo_unit;
13432   struct dwo_file *dwo_file;
13433
13434   gdb_assert (!per_cu->is_debug_types);
13435   gdb_assert (get_dwp_file () == NULL);
13436   gdb_assert (per_cu->cu != NULL);
13437
13438   dwo_unit = per_cu->cu->dwo_unit;
13439   gdb_assert (dwo_unit != NULL);
13440
13441   dwo_file = dwo_unit->dwo_file;
13442   if (dwo_file->tus != NULL)
13443     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13444 }
13445
13446 /* Free all resources associated with DWO_FILE.
13447    Close the DWO file and munmap the sections.
13448    All memory should be on the objfile obstack.  */
13449
13450 static void
13451 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13452 {
13453
13454   /* Note: dbfd is NULL for virtual DWO files.  */
13455   gdb_bfd_unref (dwo_file->dbfd);
13456
13457   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13458 }
13459
13460 /* Wrapper for free_dwo_file for use in cleanups.  */
13461
13462 static void
13463 free_dwo_file_cleanup (void *arg)
13464 {
13465   struct dwo_file *dwo_file = (struct dwo_file *) arg;
13466   struct objfile *objfile = dwarf2_per_objfile->objfile;
13467
13468   free_dwo_file (dwo_file, objfile);
13469 }
13470
13471 /* Traversal function for free_dwo_files.  */
13472
13473 static int
13474 free_dwo_file_from_slot (void **slot, void *info)
13475 {
13476   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13477   struct objfile *objfile = (struct objfile *) info;
13478
13479   free_dwo_file (dwo_file, objfile);
13480
13481   return 1;
13482 }
13483
13484 /* Free all resources associated with DWO_FILES.  */
13485
13486 static void
13487 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13488 {
13489   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13490 }
13491 \f
13492 /* Read in various DIEs.  */
13493
13494 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13495    Inherit only the children of the DW_AT_abstract_origin DIE not being
13496    already referenced by DW_AT_abstract_origin from the children of the
13497    current DIE.  */
13498
13499 static void
13500 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13501 {
13502   struct die_info *child_die;
13503   sect_offset *offsetp;
13504   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13505   struct die_info *origin_die;
13506   /* Iterator of the ORIGIN_DIE children.  */
13507   struct die_info *origin_child_die;
13508   struct attribute *attr;
13509   struct dwarf2_cu *origin_cu;
13510   struct pending **origin_previous_list_in_scope;
13511
13512   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13513   if (!attr)
13514     return;
13515
13516   /* Note that following die references may follow to a die in a
13517      different cu.  */
13518
13519   origin_cu = cu;
13520   origin_die = follow_die_ref (die, attr, &origin_cu);
13521
13522   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13523      symbols in.  */
13524   origin_previous_list_in_scope = origin_cu->list_in_scope;
13525   origin_cu->list_in_scope = cu->list_in_scope;
13526
13527   if (die->tag != origin_die->tag
13528       && !(die->tag == DW_TAG_inlined_subroutine
13529            && origin_die->tag == DW_TAG_subprogram))
13530     complaint (&symfile_complaints,
13531                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13532                to_underlying (die->sect_off),
13533                to_underlying (origin_die->sect_off));
13534
13535   std::vector<sect_offset> offsets;
13536
13537   for (child_die = die->child;
13538        child_die && child_die->tag;
13539        child_die = sibling_die (child_die))
13540     {
13541       struct die_info *child_origin_die;
13542       struct dwarf2_cu *child_origin_cu;
13543
13544       /* We are trying to process concrete instance entries:
13545          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13546          it's not relevant to our analysis here. i.e. detecting DIEs that are
13547          present in the abstract instance but not referenced in the concrete
13548          one.  */
13549       if (child_die->tag == DW_TAG_call_site
13550           || child_die->tag == DW_TAG_GNU_call_site)
13551         continue;
13552
13553       /* For each CHILD_DIE, find the corresponding child of
13554          ORIGIN_DIE.  If there is more than one layer of
13555          DW_AT_abstract_origin, follow them all; there shouldn't be,
13556          but GCC versions at least through 4.4 generate this (GCC PR
13557          40573).  */
13558       child_origin_die = child_die;
13559       child_origin_cu = cu;
13560       while (1)
13561         {
13562           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13563                               child_origin_cu);
13564           if (attr == NULL)
13565             break;
13566           child_origin_die = follow_die_ref (child_origin_die, attr,
13567                                              &child_origin_cu);
13568         }
13569
13570       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13571          counterpart may exist.  */
13572       if (child_origin_die != child_die)
13573         {
13574           if (child_die->tag != child_origin_die->tag
13575               && !(child_die->tag == DW_TAG_inlined_subroutine
13576                    && child_origin_die->tag == DW_TAG_subprogram))
13577             complaint (&symfile_complaints,
13578                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13579                          "different tags"),
13580                        to_underlying (child_die->sect_off),
13581                        to_underlying (child_origin_die->sect_off));
13582           if (child_origin_die->parent != origin_die)
13583             complaint (&symfile_complaints,
13584                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13585                          "different parents"),
13586                        to_underlying (child_die->sect_off),
13587                        to_underlying (child_origin_die->sect_off));
13588           else
13589             offsets.push_back (child_origin_die->sect_off);
13590         }
13591     }
13592   std::sort (offsets.begin (), offsets.end ());
13593   sect_offset *offsets_end = offsets.data () + offsets.size ();
13594   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13595     if (offsetp[-1] == *offsetp)
13596       complaint (&symfile_complaints,
13597                  _("Multiple children of DIE 0x%x refer "
13598                    "to DIE 0x%x as their abstract origin"),
13599                  to_underlying (die->sect_off), to_underlying (*offsetp));
13600
13601   offsetp = offsets.data ();
13602   origin_child_die = origin_die->child;
13603   while (origin_child_die && origin_child_die->tag)
13604     {
13605       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13606       while (offsetp < offsets_end
13607              && *offsetp < origin_child_die->sect_off)
13608         offsetp++;
13609       if (offsetp >= offsets_end
13610           || *offsetp > origin_child_die->sect_off)
13611         {
13612           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13613              Check whether we're already processing ORIGIN_CHILD_DIE.
13614              This can happen with mutually referenced abstract_origins.
13615              PR 16581.  */
13616           if (!origin_child_die->in_process)
13617             process_die (origin_child_die, origin_cu);
13618         }
13619       origin_child_die = sibling_die (origin_child_die);
13620     }
13621   origin_cu->list_in_scope = origin_previous_list_in_scope;
13622 }
13623
13624 static void
13625 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13626 {
13627   struct objfile *objfile = cu->objfile;
13628   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13629   struct context_stack *newobj;
13630   CORE_ADDR lowpc;
13631   CORE_ADDR highpc;
13632   struct die_info *child_die;
13633   struct attribute *attr, *call_line, *call_file;
13634   const char *name;
13635   CORE_ADDR baseaddr;
13636   struct block *block;
13637   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13638   std::vector<struct symbol *> template_args;
13639   struct template_symbol *templ_func = NULL;
13640
13641   if (inlined_func)
13642     {
13643       /* If we do not have call site information, we can't show the
13644          caller of this inlined function.  That's too confusing, so
13645          only use the scope for local variables.  */
13646       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13647       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13648       if (call_line == NULL || call_file == NULL)
13649         {
13650           read_lexical_block_scope (die, cu);
13651           return;
13652         }
13653     }
13654
13655   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13656
13657   name = dwarf2_name (die, cu);
13658
13659   /* Ignore functions with missing or empty names.  These are actually
13660      illegal according to the DWARF standard.  */
13661   if (name == NULL)
13662     {
13663       complaint (&symfile_complaints,
13664                  _("missing name for subprogram DIE at %d"),
13665                  to_underlying (die->sect_off));
13666       return;
13667     }
13668
13669   /* Ignore functions with missing or invalid low and high pc attributes.  */
13670   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13671       <= PC_BOUNDS_INVALID)
13672     {
13673       attr = dwarf2_attr (die, DW_AT_external, cu);
13674       if (!attr || !DW_UNSND (attr))
13675         complaint (&symfile_complaints,
13676                    _("cannot get low and high bounds "
13677                      "for subprogram DIE at %d"),
13678                    to_underlying (die->sect_off));
13679       return;
13680     }
13681
13682   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13683   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13684
13685   /* If we have any template arguments, then we must allocate a
13686      different sort of symbol.  */
13687   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13688     {
13689       if (child_die->tag == DW_TAG_template_type_param
13690           || child_die->tag == DW_TAG_template_value_param)
13691         {
13692           templ_func = allocate_template_symbol (objfile);
13693           templ_func->subclass = SYMBOL_TEMPLATE;
13694           break;
13695         }
13696     }
13697
13698   newobj = push_context (0, lowpc);
13699   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
13700                                (struct symbol *) templ_func);
13701
13702   /* If there is a location expression for DW_AT_frame_base, record
13703      it.  */
13704   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13705   if (attr)
13706     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13707
13708   /* If there is a location for the static link, record it.  */
13709   newobj->static_link = NULL;
13710   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13711   if (attr)
13712     {
13713       newobj->static_link
13714         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13715       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13716     }
13717
13718   cu->list_in_scope = &local_symbols;
13719
13720   if (die->child != NULL)
13721     {
13722       child_die = die->child;
13723       while (child_die && child_die->tag)
13724         {
13725           if (child_die->tag == DW_TAG_template_type_param
13726               || child_die->tag == DW_TAG_template_value_param)
13727             {
13728               struct symbol *arg = new_symbol (child_die, NULL, cu);
13729
13730               if (arg != NULL)
13731                 template_args.push_back (arg);
13732             }
13733           else
13734             process_die (child_die, cu);
13735           child_die = sibling_die (child_die);
13736         }
13737     }
13738
13739   inherit_abstract_dies (die, cu);
13740
13741   /* If we have a DW_AT_specification, we might need to import using
13742      directives from the context of the specification DIE.  See the
13743      comment in determine_prefix.  */
13744   if (cu->language == language_cplus
13745       && dwarf2_attr (die, DW_AT_specification, cu))
13746     {
13747       struct dwarf2_cu *spec_cu = cu;
13748       struct die_info *spec_die = die_specification (die, &spec_cu);
13749
13750       while (spec_die)
13751         {
13752           child_die = spec_die->child;
13753           while (child_die && child_die->tag)
13754             {
13755               if (child_die->tag == DW_TAG_imported_module)
13756                 process_die (child_die, spec_cu);
13757               child_die = sibling_die (child_die);
13758             }
13759
13760           /* In some cases, GCC generates specification DIEs that
13761              themselves contain DW_AT_specification attributes.  */
13762           spec_die = die_specification (spec_die, &spec_cu);
13763         }
13764     }
13765
13766   newobj = pop_context ();
13767   /* Make a block for the local symbols within.  */
13768   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13769                         newobj->static_link, lowpc, highpc);
13770
13771   /* For C++, set the block's scope.  */
13772   if ((cu->language == language_cplus
13773        || cu->language == language_fortran
13774        || cu->language == language_d
13775        || cu->language == language_rust)
13776       && cu->processing_has_namespace_info)
13777     block_set_scope (block, determine_prefix (die, cu),
13778                      &objfile->objfile_obstack);
13779
13780   /* If we have address ranges, record them.  */
13781   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13782
13783   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13784
13785   /* Attach template arguments to function.  */
13786   if (!template_args.empty ())
13787     {
13788       gdb_assert (templ_func != NULL);
13789
13790       templ_func->n_template_arguments = template_args.size ();
13791       templ_func->template_arguments
13792         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13793                      templ_func->n_template_arguments);
13794       memcpy (templ_func->template_arguments,
13795               template_args.data (),
13796               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13797     }
13798
13799   /* In C++, we can have functions nested inside functions (e.g., when
13800      a function declares a class that has methods).  This means that
13801      when we finish processing a function scope, we may need to go
13802      back to building a containing block's symbol lists.  */
13803   local_symbols = newobj->locals;
13804   local_using_directives = newobj->local_using_directives;
13805
13806   /* If we've finished processing a top-level function, subsequent
13807      symbols go in the file symbol list.  */
13808   if (outermost_context_p ())
13809     cu->list_in_scope = &file_symbols;
13810 }
13811
13812 /* Process all the DIES contained within a lexical block scope.  Start
13813    a new scope, process the dies, and then close the scope.  */
13814
13815 static void
13816 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13817 {
13818   struct objfile *objfile = cu->objfile;
13819   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13820   struct context_stack *newobj;
13821   CORE_ADDR lowpc, highpc;
13822   struct die_info *child_die;
13823   CORE_ADDR baseaddr;
13824
13825   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13826
13827   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13828   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13829      as multiple lexical blocks?  Handling children in a sane way would
13830      be nasty.  Might be easier to properly extend generic blocks to
13831      describe ranges.  */
13832   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13833     {
13834     case PC_BOUNDS_NOT_PRESENT:
13835       /* DW_TAG_lexical_block has no attributes, process its children as if
13836          there was no wrapping by that DW_TAG_lexical_block.
13837          GCC does no longer produces such DWARF since GCC r224161.  */
13838       for (child_die = die->child;
13839            child_die != NULL && child_die->tag;
13840            child_die = sibling_die (child_die))
13841         process_die (child_die, cu);
13842       return;
13843     case PC_BOUNDS_INVALID:
13844       return;
13845     }
13846   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13847   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13848
13849   push_context (0, lowpc);
13850   if (die->child != NULL)
13851     {
13852       child_die = die->child;
13853       while (child_die && child_die->tag)
13854         {
13855           process_die (child_die, cu);
13856           child_die = sibling_die (child_die);
13857         }
13858     }
13859   inherit_abstract_dies (die, cu);
13860   newobj = pop_context ();
13861
13862   if (local_symbols != NULL || local_using_directives != NULL)
13863     {
13864       struct block *block
13865         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13866                         newobj->start_addr, highpc);
13867
13868       /* Note that recording ranges after traversing children, as we
13869          do here, means that recording a parent's ranges entails
13870          walking across all its children's ranges as they appear in
13871          the address map, which is quadratic behavior.
13872
13873          It would be nicer to record the parent's ranges before
13874          traversing its children, simply overriding whatever you find
13875          there.  But since we don't even decide whether to create a
13876          block until after we've traversed its children, that's hard
13877          to do.  */
13878       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13879     }
13880   local_symbols = newobj->locals;
13881   local_using_directives = newobj->local_using_directives;
13882 }
13883
13884 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13885
13886 static void
13887 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13888 {
13889   struct objfile *objfile = cu->objfile;
13890   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13891   CORE_ADDR pc, baseaddr;
13892   struct attribute *attr;
13893   struct call_site *call_site, call_site_local;
13894   void **slot;
13895   int nparams;
13896   struct die_info *child_die;
13897
13898   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13899
13900   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13901   if (attr == NULL)
13902     {
13903       /* This was a pre-DWARF-5 GNU extension alias
13904          for DW_AT_call_return_pc.  */
13905       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13906     }
13907   if (!attr)
13908     {
13909       complaint (&symfile_complaints,
13910                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
13911                    "DIE 0x%x [in module %s]"),
13912                  to_underlying (die->sect_off), objfile_name (objfile));
13913       return;
13914     }
13915   pc = attr_value_as_address (attr) + baseaddr;
13916   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13917
13918   if (cu->call_site_htab == NULL)
13919     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13920                                                NULL, &objfile->objfile_obstack,
13921                                                hashtab_obstack_allocate, NULL);
13922   call_site_local.pc = pc;
13923   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13924   if (*slot != NULL)
13925     {
13926       complaint (&symfile_complaints,
13927                  _("Duplicate PC %s for DW_TAG_call_site "
13928                    "DIE 0x%x [in module %s]"),
13929                  paddress (gdbarch, pc), to_underlying (die->sect_off),
13930                  objfile_name (objfile));
13931       return;
13932     }
13933
13934   /* Count parameters at the caller.  */
13935
13936   nparams = 0;
13937   for (child_die = die->child; child_die && child_die->tag;
13938        child_die = sibling_die (child_die))
13939     {
13940       if (child_die->tag != DW_TAG_call_site_parameter
13941           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13942         {
13943           complaint (&symfile_complaints,
13944                      _("Tag %d is not DW_TAG_call_site_parameter in "
13945                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13946                      child_die->tag, to_underlying (child_die->sect_off),
13947                      objfile_name (objfile));
13948           continue;
13949         }
13950
13951       nparams++;
13952     }
13953
13954   call_site
13955     = ((struct call_site *)
13956        obstack_alloc (&objfile->objfile_obstack,
13957                       sizeof (*call_site)
13958                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13959   *slot = call_site;
13960   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13961   call_site->pc = pc;
13962
13963   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13964       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13965     {
13966       struct die_info *func_die;
13967
13968       /* Skip also over DW_TAG_inlined_subroutine.  */
13969       for (func_die = die->parent;
13970            func_die && func_die->tag != DW_TAG_subprogram
13971            && func_die->tag != DW_TAG_subroutine_type;
13972            func_die = func_die->parent);
13973
13974       /* DW_AT_call_all_calls is a superset
13975          of DW_AT_call_all_tail_calls.  */
13976       if (func_die
13977           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13978           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13979           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13980           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13981         {
13982           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13983              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13984              both the initial caller containing the real return address PC and
13985              the final callee containing the current PC of a chain of tail
13986              calls do not need to have the tail call list complete.  But any
13987              function candidate for a virtual tail call frame searched via
13988              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13989              determined unambiguously.  */
13990         }
13991       else
13992         {
13993           struct type *func_type = NULL;
13994
13995           if (func_die)
13996             func_type = get_die_type (func_die, cu);
13997           if (func_type != NULL)
13998             {
13999               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14000
14001               /* Enlist this call site to the function.  */
14002               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14003               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14004             }
14005           else
14006             complaint (&symfile_complaints,
14007                        _("Cannot find function owning DW_TAG_call_site "
14008                          "DIE 0x%x [in module %s]"),
14009                        to_underlying (die->sect_off), objfile_name (objfile));
14010         }
14011     }
14012
14013   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14014   if (attr == NULL)
14015     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14016   if (attr == NULL)
14017     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14018   if (attr == NULL)
14019     {
14020       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14021       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14022     }
14023   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14024   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14025     /* Keep NULL DWARF_BLOCK.  */;
14026   else if (attr_form_is_block (attr))
14027     {
14028       struct dwarf2_locexpr_baton *dlbaton;
14029
14030       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14031       dlbaton->data = DW_BLOCK (attr)->data;
14032       dlbaton->size = DW_BLOCK (attr)->size;
14033       dlbaton->per_cu = cu->per_cu;
14034
14035       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14036     }
14037   else if (attr_form_is_ref (attr))
14038     {
14039       struct dwarf2_cu *target_cu = cu;
14040       struct die_info *target_die;
14041
14042       target_die = follow_die_ref (die, attr, &target_cu);
14043       gdb_assert (target_cu->objfile == objfile);
14044       if (die_is_declaration (target_die, target_cu))
14045         {
14046           const char *target_physname;
14047
14048           /* Prefer the mangled name; otherwise compute the demangled one.  */
14049           target_physname = dw2_linkage_name (target_die, target_cu);
14050           if (target_physname == NULL)
14051             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14052           if (target_physname == NULL)
14053             complaint (&symfile_complaints,
14054                        _("DW_AT_call_target target DIE has invalid "
14055                          "physname, for referencing DIE 0x%x [in module %s]"),
14056                        to_underlying (die->sect_off), objfile_name (objfile));
14057           else
14058             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14059         }
14060       else
14061         {
14062           CORE_ADDR lowpc;
14063
14064           /* DW_AT_entry_pc should be preferred.  */
14065           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14066               <= PC_BOUNDS_INVALID)
14067             complaint (&symfile_complaints,
14068                        _("DW_AT_call_target target DIE has invalid "
14069                          "low pc, for referencing DIE 0x%x [in module %s]"),
14070                        to_underlying (die->sect_off), objfile_name (objfile));
14071           else
14072             {
14073               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14074               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14075             }
14076         }
14077     }
14078   else
14079     complaint (&symfile_complaints,
14080                _("DW_TAG_call_site DW_AT_call_target is neither "
14081                  "block nor reference, for DIE 0x%x [in module %s]"),
14082                to_underlying (die->sect_off), objfile_name (objfile));
14083
14084   call_site->per_cu = cu->per_cu;
14085
14086   for (child_die = die->child;
14087        child_die && child_die->tag;
14088        child_die = sibling_die (child_die))
14089     {
14090       struct call_site_parameter *parameter;
14091       struct attribute *loc, *origin;
14092
14093       if (child_die->tag != DW_TAG_call_site_parameter
14094           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14095         {
14096           /* Already printed the complaint above.  */
14097           continue;
14098         }
14099
14100       gdb_assert (call_site->parameter_count < nparams);
14101       parameter = &call_site->parameter[call_site->parameter_count];
14102
14103       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14104          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14105          register is contained in DW_AT_call_value.  */
14106
14107       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14108       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14109       if (origin == NULL)
14110         {
14111           /* This was a pre-DWARF-5 GNU extension alias
14112              for DW_AT_call_parameter.  */
14113           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14114         }
14115       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14116         {
14117           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14118
14119           sect_offset sect_off
14120             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14121           if (!offset_in_cu_p (&cu->header, sect_off))
14122             {
14123               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14124                  binding can be done only inside one CU.  Such referenced DIE
14125                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14126               complaint (&symfile_complaints,
14127                          _("DW_AT_call_parameter offset is not in CU for "
14128                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14129                          to_underlying (child_die->sect_off),
14130                          objfile_name (objfile));
14131               continue;
14132             }
14133           parameter->u.param_cu_off
14134             = (cu_offset) (sect_off - cu->header.sect_off);
14135         }
14136       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14137         {
14138           complaint (&symfile_complaints,
14139                      _("No DW_FORM_block* DW_AT_location for "
14140                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14141                      to_underlying (child_die->sect_off), objfile_name (objfile));
14142           continue;
14143         }
14144       else
14145         {
14146           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14147             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14148           if (parameter->u.dwarf_reg != -1)
14149             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14150           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14151                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14152                                              &parameter->u.fb_offset))
14153             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14154           else
14155             {
14156               complaint (&symfile_complaints,
14157                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14158                            "for DW_FORM_block* DW_AT_location is supported for "
14159                            "DW_TAG_call_site child DIE 0x%x "
14160                            "[in module %s]"),
14161                          to_underlying (child_die->sect_off),
14162                          objfile_name (objfile));
14163               continue;
14164             }
14165         }
14166
14167       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14168       if (attr == NULL)
14169         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14170       if (!attr_form_is_block (attr))
14171         {
14172           complaint (&symfile_complaints,
14173                      _("No DW_FORM_block* DW_AT_call_value for "
14174                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14175                      to_underlying (child_die->sect_off),
14176                      objfile_name (objfile));
14177           continue;
14178         }
14179       parameter->value = DW_BLOCK (attr)->data;
14180       parameter->value_size = DW_BLOCK (attr)->size;
14181
14182       /* Parameters are not pre-cleared by memset above.  */
14183       parameter->data_value = NULL;
14184       parameter->data_value_size = 0;
14185       call_site->parameter_count++;
14186
14187       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14188       if (attr == NULL)
14189         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14190       if (attr)
14191         {
14192           if (!attr_form_is_block (attr))
14193             complaint (&symfile_complaints,
14194                        _("No DW_FORM_block* DW_AT_call_data_value for "
14195                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14196                        to_underlying (child_die->sect_off),
14197                        objfile_name (objfile));
14198           else
14199             {
14200               parameter->data_value = DW_BLOCK (attr)->data;
14201               parameter->data_value_size = DW_BLOCK (attr)->size;
14202             }
14203         }
14204     }
14205 }
14206
14207 /* Helper function for read_variable.  If DIE represents a virtual
14208    table, then return the type of the concrete object that is
14209    associated with the virtual table.  Otherwise, return NULL.  */
14210
14211 static struct type *
14212 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14213 {
14214   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14215   if (attr == NULL)
14216     return NULL;
14217
14218   /* Find the type DIE.  */
14219   struct die_info *type_die = NULL;
14220   struct dwarf2_cu *type_cu = cu;
14221
14222   if (attr_form_is_ref (attr))
14223     type_die = follow_die_ref (die, attr, &type_cu);
14224   if (type_die == NULL)
14225     return NULL;
14226
14227   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14228     return NULL;
14229   return die_containing_type (type_die, type_cu);
14230 }
14231
14232 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14233
14234 static void
14235 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14236 {
14237   struct rust_vtable_symbol *storage = NULL;
14238
14239   if (cu->language == language_rust)
14240     {
14241       struct type *containing_type = rust_containing_type (die, cu);
14242
14243       if (containing_type != NULL)
14244         {
14245           struct objfile *objfile = cu->objfile;
14246
14247           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14248                                     struct rust_vtable_symbol);
14249           initialize_objfile_symbol (storage);
14250           storage->concrete_type = containing_type;
14251           storage->subclass = SYMBOL_RUST_VTABLE;
14252         }
14253     }
14254
14255   new_symbol_full (die, NULL, cu, storage);
14256 }
14257
14258 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14259    reading .debug_rnglists.
14260    Callback's type should be:
14261     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14262    Return true if the attributes are present and valid, otherwise,
14263    return false.  */
14264
14265 template <typename Callback>
14266 static bool
14267 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14268                          Callback &&callback)
14269 {
14270   struct objfile *objfile = cu->objfile;
14271   bfd *obfd = objfile->obfd;
14272   /* Base address selection entry.  */
14273   CORE_ADDR base;
14274   int found_base;
14275   const gdb_byte *buffer;
14276   CORE_ADDR baseaddr;
14277   bool overflow = false;
14278
14279   found_base = cu->base_known;
14280   base = cu->base_address;
14281
14282   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14283   if (offset >= dwarf2_per_objfile->rnglists.size)
14284     {
14285       complaint (&symfile_complaints,
14286                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14287                  offset);
14288       return false;
14289     }
14290   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14291
14292   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14293
14294   while (1)
14295     {
14296       /* Initialize it due to a false compiler warning.  */
14297       CORE_ADDR range_beginning = 0, range_end = 0;
14298       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14299                                  + dwarf2_per_objfile->rnglists.size);
14300       unsigned int bytes_read;
14301
14302       if (buffer == buf_end)
14303         {
14304           overflow = true;
14305           break;
14306         }
14307       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14308       switch (rlet)
14309         {
14310         case DW_RLE_end_of_list:
14311           break;
14312         case DW_RLE_base_address:
14313           if (buffer + cu->header.addr_size > buf_end)
14314             {
14315               overflow = true;
14316               break;
14317             }
14318           base = read_address (obfd, buffer, cu, &bytes_read);
14319           found_base = 1;
14320           buffer += bytes_read;
14321           break;
14322         case DW_RLE_start_length:
14323           if (buffer + cu->header.addr_size > buf_end)
14324             {
14325               overflow = true;
14326               break;
14327             }
14328           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14329           buffer += bytes_read;
14330           range_end = (range_beginning
14331                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14332           buffer += bytes_read;
14333           if (buffer > buf_end)
14334             {
14335               overflow = true;
14336               break;
14337             }
14338           break;
14339         case DW_RLE_offset_pair:
14340           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14341           buffer += bytes_read;
14342           if (buffer > buf_end)
14343             {
14344               overflow = true;
14345               break;
14346             }
14347           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14348           buffer += bytes_read;
14349           if (buffer > buf_end)
14350             {
14351               overflow = true;
14352               break;
14353             }
14354           break;
14355         case DW_RLE_start_end:
14356           if (buffer + 2 * cu->header.addr_size > buf_end)
14357             {
14358               overflow = true;
14359               break;
14360             }
14361           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14362           buffer += bytes_read;
14363           range_end = read_address (obfd, buffer, cu, &bytes_read);
14364           buffer += bytes_read;
14365           break;
14366         default:
14367           complaint (&symfile_complaints,
14368                      _("Invalid .debug_rnglists data (no base address)"));
14369           return false;
14370         }
14371       if (rlet == DW_RLE_end_of_list || overflow)
14372         break;
14373       if (rlet == DW_RLE_base_address)
14374         continue;
14375
14376       if (!found_base)
14377         {
14378           /* We have no valid base address for the ranges
14379              data.  */
14380           complaint (&symfile_complaints,
14381                      _("Invalid .debug_rnglists data (no base address)"));
14382           return false;
14383         }
14384
14385       if (range_beginning > range_end)
14386         {
14387           /* Inverted range entries are invalid.  */
14388           complaint (&symfile_complaints,
14389                      _("Invalid .debug_rnglists data (inverted range)"));
14390           return false;
14391         }
14392
14393       /* Empty range entries have no effect.  */
14394       if (range_beginning == range_end)
14395         continue;
14396
14397       range_beginning += base;
14398       range_end += base;
14399
14400       /* A not-uncommon case of bad debug info.
14401          Don't pollute the addrmap with bad data.  */
14402       if (range_beginning + baseaddr == 0
14403           && !dwarf2_per_objfile->has_section_at_zero)
14404         {
14405           complaint (&symfile_complaints,
14406                      _(".debug_rnglists entry has start address of zero"
14407                        " [in module %s]"), objfile_name (objfile));
14408           continue;
14409         }
14410
14411       callback (range_beginning, range_end);
14412     }
14413
14414   if (overflow)
14415     {
14416       complaint (&symfile_complaints,
14417                  _("Offset %d is not terminated "
14418                    "for DW_AT_ranges attribute"),
14419                  offset);
14420       return false;
14421     }
14422
14423   return true;
14424 }
14425
14426 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14427    Callback's type should be:
14428     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14429    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14430
14431 template <typename Callback>
14432 static int
14433 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14434                        Callback &&callback)
14435 {
14436   struct objfile *objfile = cu->objfile;
14437   struct comp_unit_head *cu_header = &cu->header;
14438   bfd *obfd = objfile->obfd;
14439   unsigned int addr_size = cu_header->addr_size;
14440   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14441   /* Base address selection entry.  */
14442   CORE_ADDR base;
14443   int found_base;
14444   unsigned int dummy;
14445   const gdb_byte *buffer;
14446   CORE_ADDR baseaddr;
14447
14448   if (cu_header->version >= 5)
14449     return dwarf2_rnglists_process (offset, cu, callback);
14450
14451   found_base = cu->base_known;
14452   base = cu->base_address;
14453
14454   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14455   if (offset >= dwarf2_per_objfile->ranges.size)
14456     {
14457       complaint (&symfile_complaints,
14458                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14459                  offset);
14460       return 0;
14461     }
14462   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14463
14464   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14465
14466   while (1)
14467     {
14468       CORE_ADDR range_beginning, range_end;
14469
14470       range_beginning = read_address (obfd, buffer, cu, &dummy);
14471       buffer += addr_size;
14472       range_end = read_address (obfd, buffer, cu, &dummy);
14473       buffer += addr_size;
14474       offset += 2 * addr_size;
14475
14476       /* An end of list marker is a pair of zero addresses.  */
14477       if (range_beginning == 0 && range_end == 0)
14478         /* Found the end of list entry.  */
14479         break;
14480
14481       /* Each base address selection entry is a pair of 2 values.
14482          The first is the largest possible address, the second is
14483          the base address.  Check for a base address here.  */
14484       if ((range_beginning & mask) == mask)
14485         {
14486           /* If we found the largest possible address, then we already
14487              have the base address in range_end.  */
14488           base = range_end;
14489           found_base = 1;
14490           continue;
14491         }
14492
14493       if (!found_base)
14494         {
14495           /* We have no valid base address for the ranges
14496              data.  */
14497           complaint (&symfile_complaints,
14498                      _("Invalid .debug_ranges data (no base address)"));
14499           return 0;
14500         }
14501
14502       if (range_beginning > range_end)
14503         {
14504           /* Inverted range entries are invalid.  */
14505           complaint (&symfile_complaints,
14506                      _("Invalid .debug_ranges data (inverted range)"));
14507           return 0;
14508         }
14509
14510       /* Empty range entries have no effect.  */
14511       if (range_beginning == range_end)
14512         continue;
14513
14514       range_beginning += base;
14515       range_end += base;
14516
14517       /* A not-uncommon case of bad debug info.
14518          Don't pollute the addrmap with bad data.  */
14519       if (range_beginning + baseaddr == 0
14520           && !dwarf2_per_objfile->has_section_at_zero)
14521         {
14522           complaint (&symfile_complaints,
14523                      _(".debug_ranges entry has start address of zero"
14524                        " [in module %s]"), objfile_name (objfile));
14525           continue;
14526         }
14527
14528       callback (range_beginning, range_end);
14529     }
14530
14531   return 1;
14532 }
14533
14534 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14535    Return 1 if the attributes are present and valid, otherwise, return 0.
14536    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14537
14538 static int
14539 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14540                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14541                     struct partial_symtab *ranges_pst)
14542 {
14543   struct objfile *objfile = cu->objfile;
14544   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14545   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14546                                        SECT_OFF_TEXT (objfile));
14547   int low_set = 0;
14548   CORE_ADDR low = 0;
14549   CORE_ADDR high = 0;
14550   int retval;
14551
14552   retval = dwarf2_ranges_process (offset, cu,
14553     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14554     {
14555       if (ranges_pst != NULL)
14556         {
14557           CORE_ADDR lowpc;
14558           CORE_ADDR highpc;
14559
14560           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14561                                               range_beginning + baseaddr);
14562           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14563                                                range_end + baseaddr);
14564           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14565                              ranges_pst);
14566         }
14567
14568       /* FIXME: This is recording everything as a low-high
14569          segment of consecutive addresses.  We should have a
14570          data structure for discontiguous block ranges
14571          instead.  */
14572       if (! low_set)
14573         {
14574           low = range_beginning;
14575           high = range_end;
14576           low_set = 1;
14577         }
14578       else
14579         {
14580           if (range_beginning < low)
14581             low = range_beginning;
14582           if (range_end > high)
14583             high = range_end;
14584         }
14585     });
14586   if (!retval)
14587     return 0;
14588
14589   if (! low_set)
14590     /* If the first entry is an end-of-list marker, the range
14591        describes an empty scope, i.e. no instructions.  */
14592     return 0;
14593
14594   if (low_return)
14595     *low_return = low;
14596   if (high_return)
14597     *high_return = high;
14598   return 1;
14599 }
14600
14601 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14602    definition for the return value.  *LOWPC and *HIGHPC are set iff
14603    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14604
14605 static enum pc_bounds_kind
14606 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14607                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14608                       struct partial_symtab *pst)
14609 {
14610   struct attribute *attr;
14611   struct attribute *attr_high;
14612   CORE_ADDR low = 0;
14613   CORE_ADDR high = 0;
14614   enum pc_bounds_kind ret;
14615
14616   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14617   if (attr_high)
14618     {
14619       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14620       if (attr)
14621         {
14622           low = attr_value_as_address (attr);
14623           high = attr_value_as_address (attr_high);
14624           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14625             high += low;
14626         }
14627       else
14628         /* Found high w/o low attribute.  */
14629         return PC_BOUNDS_INVALID;
14630
14631       /* Found consecutive range of addresses.  */
14632       ret = PC_BOUNDS_HIGH_LOW;
14633     }
14634   else
14635     {
14636       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14637       if (attr != NULL)
14638         {
14639           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14640              We take advantage of the fact that DW_AT_ranges does not appear
14641              in DW_TAG_compile_unit of DWO files.  */
14642           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14643           unsigned int ranges_offset = (DW_UNSND (attr)
14644                                         + (need_ranges_base
14645                                            ? cu->ranges_base
14646                                            : 0));
14647
14648           /* Value of the DW_AT_ranges attribute is the offset in the
14649              .debug_ranges section.  */
14650           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14651             return PC_BOUNDS_INVALID;
14652           /* Found discontinuous range of addresses.  */
14653           ret = PC_BOUNDS_RANGES;
14654         }
14655       else
14656         return PC_BOUNDS_NOT_PRESENT;
14657     }
14658
14659   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14660   if (high <= low)
14661     return PC_BOUNDS_INVALID;
14662
14663   /* When using the GNU linker, .gnu.linkonce. sections are used to
14664      eliminate duplicate copies of functions and vtables and such.
14665      The linker will arbitrarily choose one and discard the others.
14666      The AT_*_pc values for such functions refer to local labels in
14667      these sections.  If the section from that file was discarded, the
14668      labels are not in the output, so the relocs get a value of 0.
14669      If this is a discarded function, mark the pc bounds as invalid,
14670      so that GDB will ignore it.  */
14671   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14672     return PC_BOUNDS_INVALID;
14673
14674   *lowpc = low;
14675   if (highpc)
14676     *highpc = high;
14677   return ret;
14678 }
14679
14680 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14681    its low and high PC addresses.  Do nothing if these addresses could not
14682    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14683    and HIGHPC to the high address if greater than HIGHPC.  */
14684
14685 static void
14686 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14687                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14688                                  struct dwarf2_cu *cu)
14689 {
14690   CORE_ADDR low, high;
14691   struct die_info *child = die->child;
14692
14693   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14694     {
14695       *lowpc = std::min (*lowpc, low);
14696       *highpc = std::max (*highpc, high);
14697     }
14698
14699   /* If the language does not allow nested subprograms (either inside
14700      subprograms or lexical blocks), we're done.  */
14701   if (cu->language != language_ada)
14702     return;
14703
14704   /* Check all the children of the given DIE.  If it contains nested
14705      subprograms, then check their pc bounds.  Likewise, we need to
14706      check lexical blocks as well, as they may also contain subprogram
14707      definitions.  */
14708   while (child && child->tag)
14709     {
14710       if (child->tag == DW_TAG_subprogram
14711           || child->tag == DW_TAG_lexical_block)
14712         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14713       child = sibling_die (child);
14714     }
14715 }
14716
14717 /* Get the low and high pc's represented by the scope DIE, and store
14718    them in *LOWPC and *HIGHPC.  If the correct values can't be
14719    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14720
14721 static void
14722 get_scope_pc_bounds (struct die_info *die,
14723                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14724                      struct dwarf2_cu *cu)
14725 {
14726   CORE_ADDR best_low = (CORE_ADDR) -1;
14727   CORE_ADDR best_high = (CORE_ADDR) 0;
14728   CORE_ADDR current_low, current_high;
14729
14730   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14731       >= PC_BOUNDS_RANGES)
14732     {
14733       best_low = current_low;
14734       best_high = current_high;
14735     }
14736   else
14737     {
14738       struct die_info *child = die->child;
14739
14740       while (child && child->tag)
14741         {
14742           switch (child->tag) {
14743           case DW_TAG_subprogram:
14744             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14745             break;
14746           case DW_TAG_namespace:
14747           case DW_TAG_module:
14748             /* FIXME: carlton/2004-01-16: Should we do this for
14749                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14750                that current GCC's always emit the DIEs corresponding
14751                to definitions of methods of classes as children of a
14752                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14753                the DIEs giving the declarations, which could be
14754                anywhere).  But I don't see any reason why the
14755                standards says that they have to be there.  */
14756             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14757
14758             if (current_low != ((CORE_ADDR) -1))
14759               {
14760                 best_low = std::min (best_low, current_low);
14761                 best_high = std::max (best_high, current_high);
14762               }
14763             break;
14764           default:
14765             /* Ignore.  */
14766             break;
14767           }
14768
14769           child = sibling_die (child);
14770         }
14771     }
14772
14773   *lowpc = best_low;
14774   *highpc = best_high;
14775 }
14776
14777 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14778    in DIE.  */
14779
14780 static void
14781 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14782                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14783 {
14784   struct objfile *objfile = cu->objfile;
14785   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14786   struct attribute *attr;
14787   struct attribute *attr_high;
14788
14789   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14790   if (attr_high)
14791     {
14792       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14793       if (attr)
14794         {
14795           CORE_ADDR low = attr_value_as_address (attr);
14796           CORE_ADDR high = attr_value_as_address (attr_high);
14797
14798           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14799             high += low;
14800
14801           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14802           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14803           record_block_range (block, low, high - 1);
14804         }
14805     }
14806
14807   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14808   if (attr)
14809     {
14810       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14811          We take advantage of the fact that DW_AT_ranges does not appear
14812          in DW_TAG_compile_unit of DWO files.  */
14813       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14814
14815       /* The value of the DW_AT_ranges attribute is the offset of the
14816          address range list in the .debug_ranges section.  */
14817       unsigned long offset = (DW_UNSND (attr)
14818                               + (need_ranges_base ? cu->ranges_base : 0));
14819       const gdb_byte *buffer;
14820
14821       /* For some target architectures, but not others, the
14822          read_address function sign-extends the addresses it returns.
14823          To recognize base address selection entries, we need a
14824          mask.  */
14825       unsigned int addr_size = cu->header.addr_size;
14826       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14827
14828       /* The base address, to which the next pair is relative.  Note
14829          that this 'base' is a DWARF concept: most entries in a range
14830          list are relative, to reduce the number of relocs against the
14831          debugging information.  This is separate from this function's
14832          'baseaddr' argument, which GDB uses to relocate debugging
14833          information from a shared library based on the address at
14834          which the library was loaded.  */
14835       CORE_ADDR base = cu->base_address;
14836       int base_known = cu->base_known;
14837
14838       dwarf2_ranges_process (offset, cu,
14839         [&] (CORE_ADDR start, CORE_ADDR end)
14840         {
14841           start += baseaddr;
14842           end += baseaddr;
14843           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14844           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14845           record_block_range (block, start, end - 1);
14846         });
14847     }
14848 }
14849
14850 /* Check whether the producer field indicates either of GCC < 4.6, or the
14851    Intel C/C++ compiler, and cache the result in CU.  */
14852
14853 static void
14854 check_producer (struct dwarf2_cu *cu)
14855 {
14856   int major, minor;
14857
14858   if (cu->producer == NULL)
14859     {
14860       /* For unknown compilers expect their behavior is DWARF version
14861          compliant.
14862
14863          GCC started to support .debug_types sections by -gdwarf-4 since
14864          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14865          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14866          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14867          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14868     }
14869   else if (producer_is_gcc (cu->producer, &major, &minor))
14870     {
14871       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14872       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14873     }
14874   else if (producer_is_icc (cu->producer, &major, &minor))
14875     cu->producer_is_icc_lt_14 = major < 14;
14876   else
14877     {
14878       /* For other non-GCC compilers, expect their behavior is DWARF version
14879          compliant.  */
14880     }
14881
14882   cu->checked_producer = 1;
14883 }
14884
14885 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14886    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14887    during 4.6.0 experimental.  */
14888
14889 static int
14890 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14891 {
14892   if (!cu->checked_producer)
14893     check_producer (cu);
14894
14895   return cu->producer_is_gxx_lt_4_6;
14896 }
14897
14898 /* Return the default accessibility type if it is not overriden by
14899    DW_AT_accessibility.  */
14900
14901 static enum dwarf_access_attribute
14902 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14903 {
14904   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14905     {
14906       /* The default DWARF 2 accessibility for members is public, the default
14907          accessibility for inheritance is private.  */
14908
14909       if (die->tag != DW_TAG_inheritance)
14910         return DW_ACCESS_public;
14911       else
14912         return DW_ACCESS_private;
14913     }
14914   else
14915     {
14916       /* DWARF 3+ defines the default accessibility a different way.  The same
14917          rules apply now for DW_TAG_inheritance as for the members and it only
14918          depends on the container kind.  */
14919
14920       if (die->parent->tag == DW_TAG_class_type)
14921         return DW_ACCESS_private;
14922       else
14923         return DW_ACCESS_public;
14924     }
14925 }
14926
14927 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14928    offset.  If the attribute was not found return 0, otherwise return
14929    1.  If it was found but could not properly be handled, set *OFFSET
14930    to 0.  */
14931
14932 static int
14933 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14934                              LONGEST *offset)
14935 {
14936   struct attribute *attr;
14937
14938   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14939   if (attr != NULL)
14940     {
14941       *offset = 0;
14942
14943       /* Note that we do not check for a section offset first here.
14944          This is because DW_AT_data_member_location is new in DWARF 4,
14945          so if we see it, we can assume that a constant form is really
14946          a constant and not a section offset.  */
14947       if (attr_form_is_constant (attr))
14948         *offset = dwarf2_get_attr_constant_value (attr, 0);
14949       else if (attr_form_is_section_offset (attr))
14950         dwarf2_complex_location_expr_complaint ();
14951       else if (attr_form_is_block (attr))
14952         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14953       else
14954         dwarf2_complex_location_expr_complaint ();
14955
14956       return 1;
14957     }
14958
14959   return 0;
14960 }
14961
14962 /* Add an aggregate field to the field list.  */
14963
14964 static void
14965 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14966                   struct dwarf2_cu *cu)
14967 {
14968   struct objfile *objfile = cu->objfile;
14969   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14970   struct nextfield *new_field;
14971   struct attribute *attr;
14972   struct field *fp;
14973   const char *fieldname = "";
14974
14975   /* Allocate a new field list entry and link it in.  */
14976   new_field = XNEW (struct nextfield);
14977   make_cleanup (xfree, new_field);
14978   memset (new_field, 0, sizeof (struct nextfield));
14979
14980   if (die->tag == DW_TAG_inheritance)
14981     {
14982       new_field->next = fip->baseclasses;
14983       fip->baseclasses = new_field;
14984     }
14985   else
14986     {
14987       new_field->next = fip->fields;
14988       fip->fields = new_field;
14989     }
14990   fip->nfields++;
14991
14992   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14993   if (attr)
14994     new_field->accessibility = DW_UNSND (attr);
14995   else
14996     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14997   if (new_field->accessibility != DW_ACCESS_public)
14998     fip->non_public_fields = 1;
14999
15000   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15001   if (attr)
15002     new_field->virtuality = DW_UNSND (attr);
15003   else
15004     new_field->virtuality = DW_VIRTUALITY_none;
15005
15006   fp = &new_field->field;
15007
15008   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15009     {
15010       LONGEST offset;
15011
15012       /* Data member other than a C++ static data member.  */
15013
15014       /* Get type of field.  */
15015       fp->type = die_type (die, cu);
15016
15017       SET_FIELD_BITPOS (*fp, 0);
15018
15019       /* Get bit size of field (zero if none).  */
15020       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15021       if (attr)
15022         {
15023           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15024         }
15025       else
15026         {
15027           FIELD_BITSIZE (*fp) = 0;
15028         }
15029
15030       /* Get bit offset of field.  */
15031       if (handle_data_member_location (die, cu, &offset))
15032         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15033       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15034       if (attr)
15035         {
15036           if (gdbarch_bits_big_endian (gdbarch))
15037             {
15038               /* For big endian bits, the DW_AT_bit_offset gives the
15039                  additional bit offset from the MSB of the containing
15040                  anonymous object to the MSB of the field.  We don't
15041                  have to do anything special since we don't need to
15042                  know the size of the anonymous object.  */
15043               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15044             }
15045           else
15046             {
15047               /* For little endian bits, compute the bit offset to the
15048                  MSB of the anonymous object, subtract off the number of
15049                  bits from the MSB of the field to the MSB of the
15050                  object, and then subtract off the number of bits of
15051                  the field itself.  The result is the bit offset of
15052                  the LSB of the field.  */
15053               int anonymous_size;
15054               int bit_offset = DW_UNSND (attr);
15055
15056               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15057               if (attr)
15058                 {
15059                   /* The size of the anonymous object containing
15060                      the bit field is explicit, so use the
15061                      indicated size (in bytes).  */
15062                   anonymous_size = DW_UNSND (attr);
15063                 }
15064               else
15065                 {
15066                   /* The size of the anonymous object containing
15067                      the bit field must be inferred from the type
15068                      attribute of the data member containing the
15069                      bit field.  */
15070                   anonymous_size = TYPE_LENGTH (fp->type);
15071                 }
15072               SET_FIELD_BITPOS (*fp,
15073                                 (FIELD_BITPOS (*fp)
15074                                  + anonymous_size * bits_per_byte
15075                                  - bit_offset - FIELD_BITSIZE (*fp)));
15076             }
15077         }
15078       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15079       if (attr != NULL)
15080         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15081                                 + dwarf2_get_attr_constant_value (attr, 0)));
15082
15083       /* Get name of field.  */
15084       fieldname = dwarf2_name (die, cu);
15085       if (fieldname == NULL)
15086         fieldname = "";
15087
15088       /* The name is already allocated along with this objfile, so we don't
15089          need to duplicate it for the type.  */
15090       fp->name = fieldname;
15091
15092       /* Change accessibility for artificial fields (e.g. virtual table
15093          pointer or virtual base class pointer) to private.  */
15094       if (dwarf2_attr (die, DW_AT_artificial, cu))
15095         {
15096           FIELD_ARTIFICIAL (*fp) = 1;
15097           new_field->accessibility = DW_ACCESS_private;
15098           fip->non_public_fields = 1;
15099         }
15100     }
15101   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15102     {
15103       /* C++ static member.  */
15104
15105       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15106          is a declaration, but all versions of G++ as of this writing
15107          (so through at least 3.2.1) incorrectly generate
15108          DW_TAG_variable tags.  */
15109
15110       const char *physname;
15111
15112       /* Get name of field.  */
15113       fieldname = dwarf2_name (die, cu);
15114       if (fieldname == NULL)
15115         return;
15116
15117       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15118       if (attr
15119           /* Only create a symbol if this is an external value.
15120              new_symbol checks this and puts the value in the global symbol
15121              table, which we want.  If it is not external, new_symbol
15122              will try to put the value in cu->list_in_scope which is wrong.  */
15123           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15124         {
15125           /* A static const member, not much different than an enum as far as
15126              we're concerned, except that we can support more types.  */
15127           new_symbol (die, NULL, cu);
15128         }
15129
15130       /* Get physical name.  */
15131       physname = dwarf2_physname (fieldname, die, cu);
15132
15133       /* The name is already allocated along with this objfile, so we don't
15134          need to duplicate it for the type.  */
15135       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15136       FIELD_TYPE (*fp) = die_type (die, cu);
15137       FIELD_NAME (*fp) = fieldname;
15138     }
15139   else if (die->tag == DW_TAG_inheritance)
15140     {
15141       LONGEST offset;
15142
15143       /* C++ base class field.  */
15144       if (handle_data_member_location (die, cu, &offset))
15145         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15146       FIELD_BITSIZE (*fp) = 0;
15147       FIELD_TYPE (*fp) = die_type (die, cu);
15148       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15149       fip->nbaseclasses++;
15150     }
15151 }
15152
15153 /* Can the type given by DIE define another type?  */
15154
15155 static bool
15156 type_can_define_types (const struct die_info *die)
15157 {
15158   switch (die->tag)
15159     {
15160     case DW_TAG_typedef:
15161     case DW_TAG_class_type:
15162     case DW_TAG_structure_type:
15163     case DW_TAG_union_type:
15164     case DW_TAG_enumeration_type:
15165       return true;
15166
15167     default:
15168       return false;
15169     }
15170 }
15171
15172 /* Add a type definition defined in the scope of the FIP's class.  */
15173
15174 static void
15175 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15176                       struct dwarf2_cu *cu)
15177 {
15178   struct decl_field_list *new_field;
15179   struct decl_field *fp;
15180
15181   /* Allocate a new field list entry and link it in.  */
15182   new_field = XCNEW (struct decl_field_list);
15183   make_cleanup (xfree, new_field);
15184
15185   gdb_assert (type_can_define_types (die));
15186
15187   fp = &new_field->field;
15188
15189   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15190   fp->name = dwarf2_name (die, cu);
15191   fp->type = read_type_die (die, cu);
15192
15193   /* Save accessibility.  */
15194   enum dwarf_access_attribute accessibility;
15195   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15196   if (attr != NULL)
15197     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15198   else
15199     accessibility = dwarf2_default_access_attribute (die, cu);
15200   switch (accessibility)
15201     {
15202     case DW_ACCESS_public:
15203       /* The assumed value if neither private nor protected.  */
15204       break;
15205     case DW_ACCESS_private:
15206       fp->is_private = 1;
15207       break;
15208     case DW_ACCESS_protected:
15209       fp->is_protected = 1;
15210       break;
15211     default:
15212       complaint (&symfile_complaints,
15213                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15214     }
15215
15216   if (die->tag == DW_TAG_typedef)
15217     {
15218       new_field->next = fip->typedef_field_list;
15219       fip->typedef_field_list = new_field;
15220       fip->typedef_field_list_count++;
15221     }
15222   else
15223     {
15224       new_field->next = fip->nested_types_list;
15225       fip->nested_types_list = new_field;
15226       fip->nested_types_list_count++;
15227     }
15228 }
15229
15230 /* Create the vector of fields, and attach it to the type.  */
15231
15232 static void
15233 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15234                               struct dwarf2_cu *cu)
15235 {
15236   int nfields = fip->nfields;
15237
15238   /* Record the field count, allocate space for the array of fields,
15239      and create blank accessibility bitfields if necessary.  */
15240   TYPE_NFIELDS (type) = nfields;
15241   TYPE_FIELDS (type) = (struct field *)
15242     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15243   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15244
15245   if (fip->non_public_fields && cu->language != language_ada)
15246     {
15247       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15248
15249       TYPE_FIELD_PRIVATE_BITS (type) =
15250         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15251       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15252
15253       TYPE_FIELD_PROTECTED_BITS (type) =
15254         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15255       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15256
15257       TYPE_FIELD_IGNORE_BITS (type) =
15258         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15259       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15260     }
15261
15262   /* If the type has baseclasses, allocate and clear a bit vector for
15263      TYPE_FIELD_VIRTUAL_BITS.  */
15264   if (fip->nbaseclasses && cu->language != language_ada)
15265     {
15266       int num_bytes = B_BYTES (fip->nbaseclasses);
15267       unsigned char *pointer;
15268
15269       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15270       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15271       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15272       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15273       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15274     }
15275
15276   /* Copy the saved-up fields into the field vector.  Start from the head of
15277      the list, adding to the tail of the field array, so that they end up in
15278      the same order in the array in which they were added to the list.  */
15279   while (nfields-- > 0)
15280     {
15281       struct nextfield *fieldp;
15282
15283       if (fip->fields)
15284         {
15285           fieldp = fip->fields;
15286           fip->fields = fieldp->next;
15287         }
15288       else
15289         {
15290           fieldp = fip->baseclasses;
15291           fip->baseclasses = fieldp->next;
15292         }
15293
15294       TYPE_FIELD (type, nfields) = fieldp->field;
15295       switch (fieldp->accessibility)
15296         {
15297         case DW_ACCESS_private:
15298           if (cu->language != language_ada)
15299             SET_TYPE_FIELD_PRIVATE (type, nfields);
15300           break;
15301
15302         case DW_ACCESS_protected:
15303           if (cu->language != language_ada)
15304             SET_TYPE_FIELD_PROTECTED (type, nfields);
15305           break;
15306
15307         case DW_ACCESS_public:
15308           break;
15309
15310         default:
15311           /* Unknown accessibility.  Complain and treat it as public.  */
15312           {
15313             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15314                        fieldp->accessibility);
15315           }
15316           break;
15317         }
15318       if (nfields < fip->nbaseclasses)
15319         {
15320           switch (fieldp->virtuality)
15321             {
15322             case DW_VIRTUALITY_virtual:
15323             case DW_VIRTUALITY_pure_virtual:
15324               if (cu->language == language_ada)
15325                 error (_("unexpected virtuality in component of Ada type"));
15326               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15327               break;
15328             }
15329         }
15330     }
15331 }
15332
15333 /* Return true if this member function is a constructor, false
15334    otherwise.  */
15335
15336 static int
15337 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15338 {
15339   const char *fieldname;
15340   const char *type_name;
15341   int len;
15342
15343   if (die->parent == NULL)
15344     return 0;
15345
15346   if (die->parent->tag != DW_TAG_structure_type
15347       && die->parent->tag != DW_TAG_union_type
15348       && die->parent->tag != DW_TAG_class_type)
15349     return 0;
15350
15351   fieldname = dwarf2_name (die, cu);
15352   type_name = dwarf2_name (die->parent, cu);
15353   if (fieldname == NULL || type_name == NULL)
15354     return 0;
15355
15356   len = strlen (fieldname);
15357   return (strncmp (fieldname, type_name, len) == 0
15358           && (type_name[len] == '\0' || type_name[len] == '<'));
15359 }
15360
15361 /* Add a member function to the proper fieldlist.  */
15362
15363 static void
15364 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15365                       struct type *type, struct dwarf2_cu *cu)
15366 {
15367   struct objfile *objfile = cu->objfile;
15368   struct attribute *attr;
15369   struct fnfieldlist *flp;
15370   int i;
15371   struct fn_field *fnp;
15372   const char *fieldname;
15373   struct nextfnfield *new_fnfield;
15374   struct type *this_type;
15375   enum dwarf_access_attribute accessibility;
15376
15377   if (cu->language == language_ada)
15378     error (_("unexpected member function in Ada type"));
15379
15380   /* Get name of member function.  */
15381   fieldname = dwarf2_name (die, cu);
15382   if (fieldname == NULL)
15383     return;
15384
15385   /* Look up member function name in fieldlist.  */
15386   for (i = 0; i < fip->nfnfields; i++)
15387     {
15388       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15389         break;
15390     }
15391
15392   /* Create new list element if necessary.  */
15393   if (i < fip->nfnfields)
15394     flp = &fip->fnfieldlists[i];
15395   else
15396     {
15397       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15398         {
15399           fip->fnfieldlists = (struct fnfieldlist *)
15400             xrealloc (fip->fnfieldlists,
15401                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15402                       * sizeof (struct fnfieldlist));
15403           if (fip->nfnfields == 0)
15404             make_cleanup (free_current_contents, &fip->fnfieldlists);
15405         }
15406       flp = &fip->fnfieldlists[fip->nfnfields];
15407       flp->name = fieldname;
15408       flp->length = 0;
15409       flp->head = NULL;
15410       i = fip->nfnfields++;
15411     }
15412
15413   /* Create a new member function field and chain it to the field list
15414      entry.  */
15415   new_fnfield = XNEW (struct nextfnfield);
15416   make_cleanup (xfree, new_fnfield);
15417   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15418   new_fnfield->next = flp->head;
15419   flp->head = new_fnfield;
15420   flp->length++;
15421
15422   /* Fill in the member function field info.  */
15423   fnp = &new_fnfield->fnfield;
15424
15425   /* Delay processing of the physname until later.  */
15426   if (cu->language == language_cplus)
15427     {
15428       add_to_method_list (type, i, flp->length - 1, fieldname,
15429                           die, cu);
15430     }
15431   else
15432     {
15433       const char *physname = dwarf2_physname (fieldname, die, cu);
15434       fnp->physname = physname ? physname : "";
15435     }
15436
15437   fnp->type = alloc_type (objfile);
15438   this_type = read_type_die (die, cu);
15439   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15440     {
15441       int nparams = TYPE_NFIELDS (this_type);
15442
15443       /* TYPE is the domain of this method, and THIS_TYPE is the type
15444            of the method itself (TYPE_CODE_METHOD).  */
15445       smash_to_method_type (fnp->type, type,
15446                             TYPE_TARGET_TYPE (this_type),
15447                             TYPE_FIELDS (this_type),
15448                             TYPE_NFIELDS (this_type),
15449                             TYPE_VARARGS (this_type));
15450
15451       /* Handle static member functions.
15452          Dwarf2 has no clean way to discern C++ static and non-static
15453          member functions.  G++ helps GDB by marking the first
15454          parameter for non-static member functions (which is the this
15455          pointer) as artificial.  We obtain this information from
15456          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15457       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15458         fnp->voffset = VOFFSET_STATIC;
15459     }
15460   else
15461     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15462                dwarf2_full_name (fieldname, die, cu));
15463
15464   /* Get fcontext from DW_AT_containing_type if present.  */
15465   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15466     fnp->fcontext = die_containing_type (die, cu);
15467
15468   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15469      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15470
15471   /* Get accessibility.  */
15472   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15473   if (attr)
15474     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15475   else
15476     accessibility = dwarf2_default_access_attribute (die, cu);
15477   switch (accessibility)
15478     {
15479     case DW_ACCESS_private:
15480       fnp->is_private = 1;
15481       break;
15482     case DW_ACCESS_protected:
15483       fnp->is_protected = 1;
15484       break;
15485     }
15486
15487   /* Check for artificial methods.  */
15488   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15489   if (attr && DW_UNSND (attr) != 0)
15490     fnp->is_artificial = 1;
15491
15492   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15493
15494   /* Get index in virtual function table if it is a virtual member
15495      function.  For older versions of GCC, this is an offset in the
15496      appropriate virtual table, as specified by DW_AT_containing_type.
15497      For everyone else, it is an expression to be evaluated relative
15498      to the object address.  */
15499
15500   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15501   if (attr)
15502     {
15503       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15504         {
15505           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15506             {
15507               /* Old-style GCC.  */
15508               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15509             }
15510           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15511                    || (DW_BLOCK (attr)->size > 1
15512                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15513                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15514             {
15515               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15516               if ((fnp->voffset % cu->header.addr_size) != 0)
15517                 dwarf2_complex_location_expr_complaint ();
15518               else
15519                 fnp->voffset /= cu->header.addr_size;
15520               fnp->voffset += 2;
15521             }
15522           else
15523             dwarf2_complex_location_expr_complaint ();
15524
15525           if (!fnp->fcontext)
15526             {
15527               /* If there is no `this' field and no DW_AT_containing_type,
15528                  we cannot actually find a base class context for the
15529                  vtable!  */
15530               if (TYPE_NFIELDS (this_type) == 0
15531                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15532                 {
15533                   complaint (&symfile_complaints,
15534                              _("cannot determine context for virtual member "
15535                                "function \"%s\" (offset %d)"),
15536                              fieldname, to_underlying (die->sect_off));
15537                 }
15538               else
15539                 {
15540                   fnp->fcontext
15541                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15542                 }
15543             }
15544         }
15545       else if (attr_form_is_section_offset (attr))
15546         {
15547           dwarf2_complex_location_expr_complaint ();
15548         }
15549       else
15550         {
15551           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15552                                                  fieldname);
15553         }
15554     }
15555   else
15556     {
15557       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15558       if (attr && DW_UNSND (attr))
15559         {
15560           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15561           complaint (&symfile_complaints,
15562                      _("Member function \"%s\" (offset %d) is virtual "
15563                        "but the vtable offset is not specified"),
15564                      fieldname, to_underlying (die->sect_off));
15565           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15566           TYPE_CPLUS_DYNAMIC (type) = 1;
15567         }
15568     }
15569 }
15570
15571 /* Create the vector of member function fields, and attach it to the type.  */
15572
15573 static void
15574 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15575                                  struct dwarf2_cu *cu)
15576 {
15577   struct fnfieldlist *flp;
15578   int i;
15579
15580   if (cu->language == language_ada)
15581     error (_("unexpected member functions in Ada type"));
15582
15583   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15584   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15585     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15586
15587   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15588     {
15589       struct nextfnfield *nfp = flp->head;
15590       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15591       int k;
15592
15593       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15594       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15595       fn_flp->fn_fields = (struct fn_field *)
15596         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15597       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15598         fn_flp->fn_fields[k] = nfp->fnfield;
15599     }
15600
15601   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15602 }
15603
15604 /* Returns non-zero if NAME is the name of a vtable member in CU's
15605    language, zero otherwise.  */
15606 static int
15607 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15608 {
15609   static const char vptr[] = "_vptr";
15610
15611   /* Look for the C++ form of the vtable.  */
15612   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15613     return 1;
15614
15615   return 0;
15616 }
15617
15618 /* GCC outputs unnamed structures that are really pointers to member
15619    functions, with the ABI-specified layout.  If TYPE describes
15620    such a structure, smash it into a member function type.
15621
15622    GCC shouldn't do this; it should just output pointer to member DIEs.
15623    This is GCC PR debug/28767.  */
15624
15625 static void
15626 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15627 {
15628   struct type *pfn_type, *self_type, *new_type;
15629
15630   /* Check for a structure with no name and two children.  */
15631   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15632     return;
15633
15634   /* Check for __pfn and __delta members.  */
15635   if (TYPE_FIELD_NAME (type, 0) == NULL
15636       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15637       || TYPE_FIELD_NAME (type, 1) == NULL
15638       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15639     return;
15640
15641   /* Find the type of the method.  */
15642   pfn_type = TYPE_FIELD_TYPE (type, 0);
15643   if (pfn_type == NULL
15644       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15645       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15646     return;
15647
15648   /* Look for the "this" argument.  */
15649   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15650   if (TYPE_NFIELDS (pfn_type) == 0
15651       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15652       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15653     return;
15654
15655   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15656   new_type = alloc_type (objfile);
15657   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15658                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15659                         TYPE_VARARGS (pfn_type));
15660   smash_to_methodptr_type (type, new_type);
15661 }
15662
15663
15664 /* Called when we find the DIE that starts a structure or union scope
15665    (definition) to create a type for the structure or union.  Fill in
15666    the type's name and general properties; the members will not be
15667    processed until process_structure_scope.  A symbol table entry for
15668    the type will also not be done until process_structure_scope (assuming
15669    the type has a name).
15670
15671    NOTE: we need to call these functions regardless of whether or not the
15672    DIE has a DW_AT_name attribute, since it might be an anonymous
15673    structure or union.  This gets the type entered into our set of
15674    user defined types.  */
15675
15676 static struct type *
15677 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15678 {
15679   struct objfile *objfile = cu->objfile;
15680   struct type *type;
15681   struct attribute *attr;
15682   const char *name;
15683
15684   /* If the definition of this type lives in .debug_types, read that type.
15685      Don't follow DW_AT_specification though, that will take us back up
15686      the chain and we want to go down.  */
15687   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15688   if (attr)
15689     {
15690       type = get_DW_AT_signature_type (die, attr, cu);
15691
15692       /* The type's CU may not be the same as CU.
15693          Ensure TYPE is recorded with CU in die_type_hash.  */
15694       return set_die_type (die, type, cu);
15695     }
15696
15697   type = alloc_type (objfile);
15698   INIT_CPLUS_SPECIFIC (type);
15699
15700   name = dwarf2_name (die, cu);
15701   if (name != NULL)
15702     {
15703       if (cu->language == language_cplus
15704           || cu->language == language_d
15705           || cu->language == language_rust)
15706         {
15707           const char *full_name = dwarf2_full_name (name, die, cu);
15708
15709           /* dwarf2_full_name might have already finished building the DIE's
15710              type.  If so, there is no need to continue.  */
15711           if (get_die_type (die, cu) != NULL)
15712             return get_die_type (die, cu);
15713
15714           TYPE_TAG_NAME (type) = full_name;
15715           if (die->tag == DW_TAG_structure_type
15716               || die->tag == DW_TAG_class_type)
15717             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15718         }
15719       else
15720         {
15721           /* The name is already allocated along with this objfile, so
15722              we don't need to duplicate it for the type.  */
15723           TYPE_TAG_NAME (type) = name;
15724           if (die->tag == DW_TAG_class_type)
15725             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15726         }
15727     }
15728
15729   if (die->tag == DW_TAG_structure_type)
15730     {
15731       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15732     }
15733   else if (die->tag == DW_TAG_union_type)
15734     {
15735       TYPE_CODE (type) = TYPE_CODE_UNION;
15736     }
15737   else
15738     {
15739       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15740     }
15741
15742   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15743     TYPE_DECLARED_CLASS (type) = 1;
15744
15745   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15746   if (attr)
15747     {
15748       if (attr_form_is_constant (attr))
15749         TYPE_LENGTH (type) = DW_UNSND (attr);
15750       else
15751         {
15752           /* For the moment, dynamic type sizes are not supported
15753              by GDB's struct type.  The actual size is determined
15754              on-demand when resolving the type of a given object,
15755              so set the type's length to zero for now.  Otherwise,
15756              we record an expression as the length, and that expression
15757              could lead to a very large value, which could eventually
15758              lead to us trying to allocate that much memory when creating
15759              a value of that type.  */
15760           TYPE_LENGTH (type) = 0;
15761         }
15762     }
15763   else
15764     {
15765       TYPE_LENGTH (type) = 0;
15766     }
15767
15768   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15769     {
15770       /* ICC<14 does not output the required DW_AT_declaration on
15771          incomplete types, but gives them a size of zero.  */
15772       TYPE_STUB (type) = 1;
15773     }
15774   else
15775     TYPE_STUB_SUPPORTED (type) = 1;
15776
15777   if (die_is_declaration (die, cu))
15778     TYPE_STUB (type) = 1;
15779   else if (attr == NULL && die->child == NULL
15780            && producer_is_realview (cu->producer))
15781     /* RealView does not output the required DW_AT_declaration
15782        on incomplete types.  */
15783     TYPE_STUB (type) = 1;
15784
15785   /* We need to add the type field to the die immediately so we don't
15786      infinitely recurse when dealing with pointers to the structure
15787      type within the structure itself.  */
15788   set_die_type (die, type, cu);
15789
15790   /* set_die_type should be already done.  */
15791   set_descriptive_type (type, die, cu);
15792
15793   return type;
15794 }
15795
15796 /* Finish creating a structure or union type, including filling in
15797    its members and creating a symbol for it.  */
15798
15799 static void
15800 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15801 {
15802   struct objfile *objfile = cu->objfile;
15803   struct die_info *child_die;
15804   struct type *type;
15805
15806   type = get_die_type (die, cu);
15807   if (type == NULL)
15808     type = read_structure_type (die, cu);
15809
15810   if (die->child != NULL && ! die_is_declaration (die, cu))
15811     {
15812       struct field_info fi;
15813       std::vector<struct symbol *> template_args;
15814       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
15815
15816       memset (&fi, 0, sizeof (struct field_info));
15817
15818       child_die = die->child;
15819
15820       while (child_die && child_die->tag)
15821         {
15822           if (child_die->tag == DW_TAG_member
15823               || child_die->tag == DW_TAG_variable)
15824             {
15825               /* NOTE: carlton/2002-11-05: A C++ static data member
15826                  should be a DW_TAG_member that is a declaration, but
15827                  all versions of G++ as of this writing (so through at
15828                  least 3.2.1) incorrectly generate DW_TAG_variable
15829                  tags for them instead.  */
15830               dwarf2_add_field (&fi, child_die, cu);
15831             }
15832           else if (child_die->tag == DW_TAG_subprogram)
15833             {
15834               /* Rust doesn't have member functions in the C++ sense.
15835                  However, it does emit ordinary functions as children
15836                  of a struct DIE.  */
15837               if (cu->language == language_rust)
15838                 read_func_scope (child_die, cu);
15839               else
15840                 {
15841                   /* C++ member function.  */
15842                   dwarf2_add_member_fn (&fi, child_die, type, cu);
15843                 }
15844             }
15845           else if (child_die->tag == DW_TAG_inheritance)
15846             {
15847               /* C++ base class field.  */
15848               dwarf2_add_field (&fi, child_die, cu);
15849             }
15850           else if (type_can_define_types (child_die))
15851             dwarf2_add_type_defn (&fi, child_die, cu);
15852           else if (child_die->tag == DW_TAG_template_type_param
15853                    || child_die->tag == DW_TAG_template_value_param)
15854             {
15855               struct symbol *arg = new_symbol (child_die, NULL, cu);
15856
15857               if (arg != NULL)
15858                 template_args.push_back (arg);
15859             }
15860
15861           child_die = sibling_die (child_die);
15862         }
15863
15864       /* Attach template arguments to type.  */
15865       if (!template_args.empty ())
15866         {
15867           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15868           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15869           TYPE_TEMPLATE_ARGUMENTS (type)
15870             = XOBNEWVEC (&objfile->objfile_obstack,
15871                          struct symbol *,
15872                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15873           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15874                   template_args.data (),
15875                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15876                    * sizeof (struct symbol *)));
15877         }
15878
15879       /* Attach fields and member functions to the type.  */
15880       if (fi.nfields)
15881         dwarf2_attach_fields_to_type (&fi, type, cu);
15882       if (fi.nfnfields)
15883         {
15884           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15885
15886           /* Get the type which refers to the base class (possibly this
15887              class itself) which contains the vtable pointer for the current
15888              class from the DW_AT_containing_type attribute.  This use of
15889              DW_AT_containing_type is a GNU extension.  */
15890
15891           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15892             {
15893               struct type *t = die_containing_type (die, cu);
15894
15895               set_type_vptr_basetype (type, t);
15896               if (type == t)
15897                 {
15898                   int i;
15899
15900                   /* Our own class provides vtbl ptr.  */
15901                   for (i = TYPE_NFIELDS (t) - 1;
15902                        i >= TYPE_N_BASECLASSES (t);
15903                        --i)
15904                     {
15905                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15906
15907                       if (is_vtable_name (fieldname, cu))
15908                         {
15909                           set_type_vptr_fieldno (type, i);
15910                           break;
15911                         }
15912                     }
15913
15914                   /* Complain if virtual function table field not found.  */
15915                   if (i < TYPE_N_BASECLASSES (t))
15916                     complaint (&symfile_complaints,
15917                                _("virtual function table pointer "
15918                                  "not found when defining class '%s'"),
15919                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
15920                                "");
15921                 }
15922               else
15923                 {
15924                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15925                 }
15926             }
15927           else if (cu->producer
15928                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15929             {
15930               /* The IBM XLC compiler does not provide direct indication
15931                  of the containing type, but the vtable pointer is
15932                  always named __vfp.  */
15933
15934               int i;
15935
15936               for (i = TYPE_NFIELDS (type) - 1;
15937                    i >= TYPE_N_BASECLASSES (type);
15938                    --i)
15939                 {
15940                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15941                     {
15942                       set_type_vptr_fieldno (type, i);
15943                       set_type_vptr_basetype (type, type);
15944                       break;
15945                     }
15946                 }
15947             }
15948         }
15949
15950       /* Copy fi.typedef_field_list linked list elements content into the
15951          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15952       if (fi.typedef_field_list)
15953         {
15954           int i = fi.typedef_field_list_count;
15955
15956           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15957           TYPE_TYPEDEF_FIELD_ARRAY (type)
15958             = ((struct decl_field *)
15959                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
15960           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
15961
15962           /* Reverse the list order to keep the debug info elements order.  */
15963           while (--i >= 0)
15964             {
15965               struct decl_field *dest, *src;
15966
15967               dest = &TYPE_TYPEDEF_FIELD (type, i);
15968               src = &fi.typedef_field_list->field;
15969               fi.typedef_field_list = fi.typedef_field_list->next;
15970               *dest = *src;
15971             }
15972         }
15973
15974       /* Copy fi.nested_types_list linked list elements content into the
15975          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15976       if (fi.nested_types_list != NULL && cu->language != language_ada)
15977         {
15978           int i = fi.nested_types_list_count;
15979
15980           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15981           TYPE_NESTED_TYPES_ARRAY (type)
15982             = ((struct decl_field *)
15983                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
15984           TYPE_NESTED_TYPES_COUNT (type) = i;
15985
15986           /* Reverse the list order to keep the debug info elements order.  */
15987           while (--i >= 0)
15988             {
15989               struct decl_field *dest, *src;
15990
15991               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
15992               src = &fi.nested_types_list->field;
15993               fi.nested_types_list = fi.nested_types_list->next;
15994               *dest = *src;
15995             }
15996         }
15997
15998       do_cleanups (back_to);
15999     }
16000
16001   quirk_gcc_member_function_pointer (type, objfile);
16002
16003   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16004      snapshots) has been known to create a die giving a declaration
16005      for a class that has, as a child, a die giving a definition for a
16006      nested class.  So we have to process our children even if the
16007      current die is a declaration.  Normally, of course, a declaration
16008      won't have any children at all.  */
16009
16010   child_die = die->child;
16011
16012   while (child_die != NULL && child_die->tag)
16013     {
16014       if (child_die->tag == DW_TAG_member
16015           || child_die->tag == DW_TAG_variable
16016           || child_die->tag == DW_TAG_inheritance
16017           || child_die->tag == DW_TAG_template_value_param
16018           || child_die->tag == DW_TAG_template_type_param)
16019         {
16020           /* Do nothing.  */
16021         }
16022       else
16023         process_die (child_die, cu);
16024
16025       child_die = sibling_die (child_die);
16026     }
16027
16028   /* Do not consider external references.  According to the DWARF standard,
16029      these DIEs are identified by the fact that they have no byte_size
16030      attribute, and a declaration attribute.  */
16031   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16032       || !die_is_declaration (die, cu))
16033     new_symbol (die, type, cu);
16034 }
16035
16036 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16037    update TYPE using some information only available in DIE's children.  */
16038
16039 static void
16040 update_enumeration_type_from_children (struct die_info *die,
16041                                        struct type *type,
16042                                        struct dwarf2_cu *cu)
16043 {
16044   struct die_info *child_die;
16045   int unsigned_enum = 1;
16046   int flag_enum = 1;
16047   ULONGEST mask = 0;
16048
16049   auto_obstack obstack;
16050
16051   for (child_die = die->child;
16052        child_die != NULL && child_die->tag;
16053        child_die = sibling_die (child_die))
16054     {
16055       struct attribute *attr;
16056       LONGEST value;
16057       const gdb_byte *bytes;
16058       struct dwarf2_locexpr_baton *baton;
16059       const char *name;
16060
16061       if (child_die->tag != DW_TAG_enumerator)
16062         continue;
16063
16064       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16065       if (attr == NULL)
16066         continue;
16067
16068       name = dwarf2_name (child_die, cu);
16069       if (name == NULL)
16070         name = "<anonymous enumerator>";
16071
16072       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16073                                &value, &bytes, &baton);
16074       if (value < 0)
16075         {
16076           unsigned_enum = 0;
16077           flag_enum = 0;
16078         }
16079       else if ((mask & value) != 0)
16080         flag_enum = 0;
16081       else
16082         mask |= value;
16083
16084       /* If we already know that the enum type is neither unsigned, nor
16085          a flag type, no need to look at the rest of the enumerates.  */
16086       if (!unsigned_enum && !flag_enum)
16087         break;
16088     }
16089
16090   if (unsigned_enum)
16091     TYPE_UNSIGNED (type) = 1;
16092   if (flag_enum)
16093     TYPE_FLAG_ENUM (type) = 1;
16094 }
16095
16096 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16097    complete the type's fields yet, or create any symbols.  */
16098
16099 static struct type *
16100 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16101 {
16102   struct objfile *objfile = cu->objfile;
16103   struct type *type;
16104   struct attribute *attr;
16105   const char *name;
16106
16107   /* If the definition of this type lives in .debug_types, read that type.
16108      Don't follow DW_AT_specification though, that will take us back up
16109      the chain and we want to go down.  */
16110   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16111   if (attr)
16112     {
16113       type = get_DW_AT_signature_type (die, attr, cu);
16114
16115       /* The type's CU may not be the same as CU.
16116          Ensure TYPE is recorded with CU in die_type_hash.  */
16117       return set_die_type (die, type, cu);
16118     }
16119
16120   type = alloc_type (objfile);
16121
16122   TYPE_CODE (type) = TYPE_CODE_ENUM;
16123   name = dwarf2_full_name (NULL, die, cu);
16124   if (name != NULL)
16125     TYPE_TAG_NAME (type) = name;
16126
16127   attr = dwarf2_attr (die, DW_AT_type, cu);
16128   if (attr != NULL)
16129     {
16130       struct type *underlying_type = die_type (die, cu);
16131
16132       TYPE_TARGET_TYPE (type) = underlying_type;
16133     }
16134
16135   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16136   if (attr)
16137     {
16138       TYPE_LENGTH (type) = DW_UNSND (attr);
16139     }
16140   else
16141     {
16142       TYPE_LENGTH (type) = 0;
16143     }
16144
16145   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16146      declared as private in the package spec, and then defined only
16147      inside the package body.  Such types are known as Taft Amendment
16148      Types.  When another package uses such a type, an incomplete DIE
16149      may be generated by the compiler.  */
16150   if (die_is_declaration (die, cu))
16151     TYPE_STUB (type) = 1;
16152
16153   /* Finish the creation of this type by using the enum's children.
16154      We must call this even when the underlying type has been provided
16155      so that we can determine if we're looking at a "flag" enum.  */
16156   update_enumeration_type_from_children (die, type, cu);
16157
16158   /* If this type has an underlying type that is not a stub, then we
16159      may use its attributes.  We always use the "unsigned" attribute
16160      in this situation, because ordinarily we guess whether the type
16161      is unsigned -- but the guess can be wrong and the underlying type
16162      can tell us the reality.  However, we defer to a local size
16163      attribute if one exists, because this lets the compiler override
16164      the underlying type if needed.  */
16165   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16166     {
16167       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16168       if (TYPE_LENGTH (type) == 0)
16169         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16170     }
16171
16172   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16173
16174   return set_die_type (die, type, cu);
16175 }
16176
16177 /* Given a pointer to a die which begins an enumeration, process all
16178    the dies that define the members of the enumeration, and create the
16179    symbol for the enumeration type.
16180
16181    NOTE: We reverse the order of the element list.  */
16182
16183 static void
16184 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16185 {
16186   struct type *this_type;
16187
16188   this_type = get_die_type (die, cu);
16189   if (this_type == NULL)
16190     this_type = read_enumeration_type (die, cu);
16191
16192   if (die->child != NULL)
16193     {
16194       struct die_info *child_die;
16195       struct symbol *sym;
16196       struct field *fields = NULL;
16197       int num_fields = 0;
16198       const char *name;
16199
16200       child_die = die->child;
16201       while (child_die && child_die->tag)
16202         {
16203           if (child_die->tag != DW_TAG_enumerator)
16204             {
16205               process_die (child_die, cu);
16206             }
16207           else
16208             {
16209               name = dwarf2_name (child_die, cu);
16210               if (name)
16211                 {
16212                   sym = new_symbol (child_die, this_type, cu);
16213
16214                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16215                     {
16216                       fields = (struct field *)
16217                         xrealloc (fields,
16218                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16219                                   * sizeof (struct field));
16220                     }
16221
16222                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16223                   FIELD_TYPE (fields[num_fields]) = NULL;
16224                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16225                   FIELD_BITSIZE (fields[num_fields]) = 0;
16226
16227                   num_fields++;
16228                 }
16229             }
16230
16231           child_die = sibling_die (child_die);
16232         }
16233
16234       if (num_fields)
16235         {
16236           TYPE_NFIELDS (this_type) = num_fields;
16237           TYPE_FIELDS (this_type) = (struct field *)
16238             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16239           memcpy (TYPE_FIELDS (this_type), fields,
16240                   sizeof (struct field) * num_fields);
16241           xfree (fields);
16242         }
16243     }
16244
16245   /* If we are reading an enum from a .debug_types unit, and the enum
16246      is a declaration, and the enum is not the signatured type in the
16247      unit, then we do not want to add a symbol for it.  Adding a
16248      symbol would in some cases obscure the true definition of the
16249      enum, giving users an incomplete type when the definition is
16250      actually available.  Note that we do not want to do this for all
16251      enums which are just declarations, because C++0x allows forward
16252      enum declarations.  */
16253   if (cu->per_cu->is_debug_types
16254       && die_is_declaration (die, cu))
16255     {
16256       struct signatured_type *sig_type;
16257
16258       sig_type = (struct signatured_type *) cu->per_cu;
16259       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16260       if (sig_type->type_offset_in_section != die->sect_off)
16261         return;
16262     }
16263
16264   new_symbol (die, this_type, cu);
16265 }
16266
16267 /* Extract all information from a DW_TAG_array_type DIE and put it in
16268    the DIE's type field.  For now, this only handles one dimensional
16269    arrays.  */
16270
16271 static struct type *
16272 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16273 {
16274   struct objfile *objfile = cu->objfile;
16275   struct die_info *child_die;
16276   struct type *type;
16277   struct type *element_type, *range_type, *index_type;
16278   struct attribute *attr;
16279   const char *name;
16280   unsigned int bit_stride = 0;
16281
16282   element_type = die_type (die, cu);
16283
16284   /* The die_type call above may have already set the type for this DIE.  */
16285   type = get_die_type (die, cu);
16286   if (type)
16287     return type;
16288
16289   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16290   if (attr != NULL)
16291     bit_stride = DW_UNSND (attr) * 8;
16292
16293   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16294   if (attr != NULL)
16295     bit_stride = DW_UNSND (attr);
16296
16297   /* Irix 6.2 native cc creates array types without children for
16298      arrays with unspecified length.  */
16299   if (die->child == NULL)
16300     {
16301       index_type = objfile_type (objfile)->builtin_int;
16302       range_type = create_static_range_type (NULL, index_type, 0, -1);
16303       type = create_array_type_with_stride (NULL, element_type, range_type,
16304                                             bit_stride);
16305       return set_die_type (die, type, cu);
16306     }
16307
16308   std::vector<struct type *> range_types;
16309   child_die = die->child;
16310   while (child_die && child_die->tag)
16311     {
16312       if (child_die->tag == DW_TAG_subrange_type)
16313         {
16314           struct type *child_type = read_type_die (child_die, cu);
16315
16316           if (child_type != NULL)
16317             {
16318               /* The range type was succesfully read.  Save it for the
16319                  array type creation.  */
16320               range_types.push_back (child_type);
16321             }
16322         }
16323       child_die = sibling_die (child_die);
16324     }
16325
16326   /* Dwarf2 dimensions are output from left to right, create the
16327      necessary array types in backwards order.  */
16328
16329   type = element_type;
16330
16331   if (read_array_order (die, cu) == DW_ORD_col_major)
16332     {
16333       int i = 0;
16334
16335       while (i < range_types.size ())
16336         type = create_array_type_with_stride (NULL, type, range_types[i++],
16337                                               bit_stride);
16338     }
16339   else
16340     {
16341       size_t ndim = range_types.size ();
16342       while (ndim-- > 0)
16343         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16344                                               bit_stride);
16345     }
16346
16347   /* Understand Dwarf2 support for vector types (like they occur on
16348      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16349      array type.  This is not part of the Dwarf2/3 standard yet, but a
16350      custom vendor extension.  The main difference between a regular
16351      array and the vector variant is that vectors are passed by value
16352      to functions.  */
16353   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16354   if (attr)
16355     make_vector_type (type);
16356
16357   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16358      implementation may choose to implement triple vectors using this
16359      attribute.  */
16360   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16361   if (attr)
16362     {
16363       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16364         TYPE_LENGTH (type) = DW_UNSND (attr);
16365       else
16366         complaint (&symfile_complaints,
16367                    _("DW_AT_byte_size for array type smaller "
16368                      "than the total size of elements"));
16369     }
16370
16371   name = dwarf2_name (die, cu);
16372   if (name)
16373     TYPE_NAME (type) = name;
16374
16375   /* Install the type in the die.  */
16376   set_die_type (die, type, cu);
16377
16378   /* set_die_type should be already done.  */
16379   set_descriptive_type (type, die, cu);
16380
16381   return type;
16382 }
16383
16384 static enum dwarf_array_dim_ordering
16385 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16386 {
16387   struct attribute *attr;
16388
16389   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16390
16391   if (attr)
16392     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16393
16394   /* GNU F77 is a special case, as at 08/2004 array type info is the
16395      opposite order to the dwarf2 specification, but data is still
16396      laid out as per normal fortran.
16397
16398      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16399      version checking.  */
16400
16401   if (cu->language == language_fortran
16402       && cu->producer && strstr (cu->producer, "GNU F77"))
16403     {
16404       return DW_ORD_row_major;
16405     }
16406
16407   switch (cu->language_defn->la_array_ordering)
16408     {
16409     case array_column_major:
16410       return DW_ORD_col_major;
16411     case array_row_major:
16412     default:
16413       return DW_ORD_row_major;
16414     };
16415 }
16416
16417 /* Extract all information from a DW_TAG_set_type DIE and put it in
16418    the DIE's type field.  */
16419
16420 static struct type *
16421 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16422 {
16423   struct type *domain_type, *set_type;
16424   struct attribute *attr;
16425
16426   domain_type = die_type (die, cu);
16427
16428   /* The die_type call above may have already set the type for this DIE.  */
16429   set_type = get_die_type (die, cu);
16430   if (set_type)
16431     return set_type;
16432
16433   set_type = create_set_type (NULL, domain_type);
16434
16435   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16436   if (attr)
16437     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16438
16439   return set_die_type (die, set_type, cu);
16440 }
16441
16442 /* A helper for read_common_block that creates a locexpr baton.
16443    SYM is the symbol which we are marking as computed.
16444    COMMON_DIE is the DIE for the common block.
16445    COMMON_LOC is the location expression attribute for the common
16446    block itself.
16447    MEMBER_LOC is the location expression attribute for the particular
16448    member of the common block that we are processing.
16449    CU is the CU from which the above come.  */
16450
16451 static void
16452 mark_common_block_symbol_computed (struct symbol *sym,
16453                                    struct die_info *common_die,
16454                                    struct attribute *common_loc,
16455                                    struct attribute *member_loc,
16456                                    struct dwarf2_cu *cu)
16457 {
16458   struct objfile *objfile = dwarf2_per_objfile->objfile;
16459   struct dwarf2_locexpr_baton *baton;
16460   gdb_byte *ptr;
16461   unsigned int cu_off;
16462   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16463   LONGEST offset = 0;
16464
16465   gdb_assert (common_loc && member_loc);
16466   gdb_assert (attr_form_is_block (common_loc));
16467   gdb_assert (attr_form_is_block (member_loc)
16468               || attr_form_is_constant (member_loc));
16469
16470   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16471   baton->per_cu = cu->per_cu;
16472   gdb_assert (baton->per_cu);
16473
16474   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16475
16476   if (attr_form_is_constant (member_loc))
16477     {
16478       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16479       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16480     }
16481   else
16482     baton->size += DW_BLOCK (member_loc)->size;
16483
16484   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16485   baton->data = ptr;
16486
16487   *ptr++ = DW_OP_call4;
16488   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16489   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16490   ptr += 4;
16491
16492   if (attr_form_is_constant (member_loc))
16493     {
16494       *ptr++ = DW_OP_addr;
16495       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16496       ptr += cu->header.addr_size;
16497     }
16498   else
16499     {
16500       /* We have to copy the data here, because DW_OP_call4 will only
16501          use a DW_AT_location attribute.  */
16502       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16503       ptr += DW_BLOCK (member_loc)->size;
16504     }
16505
16506   *ptr++ = DW_OP_plus;
16507   gdb_assert (ptr - baton->data == baton->size);
16508
16509   SYMBOL_LOCATION_BATON (sym) = baton;
16510   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16511 }
16512
16513 /* Create appropriate locally-scoped variables for all the
16514    DW_TAG_common_block entries.  Also create a struct common_block
16515    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16516    is used to sepate the common blocks name namespace from regular
16517    variable names.  */
16518
16519 static void
16520 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16521 {
16522   struct attribute *attr;
16523
16524   attr = dwarf2_attr (die, DW_AT_location, cu);
16525   if (attr)
16526     {
16527       /* Support the .debug_loc offsets.  */
16528       if (attr_form_is_block (attr))
16529         {
16530           /* Ok.  */
16531         }
16532       else if (attr_form_is_section_offset (attr))
16533         {
16534           dwarf2_complex_location_expr_complaint ();
16535           attr = NULL;
16536         }
16537       else
16538         {
16539           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16540                                                  "common block member");
16541           attr = NULL;
16542         }
16543     }
16544
16545   if (die->child != NULL)
16546     {
16547       struct objfile *objfile = cu->objfile;
16548       struct die_info *child_die;
16549       size_t n_entries = 0, size;
16550       struct common_block *common_block;
16551       struct symbol *sym;
16552
16553       for (child_die = die->child;
16554            child_die && child_die->tag;
16555            child_die = sibling_die (child_die))
16556         ++n_entries;
16557
16558       size = (sizeof (struct common_block)
16559               + (n_entries - 1) * sizeof (struct symbol *));
16560       common_block
16561         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16562                                                  size);
16563       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16564       common_block->n_entries = 0;
16565
16566       for (child_die = die->child;
16567            child_die && child_die->tag;
16568            child_die = sibling_die (child_die))
16569         {
16570           /* Create the symbol in the DW_TAG_common_block block in the current
16571              symbol scope.  */
16572           sym = new_symbol (child_die, NULL, cu);
16573           if (sym != NULL)
16574             {
16575               struct attribute *member_loc;
16576
16577               common_block->contents[common_block->n_entries++] = sym;
16578
16579               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16580                                         cu);
16581               if (member_loc)
16582                 {
16583                   /* GDB has handled this for a long time, but it is
16584                      not specified by DWARF.  It seems to have been
16585                      emitted by gfortran at least as recently as:
16586                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16587                   complaint (&symfile_complaints,
16588                              _("Variable in common block has "
16589                                "DW_AT_data_member_location "
16590                                "- DIE at 0x%x [in module %s]"),
16591                              to_underlying (child_die->sect_off),
16592                              objfile_name (cu->objfile));
16593
16594                   if (attr_form_is_section_offset (member_loc))
16595                     dwarf2_complex_location_expr_complaint ();
16596                   else if (attr_form_is_constant (member_loc)
16597                            || attr_form_is_block (member_loc))
16598                     {
16599                       if (attr)
16600                         mark_common_block_symbol_computed (sym, die, attr,
16601                                                            member_loc, cu);
16602                     }
16603                   else
16604                     dwarf2_complex_location_expr_complaint ();
16605                 }
16606             }
16607         }
16608
16609       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16610       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16611     }
16612 }
16613
16614 /* Create a type for a C++ namespace.  */
16615
16616 static struct type *
16617 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16618 {
16619   struct objfile *objfile = cu->objfile;
16620   const char *previous_prefix, *name;
16621   int is_anonymous;
16622   struct type *type;
16623
16624   /* For extensions, reuse the type of the original namespace.  */
16625   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16626     {
16627       struct die_info *ext_die;
16628       struct dwarf2_cu *ext_cu = cu;
16629
16630       ext_die = dwarf2_extension (die, &ext_cu);
16631       type = read_type_die (ext_die, ext_cu);
16632
16633       /* EXT_CU may not be the same as CU.
16634          Ensure TYPE is recorded with CU in die_type_hash.  */
16635       return set_die_type (die, type, cu);
16636     }
16637
16638   name = namespace_name (die, &is_anonymous, cu);
16639
16640   /* Now build the name of the current namespace.  */
16641
16642   previous_prefix = determine_prefix (die, cu);
16643   if (previous_prefix[0] != '\0')
16644     name = typename_concat (&objfile->objfile_obstack,
16645                             previous_prefix, name, 0, cu);
16646
16647   /* Create the type.  */
16648   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16649   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16650
16651   return set_die_type (die, type, cu);
16652 }
16653
16654 /* Read a namespace scope.  */
16655
16656 static void
16657 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16658 {
16659   struct objfile *objfile = cu->objfile;
16660   int is_anonymous;
16661
16662   /* Add a symbol associated to this if we haven't seen the namespace
16663      before.  Also, add a using directive if it's an anonymous
16664      namespace.  */
16665
16666   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16667     {
16668       struct type *type;
16669
16670       type = read_type_die (die, cu);
16671       new_symbol (die, type, cu);
16672
16673       namespace_name (die, &is_anonymous, cu);
16674       if (is_anonymous)
16675         {
16676           const char *previous_prefix = determine_prefix (die, cu);
16677
16678           std::vector<const char *> excludes;
16679           add_using_directive (using_directives (cu->language),
16680                                previous_prefix, TYPE_NAME (type), NULL,
16681                                NULL, excludes, 0, &objfile->objfile_obstack);
16682         }
16683     }
16684
16685   if (die->child != NULL)
16686     {
16687       struct die_info *child_die = die->child;
16688
16689       while (child_die && child_die->tag)
16690         {
16691           process_die (child_die, cu);
16692           child_die = sibling_die (child_die);
16693         }
16694     }
16695 }
16696
16697 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16698    imported module.  Still we need that type as local Fortran "use ... only"
16699    declaration imports depend on the created type in determine_prefix.  */
16700
16701 static struct type *
16702 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16703 {
16704   struct objfile *objfile = cu->objfile;
16705   const char *module_name;
16706   struct type *type;
16707
16708   module_name = dwarf2_name (die, cu);
16709   if (!module_name)
16710     complaint (&symfile_complaints,
16711                _("DW_TAG_module has no name, offset 0x%x"),
16712                to_underlying (die->sect_off));
16713   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16714
16715   /* determine_prefix uses TYPE_TAG_NAME.  */
16716   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16717
16718   return set_die_type (die, type, cu);
16719 }
16720
16721 /* Read a Fortran module.  */
16722
16723 static void
16724 read_module (struct die_info *die, struct dwarf2_cu *cu)
16725 {
16726   struct die_info *child_die = die->child;
16727   struct type *type;
16728
16729   type = read_type_die (die, cu);
16730   new_symbol (die, type, cu);
16731
16732   while (child_die && child_die->tag)
16733     {
16734       process_die (child_die, cu);
16735       child_die = sibling_die (child_die);
16736     }
16737 }
16738
16739 /* Return the name of the namespace represented by DIE.  Set
16740    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16741    namespace.  */
16742
16743 static const char *
16744 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16745 {
16746   struct die_info *current_die;
16747   const char *name = NULL;
16748
16749   /* Loop through the extensions until we find a name.  */
16750
16751   for (current_die = die;
16752        current_die != NULL;
16753        current_die = dwarf2_extension (die, &cu))
16754     {
16755       /* We don't use dwarf2_name here so that we can detect the absence
16756          of a name -> anonymous namespace.  */
16757       name = dwarf2_string_attr (die, DW_AT_name, cu);
16758
16759       if (name != NULL)
16760         break;
16761     }
16762
16763   /* Is it an anonymous namespace?  */
16764
16765   *is_anonymous = (name == NULL);
16766   if (*is_anonymous)
16767     name = CP_ANONYMOUS_NAMESPACE_STR;
16768
16769   return name;
16770 }
16771
16772 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16773    the user defined type vector.  */
16774
16775 static struct type *
16776 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16777 {
16778   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
16779   struct comp_unit_head *cu_header = &cu->header;
16780   struct type *type;
16781   struct attribute *attr_byte_size;
16782   struct attribute *attr_address_class;
16783   int byte_size, addr_class;
16784   struct type *target_type;
16785
16786   target_type = die_type (die, cu);
16787
16788   /* The die_type call above may have already set the type for this DIE.  */
16789   type = get_die_type (die, cu);
16790   if (type)
16791     return type;
16792
16793   type = lookup_pointer_type (target_type);
16794
16795   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16796   if (attr_byte_size)
16797     byte_size = DW_UNSND (attr_byte_size);
16798   else
16799     byte_size = cu_header->addr_size;
16800
16801   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16802   if (attr_address_class)
16803     addr_class = DW_UNSND (attr_address_class);
16804   else
16805     addr_class = DW_ADDR_none;
16806
16807   /* If the pointer size or address class is different than the
16808      default, create a type variant marked as such and set the
16809      length accordingly.  */
16810   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
16811     {
16812       if (gdbarch_address_class_type_flags_p (gdbarch))
16813         {
16814           int type_flags;
16815
16816           type_flags = gdbarch_address_class_type_flags
16817                          (gdbarch, byte_size, addr_class);
16818           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16819                       == 0);
16820           type = make_type_with_address_space (type, type_flags);
16821         }
16822       else if (TYPE_LENGTH (type) != byte_size)
16823         {
16824           complaint (&symfile_complaints,
16825                      _("invalid pointer size %d"), byte_size);
16826         }
16827       else
16828         {
16829           /* Should we also complain about unhandled address classes?  */
16830         }
16831     }
16832
16833   TYPE_LENGTH (type) = byte_size;
16834   return set_die_type (die, type, cu);
16835 }
16836
16837 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16838    the user defined type vector.  */
16839
16840 static struct type *
16841 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16842 {
16843   struct type *type;
16844   struct type *to_type;
16845   struct type *domain;
16846
16847   to_type = die_type (die, cu);
16848   domain = die_containing_type (die, cu);
16849
16850   /* The calls above may have already set the type for this DIE.  */
16851   type = get_die_type (die, cu);
16852   if (type)
16853     return type;
16854
16855   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16856     type = lookup_methodptr_type (to_type);
16857   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16858     {
16859       struct type *new_type = alloc_type (cu->objfile);
16860
16861       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16862                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16863                             TYPE_VARARGS (to_type));
16864       type = lookup_methodptr_type (new_type);
16865     }
16866   else
16867     type = lookup_memberptr_type (to_type, domain);
16868
16869   return set_die_type (die, type, cu);
16870 }
16871
16872 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16873    the user defined type vector.  */
16874
16875 static struct type *
16876 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16877                           enum type_code refcode)
16878 {
16879   struct comp_unit_head *cu_header = &cu->header;
16880   struct type *type, *target_type;
16881   struct attribute *attr;
16882
16883   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16884
16885   target_type = die_type (die, cu);
16886
16887   /* The die_type call above may have already set the type for this DIE.  */
16888   type = get_die_type (die, cu);
16889   if (type)
16890     return type;
16891
16892   type = lookup_reference_type (target_type, refcode);
16893   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16894   if (attr)
16895     {
16896       TYPE_LENGTH (type) = DW_UNSND (attr);
16897     }
16898   else
16899     {
16900       TYPE_LENGTH (type) = cu_header->addr_size;
16901     }
16902   return set_die_type (die, type, cu);
16903 }
16904
16905 /* Add the given cv-qualifiers to the element type of the array.  GCC
16906    outputs DWARF type qualifiers that apply to an array, not the
16907    element type.  But GDB relies on the array element type to carry
16908    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16909    specification.  */
16910
16911 static struct type *
16912 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16913                    struct type *base_type, int cnst, int voltl)
16914 {
16915   struct type *el_type, *inner_array;
16916
16917   base_type = copy_type (base_type);
16918   inner_array = base_type;
16919
16920   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16921     {
16922       TYPE_TARGET_TYPE (inner_array) =
16923         copy_type (TYPE_TARGET_TYPE (inner_array));
16924       inner_array = TYPE_TARGET_TYPE (inner_array);
16925     }
16926
16927   el_type = TYPE_TARGET_TYPE (inner_array);
16928   cnst |= TYPE_CONST (el_type);
16929   voltl |= TYPE_VOLATILE (el_type);
16930   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16931
16932   return set_die_type (die, base_type, cu);
16933 }
16934
16935 static struct type *
16936 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16937 {
16938   struct type *base_type, *cv_type;
16939
16940   base_type = die_type (die, cu);
16941
16942   /* The die_type call above may have already set the type for this DIE.  */
16943   cv_type = get_die_type (die, cu);
16944   if (cv_type)
16945     return cv_type;
16946
16947   /* In case the const qualifier is applied to an array type, the element type
16948      is so qualified, not the array type (section 6.7.3 of C99).  */
16949   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16950     return add_array_cv_type (die, cu, base_type, 1, 0);
16951
16952   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16953   return set_die_type (die, cv_type, cu);
16954 }
16955
16956 static struct type *
16957 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16958 {
16959   struct type *base_type, *cv_type;
16960
16961   base_type = die_type (die, cu);
16962
16963   /* The die_type call above may have already set the type for this DIE.  */
16964   cv_type = get_die_type (die, cu);
16965   if (cv_type)
16966     return cv_type;
16967
16968   /* In case the volatile qualifier is applied to an array type, the
16969      element type is so qualified, not the array type (section 6.7.3
16970      of C99).  */
16971   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16972     return add_array_cv_type (die, cu, base_type, 0, 1);
16973
16974   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
16975   return set_die_type (die, cv_type, cu);
16976 }
16977
16978 /* Handle DW_TAG_restrict_type.  */
16979
16980 static struct type *
16981 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
16982 {
16983   struct type *base_type, *cv_type;
16984
16985   base_type = die_type (die, cu);
16986
16987   /* The die_type call above may have already set the type for this DIE.  */
16988   cv_type = get_die_type (die, cu);
16989   if (cv_type)
16990     return cv_type;
16991
16992   cv_type = make_restrict_type (base_type);
16993   return set_die_type (die, cv_type, cu);
16994 }
16995
16996 /* Handle DW_TAG_atomic_type.  */
16997
16998 static struct type *
16999 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17000 {
17001   struct type *base_type, *cv_type;
17002
17003   base_type = die_type (die, cu);
17004
17005   /* The die_type call above may have already set the type for this DIE.  */
17006   cv_type = get_die_type (die, cu);
17007   if (cv_type)
17008     return cv_type;
17009
17010   cv_type = make_atomic_type (base_type);
17011   return set_die_type (die, cv_type, cu);
17012 }
17013
17014 /* Extract all information from a DW_TAG_string_type DIE and add to
17015    the user defined type vector.  It isn't really a user defined type,
17016    but it behaves like one, with other DIE's using an AT_user_def_type
17017    attribute to reference it.  */
17018
17019 static struct type *
17020 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17021 {
17022   struct objfile *objfile = cu->objfile;
17023   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17024   struct type *type, *range_type, *index_type, *char_type;
17025   struct attribute *attr;
17026   unsigned int length;
17027
17028   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17029   if (attr)
17030     {
17031       length = DW_UNSND (attr);
17032     }
17033   else
17034     {
17035       /* Check for the DW_AT_byte_size attribute.  */
17036       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17037       if (attr)
17038         {
17039           length = DW_UNSND (attr);
17040         }
17041       else
17042         {
17043           length = 1;
17044         }
17045     }
17046
17047   index_type = objfile_type (objfile)->builtin_int;
17048   range_type = create_static_range_type (NULL, index_type, 1, length);
17049   char_type = language_string_char_type (cu->language_defn, gdbarch);
17050   type = create_string_type (NULL, char_type, range_type);
17051
17052   return set_die_type (die, type, cu);
17053 }
17054
17055 /* Assuming that DIE corresponds to a function, returns nonzero
17056    if the function is prototyped.  */
17057
17058 static int
17059 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17060 {
17061   struct attribute *attr;
17062
17063   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17064   if (attr && (DW_UNSND (attr) != 0))
17065     return 1;
17066
17067   /* The DWARF standard implies that the DW_AT_prototyped attribute
17068      is only meaninful for C, but the concept also extends to other
17069      languages that allow unprototyped functions (Eg: Objective C).
17070      For all other languages, assume that functions are always
17071      prototyped.  */
17072   if (cu->language != language_c
17073       && cu->language != language_objc
17074       && cu->language != language_opencl)
17075     return 1;
17076
17077   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17078      prototyped and unprototyped functions; default to prototyped,
17079      since that is more common in modern code (and RealView warns
17080      about unprototyped functions).  */
17081   if (producer_is_realview (cu->producer))
17082     return 1;
17083
17084   return 0;
17085 }
17086
17087 /* Handle DIES due to C code like:
17088
17089    struct foo
17090    {
17091    int (*funcp)(int a, long l);
17092    int b;
17093    };
17094
17095    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17096
17097 static struct type *
17098 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17099 {
17100   struct objfile *objfile = cu->objfile;
17101   struct type *type;            /* Type that this function returns.  */
17102   struct type *ftype;           /* Function that returns above type.  */
17103   struct attribute *attr;
17104
17105   type = die_type (die, cu);
17106
17107   /* The die_type call above may have already set the type for this DIE.  */
17108   ftype = get_die_type (die, cu);
17109   if (ftype)
17110     return ftype;
17111
17112   ftype = lookup_function_type (type);
17113
17114   if (prototyped_function_p (die, cu))
17115     TYPE_PROTOTYPED (ftype) = 1;
17116
17117   /* Store the calling convention in the type if it's available in
17118      the subroutine die.  Otherwise set the calling convention to
17119      the default value DW_CC_normal.  */
17120   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17121   if (attr)
17122     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17123   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17124     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17125   else
17126     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17127
17128   /* Record whether the function returns normally to its caller or not
17129      if the DWARF producer set that information.  */
17130   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17131   if (attr && (DW_UNSND (attr) != 0))
17132     TYPE_NO_RETURN (ftype) = 1;
17133
17134   /* We need to add the subroutine type to the die immediately so
17135      we don't infinitely recurse when dealing with parameters
17136      declared as the same subroutine type.  */
17137   set_die_type (die, ftype, cu);
17138
17139   if (die->child != NULL)
17140     {
17141       struct type *void_type = objfile_type (objfile)->builtin_void;
17142       struct die_info *child_die;
17143       int nparams, iparams;
17144
17145       /* Count the number of parameters.
17146          FIXME: GDB currently ignores vararg functions, but knows about
17147          vararg member functions.  */
17148       nparams = 0;
17149       child_die = die->child;
17150       while (child_die && child_die->tag)
17151         {
17152           if (child_die->tag == DW_TAG_formal_parameter)
17153             nparams++;
17154           else if (child_die->tag == DW_TAG_unspecified_parameters)
17155             TYPE_VARARGS (ftype) = 1;
17156           child_die = sibling_die (child_die);
17157         }
17158
17159       /* Allocate storage for parameters and fill them in.  */
17160       TYPE_NFIELDS (ftype) = nparams;
17161       TYPE_FIELDS (ftype) = (struct field *)
17162         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17163
17164       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17165          even if we error out during the parameters reading below.  */
17166       for (iparams = 0; iparams < nparams; iparams++)
17167         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17168
17169       iparams = 0;
17170       child_die = die->child;
17171       while (child_die && child_die->tag)
17172         {
17173           if (child_die->tag == DW_TAG_formal_parameter)
17174             {
17175               struct type *arg_type;
17176
17177               /* DWARF version 2 has no clean way to discern C++
17178                  static and non-static member functions.  G++ helps
17179                  GDB by marking the first parameter for non-static
17180                  member functions (which is the this pointer) as
17181                  artificial.  We pass this information to
17182                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17183
17184                  DWARF version 3 added DW_AT_object_pointer, which GCC
17185                  4.5 does not yet generate.  */
17186               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17187               if (attr)
17188                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17189               else
17190                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17191               arg_type = die_type (child_die, cu);
17192
17193               /* RealView does not mark THIS as const, which the testsuite
17194                  expects.  GCC marks THIS as const in method definitions,
17195                  but not in the class specifications (GCC PR 43053).  */
17196               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17197                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17198                 {
17199                   int is_this = 0;
17200                   struct dwarf2_cu *arg_cu = cu;
17201                   const char *name = dwarf2_name (child_die, cu);
17202
17203                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17204                   if (attr)
17205                     {
17206                       /* If the compiler emits this, use it.  */
17207                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17208                         is_this = 1;
17209                     }
17210                   else if (name && strcmp (name, "this") == 0)
17211                     /* Function definitions will have the argument names.  */
17212                     is_this = 1;
17213                   else if (name == NULL && iparams == 0)
17214                     /* Declarations may not have the names, so like
17215                        elsewhere in GDB, assume an artificial first
17216                        argument is "this".  */
17217                     is_this = 1;
17218
17219                   if (is_this)
17220                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17221                                              arg_type, 0);
17222                 }
17223
17224               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17225               iparams++;
17226             }
17227           child_die = sibling_die (child_die);
17228         }
17229     }
17230
17231   return ftype;
17232 }
17233
17234 static struct type *
17235 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17236 {
17237   struct objfile *objfile = cu->objfile;
17238   const char *name = NULL;
17239   struct type *this_type, *target_type;
17240
17241   name = dwarf2_full_name (NULL, die, cu);
17242   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17243   TYPE_TARGET_STUB (this_type) = 1;
17244   set_die_type (die, this_type, cu);
17245   target_type = die_type (die, cu);
17246   if (target_type != this_type)
17247     TYPE_TARGET_TYPE (this_type) = target_type;
17248   else
17249     {
17250       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17251          spec and cause infinite loops in GDB.  */
17252       complaint (&symfile_complaints,
17253                  _("Self-referential DW_TAG_typedef "
17254                    "- DIE at 0x%x [in module %s]"),
17255                  to_underlying (die->sect_off), objfile_name (objfile));
17256       TYPE_TARGET_TYPE (this_type) = NULL;
17257     }
17258   return this_type;
17259 }
17260
17261 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17262    (which may be different from NAME) to the architecture back-end to allow
17263    it to guess the correct format if necessary.  */
17264
17265 static struct type *
17266 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17267                         const char *name_hint)
17268 {
17269   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17270   const struct floatformat **format;
17271   struct type *type;
17272
17273   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17274   if (format)
17275     type = init_float_type (objfile, bits, name, format);
17276   else
17277     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17278
17279   return type;
17280 }
17281
17282 /* Find a representation of a given base type and install
17283    it in the TYPE field of the die.  */
17284
17285 static struct type *
17286 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17287 {
17288   struct objfile *objfile = cu->objfile;
17289   struct type *type;
17290   struct attribute *attr;
17291   int encoding = 0, bits = 0;
17292   const char *name;
17293
17294   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17295   if (attr)
17296     {
17297       encoding = DW_UNSND (attr);
17298     }
17299   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17300   if (attr)
17301     {
17302       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17303     }
17304   name = dwarf2_name (die, cu);
17305   if (!name)
17306     {
17307       complaint (&symfile_complaints,
17308                  _("DW_AT_name missing from DW_TAG_base_type"));
17309     }
17310
17311   switch (encoding)
17312     {
17313       case DW_ATE_address:
17314         /* Turn DW_ATE_address into a void * pointer.  */
17315         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17316         type = init_pointer_type (objfile, bits, name, type);
17317         break;
17318       case DW_ATE_boolean:
17319         type = init_boolean_type (objfile, bits, 1, name);
17320         break;
17321       case DW_ATE_complex_float:
17322         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17323         type = init_complex_type (objfile, name, type);
17324         break;
17325       case DW_ATE_decimal_float:
17326         type = init_decfloat_type (objfile, bits, name);
17327         break;
17328       case DW_ATE_float:
17329         type = dwarf2_init_float_type (objfile, bits, name, name);
17330         break;
17331       case DW_ATE_signed:
17332         type = init_integer_type (objfile, bits, 0, name);
17333         break;
17334       case DW_ATE_unsigned:
17335         if (cu->language == language_fortran
17336             && name
17337             && startswith (name, "character("))
17338           type = init_character_type (objfile, bits, 1, name);
17339         else
17340           type = init_integer_type (objfile, bits, 1, name);
17341         break;
17342       case DW_ATE_signed_char:
17343         if (cu->language == language_ada || cu->language == language_m2
17344             || cu->language == language_pascal
17345             || cu->language == language_fortran)
17346           type = init_character_type (objfile, bits, 0, name);
17347         else
17348           type = init_integer_type (objfile, bits, 0, name);
17349         break;
17350       case DW_ATE_unsigned_char:
17351         if (cu->language == language_ada || cu->language == language_m2
17352             || cu->language == language_pascal
17353             || cu->language == language_fortran
17354             || cu->language == language_rust)
17355           type = init_character_type (objfile, bits, 1, name);
17356         else
17357           type = init_integer_type (objfile, bits, 1, name);
17358         break;
17359       case DW_ATE_UTF:
17360         {
17361           gdbarch *arch = get_objfile_arch (objfile);
17362
17363           if (bits == 16)
17364             type = builtin_type (arch)->builtin_char16;
17365           else if (bits == 32)
17366             type = builtin_type (arch)->builtin_char32;
17367           else
17368             {
17369               complaint (&symfile_complaints,
17370                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17371                          bits);
17372               type = init_integer_type (objfile, bits, 1, name);
17373             }
17374           return set_die_type (die, type, cu);
17375         }
17376         break;
17377
17378       default:
17379         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17380                    dwarf_type_encoding_name (encoding));
17381         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17382         break;
17383     }
17384
17385   if (name && strcmp (name, "char") == 0)
17386     TYPE_NOSIGN (type) = 1;
17387
17388   return set_die_type (die, type, cu);
17389 }
17390
17391 /* Parse dwarf attribute if it's a block, reference or constant and put the
17392    resulting value of the attribute into struct bound_prop.
17393    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17394
17395 static int
17396 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17397                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17398 {
17399   struct dwarf2_property_baton *baton;
17400   struct obstack *obstack = &cu->objfile->objfile_obstack;
17401
17402   if (attr == NULL || prop == NULL)
17403     return 0;
17404
17405   if (attr_form_is_block (attr))
17406     {
17407       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17408       baton->referenced_type = NULL;
17409       baton->locexpr.per_cu = cu->per_cu;
17410       baton->locexpr.size = DW_BLOCK (attr)->size;
17411       baton->locexpr.data = DW_BLOCK (attr)->data;
17412       prop->data.baton = baton;
17413       prop->kind = PROP_LOCEXPR;
17414       gdb_assert (prop->data.baton != NULL);
17415     }
17416   else if (attr_form_is_ref (attr))
17417     {
17418       struct dwarf2_cu *target_cu = cu;
17419       struct die_info *target_die;
17420       struct attribute *target_attr;
17421
17422       target_die = follow_die_ref (die, attr, &target_cu);
17423       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17424       if (target_attr == NULL)
17425         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17426                                    target_cu);
17427       if (target_attr == NULL)
17428         return 0;
17429
17430       switch (target_attr->name)
17431         {
17432           case DW_AT_location:
17433             if (attr_form_is_section_offset (target_attr))
17434               {
17435                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17436                 baton->referenced_type = die_type (target_die, target_cu);
17437                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17438                 prop->data.baton = baton;
17439                 prop->kind = PROP_LOCLIST;
17440                 gdb_assert (prop->data.baton != NULL);
17441               }
17442             else if (attr_form_is_block (target_attr))
17443               {
17444                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17445                 baton->referenced_type = die_type (target_die, target_cu);
17446                 baton->locexpr.per_cu = cu->per_cu;
17447                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17448                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17449                 prop->data.baton = baton;
17450                 prop->kind = PROP_LOCEXPR;
17451                 gdb_assert (prop->data.baton != NULL);
17452               }
17453             else
17454               {
17455                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17456                                                        "dynamic property");
17457                 return 0;
17458               }
17459             break;
17460           case DW_AT_data_member_location:
17461             {
17462               LONGEST offset;
17463
17464               if (!handle_data_member_location (target_die, target_cu,
17465                                                 &offset))
17466                 return 0;
17467
17468               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17469               baton->referenced_type = read_type_die (target_die->parent,
17470                                                       target_cu);
17471               baton->offset_info.offset = offset;
17472               baton->offset_info.type = die_type (target_die, target_cu);
17473               prop->data.baton = baton;
17474               prop->kind = PROP_ADDR_OFFSET;
17475               break;
17476             }
17477         }
17478     }
17479   else if (attr_form_is_constant (attr))
17480     {
17481       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17482       prop->kind = PROP_CONST;
17483     }
17484   else
17485     {
17486       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17487                                              dwarf2_name (die, cu));
17488       return 0;
17489     }
17490
17491   return 1;
17492 }
17493
17494 /* Read the given DW_AT_subrange DIE.  */
17495
17496 static struct type *
17497 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17498 {
17499   struct type *base_type, *orig_base_type;
17500   struct type *range_type;
17501   struct attribute *attr;
17502   struct dynamic_prop low, high;
17503   int low_default_is_valid;
17504   int high_bound_is_count = 0;
17505   const char *name;
17506   LONGEST negative_mask;
17507
17508   orig_base_type = die_type (die, cu);
17509   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17510      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17511      creating the range type, but we use the result of check_typedef
17512      when examining properties of the type.  */
17513   base_type = check_typedef (orig_base_type);
17514
17515   /* The die_type call above may have already set the type for this DIE.  */
17516   range_type = get_die_type (die, cu);
17517   if (range_type)
17518     return range_type;
17519
17520   low.kind = PROP_CONST;
17521   high.kind = PROP_CONST;
17522   high.data.const_val = 0;
17523
17524   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17525      omitting DW_AT_lower_bound.  */
17526   switch (cu->language)
17527     {
17528     case language_c:
17529     case language_cplus:
17530       low.data.const_val = 0;
17531       low_default_is_valid = 1;
17532       break;
17533     case language_fortran:
17534       low.data.const_val = 1;
17535       low_default_is_valid = 1;
17536       break;
17537     case language_d:
17538     case language_objc:
17539     case language_rust:
17540       low.data.const_val = 0;
17541       low_default_is_valid = (cu->header.version >= 4);
17542       break;
17543     case language_ada:
17544     case language_m2:
17545     case language_pascal:
17546       low.data.const_val = 1;
17547       low_default_is_valid = (cu->header.version >= 4);
17548       break;
17549     default:
17550       low.data.const_val = 0;
17551       low_default_is_valid = 0;
17552       break;
17553     }
17554
17555   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17556   if (attr)
17557     attr_to_dynamic_prop (attr, die, cu, &low);
17558   else if (!low_default_is_valid)
17559     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17560                                       "- DIE at 0x%x [in module %s]"),
17561                to_underlying (die->sect_off), objfile_name (cu->objfile));
17562
17563   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17564   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17565     {
17566       attr = dwarf2_attr (die, DW_AT_count, cu);
17567       if (attr_to_dynamic_prop (attr, die, cu, &high))
17568         {
17569           /* If bounds are constant do the final calculation here.  */
17570           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17571             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17572           else
17573             high_bound_is_count = 1;
17574         }
17575     }
17576
17577   /* Dwarf-2 specifications explicitly allows to create subrange types
17578      without specifying a base type.
17579      In that case, the base type must be set to the type of
17580      the lower bound, upper bound or count, in that order, if any of these
17581      three attributes references an object that has a type.
17582      If no base type is found, the Dwarf-2 specifications say that
17583      a signed integer type of size equal to the size of an address should
17584      be used.
17585      For the following C code: `extern char gdb_int [];'
17586      GCC produces an empty range DIE.
17587      FIXME: muller/2010-05-28: Possible references to object for low bound,
17588      high bound or count are not yet handled by this code.  */
17589   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17590     {
17591       struct objfile *objfile = cu->objfile;
17592       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17593       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17594       struct type *int_type = objfile_type (objfile)->builtin_int;
17595
17596       /* Test "int", "long int", and "long long int" objfile types,
17597          and select the first one having a size above or equal to the
17598          architecture address size.  */
17599       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17600         base_type = int_type;
17601       else
17602         {
17603           int_type = objfile_type (objfile)->builtin_long;
17604           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17605             base_type = int_type;
17606           else
17607             {
17608               int_type = objfile_type (objfile)->builtin_long_long;
17609               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17610                 base_type = int_type;
17611             }
17612         }
17613     }
17614
17615   /* Normally, the DWARF producers are expected to use a signed
17616      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17617      But this is unfortunately not always the case, as witnessed
17618      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17619      is used instead.  To work around that ambiguity, we treat
17620      the bounds as signed, and thus sign-extend their values, when
17621      the base type is signed.  */
17622   negative_mask =
17623     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17624   if (low.kind == PROP_CONST
17625       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17626     low.data.const_val |= negative_mask;
17627   if (high.kind == PROP_CONST
17628       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17629     high.data.const_val |= negative_mask;
17630
17631   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17632
17633   if (high_bound_is_count)
17634     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17635
17636   /* Ada expects an empty array on no boundary attributes.  */
17637   if (attr == NULL && cu->language != language_ada)
17638     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17639
17640   name = dwarf2_name (die, cu);
17641   if (name)
17642     TYPE_NAME (range_type) = name;
17643
17644   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17645   if (attr)
17646     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17647
17648   set_die_type (die, range_type, cu);
17649
17650   /* set_die_type should be already done.  */
17651   set_descriptive_type (range_type, die, cu);
17652
17653   return range_type;
17654 }
17655
17656 static struct type *
17657 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17658 {
17659   struct type *type;
17660
17661   /* For now, we only support the C meaning of an unspecified type: void.  */
17662
17663   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
17664   TYPE_NAME (type) = dwarf2_name (die, cu);
17665
17666   return set_die_type (die, type, cu);
17667 }
17668
17669 /* Read a single die and all its descendents.  Set the die's sibling
17670    field to NULL; set other fields in the die correctly, and set all
17671    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17672    location of the info_ptr after reading all of those dies.  PARENT
17673    is the parent of the die in question.  */
17674
17675 static struct die_info *
17676 read_die_and_children (const struct die_reader_specs *reader,
17677                        const gdb_byte *info_ptr,
17678                        const gdb_byte **new_info_ptr,
17679                        struct die_info *parent)
17680 {
17681   struct die_info *die;
17682   const gdb_byte *cur_ptr;
17683   int has_children;
17684
17685   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17686   if (die == NULL)
17687     {
17688       *new_info_ptr = cur_ptr;
17689       return NULL;
17690     }
17691   store_in_ref_table (die, reader->cu);
17692
17693   if (has_children)
17694     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17695   else
17696     {
17697       die->child = NULL;
17698       *new_info_ptr = cur_ptr;
17699     }
17700
17701   die->sibling = NULL;
17702   die->parent = parent;
17703   return die;
17704 }
17705
17706 /* Read a die, all of its descendents, and all of its siblings; set
17707    all of the fields of all of the dies correctly.  Arguments are as
17708    in read_die_and_children.  */
17709
17710 static struct die_info *
17711 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17712                          const gdb_byte *info_ptr,
17713                          const gdb_byte **new_info_ptr,
17714                          struct die_info *parent)
17715 {
17716   struct die_info *first_die, *last_sibling;
17717   const gdb_byte *cur_ptr;
17718
17719   cur_ptr = info_ptr;
17720   first_die = last_sibling = NULL;
17721
17722   while (1)
17723     {
17724       struct die_info *die
17725         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17726
17727       if (die == NULL)
17728         {
17729           *new_info_ptr = cur_ptr;
17730           return first_die;
17731         }
17732
17733       if (!first_die)
17734         first_die = die;
17735       else
17736         last_sibling->sibling = die;
17737
17738       last_sibling = die;
17739     }
17740 }
17741
17742 /* Read a die, all of its descendents, and all of its siblings; set
17743    all of the fields of all of the dies correctly.  Arguments are as
17744    in read_die_and_children.
17745    This the main entry point for reading a DIE and all its children.  */
17746
17747 static struct die_info *
17748 read_die_and_siblings (const struct die_reader_specs *reader,
17749                        const gdb_byte *info_ptr,
17750                        const gdb_byte **new_info_ptr,
17751                        struct die_info *parent)
17752 {
17753   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17754                                                   new_info_ptr, parent);
17755
17756   if (dwarf_die_debug)
17757     {
17758       fprintf_unfiltered (gdb_stdlog,
17759                           "Read die from %s@0x%x of %s:\n",
17760                           get_section_name (reader->die_section),
17761                           (unsigned) (info_ptr - reader->die_section->buffer),
17762                           bfd_get_filename (reader->abfd));
17763       dump_die (die, dwarf_die_debug);
17764     }
17765
17766   return die;
17767 }
17768
17769 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17770    attributes.
17771    The caller is responsible for filling in the extra attributes
17772    and updating (*DIEP)->num_attrs.
17773    Set DIEP to point to a newly allocated die with its information,
17774    except for its child, sibling, and parent fields.
17775    Set HAS_CHILDREN to tell whether the die has children or not.  */
17776
17777 static const gdb_byte *
17778 read_full_die_1 (const struct die_reader_specs *reader,
17779                  struct die_info **diep, const gdb_byte *info_ptr,
17780                  int *has_children, int num_extra_attrs)
17781 {
17782   unsigned int abbrev_number, bytes_read, i;
17783   struct abbrev_info *abbrev;
17784   struct die_info *die;
17785   struct dwarf2_cu *cu = reader->cu;
17786   bfd *abfd = reader->abfd;
17787
17788   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17789   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17790   info_ptr += bytes_read;
17791   if (!abbrev_number)
17792     {
17793       *diep = NULL;
17794       *has_children = 0;
17795       return info_ptr;
17796     }
17797
17798   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
17799   if (!abbrev)
17800     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17801            abbrev_number,
17802            bfd_get_filename (abfd));
17803
17804   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17805   die->sect_off = sect_off;
17806   die->tag = abbrev->tag;
17807   die->abbrev = abbrev_number;
17808
17809   /* Make the result usable.
17810      The caller needs to update num_attrs after adding the extra
17811      attributes.  */
17812   die->num_attrs = abbrev->num_attrs;
17813
17814   for (i = 0; i < abbrev->num_attrs; ++i)
17815     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17816                                info_ptr);
17817
17818   *diep = die;
17819   *has_children = abbrev->has_children;
17820   return info_ptr;
17821 }
17822
17823 /* Read a die and all its attributes.
17824    Set DIEP to point to a newly allocated die with its information,
17825    except for its child, sibling, and parent fields.
17826    Set HAS_CHILDREN to tell whether the die has children or not.  */
17827
17828 static const gdb_byte *
17829 read_full_die (const struct die_reader_specs *reader,
17830                struct die_info **diep, const gdb_byte *info_ptr,
17831                int *has_children)
17832 {
17833   const gdb_byte *result;
17834
17835   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17836
17837   if (dwarf_die_debug)
17838     {
17839       fprintf_unfiltered (gdb_stdlog,
17840                           "Read die from %s@0x%x of %s:\n",
17841                           get_section_name (reader->die_section),
17842                           (unsigned) (info_ptr - reader->die_section->buffer),
17843                           bfd_get_filename (reader->abfd));
17844       dump_die (*diep, dwarf_die_debug);
17845     }
17846
17847   return result;
17848 }
17849 \f
17850 /* Abbreviation tables.
17851
17852    In DWARF version 2, the description of the debugging information is
17853    stored in a separate .debug_abbrev section.  Before we read any
17854    dies from a section we read in all abbreviations and install them
17855    in a hash table.  */
17856
17857 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17858
17859 static struct abbrev_info *
17860 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
17861 {
17862   struct abbrev_info *abbrev;
17863
17864   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
17865   memset (abbrev, 0, sizeof (struct abbrev_info));
17866
17867   return abbrev;
17868 }
17869
17870 /* Add an abbreviation to the table.  */
17871
17872 static void
17873 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
17874                          unsigned int abbrev_number,
17875                          struct abbrev_info *abbrev)
17876 {
17877   unsigned int hash_number;
17878
17879   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17880   abbrev->next = abbrev_table->abbrevs[hash_number];
17881   abbrev_table->abbrevs[hash_number] = abbrev;
17882 }
17883
17884 /* Look up an abbrev in the table.
17885    Returns NULL if the abbrev is not found.  */
17886
17887 static struct abbrev_info *
17888 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
17889                             unsigned int abbrev_number)
17890 {
17891   unsigned int hash_number;
17892   struct abbrev_info *abbrev;
17893
17894   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17895   abbrev = abbrev_table->abbrevs[hash_number];
17896
17897   while (abbrev)
17898     {
17899       if (abbrev->number == abbrev_number)
17900         return abbrev;
17901       abbrev = abbrev->next;
17902     }
17903   return NULL;
17904 }
17905
17906 /* Read in an abbrev table.  */
17907
17908 static struct abbrev_table *
17909 abbrev_table_read_table (struct dwarf2_section_info *section,
17910                          sect_offset sect_off)
17911 {
17912   struct objfile *objfile = dwarf2_per_objfile->objfile;
17913   bfd *abfd = get_section_bfd_owner (section);
17914   struct abbrev_table *abbrev_table;
17915   const gdb_byte *abbrev_ptr;
17916   struct abbrev_info *cur_abbrev;
17917   unsigned int abbrev_number, bytes_read, abbrev_name;
17918   unsigned int abbrev_form;
17919   struct attr_abbrev *cur_attrs;
17920   unsigned int allocated_attrs;
17921
17922   abbrev_table = XNEW (struct abbrev_table);
17923   abbrev_table->sect_off = sect_off;
17924   obstack_init (&abbrev_table->abbrev_obstack);
17925   abbrev_table->abbrevs =
17926     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
17927                ABBREV_HASH_SIZE);
17928   memset (abbrev_table->abbrevs, 0,
17929           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
17930
17931   dwarf2_read_section (objfile, section);
17932   abbrev_ptr = section->buffer + to_underlying (sect_off);
17933   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17934   abbrev_ptr += bytes_read;
17935
17936   allocated_attrs = ATTR_ALLOC_CHUNK;
17937   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
17938
17939   /* Loop until we reach an abbrev number of 0.  */
17940   while (abbrev_number)
17941     {
17942       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
17943
17944       /* read in abbrev header */
17945       cur_abbrev->number = abbrev_number;
17946       cur_abbrev->tag
17947         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17948       abbrev_ptr += bytes_read;
17949       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
17950       abbrev_ptr += 1;
17951
17952       /* now read in declarations */
17953       for (;;)
17954         {
17955           LONGEST implicit_const;
17956
17957           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17958           abbrev_ptr += bytes_read;
17959           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17960           abbrev_ptr += bytes_read;
17961           if (abbrev_form == DW_FORM_implicit_const)
17962             {
17963               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
17964                                                    &bytes_read);
17965               abbrev_ptr += bytes_read;
17966             }
17967           else
17968             {
17969               /* Initialize it due to a false compiler warning.  */
17970               implicit_const = -1;
17971             }
17972
17973           if (abbrev_name == 0)
17974             break;
17975
17976           if (cur_abbrev->num_attrs == allocated_attrs)
17977             {
17978               allocated_attrs += ATTR_ALLOC_CHUNK;
17979               cur_attrs
17980                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
17981             }
17982
17983           cur_attrs[cur_abbrev->num_attrs].name
17984             = (enum dwarf_attribute) abbrev_name;
17985           cur_attrs[cur_abbrev->num_attrs].form
17986             = (enum dwarf_form) abbrev_form;
17987           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
17988           ++cur_abbrev->num_attrs;
17989         }
17990
17991       cur_abbrev->attrs =
17992         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
17993                    cur_abbrev->num_attrs);
17994       memcpy (cur_abbrev->attrs, cur_attrs,
17995               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
17996
17997       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
17998
17999       /* Get next abbreviation.
18000          Under Irix6 the abbreviations for a compilation unit are not
18001          always properly terminated with an abbrev number of 0.
18002          Exit loop if we encounter an abbreviation which we have
18003          already read (which means we are about to read the abbreviations
18004          for the next compile unit) or if the end of the abbreviation
18005          table is reached.  */
18006       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18007         break;
18008       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18009       abbrev_ptr += bytes_read;
18010       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
18011         break;
18012     }
18013
18014   xfree (cur_attrs);
18015   return abbrev_table;
18016 }
18017
18018 /* Free the resources held by ABBREV_TABLE.  */
18019
18020 static void
18021 abbrev_table_free (struct abbrev_table *abbrev_table)
18022 {
18023   obstack_free (&abbrev_table->abbrev_obstack, NULL);
18024   xfree (abbrev_table);
18025 }
18026
18027 /* Same as abbrev_table_free but as a cleanup.
18028    We pass in a pointer to the pointer to the table so that we can
18029    set the pointer to NULL when we're done.  It also simplifies
18030    build_type_psymtabs_1.  */
18031
18032 static void
18033 abbrev_table_free_cleanup (void *table_ptr)
18034 {
18035   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
18036
18037   if (*abbrev_table_ptr != NULL)
18038     abbrev_table_free (*abbrev_table_ptr);
18039   *abbrev_table_ptr = NULL;
18040 }
18041
18042 /* Read the abbrev table for CU from ABBREV_SECTION.  */
18043
18044 static void
18045 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
18046                      struct dwarf2_section_info *abbrev_section)
18047 {
18048   cu->abbrev_table =
18049     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
18050 }
18051
18052 /* Release the memory used by the abbrev table for a compilation unit.  */
18053
18054 static void
18055 dwarf2_free_abbrev_table (void *ptr_to_cu)
18056 {
18057   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
18058
18059   if (cu->abbrev_table != NULL)
18060     abbrev_table_free (cu->abbrev_table);
18061   /* Set this to NULL so that we SEGV if we try to read it later,
18062      and also because free_comp_unit verifies this is NULL.  */
18063   cu->abbrev_table = NULL;
18064 }
18065 \f
18066 /* Returns nonzero if TAG represents a type that we might generate a partial
18067    symbol for.  */
18068
18069 static int
18070 is_type_tag_for_partial (int tag)
18071 {
18072   switch (tag)
18073     {
18074 #if 0
18075     /* Some types that would be reasonable to generate partial symbols for,
18076        that we don't at present.  */
18077     case DW_TAG_array_type:
18078     case DW_TAG_file_type:
18079     case DW_TAG_ptr_to_member_type:
18080     case DW_TAG_set_type:
18081     case DW_TAG_string_type:
18082     case DW_TAG_subroutine_type:
18083 #endif
18084     case DW_TAG_base_type:
18085     case DW_TAG_class_type:
18086     case DW_TAG_interface_type:
18087     case DW_TAG_enumeration_type:
18088     case DW_TAG_structure_type:
18089     case DW_TAG_subrange_type:
18090     case DW_TAG_typedef:
18091     case DW_TAG_union_type:
18092       return 1;
18093     default:
18094       return 0;
18095     }
18096 }
18097
18098 /* Load all DIEs that are interesting for partial symbols into memory.  */
18099
18100 static struct partial_die_info *
18101 load_partial_dies (const struct die_reader_specs *reader,
18102                    const gdb_byte *info_ptr, int building_psymtab)
18103 {
18104   struct dwarf2_cu *cu = reader->cu;
18105   struct objfile *objfile = cu->objfile;
18106   struct partial_die_info *part_die;
18107   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18108   struct abbrev_info *abbrev;
18109   unsigned int bytes_read;
18110   unsigned int load_all = 0;
18111   int nesting_level = 1;
18112
18113   parent_die = NULL;
18114   last_die = NULL;
18115
18116   gdb_assert (cu->per_cu != NULL);
18117   if (cu->per_cu->load_all_dies)
18118     load_all = 1;
18119
18120   cu->partial_dies
18121     = htab_create_alloc_ex (cu->header.length / 12,
18122                             partial_die_hash,
18123                             partial_die_eq,
18124                             NULL,
18125                             &cu->comp_unit_obstack,
18126                             hashtab_obstack_allocate,
18127                             dummy_obstack_deallocate);
18128
18129   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18130
18131   while (1)
18132     {
18133       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
18134
18135       /* A NULL abbrev means the end of a series of children.  */
18136       if (abbrev == NULL)
18137         {
18138           if (--nesting_level == 0)
18139             {
18140               /* PART_DIE was probably the last thing allocated on the
18141                  comp_unit_obstack, so we could call obstack_free
18142                  here.  We don't do that because the waste is small,
18143                  and will be cleaned up when we're done with this
18144                  compilation unit.  This way, we're also more robust
18145                  against other users of the comp_unit_obstack.  */
18146               return first_die;
18147             }
18148           info_ptr += bytes_read;
18149           last_die = parent_die;
18150           parent_die = parent_die->die_parent;
18151           continue;
18152         }
18153
18154       /* Check for template arguments.  We never save these; if
18155          they're seen, we just mark the parent, and go on our way.  */
18156       if (parent_die != NULL
18157           && cu->language == language_cplus
18158           && (abbrev->tag == DW_TAG_template_type_param
18159               || abbrev->tag == DW_TAG_template_value_param))
18160         {
18161           parent_die->has_template_arguments = 1;
18162
18163           if (!load_all)
18164             {
18165               /* We don't need a partial DIE for the template argument.  */
18166               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18167               continue;
18168             }
18169         }
18170
18171       /* We only recurse into c++ subprograms looking for template arguments.
18172          Skip their other children.  */
18173       if (!load_all
18174           && cu->language == language_cplus
18175           && parent_die != NULL
18176           && parent_die->tag == DW_TAG_subprogram)
18177         {
18178           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18179           continue;
18180         }
18181
18182       /* Check whether this DIE is interesting enough to save.  Normally
18183          we would not be interested in members here, but there may be
18184          later variables referencing them via DW_AT_specification (for
18185          static members).  */
18186       if (!load_all
18187           && !is_type_tag_for_partial (abbrev->tag)
18188           && abbrev->tag != DW_TAG_constant
18189           && abbrev->tag != DW_TAG_enumerator
18190           && abbrev->tag != DW_TAG_subprogram
18191           && abbrev->tag != DW_TAG_lexical_block
18192           && abbrev->tag != DW_TAG_variable
18193           && abbrev->tag != DW_TAG_namespace
18194           && abbrev->tag != DW_TAG_module
18195           && abbrev->tag != DW_TAG_member
18196           && abbrev->tag != DW_TAG_imported_unit
18197           && abbrev->tag != DW_TAG_imported_declaration)
18198         {
18199           /* Otherwise we skip to the next sibling, if any.  */
18200           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18201           continue;
18202         }
18203
18204       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18205                                    info_ptr);
18206
18207       /* This two-pass algorithm for processing partial symbols has a
18208          high cost in cache pressure.  Thus, handle some simple cases
18209          here which cover the majority of C partial symbols.  DIEs
18210          which neither have specification tags in them, nor could have
18211          specification tags elsewhere pointing at them, can simply be
18212          processed and discarded.
18213
18214          This segment is also optional; scan_partial_symbols and
18215          add_partial_symbol will handle these DIEs if we chain
18216          them in normally.  When compilers which do not emit large
18217          quantities of duplicate debug information are more common,
18218          this code can probably be removed.  */
18219
18220       /* Any complete simple types at the top level (pretty much all
18221          of them, for a language without namespaces), can be processed
18222          directly.  */
18223       if (parent_die == NULL
18224           && part_die->has_specification == 0
18225           && part_die->is_declaration == 0
18226           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18227               || part_die->tag == DW_TAG_base_type
18228               || part_die->tag == DW_TAG_subrange_type))
18229         {
18230           if (building_psymtab && part_die->name != NULL)
18231             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18232                                  VAR_DOMAIN, LOC_TYPEDEF,
18233                                  &objfile->static_psymbols,
18234                                  0, cu->language, objfile);
18235           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18236           continue;
18237         }
18238
18239       /* The exception for DW_TAG_typedef with has_children above is
18240          a workaround of GCC PR debug/47510.  In the case of this complaint
18241          type_name_no_tag_or_error will error on such types later.
18242
18243          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18244          it could not find the child DIEs referenced later, this is checked
18245          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18246
18247       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18248         complaint (&symfile_complaints,
18249                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18250                      "- DIE at 0x%x [in module %s]"),
18251                    to_underlying (part_die->sect_off), objfile_name (objfile));
18252
18253       /* If we're at the second level, and we're an enumerator, and
18254          our parent has no specification (meaning possibly lives in a
18255          namespace elsewhere), then we can add the partial symbol now
18256          instead of queueing it.  */
18257       if (part_die->tag == DW_TAG_enumerator
18258           && parent_die != NULL
18259           && parent_die->die_parent == NULL
18260           && parent_die->tag == DW_TAG_enumeration_type
18261           && parent_die->has_specification == 0)
18262         {
18263           if (part_die->name == NULL)
18264             complaint (&symfile_complaints,
18265                        _("malformed enumerator DIE ignored"));
18266           else if (building_psymtab)
18267             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18268                                  VAR_DOMAIN, LOC_CONST,
18269                                  cu->language == language_cplus
18270                                  ? &objfile->global_psymbols
18271                                  : &objfile->static_psymbols,
18272                                  0, cu->language, objfile);
18273
18274           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18275           continue;
18276         }
18277
18278       /* We'll save this DIE so link it in.  */
18279       part_die->die_parent = parent_die;
18280       part_die->die_sibling = NULL;
18281       part_die->die_child = NULL;
18282
18283       if (last_die && last_die == parent_die)
18284         last_die->die_child = part_die;
18285       else if (last_die)
18286         last_die->die_sibling = part_die;
18287
18288       last_die = part_die;
18289
18290       if (first_die == NULL)
18291         first_die = part_die;
18292
18293       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18294          find interesting need to be in the hash table, because we
18295          also have the parent/sibling/child chains; only those that we
18296          might refer to by offset later during partial symbol reading.
18297
18298          For now this means things that might have be the target of a
18299          DW_AT_specification, DW_AT_abstract_origin, or
18300          DW_AT_extension.  DW_AT_extension will refer only to
18301          namespaces; DW_AT_abstract_origin refers to functions (and
18302          many things under the function DIE, but we do not recurse
18303          into function DIEs during partial symbol reading) and
18304          possibly variables as well; DW_AT_specification refers to
18305          declarations.  Declarations ought to have the DW_AT_declaration
18306          flag.  It happens that GCC forgets to put it in sometimes, but
18307          only for functions, not for types.
18308
18309          Adding more things than necessary to the hash table is harmless
18310          except for the performance cost.  Adding too few will result in
18311          wasted time in find_partial_die, when we reread the compilation
18312          unit with load_all_dies set.  */
18313
18314       if (load_all
18315           || abbrev->tag == DW_TAG_constant
18316           || abbrev->tag == DW_TAG_subprogram
18317           || abbrev->tag == DW_TAG_variable
18318           || abbrev->tag == DW_TAG_namespace
18319           || part_die->is_declaration)
18320         {
18321           void **slot;
18322
18323           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18324                                            to_underlying (part_die->sect_off),
18325                                            INSERT);
18326           *slot = part_die;
18327         }
18328
18329       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18330
18331       /* For some DIEs we want to follow their children (if any).  For C
18332          we have no reason to follow the children of structures; for other
18333          languages we have to, so that we can get at method physnames
18334          to infer fully qualified class names, for DW_AT_specification,
18335          and for C++ template arguments.  For C++, we also look one level
18336          inside functions to find template arguments (if the name of the
18337          function does not already contain the template arguments).
18338
18339          For Ada, we need to scan the children of subprograms and lexical
18340          blocks as well because Ada allows the definition of nested
18341          entities that could be interesting for the debugger, such as
18342          nested subprograms for instance.  */
18343       if (last_die->has_children
18344           && (load_all
18345               || last_die->tag == DW_TAG_namespace
18346               || last_die->tag == DW_TAG_module
18347               || last_die->tag == DW_TAG_enumeration_type
18348               || (cu->language == language_cplus
18349                   && last_die->tag == DW_TAG_subprogram
18350                   && (last_die->name == NULL
18351                       || strchr (last_die->name, '<') == NULL))
18352               || (cu->language != language_c
18353                   && (last_die->tag == DW_TAG_class_type
18354                       || last_die->tag == DW_TAG_interface_type
18355                       || last_die->tag == DW_TAG_structure_type
18356                       || last_die->tag == DW_TAG_union_type))
18357               || (cu->language == language_ada
18358                   && (last_die->tag == DW_TAG_subprogram
18359                       || last_die->tag == DW_TAG_lexical_block))))
18360         {
18361           nesting_level++;
18362           parent_die = last_die;
18363           continue;
18364         }
18365
18366       /* Otherwise we skip to the next sibling, if any.  */
18367       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18368
18369       /* Back to the top, do it again.  */
18370     }
18371 }
18372
18373 /* Read a minimal amount of information into the minimal die structure.  */
18374
18375 static const gdb_byte *
18376 read_partial_die (const struct die_reader_specs *reader,
18377                   struct partial_die_info *part_die,
18378                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18379                   const gdb_byte *info_ptr)
18380 {
18381   struct dwarf2_cu *cu = reader->cu;
18382   struct objfile *objfile = cu->objfile;
18383   const gdb_byte *buffer = reader->buffer;
18384   unsigned int i;
18385   struct attribute attr;
18386   int has_low_pc_attr = 0;
18387   int has_high_pc_attr = 0;
18388   int high_pc_relative = 0;
18389
18390   memset (part_die, 0, sizeof (struct partial_die_info));
18391
18392   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18393
18394   info_ptr += abbrev_len;
18395
18396   if (abbrev == NULL)
18397     return info_ptr;
18398
18399   part_die->tag = abbrev->tag;
18400   part_die->has_children = abbrev->has_children;
18401
18402   for (i = 0; i < abbrev->num_attrs; ++i)
18403     {
18404       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18405
18406       /* Store the data if it is of an attribute we want to keep in a
18407          partial symbol table.  */
18408       switch (attr.name)
18409         {
18410         case DW_AT_name:
18411           switch (part_die->tag)
18412             {
18413             case DW_TAG_compile_unit:
18414             case DW_TAG_partial_unit:
18415             case DW_TAG_type_unit:
18416               /* Compilation units have a DW_AT_name that is a filename, not
18417                  a source language identifier.  */
18418             case DW_TAG_enumeration_type:
18419             case DW_TAG_enumerator:
18420               /* These tags always have simple identifiers already; no need
18421                  to canonicalize them.  */
18422               part_die->name = DW_STRING (&attr);
18423               break;
18424             default:
18425               part_die->name
18426                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18427                                             &objfile->per_bfd->storage_obstack);
18428               break;
18429             }
18430           break;
18431         case DW_AT_linkage_name:
18432         case DW_AT_MIPS_linkage_name:
18433           /* Note that both forms of linkage name might appear.  We
18434              assume they will be the same, and we only store the last
18435              one we see.  */
18436           if (cu->language == language_ada)
18437             part_die->name = DW_STRING (&attr);
18438           part_die->linkage_name = DW_STRING (&attr);
18439           break;
18440         case DW_AT_low_pc:
18441           has_low_pc_attr = 1;
18442           part_die->lowpc = attr_value_as_address (&attr);
18443           break;
18444         case DW_AT_high_pc:
18445           has_high_pc_attr = 1;
18446           part_die->highpc = attr_value_as_address (&attr);
18447           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18448                 high_pc_relative = 1;
18449           break;
18450         case DW_AT_location:
18451           /* Support the .debug_loc offsets.  */
18452           if (attr_form_is_block (&attr))
18453             {
18454                part_die->d.locdesc = DW_BLOCK (&attr);
18455             }
18456           else if (attr_form_is_section_offset (&attr))
18457             {
18458               dwarf2_complex_location_expr_complaint ();
18459             }
18460           else
18461             {
18462               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18463                                                      "partial symbol information");
18464             }
18465           break;
18466         case DW_AT_external:
18467           part_die->is_external = DW_UNSND (&attr);
18468           break;
18469         case DW_AT_declaration:
18470           part_die->is_declaration = DW_UNSND (&attr);
18471           break;
18472         case DW_AT_type:
18473           part_die->has_type = 1;
18474           break;
18475         case DW_AT_abstract_origin:
18476         case DW_AT_specification:
18477         case DW_AT_extension:
18478           part_die->has_specification = 1;
18479           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18480           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18481                                    || cu->per_cu->is_dwz);
18482           break;
18483         case DW_AT_sibling:
18484           /* Ignore absolute siblings, they might point outside of
18485              the current compile unit.  */
18486           if (attr.form == DW_FORM_ref_addr)
18487             complaint (&symfile_complaints,
18488                        _("ignoring absolute DW_AT_sibling"));
18489           else
18490             {
18491               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18492               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18493
18494               if (sibling_ptr < info_ptr)
18495                 complaint (&symfile_complaints,
18496                            _("DW_AT_sibling points backwards"));
18497               else if (sibling_ptr > reader->buffer_end)
18498                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18499               else
18500                 part_die->sibling = sibling_ptr;
18501             }
18502           break;
18503         case DW_AT_byte_size:
18504           part_die->has_byte_size = 1;
18505           break;
18506         case DW_AT_const_value:
18507           part_die->has_const_value = 1;
18508           break;
18509         case DW_AT_calling_convention:
18510           /* DWARF doesn't provide a way to identify a program's source-level
18511              entry point.  DW_AT_calling_convention attributes are only meant
18512              to describe functions' calling conventions.
18513
18514              However, because it's a necessary piece of information in
18515              Fortran, and before DWARF 4 DW_CC_program was the only
18516              piece of debugging information whose definition refers to
18517              a 'main program' at all, several compilers marked Fortran
18518              main programs with DW_CC_program --- even when those
18519              functions use the standard calling conventions.
18520
18521              Although DWARF now specifies a way to provide this
18522              information, we support this practice for backward
18523              compatibility.  */
18524           if (DW_UNSND (&attr) == DW_CC_program
18525               && cu->language == language_fortran)
18526             part_die->main_subprogram = 1;
18527           break;
18528         case DW_AT_inline:
18529           if (DW_UNSND (&attr) == DW_INL_inlined
18530               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18531             part_die->may_be_inlined = 1;
18532           break;
18533
18534         case DW_AT_import:
18535           if (part_die->tag == DW_TAG_imported_unit)
18536             {
18537               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18538               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18539                                   || cu->per_cu->is_dwz);
18540             }
18541           break;
18542
18543         case DW_AT_main_subprogram:
18544           part_die->main_subprogram = DW_UNSND (&attr);
18545           break;
18546
18547         default:
18548           break;
18549         }
18550     }
18551
18552   if (high_pc_relative)
18553     part_die->highpc += part_die->lowpc;
18554
18555   if (has_low_pc_attr && has_high_pc_attr)
18556     {
18557       /* When using the GNU linker, .gnu.linkonce. sections are used to
18558          eliminate duplicate copies of functions and vtables and such.
18559          The linker will arbitrarily choose one and discard the others.
18560          The AT_*_pc values for such functions refer to local labels in
18561          these sections.  If the section from that file was discarded, the
18562          labels are not in the output, so the relocs get a value of 0.
18563          If this is a discarded function, mark the pc bounds as invalid,
18564          so that GDB will ignore it.  */
18565       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18566         {
18567           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18568
18569           complaint (&symfile_complaints,
18570                      _("DW_AT_low_pc %s is zero "
18571                        "for DIE at 0x%x [in module %s]"),
18572                      paddress (gdbarch, part_die->lowpc),
18573                      to_underlying (part_die->sect_off), objfile_name (objfile));
18574         }
18575       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18576       else if (part_die->lowpc >= part_die->highpc)
18577         {
18578           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18579
18580           complaint (&symfile_complaints,
18581                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18582                        "for DIE at 0x%x [in module %s]"),
18583                      paddress (gdbarch, part_die->lowpc),
18584                      paddress (gdbarch, part_die->highpc),
18585                      to_underlying (part_die->sect_off),
18586                      objfile_name (objfile));
18587         }
18588       else
18589         part_die->has_pc_info = 1;
18590     }
18591
18592   return info_ptr;
18593 }
18594
18595 /* Find a cached partial DIE at OFFSET in CU.  */
18596
18597 static struct partial_die_info *
18598 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18599 {
18600   struct partial_die_info *lookup_die = NULL;
18601   struct partial_die_info part_die;
18602
18603   part_die.sect_off = sect_off;
18604   lookup_die = ((struct partial_die_info *)
18605                 htab_find_with_hash (cu->partial_dies, &part_die,
18606                                      to_underlying (sect_off)));
18607
18608   return lookup_die;
18609 }
18610
18611 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18612    except in the case of .debug_types DIEs which do not reference
18613    outside their CU (they do however referencing other types via
18614    DW_FORM_ref_sig8).  */
18615
18616 static struct partial_die_info *
18617 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18618 {
18619   struct objfile *objfile = cu->objfile;
18620   struct dwarf2_per_cu_data *per_cu = NULL;
18621   struct partial_die_info *pd = NULL;
18622
18623   if (offset_in_dwz == cu->per_cu->is_dwz
18624       && offset_in_cu_p (&cu->header, sect_off))
18625     {
18626       pd = find_partial_die_in_comp_unit (sect_off, cu);
18627       if (pd != NULL)
18628         return pd;
18629       /* We missed recording what we needed.
18630          Load all dies and try again.  */
18631       per_cu = cu->per_cu;
18632     }
18633   else
18634     {
18635       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18636       if (cu->per_cu->is_debug_types)
18637         {
18638           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18639                    " external reference to offset 0x%x [in module %s].\n"),
18640                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18641                  bfd_get_filename (objfile->obfd));
18642         }
18643       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18644                                                  objfile);
18645
18646       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18647         load_partial_comp_unit (per_cu);
18648
18649       per_cu->cu->last_used = 0;
18650       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18651     }
18652
18653   /* If we didn't find it, and not all dies have been loaded,
18654      load them all and try again.  */
18655
18656   if (pd == NULL && per_cu->load_all_dies == 0)
18657     {
18658       per_cu->load_all_dies = 1;
18659
18660       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18661          THIS_CU->cu may already be in use.  So we can't just free it and
18662          replace its DIEs with the ones we read in.  Instead, we leave those
18663          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18664          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18665          set.  */
18666       load_partial_comp_unit (per_cu);
18667
18668       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18669     }
18670
18671   if (pd == NULL)
18672     internal_error (__FILE__, __LINE__,
18673                     _("could not find partial DIE 0x%x "
18674                       "in cache [from module %s]\n"),
18675                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18676   return pd;
18677 }
18678
18679 /* See if we can figure out if the class lives in a namespace.  We do
18680    this by looking for a member function; its demangled name will
18681    contain namespace info, if there is any.  */
18682
18683 static void
18684 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18685                                   struct dwarf2_cu *cu)
18686 {
18687   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18688      what template types look like, because the demangler
18689      frequently doesn't give the same name as the debug info.  We
18690      could fix this by only using the demangled name to get the
18691      prefix (but see comment in read_structure_type).  */
18692
18693   struct partial_die_info *real_pdi;
18694   struct partial_die_info *child_pdi;
18695
18696   /* If this DIE (this DIE's specification, if any) has a parent, then
18697      we should not do this.  We'll prepend the parent's fully qualified
18698      name when we create the partial symbol.  */
18699
18700   real_pdi = struct_pdi;
18701   while (real_pdi->has_specification)
18702     real_pdi = find_partial_die (real_pdi->spec_offset,
18703                                  real_pdi->spec_is_dwz, cu);
18704
18705   if (real_pdi->die_parent != NULL)
18706     return;
18707
18708   for (child_pdi = struct_pdi->die_child;
18709        child_pdi != NULL;
18710        child_pdi = child_pdi->die_sibling)
18711     {
18712       if (child_pdi->tag == DW_TAG_subprogram
18713           && child_pdi->linkage_name != NULL)
18714         {
18715           char *actual_class_name
18716             = language_class_name_from_physname (cu->language_defn,
18717                                                  child_pdi->linkage_name);
18718           if (actual_class_name != NULL)
18719             {
18720               struct_pdi->name
18721                 = ((const char *)
18722                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18723                                   actual_class_name,
18724                                   strlen (actual_class_name)));
18725               xfree (actual_class_name);
18726             }
18727           break;
18728         }
18729     }
18730 }
18731
18732 /* Adjust PART_DIE before generating a symbol for it.  This function
18733    may set the is_external flag or change the DIE's name.  */
18734
18735 static void
18736 fixup_partial_die (struct partial_die_info *part_die,
18737                    struct dwarf2_cu *cu)
18738 {
18739   /* Once we've fixed up a die, there's no point in doing so again.
18740      This also avoids a memory leak if we were to call
18741      guess_partial_die_structure_name multiple times.  */
18742   if (part_die->fixup_called)
18743     return;
18744
18745   /* If we found a reference attribute and the DIE has no name, try
18746      to find a name in the referred to DIE.  */
18747
18748   if (part_die->name == NULL && part_die->has_specification)
18749     {
18750       struct partial_die_info *spec_die;
18751
18752       spec_die = find_partial_die (part_die->spec_offset,
18753                                    part_die->spec_is_dwz, cu);
18754
18755       fixup_partial_die (spec_die, cu);
18756
18757       if (spec_die->name)
18758         {
18759           part_die->name = spec_die->name;
18760
18761           /* Copy DW_AT_external attribute if it is set.  */
18762           if (spec_die->is_external)
18763             part_die->is_external = spec_die->is_external;
18764         }
18765     }
18766
18767   /* Set default names for some unnamed DIEs.  */
18768
18769   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18770     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18771
18772   /* If there is no parent die to provide a namespace, and there are
18773      children, see if we can determine the namespace from their linkage
18774      name.  */
18775   if (cu->language == language_cplus
18776       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
18777       && part_die->die_parent == NULL
18778       && part_die->has_children
18779       && (part_die->tag == DW_TAG_class_type
18780           || part_die->tag == DW_TAG_structure_type
18781           || part_die->tag == DW_TAG_union_type))
18782     guess_partial_die_structure_name (part_die, cu);
18783
18784   /* GCC might emit a nameless struct or union that has a linkage
18785      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18786   if (part_die->name == NULL
18787       && (part_die->tag == DW_TAG_class_type
18788           || part_die->tag == DW_TAG_interface_type
18789           || part_die->tag == DW_TAG_structure_type
18790           || part_die->tag == DW_TAG_union_type)
18791       && part_die->linkage_name != NULL)
18792     {
18793       char *demangled;
18794
18795       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
18796       if (demangled)
18797         {
18798           const char *base;
18799
18800           /* Strip any leading namespaces/classes, keep only the base name.
18801              DW_AT_name for named DIEs does not contain the prefixes.  */
18802           base = strrchr (demangled, ':');
18803           if (base && base > demangled && base[-1] == ':')
18804             base++;
18805           else
18806             base = demangled;
18807
18808           part_die->name
18809             = ((const char *)
18810                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
18811                               base, strlen (base)));
18812           xfree (demangled);
18813         }
18814     }
18815
18816   part_die->fixup_called = 1;
18817 }
18818
18819 /* Read an attribute value described by an attribute form.  */
18820
18821 static const gdb_byte *
18822 read_attribute_value (const struct die_reader_specs *reader,
18823                       struct attribute *attr, unsigned form,
18824                       LONGEST implicit_const, const gdb_byte *info_ptr)
18825 {
18826   struct dwarf2_cu *cu = reader->cu;
18827   struct objfile *objfile = cu->objfile;
18828   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18829   bfd *abfd = reader->abfd;
18830   struct comp_unit_head *cu_header = &cu->header;
18831   unsigned int bytes_read;
18832   struct dwarf_block *blk;
18833
18834   attr->form = (enum dwarf_form) form;
18835   switch (form)
18836     {
18837     case DW_FORM_ref_addr:
18838       if (cu->header.version == 2)
18839         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18840       else
18841         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18842                                        &cu->header, &bytes_read);
18843       info_ptr += bytes_read;
18844       break;
18845     case DW_FORM_GNU_ref_alt:
18846       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18847       info_ptr += bytes_read;
18848       break;
18849     case DW_FORM_addr:
18850       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18851       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18852       info_ptr += bytes_read;
18853       break;
18854     case DW_FORM_block2:
18855       blk = dwarf_alloc_block (cu);
18856       blk->size = read_2_bytes (abfd, info_ptr);
18857       info_ptr += 2;
18858       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18859       info_ptr += blk->size;
18860       DW_BLOCK (attr) = blk;
18861       break;
18862     case DW_FORM_block4:
18863       blk = dwarf_alloc_block (cu);
18864       blk->size = read_4_bytes (abfd, info_ptr);
18865       info_ptr += 4;
18866       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18867       info_ptr += blk->size;
18868       DW_BLOCK (attr) = blk;
18869       break;
18870     case DW_FORM_data2:
18871       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18872       info_ptr += 2;
18873       break;
18874     case DW_FORM_data4:
18875       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18876       info_ptr += 4;
18877       break;
18878     case DW_FORM_data8:
18879       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18880       info_ptr += 8;
18881       break;
18882     case DW_FORM_data16:
18883       blk = dwarf_alloc_block (cu);
18884       blk->size = 16;
18885       blk->data = read_n_bytes (abfd, info_ptr, 16);
18886       info_ptr += 16;
18887       DW_BLOCK (attr) = blk;
18888       break;
18889     case DW_FORM_sec_offset:
18890       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18891       info_ptr += bytes_read;
18892       break;
18893     case DW_FORM_string:
18894       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18895       DW_STRING_IS_CANONICAL (attr) = 0;
18896       info_ptr += bytes_read;
18897       break;
18898     case DW_FORM_strp:
18899       if (!cu->per_cu->is_dwz)
18900         {
18901           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
18902                                                    &bytes_read);
18903           DW_STRING_IS_CANONICAL (attr) = 0;
18904           info_ptr += bytes_read;
18905           break;
18906         }
18907       /* FALLTHROUGH */
18908     case DW_FORM_line_strp:
18909       if (!cu->per_cu->is_dwz)
18910         {
18911           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
18912                                                         cu_header, &bytes_read);
18913           DW_STRING_IS_CANONICAL (attr) = 0;
18914           info_ptr += bytes_read;
18915           break;
18916         }
18917       /* FALLTHROUGH */
18918     case DW_FORM_GNU_strp_alt:
18919       {
18920         struct dwz_file *dwz = dwarf2_get_dwz_file ();
18921         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18922                                           &bytes_read);
18923
18924         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
18925         DW_STRING_IS_CANONICAL (attr) = 0;
18926         info_ptr += bytes_read;
18927       }
18928       break;
18929     case DW_FORM_exprloc:
18930     case DW_FORM_block:
18931       blk = dwarf_alloc_block (cu);
18932       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18933       info_ptr += bytes_read;
18934       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18935       info_ptr += blk->size;
18936       DW_BLOCK (attr) = blk;
18937       break;
18938     case DW_FORM_block1:
18939       blk = dwarf_alloc_block (cu);
18940       blk->size = read_1_byte (abfd, info_ptr);
18941       info_ptr += 1;
18942       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18943       info_ptr += blk->size;
18944       DW_BLOCK (attr) = blk;
18945       break;
18946     case DW_FORM_data1:
18947       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18948       info_ptr += 1;
18949       break;
18950     case DW_FORM_flag:
18951       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18952       info_ptr += 1;
18953       break;
18954     case DW_FORM_flag_present:
18955       DW_UNSND (attr) = 1;
18956       break;
18957     case DW_FORM_sdata:
18958       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18959       info_ptr += bytes_read;
18960       break;
18961     case DW_FORM_udata:
18962       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18963       info_ptr += bytes_read;
18964       break;
18965     case DW_FORM_ref1:
18966       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18967                          + read_1_byte (abfd, info_ptr));
18968       info_ptr += 1;
18969       break;
18970     case DW_FORM_ref2:
18971       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18972                          + read_2_bytes (abfd, info_ptr));
18973       info_ptr += 2;
18974       break;
18975     case DW_FORM_ref4:
18976       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18977                          + read_4_bytes (abfd, info_ptr));
18978       info_ptr += 4;
18979       break;
18980     case DW_FORM_ref8:
18981       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18982                          + read_8_bytes (abfd, info_ptr));
18983       info_ptr += 8;
18984       break;
18985     case DW_FORM_ref_sig8:
18986       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18987       info_ptr += 8;
18988       break;
18989     case DW_FORM_ref_udata:
18990       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18991                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
18992       info_ptr += bytes_read;
18993       break;
18994     case DW_FORM_indirect:
18995       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18996       info_ptr += bytes_read;
18997       if (form == DW_FORM_implicit_const)
18998         {
18999           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19000           info_ptr += bytes_read;
19001         }
19002       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19003                                        info_ptr);
19004       break;
19005     case DW_FORM_implicit_const:
19006       DW_SND (attr) = implicit_const;
19007       break;
19008     case DW_FORM_GNU_addr_index:
19009       if (reader->dwo_file == NULL)
19010         {
19011           /* For now flag a hard error.
19012              Later we can turn this into a complaint.  */
19013           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19014                  dwarf_form_name (form),
19015                  bfd_get_filename (abfd));
19016         }
19017       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19018       info_ptr += bytes_read;
19019       break;
19020     case DW_FORM_GNU_str_index:
19021       if (reader->dwo_file == NULL)
19022         {
19023           /* For now flag a hard error.
19024              Later we can turn this into a complaint if warranted.  */
19025           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19026                  dwarf_form_name (form),
19027                  bfd_get_filename (abfd));
19028         }
19029       {
19030         ULONGEST str_index =
19031           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19032
19033         DW_STRING (attr) = read_str_index (reader, str_index);
19034         DW_STRING_IS_CANONICAL (attr) = 0;
19035         info_ptr += bytes_read;
19036       }
19037       break;
19038     default:
19039       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19040              dwarf_form_name (form),
19041              bfd_get_filename (abfd));
19042     }
19043
19044   /* Super hack.  */
19045   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19046     attr->form = DW_FORM_GNU_ref_alt;
19047
19048   /* We have seen instances where the compiler tried to emit a byte
19049      size attribute of -1 which ended up being encoded as an unsigned
19050      0xffffffff.  Although 0xffffffff is technically a valid size value,
19051      an object of this size seems pretty unlikely so we can relatively
19052      safely treat these cases as if the size attribute was invalid and
19053      treat them as zero by default.  */
19054   if (attr->name == DW_AT_byte_size
19055       && form == DW_FORM_data4
19056       && DW_UNSND (attr) >= 0xffffffff)
19057     {
19058       complaint
19059         (&symfile_complaints,
19060          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19061          hex_string (DW_UNSND (attr)));
19062       DW_UNSND (attr) = 0;
19063     }
19064
19065   return info_ptr;
19066 }
19067
19068 /* Read an attribute described by an abbreviated attribute.  */
19069
19070 static const gdb_byte *
19071 read_attribute (const struct die_reader_specs *reader,
19072                 struct attribute *attr, struct attr_abbrev *abbrev,
19073                 const gdb_byte *info_ptr)
19074 {
19075   attr->name = abbrev->name;
19076   return read_attribute_value (reader, attr, abbrev->form,
19077                                abbrev->implicit_const, info_ptr);
19078 }
19079
19080 /* Read dwarf information from a buffer.  */
19081
19082 static unsigned int
19083 read_1_byte (bfd *abfd, const gdb_byte *buf)
19084 {
19085   return bfd_get_8 (abfd, buf);
19086 }
19087
19088 static int
19089 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19090 {
19091   return bfd_get_signed_8 (abfd, buf);
19092 }
19093
19094 static unsigned int
19095 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19096 {
19097   return bfd_get_16 (abfd, buf);
19098 }
19099
19100 static int
19101 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19102 {
19103   return bfd_get_signed_16 (abfd, buf);
19104 }
19105
19106 static unsigned int
19107 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19108 {
19109   return bfd_get_32 (abfd, buf);
19110 }
19111
19112 static int
19113 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19114 {
19115   return bfd_get_signed_32 (abfd, buf);
19116 }
19117
19118 static ULONGEST
19119 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19120 {
19121   return bfd_get_64 (abfd, buf);
19122 }
19123
19124 static CORE_ADDR
19125 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19126               unsigned int *bytes_read)
19127 {
19128   struct comp_unit_head *cu_header = &cu->header;
19129   CORE_ADDR retval = 0;
19130
19131   if (cu_header->signed_addr_p)
19132     {
19133       switch (cu_header->addr_size)
19134         {
19135         case 2:
19136           retval = bfd_get_signed_16 (abfd, buf);
19137           break;
19138         case 4:
19139           retval = bfd_get_signed_32 (abfd, buf);
19140           break;
19141         case 8:
19142           retval = bfd_get_signed_64 (abfd, buf);
19143           break;
19144         default:
19145           internal_error (__FILE__, __LINE__,
19146                           _("read_address: bad switch, signed [in module %s]"),
19147                           bfd_get_filename (abfd));
19148         }
19149     }
19150   else
19151     {
19152       switch (cu_header->addr_size)
19153         {
19154         case 2:
19155           retval = bfd_get_16 (abfd, buf);
19156           break;
19157         case 4:
19158           retval = bfd_get_32 (abfd, buf);
19159           break;
19160         case 8:
19161           retval = bfd_get_64 (abfd, buf);
19162           break;
19163         default:
19164           internal_error (__FILE__, __LINE__,
19165                           _("read_address: bad switch, "
19166                             "unsigned [in module %s]"),
19167                           bfd_get_filename (abfd));
19168         }
19169     }
19170
19171   *bytes_read = cu_header->addr_size;
19172   return retval;
19173 }
19174
19175 /* Read the initial length from a section.  The (draft) DWARF 3
19176    specification allows the initial length to take up either 4 bytes
19177    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19178    bytes describe the length and all offsets will be 8 bytes in length
19179    instead of 4.
19180
19181    An older, non-standard 64-bit format is also handled by this
19182    function.  The older format in question stores the initial length
19183    as an 8-byte quantity without an escape value.  Lengths greater
19184    than 2^32 aren't very common which means that the initial 4 bytes
19185    is almost always zero.  Since a length value of zero doesn't make
19186    sense for the 32-bit format, this initial zero can be considered to
19187    be an escape value which indicates the presence of the older 64-bit
19188    format.  As written, the code can't detect (old format) lengths
19189    greater than 4GB.  If it becomes necessary to handle lengths
19190    somewhat larger than 4GB, we could allow other small values (such
19191    as the non-sensical values of 1, 2, and 3) to also be used as
19192    escape values indicating the presence of the old format.
19193
19194    The value returned via bytes_read should be used to increment the
19195    relevant pointer after calling read_initial_length().
19196
19197    [ Note:  read_initial_length() and read_offset() are based on the
19198      document entitled "DWARF Debugging Information Format", revision
19199      3, draft 8, dated November 19, 2001.  This document was obtained
19200      from:
19201
19202         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19203
19204      This document is only a draft and is subject to change.  (So beware.)
19205
19206      Details regarding the older, non-standard 64-bit format were
19207      determined empirically by examining 64-bit ELF files produced by
19208      the SGI toolchain on an IRIX 6.5 machine.
19209
19210      - Kevin, July 16, 2002
19211    ] */
19212
19213 static LONGEST
19214 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19215 {
19216   LONGEST length = bfd_get_32 (abfd, buf);
19217
19218   if (length == 0xffffffff)
19219     {
19220       length = bfd_get_64 (abfd, buf + 4);
19221       *bytes_read = 12;
19222     }
19223   else if (length == 0)
19224     {
19225       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19226       length = bfd_get_64 (abfd, buf);
19227       *bytes_read = 8;
19228     }
19229   else
19230     {
19231       *bytes_read = 4;
19232     }
19233
19234   return length;
19235 }
19236
19237 /* Cover function for read_initial_length.
19238    Returns the length of the object at BUF, and stores the size of the
19239    initial length in *BYTES_READ and stores the size that offsets will be in
19240    *OFFSET_SIZE.
19241    If the initial length size is not equivalent to that specified in
19242    CU_HEADER then issue a complaint.
19243    This is useful when reading non-comp-unit headers.  */
19244
19245 static LONGEST
19246 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19247                                         const struct comp_unit_head *cu_header,
19248                                         unsigned int *bytes_read,
19249                                         unsigned int *offset_size)
19250 {
19251   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19252
19253   gdb_assert (cu_header->initial_length_size == 4
19254               || cu_header->initial_length_size == 8
19255               || cu_header->initial_length_size == 12);
19256
19257   if (cu_header->initial_length_size != *bytes_read)
19258     complaint (&symfile_complaints,
19259                _("intermixed 32-bit and 64-bit DWARF sections"));
19260
19261   *offset_size = (*bytes_read == 4) ? 4 : 8;
19262   return length;
19263 }
19264
19265 /* Read an offset from the data stream.  The size of the offset is
19266    given by cu_header->offset_size.  */
19267
19268 static LONGEST
19269 read_offset (bfd *abfd, const gdb_byte *buf,
19270              const struct comp_unit_head *cu_header,
19271              unsigned int *bytes_read)
19272 {
19273   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19274
19275   *bytes_read = cu_header->offset_size;
19276   return offset;
19277 }
19278
19279 /* Read an offset from the data stream.  */
19280
19281 static LONGEST
19282 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19283 {
19284   LONGEST retval = 0;
19285
19286   switch (offset_size)
19287     {
19288     case 4:
19289       retval = bfd_get_32 (abfd, buf);
19290       break;
19291     case 8:
19292       retval = bfd_get_64 (abfd, buf);
19293       break;
19294     default:
19295       internal_error (__FILE__, __LINE__,
19296                       _("read_offset_1: bad switch [in module %s]"),
19297                       bfd_get_filename (abfd));
19298     }
19299
19300   return retval;
19301 }
19302
19303 static const gdb_byte *
19304 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19305 {
19306   /* If the size of a host char is 8 bits, we can return a pointer
19307      to the buffer, otherwise we have to copy the data to a buffer
19308      allocated on the temporary obstack.  */
19309   gdb_assert (HOST_CHAR_BIT == 8);
19310   return buf;
19311 }
19312
19313 static const char *
19314 read_direct_string (bfd *abfd, const gdb_byte *buf,
19315                     unsigned int *bytes_read_ptr)
19316 {
19317   /* If the size of a host char is 8 bits, we can return a pointer
19318      to the string, otherwise we have to copy the string to a buffer
19319      allocated on the temporary obstack.  */
19320   gdb_assert (HOST_CHAR_BIT == 8);
19321   if (*buf == '\0')
19322     {
19323       *bytes_read_ptr = 1;
19324       return NULL;
19325     }
19326   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19327   return (const char *) buf;
19328 }
19329
19330 /* Return pointer to string at section SECT offset STR_OFFSET with error
19331    reporting strings FORM_NAME and SECT_NAME.  */
19332
19333 static const char *
19334 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
19335                                      struct dwarf2_section_info *sect,
19336                                      const char *form_name,
19337                                      const char *sect_name)
19338 {
19339   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
19340   if (sect->buffer == NULL)
19341     error (_("%s used without %s section [in module %s]"),
19342            form_name, sect_name, bfd_get_filename (abfd));
19343   if (str_offset >= sect->size)
19344     error (_("%s pointing outside of %s section [in module %s]"),
19345            form_name, sect_name, bfd_get_filename (abfd));
19346   gdb_assert (HOST_CHAR_BIT == 8);
19347   if (sect->buffer[str_offset] == '\0')
19348     return NULL;
19349   return (const char *) (sect->buffer + str_offset);
19350 }
19351
19352 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19353
19354 static const char *
19355 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
19356 {
19357   return read_indirect_string_at_offset_from (abfd, str_offset,
19358                                               &dwarf2_per_objfile->str,
19359                                               "DW_FORM_strp", ".debug_str");
19360 }
19361
19362 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19363
19364 static const char *
19365 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
19366 {
19367   return read_indirect_string_at_offset_from (abfd, str_offset,
19368                                               &dwarf2_per_objfile->line_str,
19369                                               "DW_FORM_line_strp",
19370                                               ".debug_line_str");
19371 }
19372
19373 /* Read a string at offset STR_OFFSET in the .debug_str section from
19374    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19375    the string consists of a single NUL byte, return NULL; otherwise
19376    return a pointer to the string.  */
19377
19378 static const char *
19379 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
19380 {
19381   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
19382
19383   if (dwz->str.buffer == NULL)
19384     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19385              "section [in module %s]"),
19386            bfd_get_filename (dwz->dwz_bfd));
19387   if (str_offset >= dwz->str.size)
19388     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19389              ".debug_str section [in module %s]"),
19390            bfd_get_filename (dwz->dwz_bfd));
19391   gdb_assert (HOST_CHAR_BIT == 8);
19392   if (dwz->str.buffer[str_offset] == '\0')
19393     return NULL;
19394   return (const char *) (dwz->str.buffer + str_offset);
19395 }
19396
19397 /* Return pointer to string at .debug_str offset as read from BUF.
19398    BUF is assumed to be in a compilation unit described by CU_HEADER.
19399    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19400
19401 static const char *
19402 read_indirect_string (bfd *abfd, const gdb_byte *buf,
19403                       const struct comp_unit_head *cu_header,
19404                       unsigned int *bytes_read_ptr)
19405 {
19406   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19407
19408   return read_indirect_string_at_offset (abfd, str_offset);
19409 }
19410
19411 /* Return pointer to string at .debug_line_str offset as read from BUF.
19412    BUF is assumed to be in a compilation unit described by CU_HEADER.
19413    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19414
19415 static const char *
19416 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
19417                            const struct comp_unit_head *cu_header,
19418                            unsigned int *bytes_read_ptr)
19419 {
19420   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19421
19422   return read_indirect_line_string_at_offset (abfd, str_offset);
19423 }
19424
19425 ULONGEST
19426 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19427                           unsigned int *bytes_read_ptr)
19428 {
19429   ULONGEST result;
19430   unsigned int num_read;
19431   int shift;
19432   unsigned char byte;
19433
19434   result = 0;
19435   shift = 0;
19436   num_read = 0;
19437   while (1)
19438     {
19439       byte = bfd_get_8 (abfd, buf);
19440       buf++;
19441       num_read++;
19442       result |= ((ULONGEST) (byte & 127) << shift);
19443       if ((byte & 128) == 0)
19444         {
19445           break;
19446         }
19447       shift += 7;
19448     }
19449   *bytes_read_ptr = num_read;
19450   return result;
19451 }
19452
19453 static LONGEST
19454 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19455                     unsigned int *bytes_read_ptr)
19456 {
19457   LONGEST result;
19458   int shift, num_read;
19459   unsigned char byte;
19460
19461   result = 0;
19462   shift = 0;
19463   num_read = 0;
19464   while (1)
19465     {
19466       byte = bfd_get_8 (abfd, buf);
19467       buf++;
19468       num_read++;
19469       result |= ((LONGEST) (byte & 127) << shift);
19470       shift += 7;
19471       if ((byte & 128) == 0)
19472         {
19473           break;
19474         }
19475     }
19476   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19477     result |= -(((LONGEST) 1) << shift);
19478   *bytes_read_ptr = num_read;
19479   return result;
19480 }
19481
19482 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19483    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19484    ADDR_SIZE is the size of addresses from the CU header.  */
19485
19486 static CORE_ADDR
19487 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
19488 {
19489   struct objfile *objfile = dwarf2_per_objfile->objfile;
19490   bfd *abfd = objfile->obfd;
19491   const gdb_byte *info_ptr;
19492
19493   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19494   if (dwarf2_per_objfile->addr.buffer == NULL)
19495     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19496            objfile_name (objfile));
19497   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19498     error (_("DW_FORM_addr_index pointing outside of "
19499              ".debug_addr section [in module %s]"),
19500            objfile_name (objfile));
19501   info_ptr = (dwarf2_per_objfile->addr.buffer
19502               + addr_base + addr_index * addr_size);
19503   if (addr_size == 4)
19504     return bfd_get_32 (abfd, info_ptr);
19505   else
19506     return bfd_get_64 (abfd, info_ptr);
19507 }
19508
19509 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19510
19511 static CORE_ADDR
19512 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19513 {
19514   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
19515 }
19516
19517 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19518
19519 static CORE_ADDR
19520 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19521                              unsigned int *bytes_read)
19522 {
19523   bfd *abfd = cu->objfile->obfd;
19524   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19525
19526   return read_addr_index (cu, addr_index);
19527 }
19528
19529 /* Data structure to pass results from dwarf2_read_addr_index_reader
19530    back to dwarf2_read_addr_index.  */
19531
19532 struct dwarf2_read_addr_index_data
19533 {
19534   ULONGEST addr_base;
19535   int addr_size;
19536 };
19537
19538 /* die_reader_func for dwarf2_read_addr_index.  */
19539
19540 static void
19541 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19542                                const gdb_byte *info_ptr,
19543                                struct die_info *comp_unit_die,
19544                                int has_children,
19545                                void *data)
19546 {
19547   struct dwarf2_cu *cu = reader->cu;
19548   struct dwarf2_read_addr_index_data *aidata =
19549     (struct dwarf2_read_addr_index_data *) data;
19550
19551   aidata->addr_base = cu->addr_base;
19552   aidata->addr_size = cu->header.addr_size;
19553 }
19554
19555 /* Given an index in .debug_addr, fetch the value.
19556    NOTE: This can be called during dwarf expression evaluation,
19557    long after the debug information has been read, and thus per_cu->cu
19558    may no longer exist.  */
19559
19560 CORE_ADDR
19561 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19562                         unsigned int addr_index)
19563 {
19564   struct objfile *objfile = per_cu->objfile;
19565   struct dwarf2_cu *cu = per_cu->cu;
19566   ULONGEST addr_base;
19567   int addr_size;
19568
19569   /* This is intended to be called from outside this file.  */
19570   dw2_setup (objfile);
19571
19572   /* We need addr_base and addr_size.
19573      If we don't have PER_CU->cu, we have to get it.
19574      Nasty, but the alternative is storing the needed info in PER_CU,
19575      which at this point doesn't seem justified: it's not clear how frequently
19576      it would get used and it would increase the size of every PER_CU.
19577      Entry points like dwarf2_per_cu_addr_size do a similar thing
19578      so we're not in uncharted territory here.
19579      Alas we need to be a bit more complicated as addr_base is contained
19580      in the DIE.
19581
19582      We don't need to read the entire CU(/TU).
19583      We just need the header and top level die.
19584
19585      IWBN to use the aging mechanism to let us lazily later discard the CU.
19586      For now we skip this optimization.  */
19587
19588   if (cu != NULL)
19589     {
19590       addr_base = cu->addr_base;
19591       addr_size = cu->header.addr_size;
19592     }
19593   else
19594     {
19595       struct dwarf2_read_addr_index_data aidata;
19596
19597       /* Note: We can't use init_cutu_and_read_dies_simple here,
19598          we need addr_base.  */
19599       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19600                                dwarf2_read_addr_index_reader, &aidata);
19601       addr_base = aidata.addr_base;
19602       addr_size = aidata.addr_size;
19603     }
19604
19605   return read_addr_index_1 (addr_index, addr_base, addr_size);
19606 }
19607
19608 /* Given a DW_FORM_GNU_str_index, fetch the string.
19609    This is only used by the Fission support.  */
19610
19611 static const char *
19612 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19613 {
19614   struct objfile *objfile = dwarf2_per_objfile->objfile;
19615   const char *objf_name = objfile_name (objfile);
19616   bfd *abfd = objfile->obfd;
19617   struct dwarf2_cu *cu = reader->cu;
19618   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19619   struct dwarf2_section_info *str_offsets_section =
19620     &reader->dwo_file->sections.str_offsets;
19621   const gdb_byte *info_ptr;
19622   ULONGEST str_offset;
19623   static const char form_name[] = "DW_FORM_GNU_str_index";
19624
19625   dwarf2_read_section (objfile, str_section);
19626   dwarf2_read_section (objfile, str_offsets_section);
19627   if (str_section->buffer == NULL)
19628     error (_("%s used without .debug_str.dwo section"
19629              " in CU at offset 0x%x [in module %s]"),
19630            form_name, to_underlying (cu->header.sect_off), objf_name);
19631   if (str_offsets_section->buffer == NULL)
19632     error (_("%s used without .debug_str_offsets.dwo section"
19633              " in CU at offset 0x%x [in module %s]"),
19634            form_name, to_underlying (cu->header.sect_off), objf_name);
19635   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19636     error (_("%s pointing outside of .debug_str_offsets.dwo"
19637              " section in CU at offset 0x%x [in module %s]"),
19638            form_name, to_underlying (cu->header.sect_off), objf_name);
19639   info_ptr = (str_offsets_section->buffer
19640               + str_index * cu->header.offset_size);
19641   if (cu->header.offset_size == 4)
19642     str_offset = bfd_get_32 (abfd, info_ptr);
19643   else
19644     str_offset = bfd_get_64 (abfd, info_ptr);
19645   if (str_offset >= str_section->size)
19646     error (_("Offset from %s pointing outside of"
19647              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19648            form_name, to_underlying (cu->header.sect_off), objf_name);
19649   return (const char *) (str_section->buffer + str_offset);
19650 }
19651
19652 /* Return the length of an LEB128 number in BUF.  */
19653
19654 static int
19655 leb128_size (const gdb_byte *buf)
19656 {
19657   const gdb_byte *begin = buf;
19658   gdb_byte byte;
19659
19660   while (1)
19661     {
19662       byte = *buf++;
19663       if ((byte & 128) == 0)
19664         return buf - begin;
19665     }
19666 }
19667
19668 static void
19669 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19670 {
19671   switch (lang)
19672     {
19673     case DW_LANG_C89:
19674     case DW_LANG_C99:
19675     case DW_LANG_C11:
19676     case DW_LANG_C:
19677     case DW_LANG_UPC:
19678       cu->language = language_c;
19679       break;
19680     case DW_LANG_Java:
19681     case DW_LANG_C_plus_plus:
19682     case DW_LANG_C_plus_plus_11:
19683     case DW_LANG_C_plus_plus_14:
19684       cu->language = language_cplus;
19685       break;
19686     case DW_LANG_D:
19687       cu->language = language_d;
19688       break;
19689     case DW_LANG_Fortran77:
19690     case DW_LANG_Fortran90:
19691     case DW_LANG_Fortran95:
19692     case DW_LANG_Fortran03:
19693     case DW_LANG_Fortran08:
19694       cu->language = language_fortran;
19695       break;
19696     case DW_LANG_Go:
19697       cu->language = language_go;
19698       break;
19699     case DW_LANG_Mips_Assembler:
19700       cu->language = language_asm;
19701       break;
19702     case DW_LANG_Ada83:
19703     case DW_LANG_Ada95:
19704       cu->language = language_ada;
19705       break;
19706     case DW_LANG_Modula2:
19707       cu->language = language_m2;
19708       break;
19709     case DW_LANG_Pascal83:
19710       cu->language = language_pascal;
19711       break;
19712     case DW_LANG_ObjC:
19713       cu->language = language_objc;
19714       break;
19715     case DW_LANG_Rust:
19716     case DW_LANG_Rust_old:
19717       cu->language = language_rust;
19718       break;
19719     case DW_LANG_Cobol74:
19720     case DW_LANG_Cobol85:
19721     default:
19722       cu->language = language_minimal;
19723       break;
19724     }
19725   cu->language_defn = language_def (cu->language);
19726 }
19727
19728 /* Return the named attribute or NULL if not there.  */
19729
19730 static struct attribute *
19731 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19732 {
19733   for (;;)
19734     {
19735       unsigned int i;
19736       struct attribute *spec = NULL;
19737
19738       for (i = 0; i < die->num_attrs; ++i)
19739         {
19740           if (die->attrs[i].name == name)
19741             return &die->attrs[i];
19742           if (die->attrs[i].name == DW_AT_specification
19743               || die->attrs[i].name == DW_AT_abstract_origin)
19744             spec = &die->attrs[i];
19745         }
19746
19747       if (!spec)
19748         break;
19749
19750       die = follow_die_ref (die, spec, &cu);
19751     }
19752
19753   return NULL;
19754 }
19755
19756 /* Return the named attribute or NULL if not there,
19757    but do not follow DW_AT_specification, etc.
19758    This is for use in contexts where we're reading .debug_types dies.
19759    Following DW_AT_specification, DW_AT_abstract_origin will take us
19760    back up the chain, and we want to go down.  */
19761
19762 static struct attribute *
19763 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19764 {
19765   unsigned int i;
19766
19767   for (i = 0; i < die->num_attrs; ++i)
19768     if (die->attrs[i].name == name)
19769       return &die->attrs[i];
19770
19771   return NULL;
19772 }
19773
19774 /* Return the string associated with a string-typed attribute, or NULL if it
19775    is either not found or is of an incorrect type.  */
19776
19777 static const char *
19778 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19779 {
19780   struct attribute *attr;
19781   const char *str = NULL;
19782
19783   attr = dwarf2_attr (die, name, cu);
19784
19785   if (attr != NULL)
19786     {
19787       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19788           || attr->form == DW_FORM_string
19789           || attr->form == DW_FORM_GNU_str_index
19790           || attr->form == DW_FORM_GNU_strp_alt)
19791         str = DW_STRING (attr);
19792       else
19793         complaint (&symfile_complaints,
19794                    _("string type expected for attribute %s for "
19795                      "DIE at 0x%x in module %s"),
19796                    dwarf_attr_name (name), to_underlying (die->sect_off),
19797                    objfile_name (cu->objfile));
19798     }
19799
19800   return str;
19801 }
19802
19803 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19804    and holds a non-zero value.  This function should only be used for
19805    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19806
19807 static int
19808 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19809 {
19810   struct attribute *attr = dwarf2_attr (die, name, cu);
19811
19812   return (attr && DW_UNSND (attr));
19813 }
19814
19815 static int
19816 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19817 {
19818   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19819      which value is non-zero.  However, we have to be careful with
19820      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19821      (via dwarf2_flag_true_p) follows this attribute.  So we may
19822      end up accidently finding a declaration attribute that belongs
19823      to a different DIE referenced by the specification attribute,
19824      even though the given DIE does not have a declaration attribute.  */
19825   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19826           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19827 }
19828
19829 /* Return the die giving the specification for DIE, if there is
19830    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19831    containing the return value on output.  If there is no
19832    specification, but there is an abstract origin, that is
19833    returned.  */
19834
19835 static struct die_info *
19836 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19837 {
19838   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19839                                              *spec_cu);
19840
19841   if (spec_attr == NULL)
19842     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19843
19844   if (spec_attr == NULL)
19845     return NULL;
19846   else
19847     return follow_die_ref (die, spec_attr, spec_cu);
19848 }
19849
19850 /* Stub for free_line_header to match void * callback types.  */
19851
19852 static void
19853 free_line_header_voidp (void *arg)
19854 {
19855   struct line_header *lh = (struct line_header *) arg;
19856
19857   delete lh;
19858 }
19859
19860 void
19861 line_header::add_include_dir (const char *include_dir)
19862 {
19863   if (dwarf_line_debug >= 2)
19864     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19865                         include_dirs.size () + 1, include_dir);
19866
19867   include_dirs.push_back (include_dir);
19868 }
19869
19870 void
19871 line_header::add_file_name (const char *name,
19872                             dir_index d_index,
19873                             unsigned int mod_time,
19874                             unsigned int length)
19875 {
19876   if (dwarf_line_debug >= 2)
19877     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19878                         (unsigned) file_names.size () + 1, name);
19879
19880   file_names.emplace_back (name, d_index, mod_time, length);
19881 }
19882
19883 /* A convenience function to find the proper .debug_line section for a CU.  */
19884
19885 static struct dwarf2_section_info *
19886 get_debug_line_section (struct dwarf2_cu *cu)
19887 {
19888   struct dwarf2_section_info *section;
19889
19890   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19891      DWO file.  */
19892   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19893     section = &cu->dwo_unit->dwo_file->sections.line;
19894   else if (cu->per_cu->is_dwz)
19895     {
19896       struct dwz_file *dwz = dwarf2_get_dwz_file ();
19897
19898       section = &dwz->line;
19899     }
19900   else
19901     section = &dwarf2_per_objfile->line;
19902
19903   return section;
19904 }
19905
19906 /* Read directory or file name entry format, starting with byte of
19907    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19908    entries count and the entries themselves in the described entry
19909    format.  */
19910
19911 static void
19912 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
19913                         struct line_header *lh,
19914                         const struct comp_unit_head *cu_header,
19915                         void (*callback) (struct line_header *lh,
19916                                           const char *name,
19917                                           dir_index d_index,
19918                                           unsigned int mod_time,
19919                                           unsigned int length))
19920 {
19921   gdb_byte format_count, formati;
19922   ULONGEST data_count, datai;
19923   const gdb_byte *buf = *bufp;
19924   const gdb_byte *format_header_data;
19925   unsigned int bytes_read;
19926
19927   format_count = read_1_byte (abfd, buf);
19928   buf += 1;
19929   format_header_data = buf;
19930   for (formati = 0; formati < format_count; formati++)
19931     {
19932       read_unsigned_leb128 (abfd, buf, &bytes_read);
19933       buf += bytes_read;
19934       read_unsigned_leb128 (abfd, buf, &bytes_read);
19935       buf += bytes_read;
19936     }
19937
19938   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19939   buf += bytes_read;
19940   for (datai = 0; datai < data_count; datai++)
19941     {
19942       const gdb_byte *format = format_header_data;
19943       struct file_entry fe;
19944
19945       for (formati = 0; formati < format_count; formati++)
19946         {
19947           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19948           format += bytes_read;
19949
19950           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19951           format += bytes_read;
19952
19953           gdb::optional<const char *> string;
19954           gdb::optional<unsigned int> uint;
19955
19956           switch (form)
19957             {
19958             case DW_FORM_string:
19959               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19960               buf += bytes_read;
19961               break;
19962
19963             case DW_FORM_line_strp:
19964               string.emplace (read_indirect_line_string (abfd, buf,
19965                                                          cu_header,
19966                                                          &bytes_read));
19967               buf += bytes_read;
19968               break;
19969
19970             case DW_FORM_data1:
19971               uint.emplace (read_1_byte (abfd, buf));
19972               buf += 1;
19973               break;
19974
19975             case DW_FORM_data2:
19976               uint.emplace (read_2_bytes (abfd, buf));
19977               buf += 2;
19978               break;
19979
19980             case DW_FORM_data4:
19981               uint.emplace (read_4_bytes (abfd, buf));
19982               buf += 4;
19983               break;
19984
19985             case DW_FORM_data8:
19986               uint.emplace (read_8_bytes (abfd, buf));
19987               buf += 8;
19988               break;
19989
19990             case DW_FORM_udata:
19991               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
19992               buf += bytes_read;
19993               break;
19994
19995             case DW_FORM_block:
19996               /* It is valid only for DW_LNCT_timestamp which is ignored by
19997                  current GDB.  */
19998               break;
19999             }
20000
20001           switch (content_type)
20002             {
20003             case DW_LNCT_path:
20004               if (string.has_value ())
20005                 fe.name = *string;
20006               break;
20007             case DW_LNCT_directory_index:
20008               if (uint.has_value ())
20009                 fe.d_index = (dir_index) *uint;
20010               break;
20011             case DW_LNCT_timestamp:
20012               if (uint.has_value ())
20013                 fe.mod_time = *uint;
20014               break;
20015             case DW_LNCT_size:
20016               if (uint.has_value ())
20017                 fe.length = *uint;
20018               break;
20019             case DW_LNCT_MD5:
20020               break;
20021             default:
20022               complaint (&symfile_complaints,
20023                          _("Unknown format content type %s"),
20024                          pulongest (content_type));
20025             }
20026         }
20027
20028       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20029     }
20030
20031   *bufp = buf;
20032 }
20033
20034 /* Read the statement program header starting at OFFSET in
20035    .debug_line, or .debug_line.dwo.  Return a pointer
20036    to a struct line_header, allocated using xmalloc.
20037    Returns NULL if there is a problem reading the header, e.g., if it
20038    has a version we don't understand.
20039
20040    NOTE: the strings in the include directory and file name tables of
20041    the returned object point into the dwarf line section buffer,
20042    and must not be freed.  */
20043
20044 static line_header_up
20045 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20046 {
20047   const gdb_byte *line_ptr;
20048   unsigned int bytes_read, offset_size;
20049   int i;
20050   const char *cur_dir, *cur_file;
20051   struct dwarf2_section_info *section;
20052   bfd *abfd;
20053
20054   section = get_debug_line_section (cu);
20055   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20056   if (section->buffer == NULL)
20057     {
20058       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20059         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20060       else
20061         complaint (&symfile_complaints, _("missing .debug_line section"));
20062       return 0;
20063     }
20064
20065   /* We can't do this until we know the section is non-empty.
20066      Only then do we know we have such a section.  */
20067   abfd = get_section_bfd_owner (section);
20068
20069   /* Make sure that at least there's room for the total_length field.
20070      That could be 12 bytes long, but we're just going to fudge that.  */
20071   if (to_underlying (sect_off) + 4 >= section->size)
20072     {
20073       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20074       return 0;
20075     }
20076
20077   line_header_up lh (new line_header ());
20078
20079   lh->sect_off = sect_off;
20080   lh->offset_in_dwz = cu->per_cu->is_dwz;
20081
20082   line_ptr = section->buffer + to_underlying (sect_off);
20083
20084   /* Read in the header.  */
20085   lh->total_length =
20086     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20087                                             &bytes_read, &offset_size);
20088   line_ptr += bytes_read;
20089   if (line_ptr + lh->total_length > (section->buffer + section->size))
20090     {
20091       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20092       return 0;
20093     }
20094   lh->statement_program_end = line_ptr + lh->total_length;
20095   lh->version = read_2_bytes (abfd, line_ptr);
20096   line_ptr += 2;
20097   if (lh->version > 5)
20098     {
20099       /* This is a version we don't understand.  The format could have
20100          changed in ways we don't handle properly so just punt.  */
20101       complaint (&symfile_complaints,
20102                  _("unsupported version in .debug_line section"));
20103       return NULL;
20104     }
20105   if (lh->version >= 5)
20106     {
20107       gdb_byte segment_selector_size;
20108
20109       /* Skip address size.  */
20110       read_1_byte (abfd, line_ptr);
20111       line_ptr += 1;
20112
20113       segment_selector_size = read_1_byte (abfd, line_ptr);
20114       line_ptr += 1;
20115       if (segment_selector_size != 0)
20116         {
20117           complaint (&symfile_complaints,
20118                      _("unsupported segment selector size %u "
20119                        "in .debug_line section"),
20120                      segment_selector_size);
20121           return NULL;
20122         }
20123     }
20124   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20125   line_ptr += offset_size;
20126   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20127   line_ptr += 1;
20128   if (lh->version >= 4)
20129     {
20130       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20131       line_ptr += 1;
20132     }
20133   else
20134     lh->maximum_ops_per_instruction = 1;
20135
20136   if (lh->maximum_ops_per_instruction == 0)
20137     {
20138       lh->maximum_ops_per_instruction = 1;
20139       complaint (&symfile_complaints,
20140                  _("invalid maximum_ops_per_instruction "
20141                    "in `.debug_line' section"));
20142     }
20143
20144   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20145   line_ptr += 1;
20146   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20147   line_ptr += 1;
20148   lh->line_range = read_1_byte (abfd, line_ptr);
20149   line_ptr += 1;
20150   lh->opcode_base = read_1_byte (abfd, line_ptr);
20151   line_ptr += 1;
20152   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20153
20154   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20155   for (i = 1; i < lh->opcode_base; ++i)
20156     {
20157       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20158       line_ptr += 1;
20159     }
20160
20161   if (lh->version >= 5)
20162     {
20163       /* Read directory table.  */
20164       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20165                               [] (struct line_header *lh, const char *name,
20166                                   dir_index d_index, unsigned int mod_time,
20167                                   unsigned int length)
20168         {
20169           lh->add_include_dir (name);
20170         });
20171
20172       /* Read file name table.  */
20173       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
20174                               [] (struct line_header *lh, const char *name,
20175                                   dir_index d_index, unsigned int mod_time,
20176                                   unsigned int length)
20177         {
20178           lh->add_file_name (name, d_index, mod_time, length);
20179         });
20180     }
20181   else
20182     {
20183       /* Read directory table.  */
20184       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20185         {
20186           line_ptr += bytes_read;
20187           lh->add_include_dir (cur_dir);
20188         }
20189       line_ptr += bytes_read;
20190
20191       /* Read file name table.  */
20192       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20193         {
20194           unsigned int mod_time, length;
20195           dir_index d_index;
20196
20197           line_ptr += bytes_read;
20198           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20199           line_ptr += bytes_read;
20200           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20201           line_ptr += bytes_read;
20202           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20203           line_ptr += bytes_read;
20204
20205           lh->add_file_name (cur_file, d_index, mod_time, length);
20206         }
20207       line_ptr += bytes_read;
20208     }
20209   lh->statement_program_start = line_ptr;
20210
20211   if (line_ptr > (section->buffer + section->size))
20212     complaint (&symfile_complaints,
20213                _("line number info header doesn't "
20214                  "fit in `.debug_line' section"));
20215
20216   return lh;
20217 }
20218
20219 /* Subroutine of dwarf_decode_lines to simplify it.
20220    Return the file name of the psymtab for included file FILE_INDEX
20221    in line header LH of PST.
20222    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20223    If space for the result is malloc'd, it will be freed by a cleanup.
20224    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
20225
20226    The function creates dangling cleanup registration.  */
20227
20228 static const char *
20229 psymtab_include_file_name (const struct line_header *lh, int file_index,
20230                            const struct partial_symtab *pst,
20231                            const char *comp_dir)
20232 {
20233   const file_entry &fe = lh->file_names[file_index];
20234   const char *include_name = fe.name;
20235   const char *include_name_to_compare = include_name;
20236   const char *pst_filename;
20237   char *copied_name = NULL;
20238   int file_is_pst;
20239
20240   const char *dir_name = fe.include_dir (lh);
20241
20242   if (!IS_ABSOLUTE_PATH (include_name)
20243       && (dir_name != NULL || comp_dir != NULL))
20244     {
20245       /* Avoid creating a duplicate psymtab for PST.
20246          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20247          Before we do the comparison, however, we need to account
20248          for DIR_NAME and COMP_DIR.
20249          First prepend dir_name (if non-NULL).  If we still don't
20250          have an absolute path prepend comp_dir (if non-NULL).
20251          However, the directory we record in the include-file's
20252          psymtab does not contain COMP_DIR (to match the
20253          corresponding symtab(s)).
20254
20255          Example:
20256
20257          bash$ cd /tmp
20258          bash$ gcc -g ./hello.c
20259          include_name = "hello.c"
20260          dir_name = "."
20261          DW_AT_comp_dir = comp_dir = "/tmp"
20262          DW_AT_name = "./hello.c"
20263
20264       */
20265
20266       if (dir_name != NULL)
20267         {
20268           char *tem = concat (dir_name, SLASH_STRING,
20269                               include_name, (char *)NULL);
20270
20271           make_cleanup (xfree, tem);
20272           include_name = tem;
20273           include_name_to_compare = include_name;
20274         }
20275       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20276         {
20277           char *tem = concat (comp_dir, SLASH_STRING,
20278                               include_name, (char *)NULL);
20279
20280           make_cleanup (xfree, tem);
20281           include_name_to_compare = tem;
20282         }
20283     }
20284
20285   pst_filename = pst->filename;
20286   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20287     {
20288       copied_name = concat (pst->dirname, SLASH_STRING,
20289                             pst_filename, (char *)NULL);
20290       pst_filename = copied_name;
20291     }
20292
20293   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20294
20295   if (copied_name != NULL)
20296     xfree (copied_name);
20297
20298   if (file_is_pst)
20299     return NULL;
20300   return include_name;
20301 }
20302
20303 /* State machine to track the state of the line number program.  */
20304
20305 class lnp_state_machine
20306 {
20307 public:
20308   /* Initialize a machine state for the start of a line number
20309      program.  */
20310   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20311
20312   file_entry *current_file ()
20313   {
20314     /* lh->file_names is 0-based, but the file name numbers in the
20315        statement program are 1-based.  */
20316     return m_line_header->file_name_at (m_file);
20317   }
20318
20319   /* Record the line in the state machine.  END_SEQUENCE is true if
20320      we're processing the end of a sequence.  */
20321   void record_line (bool end_sequence);
20322
20323   /* Check address and if invalid nop-out the rest of the lines in this
20324      sequence.  */
20325   void check_line_address (struct dwarf2_cu *cu,
20326                            const gdb_byte *line_ptr,
20327                            CORE_ADDR lowpc, CORE_ADDR address);
20328
20329   void handle_set_discriminator (unsigned int discriminator)
20330   {
20331     m_discriminator = discriminator;
20332     m_line_has_non_zero_discriminator |= discriminator != 0;
20333   }
20334
20335   /* Handle DW_LNE_set_address.  */
20336   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20337   {
20338     m_op_index = 0;
20339     address += baseaddr;
20340     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20341   }
20342
20343   /* Handle DW_LNS_advance_pc.  */
20344   void handle_advance_pc (CORE_ADDR adjust);
20345
20346   /* Handle a special opcode.  */
20347   void handle_special_opcode (unsigned char op_code);
20348
20349   /* Handle DW_LNS_advance_line.  */
20350   void handle_advance_line (int line_delta)
20351   {
20352     advance_line (line_delta);
20353   }
20354
20355   /* Handle DW_LNS_set_file.  */
20356   void handle_set_file (file_name_index file);
20357
20358   /* Handle DW_LNS_negate_stmt.  */
20359   void handle_negate_stmt ()
20360   {
20361     m_is_stmt = !m_is_stmt;
20362   }
20363
20364   /* Handle DW_LNS_const_add_pc.  */
20365   void handle_const_add_pc ();
20366
20367   /* Handle DW_LNS_fixed_advance_pc.  */
20368   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20369   {
20370     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20371     m_op_index = 0;
20372   }
20373
20374   /* Handle DW_LNS_copy.  */
20375   void handle_copy ()
20376   {
20377     record_line (false);
20378     m_discriminator = 0;
20379   }
20380
20381   /* Handle DW_LNE_end_sequence.  */
20382   void handle_end_sequence ()
20383   {
20384     m_record_line_callback = ::record_line;
20385   }
20386
20387 private:
20388   /* Advance the line by LINE_DELTA.  */
20389   void advance_line (int line_delta)
20390   {
20391     m_line += line_delta;
20392
20393     if (line_delta != 0)
20394       m_line_has_non_zero_discriminator = m_discriminator != 0;
20395   }
20396
20397   gdbarch *m_gdbarch;
20398
20399   /* True if we're recording lines.
20400      Otherwise we're building partial symtabs and are just interested in
20401      finding include files mentioned by the line number program.  */
20402   bool m_record_lines_p;
20403
20404   /* The line number header.  */
20405   line_header *m_line_header;
20406
20407   /* These are part of the standard DWARF line number state machine,
20408      and initialized according to the DWARF spec.  */
20409
20410   unsigned char m_op_index = 0;
20411   /* The line table index (1-based) of the current file.  */
20412   file_name_index m_file = (file_name_index) 1;
20413   unsigned int m_line = 1;
20414
20415   /* These are initialized in the constructor.  */
20416
20417   CORE_ADDR m_address;
20418   bool m_is_stmt;
20419   unsigned int m_discriminator;
20420
20421   /* Additional bits of state we need to track.  */
20422
20423   /* The last file that we called dwarf2_start_subfile for.
20424      This is only used for TLLs.  */
20425   unsigned int m_last_file = 0;
20426   /* The last file a line number was recorded for.  */
20427   struct subfile *m_last_subfile = NULL;
20428
20429   /* The function to call to record a line.  */
20430   record_line_ftype *m_record_line_callback = NULL;
20431
20432   /* The last line number that was recorded, used to coalesce
20433      consecutive entries for the same line.  This can happen, for
20434      example, when discriminators are present.  PR 17276.  */
20435   unsigned int m_last_line = 0;
20436   bool m_line_has_non_zero_discriminator = false;
20437 };
20438
20439 void
20440 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20441 {
20442   CORE_ADDR addr_adj = (((m_op_index + adjust)
20443                          / m_line_header->maximum_ops_per_instruction)
20444                         * m_line_header->minimum_instruction_length);
20445   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20446   m_op_index = ((m_op_index + adjust)
20447                 % m_line_header->maximum_ops_per_instruction);
20448 }
20449
20450 void
20451 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20452 {
20453   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20454   CORE_ADDR addr_adj = (((m_op_index
20455                           + (adj_opcode / m_line_header->line_range))
20456                          / m_line_header->maximum_ops_per_instruction)
20457                         * m_line_header->minimum_instruction_length);
20458   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20459   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20460                 % m_line_header->maximum_ops_per_instruction);
20461
20462   int line_delta = (m_line_header->line_base
20463                     + (adj_opcode % m_line_header->line_range));
20464   advance_line (line_delta);
20465   record_line (false);
20466   m_discriminator = 0;
20467 }
20468
20469 void
20470 lnp_state_machine::handle_set_file (file_name_index file)
20471 {
20472   m_file = file;
20473
20474   const file_entry *fe = current_file ();
20475   if (fe == NULL)
20476     dwarf2_debug_line_missing_file_complaint ();
20477   else if (m_record_lines_p)
20478     {
20479       const char *dir = fe->include_dir (m_line_header);
20480
20481       m_last_subfile = current_subfile;
20482       m_line_has_non_zero_discriminator = m_discriminator != 0;
20483       dwarf2_start_subfile (fe->name, dir);
20484     }
20485 }
20486
20487 void
20488 lnp_state_machine::handle_const_add_pc ()
20489 {
20490   CORE_ADDR adjust
20491     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20492
20493   CORE_ADDR addr_adj
20494     = (((m_op_index + adjust)
20495         / m_line_header->maximum_ops_per_instruction)
20496        * m_line_header->minimum_instruction_length);
20497
20498   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20499   m_op_index = ((m_op_index + adjust)
20500                 % m_line_header->maximum_ops_per_instruction);
20501 }
20502
20503 /* Ignore this record_line request.  */
20504
20505 static void
20506 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20507 {
20508   return;
20509 }
20510
20511 /* Return non-zero if we should add LINE to the line number table.
20512    LINE is the line to add, LAST_LINE is the last line that was added,
20513    LAST_SUBFILE is the subfile for LAST_LINE.
20514    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20515    had a non-zero discriminator.
20516
20517    We have to be careful in the presence of discriminators.
20518    E.g., for this line:
20519
20520      for (i = 0; i < 100000; i++);
20521
20522    clang can emit four line number entries for that one line,
20523    each with a different discriminator.
20524    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20525
20526    However, we want gdb to coalesce all four entries into one.
20527    Otherwise the user could stepi into the middle of the line and
20528    gdb would get confused about whether the pc really was in the
20529    middle of the line.
20530
20531    Things are further complicated by the fact that two consecutive
20532    line number entries for the same line is a heuristic used by gcc
20533    to denote the end of the prologue.  So we can't just discard duplicate
20534    entries, we have to be selective about it.  The heuristic we use is
20535    that we only collapse consecutive entries for the same line if at least
20536    one of those entries has a non-zero discriminator.  PR 17276.
20537
20538    Note: Addresses in the line number state machine can never go backwards
20539    within one sequence, thus this coalescing is ok.  */
20540
20541 static int
20542 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20543                      int line_has_non_zero_discriminator,
20544                      struct subfile *last_subfile)
20545 {
20546   if (current_subfile != last_subfile)
20547     return 1;
20548   if (line != last_line)
20549     return 1;
20550   /* Same line for the same file that we've seen already.
20551      As a last check, for pr 17276, only record the line if the line
20552      has never had a non-zero discriminator.  */
20553   if (!line_has_non_zero_discriminator)
20554     return 1;
20555   return 0;
20556 }
20557
20558 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20559    in the line table of subfile SUBFILE.  */
20560
20561 static void
20562 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20563                      unsigned int line, CORE_ADDR address,
20564                      record_line_ftype p_record_line)
20565 {
20566   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20567
20568   if (dwarf_line_debug)
20569     {
20570       fprintf_unfiltered (gdb_stdlog,
20571                           "Recording line %u, file %s, address %s\n",
20572                           line, lbasename (subfile->name),
20573                           paddress (gdbarch, address));
20574     }
20575
20576   (*p_record_line) (subfile, line, addr);
20577 }
20578
20579 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20580    Mark the end of a set of line number records.
20581    The arguments are the same as for dwarf_record_line_1.
20582    If SUBFILE is NULL the request is ignored.  */
20583
20584 static void
20585 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20586                    CORE_ADDR address, record_line_ftype p_record_line)
20587 {
20588   if (subfile == NULL)
20589     return;
20590
20591   if (dwarf_line_debug)
20592     {
20593       fprintf_unfiltered (gdb_stdlog,
20594                           "Finishing current line, file %s, address %s\n",
20595                           lbasename (subfile->name),
20596                           paddress (gdbarch, address));
20597     }
20598
20599   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20600 }
20601
20602 void
20603 lnp_state_machine::record_line (bool end_sequence)
20604 {
20605   if (dwarf_line_debug)
20606     {
20607       fprintf_unfiltered (gdb_stdlog,
20608                           "Processing actual line %u: file %u,"
20609                           " address %s, is_stmt %u, discrim %u\n",
20610                           m_line, to_underlying (m_file),
20611                           paddress (m_gdbarch, m_address),
20612                           m_is_stmt, m_discriminator);
20613     }
20614
20615   file_entry *fe = current_file ();
20616
20617   if (fe == NULL)
20618     dwarf2_debug_line_missing_file_complaint ();
20619   /* For now we ignore lines not starting on an instruction boundary.
20620      But not when processing end_sequence for compatibility with the
20621      previous version of the code.  */
20622   else if (m_op_index == 0 || end_sequence)
20623     {
20624       fe->included_p = 1;
20625       if (m_record_lines_p && m_is_stmt)
20626         {
20627           if (m_last_subfile != current_subfile || end_sequence)
20628             {
20629               dwarf_finish_line (m_gdbarch, m_last_subfile,
20630                                  m_address, m_record_line_callback);
20631             }
20632
20633           if (!end_sequence)
20634             {
20635               if (dwarf_record_line_p (m_line, m_last_line,
20636                                        m_line_has_non_zero_discriminator,
20637                                        m_last_subfile))
20638                 {
20639                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20640                                        m_line, m_address,
20641                                        m_record_line_callback);
20642                 }
20643               m_last_subfile = current_subfile;
20644               m_last_line = m_line;
20645             }
20646         }
20647     }
20648 }
20649
20650 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20651                                       bool record_lines_p)
20652 {
20653   m_gdbarch = arch;
20654   m_record_lines_p = record_lines_p;
20655   m_line_header = lh;
20656
20657   m_record_line_callback = ::record_line;
20658
20659   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20660      was a line entry for it so that the backend has a chance to adjust it
20661      and also record it in case it needs it.  This is currently used by MIPS
20662      code, cf. `mips_adjust_dwarf2_line'.  */
20663   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20664   m_is_stmt = lh->default_is_stmt;
20665   m_discriminator = 0;
20666 }
20667
20668 void
20669 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20670                                        const gdb_byte *line_ptr,
20671                                        CORE_ADDR lowpc, CORE_ADDR address)
20672 {
20673   /* If address < lowpc then it's not a usable value, it's outside the
20674      pc range of the CU.  However, we restrict the test to only address
20675      values of zero to preserve GDB's previous behaviour which is to
20676      handle the specific case of a function being GC'd by the linker.  */
20677
20678   if (address == 0 && address < lowpc)
20679     {
20680       /* This line table is for a function which has been
20681          GCd by the linker.  Ignore it.  PR gdb/12528 */
20682
20683       struct objfile *objfile = cu->objfile;
20684       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20685
20686       complaint (&symfile_complaints,
20687                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20688                  line_offset, objfile_name (objfile));
20689       m_record_line_callback = noop_record_line;
20690       /* Note: record_line_callback is left as noop_record_line until
20691          we see DW_LNE_end_sequence.  */
20692     }
20693 }
20694
20695 /* Subroutine of dwarf_decode_lines to simplify it.
20696    Process the line number information in LH.
20697    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20698    program in order to set included_p for every referenced header.  */
20699
20700 static void
20701 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20702                       const int decode_for_pst_p, CORE_ADDR lowpc)
20703 {
20704   const gdb_byte *line_ptr, *extended_end;
20705   const gdb_byte *line_end;
20706   unsigned int bytes_read, extended_len;
20707   unsigned char op_code, extended_op;
20708   CORE_ADDR baseaddr;
20709   struct objfile *objfile = cu->objfile;
20710   bfd *abfd = objfile->obfd;
20711   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20712   /* True if we're recording line info (as opposed to building partial
20713      symtabs and just interested in finding include files mentioned by
20714      the line number program).  */
20715   bool record_lines_p = !decode_for_pst_p;
20716
20717   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20718
20719   line_ptr = lh->statement_program_start;
20720   line_end = lh->statement_program_end;
20721
20722   /* Read the statement sequences until there's nothing left.  */
20723   while (line_ptr < line_end)
20724     {
20725       /* The DWARF line number program state machine.  Reset the state
20726          machine at the start of each sequence.  */
20727       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20728       bool end_sequence = false;
20729
20730       if (record_lines_p)
20731         {
20732           /* Start a subfile for the current file of the state
20733              machine.  */
20734           const file_entry *fe = state_machine.current_file ();
20735
20736           if (fe != NULL)
20737             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20738         }
20739
20740       /* Decode the table.  */
20741       while (line_ptr < line_end && !end_sequence)
20742         {
20743           op_code = read_1_byte (abfd, line_ptr);
20744           line_ptr += 1;
20745
20746           if (op_code >= lh->opcode_base)
20747             {
20748               /* Special opcode.  */
20749               state_machine.handle_special_opcode (op_code);
20750             }
20751           else switch (op_code)
20752             {
20753             case DW_LNS_extended_op:
20754               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20755                                                    &bytes_read);
20756               line_ptr += bytes_read;
20757               extended_end = line_ptr + extended_len;
20758               extended_op = read_1_byte (abfd, line_ptr);
20759               line_ptr += 1;
20760               switch (extended_op)
20761                 {
20762                 case DW_LNE_end_sequence:
20763                   state_machine.handle_end_sequence ();
20764                   end_sequence = true;
20765                   break;
20766                 case DW_LNE_set_address:
20767                   {
20768                     CORE_ADDR address
20769                       = read_address (abfd, line_ptr, cu, &bytes_read);
20770                     line_ptr += bytes_read;
20771
20772                     state_machine.check_line_address (cu, line_ptr,
20773                                                       lowpc, address);
20774                     state_machine.handle_set_address (baseaddr, address);
20775                   }
20776                   break;
20777                 case DW_LNE_define_file:
20778                   {
20779                     const char *cur_file;
20780                     unsigned int mod_time, length;
20781                     dir_index dindex;
20782
20783                     cur_file = read_direct_string (abfd, line_ptr,
20784                                                    &bytes_read);
20785                     line_ptr += bytes_read;
20786                     dindex = (dir_index)
20787                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20788                     line_ptr += bytes_read;
20789                     mod_time =
20790                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20791                     line_ptr += bytes_read;
20792                     length =
20793                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20794                     line_ptr += bytes_read;
20795                     lh->add_file_name (cur_file, dindex, mod_time, length);
20796                   }
20797                   break;
20798                 case DW_LNE_set_discriminator:
20799                   {
20800                     /* The discriminator is not interesting to the
20801                        debugger; just ignore it.  We still need to
20802                        check its value though:
20803                        if there are consecutive entries for the same
20804                        (non-prologue) line we want to coalesce them.
20805                        PR 17276.  */
20806                     unsigned int discr
20807                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20808                     line_ptr += bytes_read;
20809
20810                     state_machine.handle_set_discriminator (discr);
20811                   }
20812                   break;
20813                 default:
20814                   complaint (&symfile_complaints,
20815                              _("mangled .debug_line section"));
20816                   return;
20817                 }
20818               /* Make sure that we parsed the extended op correctly.  If e.g.
20819                  we expected a different address size than the producer used,
20820                  we may have read the wrong number of bytes.  */
20821               if (line_ptr != extended_end)
20822                 {
20823                   complaint (&symfile_complaints,
20824                              _("mangled .debug_line section"));
20825                   return;
20826                 }
20827               break;
20828             case DW_LNS_copy:
20829               state_machine.handle_copy ();
20830               break;
20831             case DW_LNS_advance_pc:
20832               {
20833                 CORE_ADDR adjust
20834                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20835                 line_ptr += bytes_read;
20836
20837                 state_machine.handle_advance_pc (adjust);
20838               }
20839               break;
20840             case DW_LNS_advance_line:
20841               {
20842                 int line_delta
20843                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20844                 line_ptr += bytes_read;
20845
20846                 state_machine.handle_advance_line (line_delta);
20847               }
20848               break;
20849             case DW_LNS_set_file:
20850               {
20851                 file_name_index file
20852                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20853                                                             &bytes_read);
20854                 line_ptr += bytes_read;
20855
20856                 state_machine.handle_set_file (file);
20857               }
20858               break;
20859             case DW_LNS_set_column:
20860               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20861               line_ptr += bytes_read;
20862               break;
20863             case DW_LNS_negate_stmt:
20864               state_machine.handle_negate_stmt ();
20865               break;
20866             case DW_LNS_set_basic_block:
20867               break;
20868             /* Add to the address register of the state machine the
20869                address increment value corresponding to special opcode
20870                255.  I.e., this value is scaled by the minimum
20871                instruction length since special opcode 255 would have
20872                scaled the increment.  */
20873             case DW_LNS_const_add_pc:
20874               state_machine.handle_const_add_pc ();
20875               break;
20876             case DW_LNS_fixed_advance_pc:
20877               {
20878                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20879                 line_ptr += 2;
20880
20881                 state_machine.handle_fixed_advance_pc (addr_adj);
20882               }
20883               break;
20884             default:
20885               {
20886                 /* Unknown standard opcode, ignore it.  */
20887                 int i;
20888
20889                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20890                   {
20891                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20892                     line_ptr += bytes_read;
20893                   }
20894               }
20895             }
20896         }
20897
20898       if (!end_sequence)
20899         dwarf2_debug_line_missing_end_sequence_complaint ();
20900
20901       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20902          in which case we still finish recording the last line).  */
20903       state_machine.record_line (true);
20904     }
20905 }
20906
20907 /* Decode the Line Number Program (LNP) for the given line_header
20908    structure and CU.  The actual information extracted and the type
20909    of structures created from the LNP depends on the value of PST.
20910
20911    1. If PST is NULL, then this procedure uses the data from the program
20912       to create all necessary symbol tables, and their linetables.
20913
20914    2. If PST is not NULL, this procedure reads the program to determine
20915       the list of files included by the unit represented by PST, and
20916       builds all the associated partial symbol tables.
20917
20918    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20919    It is used for relative paths in the line table.
20920    NOTE: When processing partial symtabs (pst != NULL),
20921    comp_dir == pst->dirname.
20922
20923    NOTE: It is important that psymtabs have the same file name (via strcmp)
20924    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20925    symtab we don't use it in the name of the psymtabs we create.
20926    E.g. expand_line_sal requires this when finding psymtabs to expand.
20927    A good testcase for this is mb-inline.exp.
20928
20929    LOWPC is the lowest address in CU (or 0 if not known).
20930
20931    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20932    for its PC<->lines mapping information.  Otherwise only the filename
20933    table is read in.  */
20934
20935 static void
20936 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20937                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20938                     CORE_ADDR lowpc, int decode_mapping)
20939 {
20940   struct objfile *objfile = cu->objfile;
20941   const int decode_for_pst_p = (pst != NULL);
20942
20943   if (decode_mapping)
20944     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20945
20946   if (decode_for_pst_p)
20947     {
20948       int file_index;
20949
20950       /* Now that we're done scanning the Line Header Program, we can
20951          create the psymtab of each included file.  */
20952       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20953         if (lh->file_names[file_index].included_p == 1)
20954           {
20955             const char *include_name =
20956               psymtab_include_file_name (lh, file_index, pst, comp_dir);
20957             if (include_name != NULL)
20958               dwarf2_create_include_psymtab (include_name, pst, objfile);
20959           }
20960     }
20961   else
20962     {
20963       /* Make sure a symtab is created for every file, even files
20964          which contain only variables (i.e. no code with associated
20965          line numbers).  */
20966       struct compunit_symtab *cust = buildsym_compunit_symtab ();
20967       int i;
20968
20969       for (i = 0; i < lh->file_names.size (); i++)
20970         {
20971           file_entry &fe = lh->file_names[i];
20972
20973           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
20974
20975           if (current_subfile->symtab == NULL)
20976             {
20977               current_subfile->symtab
20978                 = allocate_symtab (cust, current_subfile->name);
20979             }
20980           fe.symtab = current_subfile->symtab;
20981         }
20982     }
20983 }
20984
20985 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20986    DIRNAME the name of the source directory which contains FILENAME
20987    or NULL if not known.
20988    This routine tries to keep line numbers from identical absolute and
20989    relative file names in a common subfile.
20990
20991    Using the `list' example from the GDB testsuite, which resides in
20992    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20993    of /srcdir/list0.c yields the following debugging information for list0.c:
20994
20995    DW_AT_name:          /srcdir/list0.c
20996    DW_AT_comp_dir:      /compdir
20997    files.files[0].name: list0.h
20998    files.files[0].dir:  /srcdir
20999    files.files[1].name: list0.c
21000    files.files[1].dir:  /srcdir
21001
21002    The line number information for list0.c has to end up in a single
21003    subfile, so that `break /srcdir/list0.c:1' works as expected.
21004    start_subfile will ensure that this happens provided that we pass the
21005    concatenation of files.files[1].dir and files.files[1].name as the
21006    subfile's name.  */
21007
21008 static void
21009 dwarf2_start_subfile (const char *filename, const char *dirname)
21010 {
21011   char *copy = NULL;
21012
21013   /* In order not to lose the line information directory,
21014      we concatenate it to the filename when it makes sense.
21015      Note that the Dwarf3 standard says (speaking of filenames in line
21016      information): ``The directory index is ignored for file names
21017      that represent full path names''.  Thus ignoring dirname in the
21018      `else' branch below isn't an issue.  */
21019
21020   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21021     {
21022       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21023       filename = copy;
21024     }
21025
21026   start_subfile (filename);
21027
21028   if (copy != NULL)
21029     xfree (copy);
21030 }
21031
21032 /* Start a symtab for DWARF.
21033    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21034
21035 static struct compunit_symtab *
21036 dwarf2_start_symtab (struct dwarf2_cu *cu,
21037                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21038 {
21039   struct compunit_symtab *cust
21040     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
21041
21042   record_debugformat ("DWARF 2");
21043   record_producer (cu->producer);
21044
21045   /* We assume that we're processing GCC output.  */
21046   processing_gcc_compilation = 2;
21047
21048   cu->processing_has_namespace_info = 0;
21049
21050   return cust;
21051 }
21052
21053 static void
21054 var_decode_location (struct attribute *attr, struct symbol *sym,
21055                      struct dwarf2_cu *cu)
21056 {
21057   struct objfile *objfile = cu->objfile;
21058   struct comp_unit_head *cu_header = &cu->header;
21059
21060   /* NOTE drow/2003-01-30: There used to be a comment and some special
21061      code here to turn a symbol with DW_AT_external and a
21062      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21063      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21064      with some versions of binutils) where shared libraries could have
21065      relocations against symbols in their debug information - the
21066      minimal symbol would have the right address, but the debug info
21067      would not.  It's no longer necessary, because we will explicitly
21068      apply relocations when we read in the debug information now.  */
21069
21070   /* A DW_AT_location attribute with no contents indicates that a
21071      variable has been optimized away.  */
21072   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21073     {
21074       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21075       return;
21076     }
21077
21078   /* Handle one degenerate form of location expression specially, to
21079      preserve GDB's previous behavior when section offsets are
21080      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21081      then mark this symbol as LOC_STATIC.  */
21082
21083   if (attr_form_is_block (attr)
21084       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21085            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21086           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21087               && (DW_BLOCK (attr)->size
21088                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21089     {
21090       unsigned int dummy;
21091
21092       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21093         SYMBOL_VALUE_ADDRESS (sym) =
21094           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21095       else
21096         SYMBOL_VALUE_ADDRESS (sym) =
21097           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21098       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21099       fixup_symbol_section (sym, objfile);
21100       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21101                                               SYMBOL_SECTION (sym));
21102       return;
21103     }
21104
21105   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21106      expression evaluator, and use LOC_COMPUTED only when necessary
21107      (i.e. when the value of a register or memory location is
21108      referenced, or a thread-local block, etc.).  Then again, it might
21109      not be worthwhile.  I'm assuming that it isn't unless performance
21110      or memory numbers show me otherwise.  */
21111
21112   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21113
21114   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21115     cu->has_loclist = 1;
21116 }
21117
21118 /* Given a pointer to a DWARF information entry, figure out if we need
21119    to make a symbol table entry for it, and if so, create a new entry
21120    and return a pointer to it.
21121    If TYPE is NULL, determine symbol type from the die, otherwise
21122    used the passed type.
21123    If SPACE is not NULL, use it to hold the new symbol.  If it is
21124    NULL, allocate a new symbol on the objfile's obstack.  */
21125
21126 static struct symbol *
21127 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21128                  struct symbol *space)
21129 {
21130   struct objfile *objfile = cu->objfile;
21131   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21132   struct symbol *sym = NULL;
21133   const char *name;
21134   struct attribute *attr = NULL;
21135   struct attribute *attr2 = NULL;
21136   CORE_ADDR baseaddr;
21137   struct pending **list_to_add = NULL;
21138
21139   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21140
21141   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21142
21143   name = dwarf2_name (die, cu);
21144   if (name)
21145     {
21146       const char *linkagename;
21147       int suppress_add = 0;
21148
21149       if (space)
21150         sym = space;
21151       else
21152         sym = allocate_symbol (objfile);
21153       OBJSTAT (objfile, n_syms++);
21154
21155       /* Cache this symbol's name and the name's demangled form (if any).  */
21156       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21157       linkagename = dwarf2_physname (name, die, cu);
21158       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21159
21160       /* Fortran does not have mangling standard and the mangling does differ
21161          between gfortran, iFort etc.  */
21162       if (cu->language == language_fortran
21163           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21164         symbol_set_demangled_name (&(sym->ginfo),
21165                                    dwarf2_full_name (name, die, cu),
21166                                    NULL);
21167
21168       /* Default assumptions.
21169          Use the passed type or decode it from the die.  */
21170       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21171       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21172       if (type != NULL)
21173         SYMBOL_TYPE (sym) = type;
21174       else
21175         SYMBOL_TYPE (sym) = die_type (die, cu);
21176       attr = dwarf2_attr (die,
21177                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21178                           cu);
21179       if (attr)
21180         {
21181           SYMBOL_LINE (sym) = DW_UNSND (attr);
21182         }
21183
21184       attr = dwarf2_attr (die,
21185                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21186                           cu);
21187       if (attr)
21188         {
21189           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21190           struct file_entry *fe;
21191
21192           if (cu->line_header != NULL)
21193             fe = cu->line_header->file_name_at (file_index);
21194           else
21195             fe = NULL;
21196
21197           if (fe == NULL)
21198             complaint (&symfile_complaints,
21199                        _("file index out of range"));
21200           else
21201             symbol_set_symtab (sym, fe->symtab);
21202         }
21203
21204       switch (die->tag)
21205         {
21206         case DW_TAG_label:
21207           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21208           if (attr)
21209             {
21210               CORE_ADDR addr;
21211
21212               addr = attr_value_as_address (attr);
21213               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21214               SYMBOL_VALUE_ADDRESS (sym) = addr;
21215             }
21216           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21217           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21218           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21219           add_symbol_to_list (sym, cu->list_in_scope);
21220           break;
21221         case DW_TAG_subprogram:
21222           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21223              finish_block.  */
21224           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21225           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21226           if ((attr2 && (DW_UNSND (attr2) != 0))
21227               || cu->language == language_ada)
21228             {
21229               /* Subprograms marked external are stored as a global symbol.
21230                  Ada subprograms, whether marked external or not, are always
21231                  stored as a global symbol, because we want to be able to
21232                  access them globally.  For instance, we want to be able
21233                  to break on a nested subprogram without having to
21234                  specify the context.  */
21235               list_to_add = &global_symbols;
21236             }
21237           else
21238             {
21239               list_to_add = cu->list_in_scope;
21240             }
21241           break;
21242         case DW_TAG_inlined_subroutine:
21243           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21244              finish_block.  */
21245           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21246           SYMBOL_INLINED (sym) = 1;
21247           list_to_add = cu->list_in_scope;
21248           break;
21249         case DW_TAG_template_value_param:
21250           suppress_add = 1;
21251           /* Fall through.  */
21252         case DW_TAG_constant:
21253         case DW_TAG_variable:
21254         case DW_TAG_member:
21255           /* Compilation with minimal debug info may result in
21256              variables with missing type entries.  Change the
21257              misleading `void' type to something sensible.  */
21258           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21259             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21260
21261           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21262           /* In the case of DW_TAG_member, we should only be called for
21263              static const members.  */
21264           if (die->tag == DW_TAG_member)
21265             {
21266               /* dwarf2_add_field uses die_is_declaration,
21267                  so we do the same.  */
21268               gdb_assert (die_is_declaration (die, cu));
21269               gdb_assert (attr);
21270             }
21271           if (attr)
21272             {
21273               dwarf2_const_value (attr, sym, cu);
21274               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21275               if (!suppress_add)
21276                 {
21277                   if (attr2 && (DW_UNSND (attr2) != 0))
21278                     list_to_add = &global_symbols;
21279                   else
21280                     list_to_add = cu->list_in_scope;
21281                 }
21282               break;
21283             }
21284           attr = dwarf2_attr (die, DW_AT_location, cu);
21285           if (attr)
21286             {
21287               var_decode_location (attr, sym, cu);
21288               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21289
21290               /* Fortran explicitly imports any global symbols to the local
21291                  scope by DW_TAG_common_block.  */
21292               if (cu->language == language_fortran && die->parent
21293                   && die->parent->tag == DW_TAG_common_block)
21294                 attr2 = NULL;
21295
21296               if (SYMBOL_CLASS (sym) == LOC_STATIC
21297                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21298                   && !dwarf2_per_objfile->has_section_at_zero)
21299                 {
21300                   /* When a static variable is eliminated by the linker,
21301                      the corresponding debug information is not stripped
21302                      out, but the variable address is set to null;
21303                      do not add such variables into symbol table.  */
21304                 }
21305               else if (attr2 && (DW_UNSND (attr2) != 0))
21306                 {
21307                   /* Workaround gfortran PR debug/40040 - it uses
21308                      DW_AT_location for variables in -fPIC libraries which may
21309                      get overriden by other libraries/executable and get
21310                      a different address.  Resolve it by the minimal symbol
21311                      which may come from inferior's executable using copy
21312                      relocation.  Make this workaround only for gfortran as for
21313                      other compilers GDB cannot guess the minimal symbol
21314                      Fortran mangling kind.  */
21315                   if (cu->language == language_fortran && die->parent
21316                       && die->parent->tag == DW_TAG_module
21317                       && cu->producer
21318                       && startswith (cu->producer, "GNU Fortran"))
21319                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21320
21321                   /* A variable with DW_AT_external is never static,
21322                      but it may be block-scoped.  */
21323                   list_to_add = (cu->list_in_scope == &file_symbols
21324                                  ? &global_symbols : cu->list_in_scope);
21325                 }
21326               else
21327                 list_to_add = cu->list_in_scope;
21328             }
21329           else
21330             {
21331               /* We do not know the address of this symbol.
21332                  If it is an external symbol and we have type information
21333                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21334                  The address of the variable will then be determined from
21335                  the minimal symbol table whenever the variable is
21336                  referenced.  */
21337               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21338
21339               /* Fortran explicitly imports any global symbols to the local
21340                  scope by DW_TAG_common_block.  */
21341               if (cu->language == language_fortran && die->parent
21342                   && die->parent->tag == DW_TAG_common_block)
21343                 {
21344                   /* SYMBOL_CLASS doesn't matter here because
21345                      read_common_block is going to reset it.  */
21346                   if (!suppress_add)
21347                     list_to_add = cu->list_in_scope;
21348                 }
21349               else if (attr2 && (DW_UNSND (attr2) != 0)
21350                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21351                 {
21352                   /* A variable with DW_AT_external is never static, but it
21353                      may be block-scoped.  */
21354                   list_to_add = (cu->list_in_scope == &file_symbols
21355                                  ? &global_symbols : cu->list_in_scope);
21356
21357                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21358                 }
21359               else if (!die_is_declaration (die, cu))
21360                 {
21361                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21362                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21363                   if (!suppress_add)
21364                     list_to_add = cu->list_in_scope;
21365                 }
21366             }
21367           break;
21368         case DW_TAG_formal_parameter:
21369           /* If we are inside a function, mark this as an argument.  If
21370              not, we might be looking at an argument to an inlined function
21371              when we do not have enough information to show inlined frames;
21372              pretend it's a local variable in that case so that the user can
21373              still see it.  */
21374           if (context_stack_depth > 0
21375               && context_stack[context_stack_depth - 1].name != NULL)
21376             SYMBOL_IS_ARGUMENT (sym) = 1;
21377           attr = dwarf2_attr (die, DW_AT_location, cu);
21378           if (attr)
21379             {
21380               var_decode_location (attr, sym, cu);
21381             }
21382           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21383           if (attr)
21384             {
21385               dwarf2_const_value (attr, sym, cu);
21386             }
21387
21388           list_to_add = cu->list_in_scope;
21389           break;
21390         case DW_TAG_unspecified_parameters:
21391           /* From varargs functions; gdb doesn't seem to have any
21392              interest in this information, so just ignore it for now.
21393              (FIXME?) */
21394           break;
21395         case DW_TAG_template_type_param:
21396           suppress_add = 1;
21397           /* Fall through.  */
21398         case DW_TAG_class_type:
21399         case DW_TAG_interface_type:
21400         case DW_TAG_structure_type:
21401         case DW_TAG_union_type:
21402         case DW_TAG_set_type:
21403         case DW_TAG_enumeration_type:
21404           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21405           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21406
21407           {
21408             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21409                really ever be static objects: otherwise, if you try
21410                to, say, break of a class's method and you're in a file
21411                which doesn't mention that class, it won't work unless
21412                the check for all static symbols in lookup_symbol_aux
21413                saves you.  See the OtherFileClass tests in
21414                gdb.c++/namespace.exp.  */
21415
21416             if (!suppress_add)
21417               {
21418                 list_to_add = (cu->list_in_scope == &file_symbols
21419                                && cu->language == language_cplus
21420                                ? &global_symbols : cu->list_in_scope);
21421
21422                 /* The semantics of C++ state that "struct foo {
21423                    ... }" also defines a typedef for "foo".  */
21424                 if (cu->language == language_cplus
21425                     || cu->language == language_ada
21426                     || cu->language == language_d
21427                     || cu->language == language_rust)
21428                   {
21429                     /* The symbol's name is already allocated along
21430                        with this objfile, so we don't need to
21431                        duplicate it for the type.  */
21432                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21433                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21434                   }
21435               }
21436           }
21437           break;
21438         case DW_TAG_typedef:
21439           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21440           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21441           list_to_add = cu->list_in_scope;
21442           break;
21443         case DW_TAG_base_type:
21444         case DW_TAG_subrange_type:
21445           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21446           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21447           list_to_add = cu->list_in_scope;
21448           break;
21449         case DW_TAG_enumerator:
21450           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21451           if (attr)
21452             {
21453               dwarf2_const_value (attr, sym, cu);
21454             }
21455           {
21456             /* NOTE: carlton/2003-11-10: See comment above in the
21457                DW_TAG_class_type, etc. block.  */
21458
21459             list_to_add = (cu->list_in_scope == &file_symbols
21460                            && cu->language == language_cplus
21461                            ? &global_symbols : cu->list_in_scope);
21462           }
21463           break;
21464         case DW_TAG_imported_declaration:
21465         case DW_TAG_namespace:
21466           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21467           list_to_add = &global_symbols;
21468           break;
21469         case DW_TAG_module:
21470           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21471           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21472           list_to_add = &global_symbols;
21473           break;
21474         case DW_TAG_common_block:
21475           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21476           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21477           add_symbol_to_list (sym, cu->list_in_scope);
21478           break;
21479         default:
21480           /* Not a tag we recognize.  Hopefully we aren't processing
21481              trash data, but since we must specifically ignore things
21482              we don't recognize, there is nothing else we should do at
21483              this point.  */
21484           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21485                      dwarf_tag_name (die->tag));
21486           break;
21487         }
21488
21489       if (suppress_add)
21490         {
21491           sym->hash_next = objfile->template_symbols;
21492           objfile->template_symbols = sym;
21493           list_to_add = NULL;
21494         }
21495
21496       if (list_to_add != NULL)
21497         add_symbol_to_list (sym, list_to_add);
21498
21499       /* For the benefit of old versions of GCC, check for anonymous
21500          namespaces based on the demangled name.  */
21501       if (!cu->processing_has_namespace_info
21502           && cu->language == language_cplus)
21503         cp_scan_for_anonymous_namespaces (sym, objfile);
21504     }
21505   return (sym);
21506 }
21507
21508 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
21509
21510 static struct symbol *
21511 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
21512 {
21513   return new_symbol_full (die, type, cu, NULL);
21514 }
21515
21516 /* Given an attr with a DW_FORM_dataN value in host byte order,
21517    zero-extend it as appropriate for the symbol's type.  The DWARF
21518    standard (v4) is not entirely clear about the meaning of using
21519    DW_FORM_dataN for a constant with a signed type, where the type is
21520    wider than the data.  The conclusion of a discussion on the DWARF
21521    list was that this is unspecified.  We choose to always zero-extend
21522    because that is the interpretation long in use by GCC.  */
21523
21524 static gdb_byte *
21525 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21526                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21527 {
21528   struct objfile *objfile = cu->objfile;
21529   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21530                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21531   LONGEST l = DW_UNSND (attr);
21532
21533   if (bits < sizeof (*value) * 8)
21534     {
21535       l &= ((LONGEST) 1 << bits) - 1;
21536       *value = l;
21537     }
21538   else if (bits == sizeof (*value) * 8)
21539     *value = l;
21540   else
21541     {
21542       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21543       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21544       return bytes;
21545     }
21546
21547   return NULL;
21548 }
21549
21550 /* Read a constant value from an attribute.  Either set *VALUE, or if
21551    the value does not fit in *VALUE, set *BYTES - either already
21552    allocated on the objfile obstack, or newly allocated on OBSTACK,
21553    or, set *BATON, if we translated the constant to a location
21554    expression.  */
21555
21556 static void
21557 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21558                          const char *name, struct obstack *obstack,
21559                          struct dwarf2_cu *cu,
21560                          LONGEST *value, const gdb_byte **bytes,
21561                          struct dwarf2_locexpr_baton **baton)
21562 {
21563   struct objfile *objfile = cu->objfile;
21564   struct comp_unit_head *cu_header = &cu->header;
21565   struct dwarf_block *blk;
21566   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21567                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21568
21569   *value = 0;
21570   *bytes = NULL;
21571   *baton = NULL;
21572
21573   switch (attr->form)
21574     {
21575     case DW_FORM_addr:
21576     case DW_FORM_GNU_addr_index:
21577       {
21578         gdb_byte *data;
21579
21580         if (TYPE_LENGTH (type) != cu_header->addr_size)
21581           dwarf2_const_value_length_mismatch_complaint (name,
21582                                                         cu_header->addr_size,
21583                                                         TYPE_LENGTH (type));
21584         /* Symbols of this form are reasonably rare, so we just
21585            piggyback on the existing location code rather than writing
21586            a new implementation of symbol_computed_ops.  */
21587         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21588         (*baton)->per_cu = cu->per_cu;
21589         gdb_assert ((*baton)->per_cu);
21590
21591         (*baton)->size = 2 + cu_header->addr_size;
21592         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21593         (*baton)->data = data;
21594
21595         data[0] = DW_OP_addr;
21596         store_unsigned_integer (&data[1], cu_header->addr_size,
21597                                 byte_order, DW_ADDR (attr));
21598         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21599       }
21600       break;
21601     case DW_FORM_string:
21602     case DW_FORM_strp:
21603     case DW_FORM_GNU_str_index:
21604     case DW_FORM_GNU_strp_alt:
21605       /* DW_STRING is already allocated on the objfile obstack, point
21606          directly to it.  */
21607       *bytes = (const gdb_byte *) DW_STRING (attr);
21608       break;
21609     case DW_FORM_block1:
21610     case DW_FORM_block2:
21611     case DW_FORM_block4:
21612     case DW_FORM_block:
21613     case DW_FORM_exprloc:
21614     case DW_FORM_data16:
21615       blk = DW_BLOCK (attr);
21616       if (TYPE_LENGTH (type) != blk->size)
21617         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21618                                                       TYPE_LENGTH (type));
21619       *bytes = blk->data;
21620       break;
21621
21622       /* The DW_AT_const_value attributes are supposed to carry the
21623          symbol's value "represented as it would be on the target
21624          architecture."  By the time we get here, it's already been
21625          converted to host endianness, so we just need to sign- or
21626          zero-extend it as appropriate.  */
21627     case DW_FORM_data1:
21628       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21629       break;
21630     case DW_FORM_data2:
21631       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21632       break;
21633     case DW_FORM_data4:
21634       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21635       break;
21636     case DW_FORM_data8:
21637       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21638       break;
21639
21640     case DW_FORM_sdata:
21641     case DW_FORM_implicit_const:
21642       *value = DW_SND (attr);
21643       break;
21644
21645     case DW_FORM_udata:
21646       *value = DW_UNSND (attr);
21647       break;
21648
21649     default:
21650       complaint (&symfile_complaints,
21651                  _("unsupported const value attribute form: '%s'"),
21652                  dwarf_form_name (attr->form));
21653       *value = 0;
21654       break;
21655     }
21656 }
21657
21658
21659 /* Copy constant value from an attribute to a symbol.  */
21660
21661 static void
21662 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21663                     struct dwarf2_cu *cu)
21664 {
21665   struct objfile *objfile = cu->objfile;
21666   LONGEST value;
21667   const gdb_byte *bytes;
21668   struct dwarf2_locexpr_baton *baton;
21669
21670   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21671                            SYMBOL_PRINT_NAME (sym),
21672                            &objfile->objfile_obstack, cu,
21673                            &value, &bytes, &baton);
21674
21675   if (baton != NULL)
21676     {
21677       SYMBOL_LOCATION_BATON (sym) = baton;
21678       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21679     }
21680   else if (bytes != NULL)
21681      {
21682       SYMBOL_VALUE_BYTES (sym) = bytes;
21683       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21684     }
21685   else
21686     {
21687       SYMBOL_VALUE (sym) = value;
21688       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21689     }
21690 }
21691
21692 /* Return the type of the die in question using its DW_AT_type attribute.  */
21693
21694 static struct type *
21695 die_type (struct die_info *die, struct dwarf2_cu *cu)
21696 {
21697   struct attribute *type_attr;
21698
21699   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21700   if (!type_attr)
21701     {
21702       /* A missing DW_AT_type represents a void type.  */
21703       return objfile_type (cu->objfile)->builtin_void;
21704     }
21705
21706   return lookup_die_type (die, type_attr, cu);
21707 }
21708
21709 /* True iff CU's producer generates GNAT Ada auxiliary information
21710    that allows to find parallel types through that information instead
21711    of having to do expensive parallel lookups by type name.  */
21712
21713 static int
21714 need_gnat_info (struct dwarf2_cu *cu)
21715 {
21716   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21717      of GNAT produces this auxiliary information, without any indication
21718      that it is produced.  Part of enhancing the FSF version of GNAT
21719      to produce that information will be to put in place an indicator
21720      that we can use in order to determine whether the descriptive type
21721      info is available or not.  One suggestion that has been made is
21722      to use a new attribute, attached to the CU die.  For now, assume
21723      that the descriptive type info is not available.  */
21724   return 0;
21725 }
21726
21727 /* Return the auxiliary type of the die in question using its
21728    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21729    attribute is not present.  */
21730
21731 static struct type *
21732 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21733 {
21734   struct attribute *type_attr;
21735
21736   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21737   if (!type_attr)
21738     return NULL;
21739
21740   return lookup_die_type (die, type_attr, cu);
21741 }
21742
21743 /* If DIE has a descriptive_type attribute, then set the TYPE's
21744    descriptive type accordingly.  */
21745
21746 static void
21747 set_descriptive_type (struct type *type, struct die_info *die,
21748                       struct dwarf2_cu *cu)
21749 {
21750   struct type *descriptive_type = die_descriptive_type (die, cu);
21751
21752   if (descriptive_type)
21753     {
21754       ALLOCATE_GNAT_AUX_TYPE (type);
21755       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21756     }
21757 }
21758
21759 /* Return the containing type of the die in question using its
21760    DW_AT_containing_type attribute.  */
21761
21762 static struct type *
21763 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21764 {
21765   struct attribute *type_attr;
21766
21767   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21768   if (!type_attr)
21769     error (_("Dwarf Error: Problem turning containing type into gdb type "
21770              "[in module %s]"), objfile_name (cu->objfile));
21771
21772   return lookup_die_type (die, type_attr, cu);
21773 }
21774
21775 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21776
21777 static struct type *
21778 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21779 {
21780   struct objfile *objfile = dwarf2_per_objfile->objfile;
21781   char *message, *saved;
21782
21783   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
21784                         objfile_name (objfile),
21785                         to_underlying (cu->header.sect_off),
21786                         to_underlying (die->sect_off));
21787   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21788                                   message, strlen (message));
21789   xfree (message);
21790
21791   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21792 }
21793
21794 /* Look up the type of DIE in CU using its type attribute ATTR.
21795    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21796    DW_AT_containing_type.
21797    If there is no type substitute an error marker.  */
21798
21799 static struct type *
21800 lookup_die_type (struct die_info *die, const struct attribute *attr,
21801                  struct dwarf2_cu *cu)
21802 {
21803   struct objfile *objfile = cu->objfile;
21804   struct type *this_type;
21805
21806   gdb_assert (attr->name == DW_AT_type
21807               || attr->name == DW_AT_GNAT_descriptive_type
21808               || attr->name == DW_AT_containing_type);
21809
21810   /* First see if we have it cached.  */
21811
21812   if (attr->form == DW_FORM_GNU_ref_alt)
21813     {
21814       struct dwarf2_per_cu_data *per_cu;
21815       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21816
21817       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
21818       this_type = get_die_type_at_offset (sect_off, per_cu);
21819     }
21820   else if (attr_form_is_ref (attr))
21821     {
21822       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21823
21824       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21825     }
21826   else if (attr->form == DW_FORM_ref_sig8)
21827     {
21828       ULONGEST signature = DW_SIGNATURE (attr);
21829
21830       return get_signatured_type (die, signature, cu);
21831     }
21832   else
21833     {
21834       complaint (&symfile_complaints,
21835                  _("Dwarf Error: Bad type attribute %s in DIE"
21836                    " at 0x%x [in module %s]"),
21837                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
21838                  objfile_name (objfile));
21839       return build_error_marker_type (cu, die);
21840     }
21841
21842   /* If not cached we need to read it in.  */
21843
21844   if (this_type == NULL)
21845     {
21846       struct die_info *type_die = NULL;
21847       struct dwarf2_cu *type_cu = cu;
21848
21849       if (attr_form_is_ref (attr))
21850         type_die = follow_die_ref (die, attr, &type_cu);
21851       if (type_die == NULL)
21852         return build_error_marker_type (cu, die);
21853       /* If we find the type now, it's probably because the type came
21854          from an inter-CU reference and the type's CU got expanded before
21855          ours.  */
21856       this_type = read_type_die (type_die, type_cu);
21857     }
21858
21859   /* If we still don't have a type use an error marker.  */
21860
21861   if (this_type == NULL)
21862     return build_error_marker_type (cu, die);
21863
21864   return this_type;
21865 }
21866
21867 /* Return the type in DIE, CU.
21868    Returns NULL for invalid types.
21869
21870    This first does a lookup in die_type_hash,
21871    and only reads the die in if necessary.
21872
21873    NOTE: This can be called when reading in partial or full symbols.  */
21874
21875 static struct type *
21876 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21877 {
21878   struct type *this_type;
21879
21880   this_type = get_die_type (die, cu);
21881   if (this_type)
21882     return this_type;
21883
21884   return read_type_die_1 (die, cu);
21885 }
21886
21887 /* Read the type in DIE, CU.
21888    Returns NULL for invalid types.  */
21889
21890 static struct type *
21891 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21892 {
21893   struct type *this_type = NULL;
21894
21895   switch (die->tag)
21896     {
21897     case DW_TAG_class_type:
21898     case DW_TAG_interface_type:
21899     case DW_TAG_structure_type:
21900     case DW_TAG_union_type:
21901       this_type = read_structure_type (die, cu);
21902       break;
21903     case DW_TAG_enumeration_type:
21904       this_type = read_enumeration_type (die, cu);
21905       break;
21906     case DW_TAG_subprogram:
21907     case DW_TAG_subroutine_type:
21908     case DW_TAG_inlined_subroutine:
21909       this_type = read_subroutine_type (die, cu);
21910       break;
21911     case DW_TAG_array_type:
21912       this_type = read_array_type (die, cu);
21913       break;
21914     case DW_TAG_set_type:
21915       this_type = read_set_type (die, cu);
21916       break;
21917     case DW_TAG_pointer_type:
21918       this_type = read_tag_pointer_type (die, cu);
21919       break;
21920     case DW_TAG_ptr_to_member_type:
21921       this_type = read_tag_ptr_to_member_type (die, cu);
21922       break;
21923     case DW_TAG_reference_type:
21924       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21925       break;
21926     case DW_TAG_rvalue_reference_type:
21927       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21928       break;
21929     case DW_TAG_const_type:
21930       this_type = read_tag_const_type (die, cu);
21931       break;
21932     case DW_TAG_volatile_type:
21933       this_type = read_tag_volatile_type (die, cu);
21934       break;
21935     case DW_TAG_restrict_type:
21936       this_type = read_tag_restrict_type (die, cu);
21937       break;
21938     case DW_TAG_string_type:
21939       this_type = read_tag_string_type (die, cu);
21940       break;
21941     case DW_TAG_typedef:
21942       this_type = read_typedef (die, cu);
21943       break;
21944     case DW_TAG_subrange_type:
21945       this_type = read_subrange_type (die, cu);
21946       break;
21947     case DW_TAG_base_type:
21948       this_type = read_base_type (die, cu);
21949       break;
21950     case DW_TAG_unspecified_type:
21951       this_type = read_unspecified_type (die, cu);
21952       break;
21953     case DW_TAG_namespace:
21954       this_type = read_namespace_type (die, cu);
21955       break;
21956     case DW_TAG_module:
21957       this_type = read_module_type (die, cu);
21958       break;
21959     case DW_TAG_atomic_type:
21960       this_type = read_tag_atomic_type (die, cu);
21961       break;
21962     default:
21963       complaint (&symfile_complaints,
21964                  _("unexpected tag in read_type_die: '%s'"),
21965                  dwarf_tag_name (die->tag));
21966       break;
21967     }
21968
21969   return this_type;
21970 }
21971
21972 /* See if we can figure out if the class lives in a namespace.  We do
21973    this by looking for a member function; its demangled name will
21974    contain namespace info, if there is any.
21975    Return the computed name or NULL.
21976    Space for the result is allocated on the objfile's obstack.
21977    This is the full-die version of guess_partial_die_structure_name.
21978    In this case we know DIE has no useful parent.  */
21979
21980 static char *
21981 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21982 {
21983   struct die_info *spec_die;
21984   struct dwarf2_cu *spec_cu;
21985   struct die_info *child;
21986
21987   spec_cu = cu;
21988   spec_die = die_specification (die, &spec_cu);
21989   if (spec_die != NULL)
21990     {
21991       die = spec_die;
21992       cu = spec_cu;
21993     }
21994
21995   for (child = die->child;
21996        child != NULL;
21997        child = child->sibling)
21998     {
21999       if (child->tag == DW_TAG_subprogram)
22000         {
22001           const char *linkage_name = dw2_linkage_name (child, cu);
22002
22003           if (linkage_name != NULL)
22004             {
22005               char *actual_name
22006                 = language_class_name_from_physname (cu->language_defn,
22007                                                      linkage_name);
22008               char *name = NULL;
22009
22010               if (actual_name != NULL)
22011                 {
22012                   const char *die_name = dwarf2_name (die, cu);
22013
22014                   if (die_name != NULL
22015                       && strcmp (die_name, actual_name) != 0)
22016                     {
22017                       /* Strip off the class name from the full name.
22018                          We want the prefix.  */
22019                       int die_name_len = strlen (die_name);
22020                       int actual_name_len = strlen (actual_name);
22021
22022                       /* Test for '::' as a sanity check.  */
22023                       if (actual_name_len > die_name_len + 2
22024                           && actual_name[actual_name_len
22025                                          - die_name_len - 1] == ':')
22026                         name = (char *) obstack_copy0 (
22027                           &cu->objfile->per_bfd->storage_obstack,
22028                           actual_name, actual_name_len - die_name_len - 2);
22029                     }
22030                 }
22031               xfree (actual_name);
22032               return name;
22033             }
22034         }
22035     }
22036
22037   return NULL;
22038 }
22039
22040 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22041    prefix part in such case.  See
22042    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22043
22044 static const char *
22045 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22046 {
22047   struct attribute *attr;
22048   const char *base;
22049
22050   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22051       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22052     return NULL;
22053
22054   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22055     return NULL;
22056
22057   attr = dw2_linkage_name_attr (die, cu);
22058   if (attr == NULL || DW_STRING (attr) == NULL)
22059     return NULL;
22060
22061   /* dwarf2_name had to be already called.  */
22062   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22063
22064   /* Strip the base name, keep any leading namespaces/classes.  */
22065   base = strrchr (DW_STRING (attr), ':');
22066   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22067     return "";
22068
22069   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
22070                                  DW_STRING (attr),
22071                                  &base[-1] - DW_STRING (attr));
22072 }
22073
22074 /* Return the name of the namespace/class that DIE is defined within,
22075    or "" if we can't tell.  The caller should not xfree the result.
22076
22077    For example, if we're within the method foo() in the following
22078    code:
22079
22080    namespace N {
22081      class C {
22082        void foo () {
22083        }
22084      };
22085    }
22086
22087    then determine_prefix on foo's die will return "N::C".  */
22088
22089 static const char *
22090 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22091 {
22092   struct die_info *parent, *spec_die;
22093   struct dwarf2_cu *spec_cu;
22094   struct type *parent_type;
22095   const char *retval;
22096
22097   if (cu->language != language_cplus
22098       && cu->language != language_fortran && cu->language != language_d
22099       && cu->language != language_rust)
22100     return "";
22101
22102   retval = anonymous_struct_prefix (die, cu);
22103   if (retval)
22104     return retval;
22105
22106   /* We have to be careful in the presence of DW_AT_specification.
22107      For example, with GCC 3.4, given the code
22108
22109      namespace N {
22110        void foo() {
22111          // Definition of N::foo.
22112        }
22113      }
22114
22115      then we'll have a tree of DIEs like this:
22116
22117      1: DW_TAG_compile_unit
22118        2: DW_TAG_namespace        // N
22119          3: DW_TAG_subprogram     // declaration of N::foo
22120        4: DW_TAG_subprogram       // definition of N::foo
22121             DW_AT_specification   // refers to die #3
22122
22123      Thus, when processing die #4, we have to pretend that we're in
22124      the context of its DW_AT_specification, namely the contex of die
22125      #3.  */
22126   spec_cu = cu;
22127   spec_die = die_specification (die, &spec_cu);
22128   if (spec_die == NULL)
22129     parent = die->parent;
22130   else
22131     {
22132       parent = spec_die->parent;
22133       cu = spec_cu;
22134     }
22135
22136   if (parent == NULL)
22137     return "";
22138   else if (parent->building_fullname)
22139     {
22140       const char *name;
22141       const char *parent_name;
22142
22143       /* It has been seen on RealView 2.2 built binaries,
22144          DW_TAG_template_type_param types actually _defined_ as
22145          children of the parent class:
22146
22147          enum E {};
22148          template class <class Enum> Class{};
22149          Class<enum E> class_e;
22150
22151          1: DW_TAG_class_type (Class)
22152            2: DW_TAG_enumeration_type (E)
22153              3: DW_TAG_enumerator (enum1:0)
22154              3: DW_TAG_enumerator (enum2:1)
22155              ...
22156            2: DW_TAG_template_type_param
22157               DW_AT_type  DW_FORM_ref_udata (E)
22158
22159          Besides being broken debug info, it can put GDB into an
22160          infinite loop.  Consider:
22161
22162          When we're building the full name for Class<E>, we'll start
22163          at Class, and go look over its template type parameters,
22164          finding E.  We'll then try to build the full name of E, and
22165          reach here.  We're now trying to build the full name of E,
22166          and look over the parent DIE for containing scope.  In the
22167          broken case, if we followed the parent DIE of E, we'd again
22168          find Class, and once again go look at its template type
22169          arguments, etc., etc.  Simply don't consider such parent die
22170          as source-level parent of this die (it can't be, the language
22171          doesn't allow it), and break the loop here.  */
22172       name = dwarf2_name (die, cu);
22173       parent_name = dwarf2_name (parent, cu);
22174       complaint (&symfile_complaints,
22175                  _("template param type '%s' defined within parent '%s'"),
22176                  name ? name : "<unknown>",
22177                  parent_name ? parent_name : "<unknown>");
22178       return "";
22179     }
22180   else
22181     switch (parent->tag)
22182       {
22183       case DW_TAG_namespace:
22184         parent_type = read_type_die (parent, cu);
22185         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22186            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22187            Work around this problem here.  */
22188         if (cu->language == language_cplus
22189             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22190           return "";
22191         /* We give a name to even anonymous namespaces.  */
22192         return TYPE_TAG_NAME (parent_type);
22193       case DW_TAG_class_type:
22194       case DW_TAG_interface_type:
22195       case DW_TAG_structure_type:
22196       case DW_TAG_union_type:
22197       case DW_TAG_module:
22198         parent_type = read_type_die (parent, cu);
22199         if (TYPE_TAG_NAME (parent_type) != NULL)
22200           return TYPE_TAG_NAME (parent_type);
22201         else
22202           /* An anonymous structure is only allowed non-static data
22203              members; no typedefs, no member functions, et cetera.
22204              So it does not need a prefix.  */
22205           return "";
22206       case DW_TAG_compile_unit:
22207       case DW_TAG_partial_unit:
22208         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22209         if (cu->language == language_cplus
22210             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22211             && die->child != NULL
22212             && (die->tag == DW_TAG_class_type
22213                 || die->tag == DW_TAG_structure_type
22214                 || die->tag == DW_TAG_union_type))
22215           {
22216             char *name = guess_full_die_structure_name (die, cu);
22217             if (name != NULL)
22218               return name;
22219           }
22220         return "";
22221       case DW_TAG_enumeration_type:
22222         parent_type = read_type_die (parent, cu);
22223         if (TYPE_DECLARED_CLASS (parent_type))
22224           {
22225             if (TYPE_TAG_NAME (parent_type) != NULL)
22226               return TYPE_TAG_NAME (parent_type);
22227             return "";
22228           }
22229         /* Fall through.  */
22230       default:
22231         return determine_prefix (parent, cu);
22232       }
22233 }
22234
22235 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22236    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22237    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22238    an obconcat, otherwise allocate storage for the result.  The CU argument is
22239    used to determine the language and hence, the appropriate separator.  */
22240
22241 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22242
22243 static char *
22244 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22245                  int physname, struct dwarf2_cu *cu)
22246 {
22247   const char *lead = "";
22248   const char *sep;
22249
22250   if (suffix == NULL || suffix[0] == '\0'
22251       || prefix == NULL || prefix[0] == '\0')
22252     sep = "";
22253   else if (cu->language == language_d)
22254     {
22255       /* For D, the 'main' function could be defined in any module, but it
22256          should never be prefixed.  */
22257       if (strcmp (suffix, "D main") == 0)
22258         {
22259           prefix = "";
22260           sep = "";
22261         }
22262       else
22263         sep = ".";
22264     }
22265   else if (cu->language == language_fortran && physname)
22266     {
22267       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22268          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22269
22270       lead = "__";
22271       sep = "_MOD_";
22272     }
22273   else
22274     sep = "::";
22275
22276   if (prefix == NULL)
22277     prefix = "";
22278   if (suffix == NULL)
22279     suffix = "";
22280
22281   if (obs == NULL)
22282     {
22283       char *retval
22284         = ((char *)
22285            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22286
22287       strcpy (retval, lead);
22288       strcat (retval, prefix);
22289       strcat (retval, sep);
22290       strcat (retval, suffix);
22291       return retval;
22292     }
22293   else
22294     {
22295       /* We have an obstack.  */
22296       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22297     }
22298 }
22299
22300 /* Return sibling of die, NULL if no sibling.  */
22301
22302 static struct die_info *
22303 sibling_die (struct die_info *die)
22304 {
22305   return die->sibling;
22306 }
22307
22308 /* Get name of a die, return NULL if not found.  */
22309
22310 static const char *
22311 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22312                           struct obstack *obstack)
22313 {
22314   if (name && cu->language == language_cplus)
22315     {
22316       std::string canon_name = cp_canonicalize_string (name);
22317
22318       if (!canon_name.empty ())
22319         {
22320           if (canon_name != name)
22321             name = (const char *) obstack_copy0 (obstack,
22322                                                  canon_name.c_str (),
22323                                                  canon_name.length ());
22324         }
22325     }
22326
22327   return name;
22328 }
22329
22330 /* Get name of a die, return NULL if not found.
22331    Anonymous namespaces are converted to their magic string.  */
22332
22333 static const char *
22334 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22335 {
22336   struct attribute *attr;
22337
22338   attr = dwarf2_attr (die, DW_AT_name, cu);
22339   if ((!attr || !DW_STRING (attr))
22340       && die->tag != DW_TAG_namespace
22341       && die->tag != DW_TAG_class_type
22342       && die->tag != DW_TAG_interface_type
22343       && die->tag != DW_TAG_structure_type
22344       && die->tag != DW_TAG_union_type)
22345     return NULL;
22346
22347   switch (die->tag)
22348     {
22349     case DW_TAG_compile_unit:
22350     case DW_TAG_partial_unit:
22351       /* Compilation units have a DW_AT_name that is a filename, not
22352          a source language identifier.  */
22353     case DW_TAG_enumeration_type:
22354     case DW_TAG_enumerator:
22355       /* These tags always have simple identifiers already; no need
22356          to canonicalize them.  */
22357       return DW_STRING (attr);
22358
22359     case DW_TAG_namespace:
22360       if (attr != NULL && DW_STRING (attr) != NULL)
22361         return DW_STRING (attr);
22362       return CP_ANONYMOUS_NAMESPACE_STR;
22363
22364     case DW_TAG_class_type:
22365     case DW_TAG_interface_type:
22366     case DW_TAG_structure_type:
22367     case DW_TAG_union_type:
22368       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22369          structures or unions.  These were of the form "._%d" in GCC 4.1,
22370          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22371          and GCC 4.4.  We work around this problem by ignoring these.  */
22372       if (attr && DW_STRING (attr)
22373           && (startswith (DW_STRING (attr), "._")
22374               || startswith (DW_STRING (attr), "<anonymous")))
22375         return NULL;
22376
22377       /* GCC might emit a nameless typedef that has a linkage name.  See
22378          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22379       if (!attr || DW_STRING (attr) == NULL)
22380         {
22381           char *demangled = NULL;
22382
22383           attr = dw2_linkage_name_attr (die, cu);
22384           if (attr == NULL || DW_STRING (attr) == NULL)
22385             return NULL;
22386
22387           /* Avoid demangling DW_STRING (attr) the second time on a second
22388              call for the same DIE.  */
22389           if (!DW_STRING_IS_CANONICAL (attr))
22390             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22391
22392           if (demangled)
22393             {
22394               const char *base;
22395
22396               /* FIXME: we already did this for the partial symbol... */
22397               DW_STRING (attr)
22398                 = ((const char *)
22399                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
22400                                   demangled, strlen (demangled)));
22401               DW_STRING_IS_CANONICAL (attr) = 1;
22402               xfree (demangled);
22403
22404               /* Strip any leading namespaces/classes, keep only the base name.
22405                  DW_AT_name for named DIEs does not contain the prefixes.  */
22406               base = strrchr (DW_STRING (attr), ':');
22407               if (base && base > DW_STRING (attr) && base[-1] == ':')
22408                 return &base[1];
22409               else
22410                 return DW_STRING (attr);
22411             }
22412         }
22413       break;
22414
22415     default:
22416       break;
22417     }
22418
22419   if (!DW_STRING_IS_CANONICAL (attr))
22420     {
22421       DW_STRING (attr)
22422         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22423                                     &cu->objfile->per_bfd->storage_obstack);
22424       DW_STRING_IS_CANONICAL (attr) = 1;
22425     }
22426   return DW_STRING (attr);
22427 }
22428
22429 /* Return the die that this die in an extension of, or NULL if there
22430    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22431    containing the return value on output.  */
22432
22433 static struct die_info *
22434 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22435 {
22436   struct attribute *attr;
22437
22438   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22439   if (attr == NULL)
22440     return NULL;
22441
22442   return follow_die_ref (die, attr, ext_cu);
22443 }
22444
22445 /* Convert a DIE tag into its string name.  */
22446
22447 static const char *
22448 dwarf_tag_name (unsigned tag)
22449 {
22450   const char *name = get_DW_TAG_name (tag);
22451
22452   if (name == NULL)
22453     return "DW_TAG_<unknown>";
22454
22455   return name;
22456 }
22457
22458 /* Convert a DWARF attribute code into its string name.  */
22459
22460 static const char *
22461 dwarf_attr_name (unsigned attr)
22462 {
22463   const char *name;
22464
22465 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22466   if (attr == DW_AT_MIPS_fde)
22467     return "DW_AT_MIPS_fde";
22468 #else
22469   if (attr == DW_AT_HP_block_index)
22470     return "DW_AT_HP_block_index";
22471 #endif
22472
22473   name = get_DW_AT_name (attr);
22474
22475   if (name == NULL)
22476     return "DW_AT_<unknown>";
22477
22478   return name;
22479 }
22480
22481 /* Convert a DWARF value form code into its string name.  */
22482
22483 static const char *
22484 dwarf_form_name (unsigned form)
22485 {
22486   const char *name = get_DW_FORM_name (form);
22487
22488   if (name == NULL)
22489     return "DW_FORM_<unknown>";
22490
22491   return name;
22492 }
22493
22494 static const char *
22495 dwarf_bool_name (unsigned mybool)
22496 {
22497   if (mybool)
22498     return "TRUE";
22499   else
22500     return "FALSE";
22501 }
22502
22503 /* Convert a DWARF type code into its string name.  */
22504
22505 static const char *
22506 dwarf_type_encoding_name (unsigned enc)
22507 {
22508   const char *name = get_DW_ATE_name (enc);
22509
22510   if (name == NULL)
22511     return "DW_ATE_<unknown>";
22512
22513   return name;
22514 }
22515
22516 static void
22517 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22518 {
22519   unsigned int i;
22520
22521   print_spaces (indent, f);
22522   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22523                       dwarf_tag_name (die->tag), die->abbrev,
22524                       to_underlying (die->sect_off));
22525
22526   if (die->parent != NULL)
22527     {
22528       print_spaces (indent, f);
22529       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22530                           to_underlying (die->parent->sect_off));
22531     }
22532
22533   print_spaces (indent, f);
22534   fprintf_unfiltered (f, "  has children: %s\n",
22535            dwarf_bool_name (die->child != NULL));
22536
22537   print_spaces (indent, f);
22538   fprintf_unfiltered (f, "  attributes:\n");
22539
22540   for (i = 0; i < die->num_attrs; ++i)
22541     {
22542       print_spaces (indent, f);
22543       fprintf_unfiltered (f, "    %s (%s) ",
22544                dwarf_attr_name (die->attrs[i].name),
22545                dwarf_form_name (die->attrs[i].form));
22546
22547       switch (die->attrs[i].form)
22548         {
22549         case DW_FORM_addr:
22550         case DW_FORM_GNU_addr_index:
22551           fprintf_unfiltered (f, "address: ");
22552           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22553           break;
22554         case DW_FORM_block2:
22555         case DW_FORM_block4:
22556         case DW_FORM_block:
22557         case DW_FORM_block1:
22558           fprintf_unfiltered (f, "block: size %s",
22559                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22560           break;
22561         case DW_FORM_exprloc:
22562           fprintf_unfiltered (f, "expression: size %s",
22563                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22564           break;
22565         case DW_FORM_data16:
22566           fprintf_unfiltered (f, "constant of 16 bytes");
22567           break;
22568         case DW_FORM_ref_addr:
22569           fprintf_unfiltered (f, "ref address: ");
22570           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22571           break;
22572         case DW_FORM_GNU_ref_alt:
22573           fprintf_unfiltered (f, "alt ref address: ");
22574           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22575           break;
22576         case DW_FORM_ref1:
22577         case DW_FORM_ref2:
22578         case DW_FORM_ref4:
22579         case DW_FORM_ref8:
22580         case DW_FORM_ref_udata:
22581           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22582                               (long) (DW_UNSND (&die->attrs[i])));
22583           break;
22584         case DW_FORM_data1:
22585         case DW_FORM_data2:
22586         case DW_FORM_data4:
22587         case DW_FORM_data8:
22588         case DW_FORM_udata:
22589         case DW_FORM_sdata:
22590           fprintf_unfiltered (f, "constant: %s",
22591                               pulongest (DW_UNSND (&die->attrs[i])));
22592           break;
22593         case DW_FORM_sec_offset:
22594           fprintf_unfiltered (f, "section offset: %s",
22595                               pulongest (DW_UNSND (&die->attrs[i])));
22596           break;
22597         case DW_FORM_ref_sig8:
22598           fprintf_unfiltered (f, "signature: %s",
22599                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22600           break;
22601         case DW_FORM_string:
22602         case DW_FORM_strp:
22603         case DW_FORM_line_strp:
22604         case DW_FORM_GNU_str_index:
22605         case DW_FORM_GNU_strp_alt:
22606           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22607                    DW_STRING (&die->attrs[i])
22608                    ? DW_STRING (&die->attrs[i]) : "",
22609                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22610           break;
22611         case DW_FORM_flag:
22612           if (DW_UNSND (&die->attrs[i]))
22613             fprintf_unfiltered (f, "flag: TRUE");
22614           else
22615             fprintf_unfiltered (f, "flag: FALSE");
22616           break;
22617         case DW_FORM_flag_present:
22618           fprintf_unfiltered (f, "flag: TRUE");
22619           break;
22620         case DW_FORM_indirect:
22621           /* The reader will have reduced the indirect form to
22622              the "base form" so this form should not occur.  */
22623           fprintf_unfiltered (f, 
22624                               "unexpected attribute form: DW_FORM_indirect");
22625           break;
22626         case DW_FORM_implicit_const:
22627           fprintf_unfiltered (f, "constant: %s",
22628                               plongest (DW_SND (&die->attrs[i])));
22629           break;
22630         default:
22631           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22632                    die->attrs[i].form);
22633           break;
22634         }
22635       fprintf_unfiltered (f, "\n");
22636     }
22637 }
22638
22639 static void
22640 dump_die_for_error (struct die_info *die)
22641 {
22642   dump_die_shallow (gdb_stderr, 0, die);
22643 }
22644
22645 static void
22646 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22647 {
22648   int indent = level * 4;
22649
22650   gdb_assert (die != NULL);
22651
22652   if (level >= max_level)
22653     return;
22654
22655   dump_die_shallow (f, indent, die);
22656
22657   if (die->child != NULL)
22658     {
22659       print_spaces (indent, f);
22660       fprintf_unfiltered (f, "  Children:");
22661       if (level + 1 < max_level)
22662         {
22663           fprintf_unfiltered (f, "\n");
22664           dump_die_1 (f, level + 1, max_level, die->child);
22665         }
22666       else
22667         {
22668           fprintf_unfiltered (f,
22669                               " [not printed, max nesting level reached]\n");
22670         }
22671     }
22672
22673   if (die->sibling != NULL && level > 0)
22674     {
22675       dump_die_1 (f, level, max_level, die->sibling);
22676     }
22677 }
22678
22679 /* This is called from the pdie macro in gdbinit.in.
22680    It's not static so gcc will keep a copy callable from gdb.  */
22681
22682 void
22683 dump_die (struct die_info *die, int max_level)
22684 {
22685   dump_die_1 (gdb_stdlog, 0, max_level, die);
22686 }
22687
22688 static void
22689 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22690 {
22691   void **slot;
22692
22693   slot = htab_find_slot_with_hash (cu->die_hash, die,
22694                                    to_underlying (die->sect_off),
22695                                    INSERT);
22696
22697   *slot = die;
22698 }
22699
22700 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22701    required kind.  */
22702
22703 static sect_offset
22704 dwarf2_get_ref_die_offset (const struct attribute *attr)
22705 {
22706   if (attr_form_is_ref (attr))
22707     return (sect_offset) DW_UNSND (attr);
22708
22709   complaint (&symfile_complaints,
22710              _("unsupported die ref attribute form: '%s'"),
22711              dwarf_form_name (attr->form));
22712   return {};
22713 }
22714
22715 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22716  * the value held by the attribute is not constant.  */
22717
22718 static LONGEST
22719 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22720 {
22721   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22722     return DW_SND (attr);
22723   else if (attr->form == DW_FORM_udata
22724            || attr->form == DW_FORM_data1
22725            || attr->form == DW_FORM_data2
22726            || attr->form == DW_FORM_data4
22727            || attr->form == DW_FORM_data8)
22728     return DW_UNSND (attr);
22729   else
22730     {
22731       /* For DW_FORM_data16 see attr_form_is_constant.  */
22732       complaint (&symfile_complaints,
22733                  _("Attribute value is not a constant (%s)"),
22734                  dwarf_form_name (attr->form));
22735       return default_value;
22736     }
22737 }
22738
22739 /* Follow reference or signature attribute ATTR of SRC_DIE.
22740    On entry *REF_CU is the CU of SRC_DIE.
22741    On exit *REF_CU is the CU of the result.  */
22742
22743 static struct die_info *
22744 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22745                        struct dwarf2_cu **ref_cu)
22746 {
22747   struct die_info *die;
22748
22749   if (attr_form_is_ref (attr))
22750     die = follow_die_ref (src_die, attr, ref_cu);
22751   else if (attr->form == DW_FORM_ref_sig8)
22752     die = follow_die_sig (src_die, attr, ref_cu);
22753   else
22754     {
22755       dump_die_for_error (src_die);
22756       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22757              objfile_name ((*ref_cu)->objfile));
22758     }
22759
22760   return die;
22761 }
22762
22763 /* Follow reference OFFSET.
22764    On entry *REF_CU is the CU of the source die referencing OFFSET.
22765    On exit *REF_CU is the CU of the result.
22766    Returns NULL if OFFSET is invalid.  */
22767
22768 static struct die_info *
22769 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22770                    struct dwarf2_cu **ref_cu)
22771 {
22772   struct die_info temp_die;
22773   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22774
22775   gdb_assert (cu->per_cu != NULL);
22776
22777   target_cu = cu;
22778
22779   if (cu->per_cu->is_debug_types)
22780     {
22781       /* .debug_types CUs cannot reference anything outside their CU.
22782          If they need to, they have to reference a signatured type via
22783          DW_FORM_ref_sig8.  */
22784       if (!offset_in_cu_p (&cu->header, sect_off))
22785         return NULL;
22786     }
22787   else if (offset_in_dwz != cu->per_cu->is_dwz
22788            || !offset_in_cu_p (&cu->header, sect_off))
22789     {
22790       struct dwarf2_per_cu_data *per_cu;
22791
22792       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22793                                                  cu->objfile);
22794
22795       /* If necessary, add it to the queue and load its DIEs.  */
22796       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22797         load_full_comp_unit (per_cu, cu->language);
22798
22799       target_cu = per_cu->cu;
22800     }
22801   else if (cu->dies == NULL)
22802     {
22803       /* We're loading full DIEs during partial symbol reading.  */
22804       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22805       load_full_comp_unit (cu->per_cu, language_minimal);
22806     }
22807
22808   *ref_cu = target_cu;
22809   temp_die.sect_off = sect_off;
22810   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22811                                                   &temp_die,
22812                                                   to_underlying (sect_off));
22813 }
22814
22815 /* Follow reference attribute ATTR of SRC_DIE.
22816    On entry *REF_CU is the CU of SRC_DIE.
22817    On exit *REF_CU is the CU of the result.  */
22818
22819 static struct die_info *
22820 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22821                 struct dwarf2_cu **ref_cu)
22822 {
22823   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22824   struct dwarf2_cu *cu = *ref_cu;
22825   struct die_info *die;
22826
22827   die = follow_die_offset (sect_off,
22828                            (attr->form == DW_FORM_GNU_ref_alt
22829                             || cu->per_cu->is_dwz),
22830                            ref_cu);
22831   if (!die)
22832     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
22833            "at 0x%x [in module %s]"),
22834            to_underlying (sect_off), to_underlying (src_die->sect_off),
22835            objfile_name (cu->objfile));
22836
22837   return die;
22838 }
22839
22840 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22841    Returned value is intended for DW_OP_call*.  Returned
22842    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
22843
22844 struct dwarf2_locexpr_baton
22845 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22846                                struct dwarf2_per_cu_data *per_cu,
22847                                CORE_ADDR (*get_frame_pc) (void *baton),
22848                                void *baton)
22849 {
22850   struct dwarf2_cu *cu;
22851   struct die_info *die;
22852   struct attribute *attr;
22853   struct dwarf2_locexpr_baton retval;
22854
22855   dw2_setup (per_cu->objfile);
22856
22857   if (per_cu->cu == NULL)
22858     load_cu (per_cu);
22859   cu = per_cu->cu;
22860   if (cu == NULL)
22861     {
22862       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22863          Instead just throw an error, not much else we can do.  */
22864       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22865              to_underlying (sect_off), objfile_name (per_cu->objfile));
22866     }
22867
22868   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22869   if (!die)
22870     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
22871            to_underlying (sect_off), objfile_name (per_cu->objfile));
22872
22873   attr = dwarf2_attr (die, DW_AT_location, cu);
22874   if (!attr)
22875     {
22876       /* DWARF: "If there is no such attribute, then there is no effect.".
22877          DATA is ignored if SIZE is 0.  */
22878
22879       retval.data = NULL;
22880       retval.size = 0;
22881     }
22882   else if (attr_form_is_section_offset (attr))
22883     {
22884       struct dwarf2_loclist_baton loclist_baton;
22885       CORE_ADDR pc = (*get_frame_pc) (baton);
22886       size_t size;
22887
22888       fill_in_loclist_baton (cu, &loclist_baton, attr);
22889
22890       retval.data = dwarf2_find_location_expression (&loclist_baton,
22891                                                      &size, pc);
22892       retval.size = size;
22893     }
22894   else
22895     {
22896       if (!attr_form_is_block (attr))
22897         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
22898                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22899                to_underlying (sect_off), objfile_name (per_cu->objfile));
22900
22901       retval.data = DW_BLOCK (attr)->data;
22902       retval.size = DW_BLOCK (attr)->size;
22903     }
22904   retval.per_cu = cu->per_cu;
22905
22906   age_cached_comp_units ();
22907
22908   return retval;
22909 }
22910
22911 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22912    offset.  */
22913
22914 struct dwarf2_locexpr_baton
22915 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22916                              struct dwarf2_per_cu_data *per_cu,
22917                              CORE_ADDR (*get_frame_pc) (void *baton),
22918                              void *baton)
22919 {
22920   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22921
22922   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22923 }
22924
22925 /* Write a constant of a given type as target-ordered bytes into
22926    OBSTACK.  */
22927
22928 static const gdb_byte *
22929 write_constant_as_bytes (struct obstack *obstack,
22930                          enum bfd_endian byte_order,
22931                          struct type *type,
22932                          ULONGEST value,
22933                          LONGEST *len)
22934 {
22935   gdb_byte *result;
22936
22937   *len = TYPE_LENGTH (type);
22938   result = (gdb_byte *) obstack_alloc (obstack, *len);
22939   store_unsigned_integer (result, *len, byte_order, value);
22940
22941   return result;
22942 }
22943
22944 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22945    pointer to the constant bytes and set LEN to the length of the
22946    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22947    does not have a DW_AT_const_value, return NULL.  */
22948
22949 const gdb_byte *
22950 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22951                              struct dwarf2_per_cu_data *per_cu,
22952                              struct obstack *obstack,
22953                              LONGEST *len)
22954 {
22955   struct dwarf2_cu *cu;
22956   struct die_info *die;
22957   struct attribute *attr;
22958   const gdb_byte *result = NULL;
22959   struct type *type;
22960   LONGEST value;
22961   enum bfd_endian byte_order;
22962
22963   dw2_setup (per_cu->objfile);
22964
22965   if (per_cu->cu == NULL)
22966     load_cu (per_cu);
22967   cu = per_cu->cu;
22968   if (cu == NULL)
22969     {
22970       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22971          Instead just throw an error, not much else we can do.  */
22972       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
22973              to_underlying (sect_off), objfile_name (per_cu->objfile));
22974     }
22975
22976   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22977   if (!die)
22978     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
22979            to_underlying (sect_off), objfile_name (per_cu->objfile));
22980
22981
22982   attr = dwarf2_attr (die, DW_AT_const_value, cu);
22983   if (attr == NULL)
22984     return NULL;
22985
22986   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
22987                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22988
22989   switch (attr->form)
22990     {
22991     case DW_FORM_addr:
22992     case DW_FORM_GNU_addr_index:
22993       {
22994         gdb_byte *tem;
22995
22996         *len = cu->header.addr_size;
22997         tem = (gdb_byte *) obstack_alloc (obstack, *len);
22998         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
22999         result = tem;
23000       }
23001       break;
23002     case DW_FORM_string:
23003     case DW_FORM_strp:
23004     case DW_FORM_GNU_str_index:
23005     case DW_FORM_GNU_strp_alt:
23006       /* DW_STRING is already allocated on the objfile obstack, point
23007          directly to it.  */
23008       result = (const gdb_byte *) DW_STRING (attr);
23009       *len = strlen (DW_STRING (attr));
23010       break;
23011     case DW_FORM_block1:
23012     case DW_FORM_block2:
23013     case DW_FORM_block4:
23014     case DW_FORM_block:
23015     case DW_FORM_exprloc:
23016     case DW_FORM_data16:
23017       result = DW_BLOCK (attr)->data;
23018       *len = DW_BLOCK (attr)->size;
23019       break;
23020
23021       /* The DW_AT_const_value attributes are supposed to carry the
23022          symbol's value "represented as it would be on the target
23023          architecture."  By the time we get here, it's already been
23024          converted to host endianness, so we just need to sign- or
23025          zero-extend it as appropriate.  */
23026     case DW_FORM_data1:
23027       type = die_type (die, cu);
23028       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23029       if (result == NULL)
23030         result = write_constant_as_bytes (obstack, byte_order,
23031                                           type, value, len);
23032       break;
23033     case DW_FORM_data2:
23034       type = die_type (die, cu);
23035       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23036       if (result == NULL)
23037         result = write_constant_as_bytes (obstack, byte_order,
23038                                           type, value, len);
23039       break;
23040     case DW_FORM_data4:
23041       type = die_type (die, cu);
23042       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23043       if (result == NULL)
23044         result = write_constant_as_bytes (obstack, byte_order,
23045                                           type, value, len);
23046       break;
23047     case DW_FORM_data8:
23048       type = die_type (die, cu);
23049       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23050       if (result == NULL)
23051         result = write_constant_as_bytes (obstack, byte_order,
23052                                           type, value, len);
23053       break;
23054
23055     case DW_FORM_sdata:
23056     case DW_FORM_implicit_const:
23057       type = die_type (die, cu);
23058       result = write_constant_as_bytes (obstack, byte_order,
23059                                         type, DW_SND (attr), len);
23060       break;
23061
23062     case DW_FORM_udata:
23063       type = die_type (die, cu);
23064       result = write_constant_as_bytes (obstack, byte_order,
23065                                         type, DW_UNSND (attr), len);
23066       break;
23067
23068     default:
23069       complaint (&symfile_complaints,
23070                  _("unsupported const value attribute form: '%s'"),
23071                  dwarf_form_name (attr->form));
23072       break;
23073     }
23074
23075   return result;
23076 }
23077
23078 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23079    valid type for this die is found.  */
23080
23081 struct type *
23082 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23083                                 struct dwarf2_per_cu_data *per_cu)
23084 {
23085   struct dwarf2_cu *cu;
23086   struct die_info *die;
23087
23088   dw2_setup (per_cu->objfile);
23089
23090   if (per_cu->cu == NULL)
23091     load_cu (per_cu);
23092   cu = per_cu->cu;
23093   if (!cu)
23094     return NULL;
23095
23096   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23097   if (!die)
23098     return NULL;
23099
23100   return die_type (die, cu);
23101 }
23102
23103 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23104    PER_CU.  */
23105
23106 struct type *
23107 dwarf2_get_die_type (cu_offset die_offset,
23108                      struct dwarf2_per_cu_data *per_cu)
23109 {
23110   dw2_setup (per_cu->objfile);
23111
23112   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23113   return get_die_type_at_offset (die_offset_sect, per_cu);
23114 }
23115
23116 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23117    On entry *REF_CU is the CU of SRC_DIE.
23118    On exit *REF_CU is the CU of the result.
23119    Returns NULL if the referenced DIE isn't found.  */
23120
23121 static struct die_info *
23122 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23123                   struct dwarf2_cu **ref_cu)
23124 {
23125   struct die_info temp_die;
23126   struct dwarf2_cu *sig_cu;
23127   struct die_info *die;
23128
23129   /* While it might be nice to assert sig_type->type == NULL here,
23130      we can get here for DW_AT_imported_declaration where we need
23131      the DIE not the type.  */
23132
23133   /* If necessary, add it to the queue and load its DIEs.  */
23134
23135   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23136     read_signatured_type (sig_type);
23137
23138   sig_cu = sig_type->per_cu.cu;
23139   gdb_assert (sig_cu != NULL);
23140   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23141   temp_die.sect_off = sig_type->type_offset_in_section;
23142   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23143                                                  to_underlying (temp_die.sect_off));
23144   if (die)
23145     {
23146       /* For .gdb_index version 7 keep track of included TUs.
23147          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23148       if (dwarf2_per_objfile->index_table != NULL
23149           && dwarf2_per_objfile->index_table->version <= 7)
23150         {
23151           VEC_safe_push (dwarf2_per_cu_ptr,
23152                          (*ref_cu)->per_cu->imported_symtabs,
23153                          sig_cu->per_cu);
23154         }
23155
23156       *ref_cu = sig_cu;
23157       return die;
23158     }
23159
23160   return NULL;
23161 }
23162
23163 /* Follow signatured type referenced by ATTR in SRC_DIE.
23164    On entry *REF_CU is the CU of SRC_DIE.
23165    On exit *REF_CU is the CU of the result.
23166    The result is the DIE of the type.
23167    If the referenced type cannot be found an error is thrown.  */
23168
23169 static struct die_info *
23170 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23171                 struct dwarf2_cu **ref_cu)
23172 {
23173   ULONGEST signature = DW_SIGNATURE (attr);
23174   struct signatured_type *sig_type;
23175   struct die_info *die;
23176
23177   gdb_assert (attr->form == DW_FORM_ref_sig8);
23178
23179   sig_type = lookup_signatured_type (*ref_cu, signature);
23180   /* sig_type will be NULL if the signatured type is missing from
23181      the debug info.  */
23182   if (sig_type == NULL)
23183     {
23184       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23185                " from DIE at 0x%x [in module %s]"),
23186              hex_string (signature), to_underlying (src_die->sect_off),
23187              objfile_name ((*ref_cu)->objfile));
23188     }
23189
23190   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23191   if (die == NULL)
23192     {
23193       dump_die_for_error (src_die);
23194       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23195                " from DIE at 0x%x [in module %s]"),
23196              hex_string (signature), to_underlying (src_die->sect_off),
23197              objfile_name ((*ref_cu)->objfile));
23198     }
23199
23200   return die;
23201 }
23202
23203 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23204    reading in and processing the type unit if necessary.  */
23205
23206 static struct type *
23207 get_signatured_type (struct die_info *die, ULONGEST signature,
23208                      struct dwarf2_cu *cu)
23209 {
23210   struct signatured_type *sig_type;
23211   struct dwarf2_cu *type_cu;
23212   struct die_info *type_die;
23213   struct type *type;
23214
23215   sig_type = lookup_signatured_type (cu, signature);
23216   /* sig_type will be NULL if the signatured type is missing from
23217      the debug info.  */
23218   if (sig_type == NULL)
23219     {
23220       complaint (&symfile_complaints,
23221                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23222                    " from DIE at 0x%x [in module %s]"),
23223                  hex_string (signature), to_underlying (die->sect_off),
23224                  objfile_name (dwarf2_per_objfile->objfile));
23225       return build_error_marker_type (cu, die);
23226     }
23227
23228   /* If we already know the type we're done.  */
23229   if (sig_type->type != NULL)
23230     return sig_type->type;
23231
23232   type_cu = cu;
23233   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23234   if (type_die != NULL)
23235     {
23236       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23237          is created.  This is important, for example, because for c++ classes
23238          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23239       type = read_type_die (type_die, type_cu);
23240       if (type == NULL)
23241         {
23242           complaint (&symfile_complaints,
23243                      _("Dwarf Error: Cannot build signatured type %s"
23244                        " referenced from DIE at 0x%x [in module %s]"),
23245                      hex_string (signature), to_underlying (die->sect_off),
23246                      objfile_name (dwarf2_per_objfile->objfile));
23247           type = build_error_marker_type (cu, die);
23248         }
23249     }
23250   else
23251     {
23252       complaint (&symfile_complaints,
23253                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23254                    " from DIE at 0x%x [in module %s]"),
23255                  hex_string (signature), to_underlying (die->sect_off),
23256                  objfile_name (dwarf2_per_objfile->objfile));
23257       type = build_error_marker_type (cu, die);
23258     }
23259   sig_type->type = type;
23260
23261   return type;
23262 }
23263
23264 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23265    reading in and processing the type unit if necessary.  */
23266
23267 static struct type *
23268 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23269                           struct dwarf2_cu *cu) /* ARI: editCase function */
23270 {
23271   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23272   if (attr_form_is_ref (attr))
23273     {
23274       struct dwarf2_cu *type_cu = cu;
23275       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23276
23277       return read_type_die (type_die, type_cu);
23278     }
23279   else if (attr->form == DW_FORM_ref_sig8)
23280     {
23281       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23282     }
23283   else
23284     {
23285       complaint (&symfile_complaints,
23286                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23287                    " at 0x%x [in module %s]"),
23288                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23289                  objfile_name (dwarf2_per_objfile->objfile));
23290       return build_error_marker_type (cu, die);
23291     }
23292 }
23293
23294 /* Load the DIEs associated with type unit PER_CU into memory.  */
23295
23296 static void
23297 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23298 {
23299   struct signatured_type *sig_type;
23300
23301   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23302   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23303
23304   /* We have the per_cu, but we need the signatured_type.
23305      Fortunately this is an easy translation.  */
23306   gdb_assert (per_cu->is_debug_types);
23307   sig_type = (struct signatured_type *) per_cu;
23308
23309   gdb_assert (per_cu->cu == NULL);
23310
23311   read_signatured_type (sig_type);
23312
23313   gdb_assert (per_cu->cu != NULL);
23314 }
23315
23316 /* die_reader_func for read_signatured_type.
23317    This is identical to load_full_comp_unit_reader,
23318    but is kept separate for now.  */
23319
23320 static void
23321 read_signatured_type_reader (const struct die_reader_specs *reader,
23322                              const gdb_byte *info_ptr,
23323                              struct die_info *comp_unit_die,
23324                              int has_children,
23325                              void *data)
23326 {
23327   struct dwarf2_cu *cu = reader->cu;
23328
23329   gdb_assert (cu->die_hash == NULL);
23330   cu->die_hash =
23331     htab_create_alloc_ex (cu->header.length / 12,
23332                           die_hash,
23333                           die_eq,
23334                           NULL,
23335                           &cu->comp_unit_obstack,
23336                           hashtab_obstack_allocate,
23337                           dummy_obstack_deallocate);
23338
23339   if (has_children)
23340     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23341                                                   &info_ptr, comp_unit_die);
23342   cu->dies = comp_unit_die;
23343   /* comp_unit_die is not stored in die_hash, no need.  */
23344
23345   /* We try not to read any attributes in this function, because not
23346      all CUs needed for references have been loaded yet, and symbol
23347      table processing isn't initialized.  But we have to set the CU language,
23348      or we won't be able to build types correctly.
23349      Similarly, if we do not read the producer, we can not apply
23350      producer-specific interpretation.  */
23351   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23352 }
23353
23354 /* Read in a signatured type and build its CU and DIEs.
23355    If the type is a stub for the real type in a DWO file,
23356    read in the real type from the DWO file as well.  */
23357
23358 static void
23359 read_signatured_type (struct signatured_type *sig_type)
23360 {
23361   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23362
23363   gdb_assert (per_cu->is_debug_types);
23364   gdb_assert (per_cu->cu == NULL);
23365
23366   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23367                            read_signatured_type_reader, NULL);
23368   sig_type->per_cu.tu_read = 1;
23369 }
23370
23371 /* Decode simple location descriptions.
23372    Given a pointer to a dwarf block that defines a location, compute
23373    the location and return the value.
23374
23375    NOTE drow/2003-11-18: This function is called in two situations
23376    now: for the address of static or global variables (partial symbols
23377    only) and for offsets into structures which are expected to be
23378    (more or less) constant.  The partial symbol case should go away,
23379    and only the constant case should remain.  That will let this
23380    function complain more accurately.  A few special modes are allowed
23381    without complaint for global variables (for instance, global
23382    register values and thread-local values).
23383
23384    A location description containing no operations indicates that the
23385    object is optimized out.  The return value is 0 for that case.
23386    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23387    callers will only want a very basic result and this can become a
23388    complaint.
23389
23390    Note that stack[0] is unused except as a default error return.  */
23391
23392 static CORE_ADDR
23393 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23394 {
23395   struct objfile *objfile = cu->objfile;
23396   size_t i;
23397   size_t size = blk->size;
23398   const gdb_byte *data = blk->data;
23399   CORE_ADDR stack[64];
23400   int stacki;
23401   unsigned int bytes_read, unsnd;
23402   gdb_byte op;
23403
23404   i = 0;
23405   stacki = 0;
23406   stack[stacki] = 0;
23407   stack[++stacki] = 0;
23408
23409   while (i < size)
23410     {
23411       op = data[i++];
23412       switch (op)
23413         {
23414         case DW_OP_lit0:
23415         case DW_OP_lit1:
23416         case DW_OP_lit2:
23417         case DW_OP_lit3:
23418         case DW_OP_lit4:
23419         case DW_OP_lit5:
23420         case DW_OP_lit6:
23421         case DW_OP_lit7:
23422         case DW_OP_lit8:
23423         case DW_OP_lit9:
23424         case DW_OP_lit10:
23425         case DW_OP_lit11:
23426         case DW_OP_lit12:
23427         case DW_OP_lit13:
23428         case DW_OP_lit14:
23429         case DW_OP_lit15:
23430         case DW_OP_lit16:
23431         case DW_OP_lit17:
23432         case DW_OP_lit18:
23433         case DW_OP_lit19:
23434         case DW_OP_lit20:
23435         case DW_OP_lit21:
23436         case DW_OP_lit22:
23437         case DW_OP_lit23:
23438         case DW_OP_lit24:
23439         case DW_OP_lit25:
23440         case DW_OP_lit26:
23441         case DW_OP_lit27:
23442         case DW_OP_lit28:
23443         case DW_OP_lit29:
23444         case DW_OP_lit30:
23445         case DW_OP_lit31:
23446           stack[++stacki] = op - DW_OP_lit0;
23447           break;
23448
23449         case DW_OP_reg0:
23450         case DW_OP_reg1:
23451         case DW_OP_reg2:
23452         case DW_OP_reg3:
23453         case DW_OP_reg4:
23454         case DW_OP_reg5:
23455         case DW_OP_reg6:
23456         case DW_OP_reg7:
23457         case DW_OP_reg8:
23458         case DW_OP_reg9:
23459         case DW_OP_reg10:
23460         case DW_OP_reg11:
23461         case DW_OP_reg12:
23462         case DW_OP_reg13:
23463         case DW_OP_reg14:
23464         case DW_OP_reg15:
23465         case DW_OP_reg16:
23466         case DW_OP_reg17:
23467         case DW_OP_reg18:
23468         case DW_OP_reg19:
23469         case DW_OP_reg20:
23470         case DW_OP_reg21:
23471         case DW_OP_reg22:
23472         case DW_OP_reg23:
23473         case DW_OP_reg24:
23474         case DW_OP_reg25:
23475         case DW_OP_reg26:
23476         case DW_OP_reg27:
23477         case DW_OP_reg28:
23478         case DW_OP_reg29:
23479         case DW_OP_reg30:
23480         case DW_OP_reg31:
23481           stack[++stacki] = op - DW_OP_reg0;
23482           if (i < size)
23483             dwarf2_complex_location_expr_complaint ();
23484           break;
23485
23486         case DW_OP_regx:
23487           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23488           i += bytes_read;
23489           stack[++stacki] = unsnd;
23490           if (i < size)
23491             dwarf2_complex_location_expr_complaint ();
23492           break;
23493
23494         case DW_OP_addr:
23495           stack[++stacki] = read_address (objfile->obfd, &data[i],
23496                                           cu, &bytes_read);
23497           i += bytes_read;
23498           break;
23499
23500         case DW_OP_const1u:
23501           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23502           i += 1;
23503           break;
23504
23505         case DW_OP_const1s:
23506           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23507           i += 1;
23508           break;
23509
23510         case DW_OP_const2u:
23511           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23512           i += 2;
23513           break;
23514
23515         case DW_OP_const2s:
23516           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23517           i += 2;
23518           break;
23519
23520         case DW_OP_const4u:
23521           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23522           i += 4;
23523           break;
23524
23525         case DW_OP_const4s:
23526           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23527           i += 4;
23528           break;
23529
23530         case DW_OP_const8u:
23531           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23532           i += 8;
23533           break;
23534
23535         case DW_OP_constu:
23536           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23537                                                   &bytes_read);
23538           i += bytes_read;
23539           break;
23540
23541         case DW_OP_consts:
23542           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23543           i += bytes_read;
23544           break;
23545
23546         case DW_OP_dup:
23547           stack[stacki + 1] = stack[stacki];
23548           stacki++;
23549           break;
23550
23551         case DW_OP_plus:
23552           stack[stacki - 1] += stack[stacki];
23553           stacki--;
23554           break;
23555
23556         case DW_OP_plus_uconst:
23557           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23558                                                  &bytes_read);
23559           i += bytes_read;
23560           break;
23561
23562         case DW_OP_minus:
23563           stack[stacki - 1] -= stack[stacki];
23564           stacki--;
23565           break;
23566
23567         case DW_OP_deref:
23568           /* If we're not the last op, then we definitely can't encode
23569              this using GDB's address_class enum.  This is valid for partial
23570              global symbols, although the variable's address will be bogus
23571              in the psymtab.  */
23572           if (i < size)
23573             dwarf2_complex_location_expr_complaint ();
23574           break;
23575
23576         case DW_OP_GNU_push_tls_address:
23577         case DW_OP_form_tls_address:
23578           /* The top of the stack has the offset from the beginning
23579              of the thread control block at which the variable is located.  */
23580           /* Nothing should follow this operator, so the top of stack would
23581              be returned.  */
23582           /* This is valid for partial global symbols, but the variable's
23583              address will be bogus in the psymtab.  Make it always at least
23584              non-zero to not look as a variable garbage collected by linker
23585              which have DW_OP_addr 0.  */
23586           if (i < size)
23587             dwarf2_complex_location_expr_complaint ();
23588           stack[stacki]++;
23589           break;
23590
23591         case DW_OP_GNU_uninit:
23592           break;
23593
23594         case DW_OP_GNU_addr_index:
23595         case DW_OP_GNU_const_index:
23596           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23597                                                          &bytes_read);
23598           i += bytes_read;
23599           break;
23600
23601         default:
23602           {
23603             const char *name = get_DW_OP_name (op);
23604
23605             if (name)
23606               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23607                          name);
23608             else
23609               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23610                          op);
23611           }
23612
23613           return (stack[stacki]);
23614         }
23615
23616       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23617          outside of the allocated space.  Also enforce minimum>0.  */
23618       if (stacki >= ARRAY_SIZE (stack) - 1)
23619         {
23620           complaint (&symfile_complaints,
23621                      _("location description stack overflow"));
23622           return 0;
23623         }
23624
23625       if (stacki <= 0)
23626         {
23627           complaint (&symfile_complaints,
23628                      _("location description stack underflow"));
23629           return 0;
23630         }
23631     }
23632   return (stack[stacki]);
23633 }
23634
23635 /* memory allocation interface */
23636
23637 static struct dwarf_block *
23638 dwarf_alloc_block (struct dwarf2_cu *cu)
23639 {
23640   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23641 }
23642
23643 static struct die_info *
23644 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23645 {
23646   struct die_info *die;
23647   size_t size = sizeof (struct die_info);
23648
23649   if (num_attrs > 1)
23650     size += (num_attrs - 1) * sizeof (struct attribute);
23651
23652   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23653   memset (die, 0, sizeof (struct die_info));
23654   return (die);
23655 }
23656
23657 \f
23658 /* Macro support.  */
23659
23660 /* Return file name relative to the compilation directory of file number I in
23661    *LH's file name table.  The result is allocated using xmalloc; the caller is
23662    responsible for freeing it.  */
23663
23664 static char *
23665 file_file_name (int file, struct line_header *lh)
23666 {
23667   /* Is the file number a valid index into the line header's file name
23668      table?  Remember that file numbers start with one, not zero.  */
23669   if (1 <= file && file <= lh->file_names.size ())
23670     {
23671       const file_entry &fe = lh->file_names[file - 1];
23672
23673       if (!IS_ABSOLUTE_PATH (fe.name))
23674         {
23675           const char *dir = fe.include_dir (lh);
23676           if (dir != NULL)
23677             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23678         }
23679       return xstrdup (fe.name);
23680     }
23681   else
23682     {
23683       /* The compiler produced a bogus file number.  We can at least
23684          record the macro definitions made in the file, even if we
23685          won't be able to find the file by name.  */
23686       char fake_name[80];
23687
23688       xsnprintf (fake_name, sizeof (fake_name),
23689                  "<bad macro file number %d>", file);
23690
23691       complaint (&symfile_complaints,
23692                  _("bad file number in macro information (%d)"),
23693                  file);
23694
23695       return xstrdup (fake_name);
23696     }
23697 }
23698
23699 /* Return the full name of file number I in *LH's file name table.
23700    Use COMP_DIR as the name of the current directory of the
23701    compilation.  The result is allocated using xmalloc; the caller is
23702    responsible for freeing it.  */
23703 static char *
23704 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23705 {
23706   /* Is the file number a valid index into the line header's file name
23707      table?  Remember that file numbers start with one, not zero.  */
23708   if (1 <= file && file <= lh->file_names.size ())
23709     {
23710       char *relative = file_file_name (file, lh);
23711
23712       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23713         return relative;
23714       return reconcat (relative, comp_dir, SLASH_STRING,
23715                        relative, (char *) NULL);
23716     }
23717   else
23718     return file_file_name (file, lh);
23719 }
23720
23721
23722 static struct macro_source_file *
23723 macro_start_file (int file, int line,
23724                   struct macro_source_file *current_file,
23725                   struct line_header *lh)
23726 {
23727   /* File name relative to the compilation directory of this source file.  */
23728   char *file_name = file_file_name (file, lh);
23729
23730   if (! current_file)
23731     {
23732       /* Note: We don't create a macro table for this compilation unit
23733          at all until we actually get a filename.  */
23734       struct macro_table *macro_table = get_macro_table ();
23735
23736       /* If we have no current file, then this must be the start_file
23737          directive for the compilation unit's main source file.  */
23738       current_file = macro_set_main (macro_table, file_name);
23739       macro_define_special (macro_table);
23740     }
23741   else
23742     current_file = macro_include (current_file, line, file_name);
23743
23744   xfree (file_name);
23745
23746   return current_file;
23747 }
23748
23749 static const char *
23750 consume_improper_spaces (const char *p, const char *body)
23751 {
23752   if (*p == ' ')
23753     {
23754       complaint (&symfile_complaints,
23755                  _("macro definition contains spaces "
23756                    "in formal argument list:\n`%s'"),
23757                  body);
23758
23759       while (*p == ' ')
23760         p++;
23761     }
23762
23763   return p;
23764 }
23765
23766
23767 static void
23768 parse_macro_definition (struct macro_source_file *file, int line,
23769                         const char *body)
23770 {
23771   const char *p;
23772
23773   /* The body string takes one of two forms.  For object-like macro
23774      definitions, it should be:
23775
23776         <macro name> " " <definition>
23777
23778      For function-like macro definitions, it should be:
23779
23780         <macro name> "() " <definition>
23781      or
23782         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23783
23784      Spaces may appear only where explicitly indicated, and in the
23785      <definition>.
23786
23787      The Dwarf 2 spec says that an object-like macro's name is always
23788      followed by a space, but versions of GCC around March 2002 omit
23789      the space when the macro's definition is the empty string.
23790
23791      The Dwarf 2 spec says that there should be no spaces between the
23792      formal arguments in a function-like macro's formal argument list,
23793      but versions of GCC around March 2002 include spaces after the
23794      commas.  */
23795
23796
23797   /* Find the extent of the macro name.  The macro name is terminated
23798      by either a space or null character (for an object-like macro) or
23799      an opening paren (for a function-like macro).  */
23800   for (p = body; *p; p++)
23801     if (*p == ' ' || *p == '(')
23802       break;
23803
23804   if (*p == ' ' || *p == '\0')
23805     {
23806       /* It's an object-like macro.  */
23807       int name_len = p - body;
23808       char *name = savestring (body, name_len);
23809       const char *replacement;
23810
23811       if (*p == ' ')
23812         replacement = body + name_len + 1;
23813       else
23814         {
23815           dwarf2_macro_malformed_definition_complaint (body);
23816           replacement = body + name_len;
23817         }
23818
23819       macro_define_object (file, line, name, replacement);
23820
23821       xfree (name);
23822     }
23823   else if (*p == '(')
23824     {
23825       /* It's a function-like macro.  */
23826       char *name = savestring (body, p - body);
23827       int argc = 0;
23828       int argv_size = 1;
23829       char **argv = XNEWVEC (char *, argv_size);
23830
23831       p++;
23832
23833       p = consume_improper_spaces (p, body);
23834
23835       /* Parse the formal argument list.  */
23836       while (*p && *p != ')')
23837         {
23838           /* Find the extent of the current argument name.  */
23839           const char *arg_start = p;
23840
23841           while (*p && *p != ',' && *p != ')' && *p != ' ')
23842             p++;
23843
23844           if (! *p || p == arg_start)
23845             dwarf2_macro_malformed_definition_complaint (body);
23846           else
23847             {
23848               /* Make sure argv has room for the new argument.  */
23849               if (argc >= argv_size)
23850                 {
23851                   argv_size *= 2;
23852                   argv = XRESIZEVEC (char *, argv, argv_size);
23853                 }
23854
23855               argv[argc++] = savestring (arg_start, p - arg_start);
23856             }
23857
23858           p = consume_improper_spaces (p, body);
23859
23860           /* Consume the comma, if present.  */
23861           if (*p == ',')
23862             {
23863               p++;
23864
23865               p = consume_improper_spaces (p, body);
23866             }
23867         }
23868
23869       if (*p == ')')
23870         {
23871           p++;
23872
23873           if (*p == ' ')
23874             /* Perfectly formed definition, no complaints.  */
23875             macro_define_function (file, line, name,
23876                                    argc, (const char **) argv,
23877                                    p + 1);
23878           else if (*p == '\0')
23879             {
23880               /* Complain, but do define it.  */
23881               dwarf2_macro_malformed_definition_complaint (body);
23882               macro_define_function (file, line, name,
23883                                      argc, (const char **) argv,
23884                                      p);
23885             }
23886           else
23887             /* Just complain.  */
23888             dwarf2_macro_malformed_definition_complaint (body);
23889         }
23890       else
23891         /* Just complain.  */
23892         dwarf2_macro_malformed_definition_complaint (body);
23893
23894       xfree (name);
23895       {
23896         int i;
23897
23898         for (i = 0; i < argc; i++)
23899           xfree (argv[i]);
23900       }
23901       xfree (argv);
23902     }
23903   else
23904     dwarf2_macro_malformed_definition_complaint (body);
23905 }
23906
23907 /* Skip some bytes from BYTES according to the form given in FORM.
23908    Returns the new pointer.  */
23909
23910 static const gdb_byte *
23911 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23912                  enum dwarf_form form,
23913                  unsigned int offset_size,
23914                  struct dwarf2_section_info *section)
23915 {
23916   unsigned int bytes_read;
23917
23918   switch (form)
23919     {
23920     case DW_FORM_data1:
23921     case DW_FORM_flag:
23922       ++bytes;
23923       break;
23924
23925     case DW_FORM_data2:
23926       bytes += 2;
23927       break;
23928
23929     case DW_FORM_data4:
23930       bytes += 4;
23931       break;
23932
23933     case DW_FORM_data8:
23934       bytes += 8;
23935       break;
23936
23937     case DW_FORM_data16:
23938       bytes += 16;
23939       break;
23940
23941     case DW_FORM_string:
23942       read_direct_string (abfd, bytes, &bytes_read);
23943       bytes += bytes_read;
23944       break;
23945
23946     case DW_FORM_sec_offset:
23947     case DW_FORM_strp:
23948     case DW_FORM_GNU_strp_alt:
23949       bytes += offset_size;
23950       break;
23951
23952     case DW_FORM_block:
23953       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23954       bytes += bytes_read;
23955       break;
23956
23957     case DW_FORM_block1:
23958       bytes += 1 + read_1_byte (abfd, bytes);
23959       break;
23960     case DW_FORM_block2:
23961       bytes += 2 + read_2_bytes (abfd, bytes);
23962       break;
23963     case DW_FORM_block4:
23964       bytes += 4 + read_4_bytes (abfd, bytes);
23965       break;
23966
23967     case DW_FORM_sdata:
23968     case DW_FORM_udata:
23969     case DW_FORM_GNU_addr_index:
23970     case DW_FORM_GNU_str_index:
23971       bytes = gdb_skip_leb128 (bytes, buffer_end);
23972       if (bytes == NULL)
23973         {
23974           dwarf2_section_buffer_overflow_complaint (section);
23975           return NULL;
23976         }
23977       break;
23978
23979     case DW_FORM_implicit_const:
23980       break;
23981
23982     default:
23983       {
23984         complaint (&symfile_complaints,
23985                    _("invalid form 0x%x in `%s'"),
23986                    form, get_section_name (section));
23987         return NULL;
23988       }
23989     }
23990
23991   return bytes;
23992 }
23993
23994 /* A helper for dwarf_decode_macros that handles skipping an unknown
23995    opcode.  Returns an updated pointer to the macro data buffer; or,
23996    on error, issues a complaint and returns NULL.  */
23997
23998 static const gdb_byte *
23999 skip_unknown_opcode (unsigned int opcode,
24000                      const gdb_byte **opcode_definitions,
24001                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24002                      bfd *abfd,
24003                      unsigned int offset_size,
24004                      struct dwarf2_section_info *section)
24005 {
24006   unsigned int bytes_read, i;
24007   unsigned long arg;
24008   const gdb_byte *defn;
24009
24010   if (opcode_definitions[opcode] == NULL)
24011     {
24012       complaint (&symfile_complaints,
24013                  _("unrecognized DW_MACFINO opcode 0x%x"),
24014                  opcode);
24015       return NULL;
24016     }
24017
24018   defn = opcode_definitions[opcode];
24019   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24020   defn += bytes_read;
24021
24022   for (i = 0; i < arg; ++i)
24023     {
24024       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24025                                  (enum dwarf_form) defn[i], offset_size,
24026                                  section);
24027       if (mac_ptr == NULL)
24028         {
24029           /* skip_form_bytes already issued the complaint.  */
24030           return NULL;
24031         }
24032     }
24033
24034   return mac_ptr;
24035 }
24036
24037 /* A helper function which parses the header of a macro section.
24038    If the macro section is the extended (for now called "GNU") type,
24039    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24040    the header, or issues a complaint and returns NULL on error.  */
24041
24042 static const gdb_byte *
24043 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24044                           bfd *abfd,
24045                           const gdb_byte *mac_ptr,
24046                           unsigned int *offset_size,
24047                           int section_is_gnu)
24048 {
24049   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24050
24051   if (section_is_gnu)
24052     {
24053       unsigned int version, flags;
24054
24055       version = read_2_bytes (abfd, mac_ptr);
24056       if (version != 4 && version != 5)
24057         {
24058           complaint (&symfile_complaints,
24059                      _("unrecognized version `%d' in .debug_macro section"),
24060                      version);
24061           return NULL;
24062         }
24063       mac_ptr += 2;
24064
24065       flags = read_1_byte (abfd, mac_ptr);
24066       ++mac_ptr;
24067       *offset_size = (flags & 1) ? 8 : 4;
24068
24069       if ((flags & 2) != 0)
24070         /* We don't need the line table offset.  */
24071         mac_ptr += *offset_size;
24072
24073       /* Vendor opcode descriptions.  */
24074       if ((flags & 4) != 0)
24075         {
24076           unsigned int i, count;
24077
24078           count = read_1_byte (abfd, mac_ptr);
24079           ++mac_ptr;
24080           for (i = 0; i < count; ++i)
24081             {
24082               unsigned int opcode, bytes_read;
24083               unsigned long arg;
24084
24085               opcode = read_1_byte (abfd, mac_ptr);
24086               ++mac_ptr;
24087               opcode_definitions[opcode] = mac_ptr;
24088               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24089               mac_ptr += bytes_read;
24090               mac_ptr += arg;
24091             }
24092         }
24093     }
24094
24095   return mac_ptr;
24096 }
24097
24098 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24099    including DW_MACRO_import.  */
24100
24101 static void
24102 dwarf_decode_macro_bytes (bfd *abfd,
24103                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24104                           struct macro_source_file *current_file,
24105                           struct line_header *lh,
24106                           struct dwarf2_section_info *section,
24107                           int section_is_gnu, int section_is_dwz,
24108                           unsigned int offset_size,
24109                           htab_t include_hash)
24110 {
24111   struct objfile *objfile = dwarf2_per_objfile->objfile;
24112   enum dwarf_macro_record_type macinfo_type;
24113   int at_commandline;
24114   const gdb_byte *opcode_definitions[256];
24115
24116   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24117                                       &offset_size, section_is_gnu);
24118   if (mac_ptr == NULL)
24119     {
24120       /* We already issued a complaint.  */
24121       return;
24122     }
24123
24124   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24125      GDB is still reading the definitions from command line.  First
24126      DW_MACINFO_start_file will need to be ignored as it was already executed
24127      to create CURRENT_FILE for the main source holding also the command line
24128      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24129      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24130
24131   at_commandline = 1;
24132
24133   do
24134     {
24135       /* Do we at least have room for a macinfo type byte?  */
24136       if (mac_ptr >= mac_end)
24137         {
24138           dwarf2_section_buffer_overflow_complaint (section);
24139           break;
24140         }
24141
24142       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24143       mac_ptr++;
24144
24145       /* Note that we rely on the fact that the corresponding GNU and
24146          DWARF constants are the same.  */
24147       switch (macinfo_type)
24148         {
24149           /* A zero macinfo type indicates the end of the macro
24150              information.  */
24151         case 0:
24152           break;
24153
24154         case DW_MACRO_define:
24155         case DW_MACRO_undef:
24156         case DW_MACRO_define_strp:
24157         case DW_MACRO_undef_strp:
24158         case DW_MACRO_define_sup:
24159         case DW_MACRO_undef_sup:
24160           {
24161             unsigned int bytes_read;
24162             int line;
24163             const char *body;
24164             int is_define;
24165
24166             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24167             mac_ptr += bytes_read;
24168
24169             if (macinfo_type == DW_MACRO_define
24170                 || macinfo_type == DW_MACRO_undef)
24171               {
24172                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24173                 mac_ptr += bytes_read;
24174               }
24175             else
24176               {
24177                 LONGEST str_offset;
24178
24179                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24180                 mac_ptr += offset_size;
24181
24182                 if (macinfo_type == DW_MACRO_define_sup
24183                     || macinfo_type == DW_MACRO_undef_sup
24184                     || section_is_dwz)
24185                   {
24186                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
24187
24188                     body = read_indirect_string_from_dwz (dwz, str_offset);
24189                   }
24190                 else
24191                   body = read_indirect_string_at_offset (abfd, str_offset);
24192               }
24193
24194             is_define = (macinfo_type == DW_MACRO_define
24195                          || macinfo_type == DW_MACRO_define_strp
24196                          || macinfo_type == DW_MACRO_define_sup);
24197             if (! current_file)
24198               {
24199                 /* DWARF violation as no main source is present.  */
24200                 complaint (&symfile_complaints,
24201                            _("debug info with no main source gives macro %s "
24202                              "on line %d: %s"),
24203                            is_define ? _("definition") : _("undefinition"),
24204                            line, body);
24205                 break;
24206               }
24207             if ((line == 0 && !at_commandline)
24208                 || (line != 0 && at_commandline))
24209               complaint (&symfile_complaints,
24210                          _("debug info gives %s macro %s with %s line %d: %s"),
24211                          at_commandline ? _("command-line") : _("in-file"),
24212                          is_define ? _("definition") : _("undefinition"),
24213                          line == 0 ? _("zero") : _("non-zero"), line, body);
24214
24215             if (is_define)
24216               parse_macro_definition (current_file, line, body);
24217             else
24218               {
24219                 gdb_assert (macinfo_type == DW_MACRO_undef
24220                             || macinfo_type == DW_MACRO_undef_strp
24221                             || macinfo_type == DW_MACRO_undef_sup);
24222                 macro_undef (current_file, line, body);
24223               }
24224           }
24225           break;
24226
24227         case DW_MACRO_start_file:
24228           {
24229             unsigned int bytes_read;
24230             int line, file;
24231
24232             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24233             mac_ptr += bytes_read;
24234             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24235             mac_ptr += bytes_read;
24236
24237             if ((line == 0 && !at_commandline)
24238                 || (line != 0 && at_commandline))
24239               complaint (&symfile_complaints,
24240                          _("debug info gives source %d included "
24241                            "from %s at %s line %d"),
24242                          file, at_commandline ? _("command-line") : _("file"),
24243                          line == 0 ? _("zero") : _("non-zero"), line);
24244
24245             if (at_commandline)
24246               {
24247                 /* This DW_MACRO_start_file was executed in the
24248                    pass one.  */
24249                 at_commandline = 0;
24250               }
24251             else
24252               current_file = macro_start_file (file, line, current_file, lh);
24253           }
24254           break;
24255
24256         case DW_MACRO_end_file:
24257           if (! current_file)
24258             complaint (&symfile_complaints,
24259                        _("macro debug info has an unmatched "
24260                          "`close_file' directive"));
24261           else
24262             {
24263               current_file = current_file->included_by;
24264               if (! current_file)
24265                 {
24266                   enum dwarf_macro_record_type next_type;
24267
24268                   /* GCC circa March 2002 doesn't produce the zero
24269                      type byte marking the end of the compilation
24270                      unit.  Complain if it's not there, but exit no
24271                      matter what.  */
24272
24273                   /* Do we at least have room for a macinfo type byte?  */
24274                   if (mac_ptr >= mac_end)
24275                     {
24276                       dwarf2_section_buffer_overflow_complaint (section);
24277                       return;
24278                     }
24279
24280                   /* We don't increment mac_ptr here, so this is just
24281                      a look-ahead.  */
24282                   next_type
24283                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24284                                                                   mac_ptr);
24285                   if (next_type != 0)
24286                     complaint (&symfile_complaints,
24287                                _("no terminating 0-type entry for "
24288                                  "macros in `.debug_macinfo' section"));
24289
24290                   return;
24291                 }
24292             }
24293           break;
24294
24295         case DW_MACRO_import:
24296         case DW_MACRO_import_sup:
24297           {
24298             LONGEST offset;
24299             void **slot;
24300             bfd *include_bfd = abfd;
24301             struct dwarf2_section_info *include_section = section;
24302             const gdb_byte *include_mac_end = mac_end;
24303             int is_dwz = section_is_dwz;
24304             const gdb_byte *new_mac_ptr;
24305
24306             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24307             mac_ptr += offset_size;
24308
24309             if (macinfo_type == DW_MACRO_import_sup)
24310               {
24311                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
24312
24313                 dwarf2_read_section (objfile, &dwz->macro);
24314
24315                 include_section = &dwz->macro;
24316                 include_bfd = get_section_bfd_owner (include_section);
24317                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24318                 is_dwz = 1;
24319               }
24320
24321             new_mac_ptr = include_section->buffer + offset;
24322             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24323
24324             if (*slot != NULL)
24325               {
24326                 /* This has actually happened; see
24327                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24328                 complaint (&symfile_complaints,
24329                            _("recursive DW_MACRO_import in "
24330                              ".debug_macro section"));
24331               }
24332             else
24333               {
24334                 *slot = (void *) new_mac_ptr;
24335
24336                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
24337                                           include_mac_end, current_file, lh,
24338                                           section, section_is_gnu, is_dwz,
24339                                           offset_size, include_hash);
24340
24341                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24342               }
24343           }
24344           break;
24345
24346         case DW_MACINFO_vendor_ext:
24347           if (!section_is_gnu)
24348             {
24349               unsigned int bytes_read;
24350
24351               /* This reads the constant, but since we don't recognize
24352                  any vendor extensions, we ignore it.  */
24353               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24354               mac_ptr += bytes_read;
24355               read_direct_string (abfd, mac_ptr, &bytes_read);
24356               mac_ptr += bytes_read;
24357
24358               /* We don't recognize any vendor extensions.  */
24359               break;
24360             }
24361           /* FALLTHROUGH */
24362
24363         default:
24364           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24365                                          mac_ptr, mac_end, abfd, offset_size,
24366                                          section);
24367           if (mac_ptr == NULL)
24368             return;
24369           break;
24370         }
24371     } while (macinfo_type != 0);
24372 }
24373
24374 static void
24375 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24376                      int section_is_gnu)
24377 {
24378   struct objfile *objfile = dwarf2_per_objfile->objfile;
24379   struct line_header *lh = cu->line_header;
24380   bfd *abfd;
24381   const gdb_byte *mac_ptr, *mac_end;
24382   struct macro_source_file *current_file = 0;
24383   enum dwarf_macro_record_type macinfo_type;
24384   unsigned int offset_size = cu->header.offset_size;
24385   const gdb_byte *opcode_definitions[256];
24386   void **slot;
24387   struct dwarf2_section_info *section;
24388   const char *section_name;
24389
24390   if (cu->dwo_unit != NULL)
24391     {
24392       if (section_is_gnu)
24393         {
24394           section = &cu->dwo_unit->dwo_file->sections.macro;
24395           section_name = ".debug_macro.dwo";
24396         }
24397       else
24398         {
24399           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24400           section_name = ".debug_macinfo.dwo";
24401         }
24402     }
24403   else
24404     {
24405       if (section_is_gnu)
24406         {
24407           section = &dwarf2_per_objfile->macro;
24408           section_name = ".debug_macro";
24409         }
24410       else
24411         {
24412           section = &dwarf2_per_objfile->macinfo;
24413           section_name = ".debug_macinfo";
24414         }
24415     }
24416
24417   dwarf2_read_section (objfile, section);
24418   if (section->buffer == NULL)
24419     {
24420       complaint (&symfile_complaints, _("missing %s section"), section_name);
24421       return;
24422     }
24423   abfd = get_section_bfd_owner (section);
24424
24425   /* First pass: Find the name of the base filename.
24426      This filename is needed in order to process all macros whose definition
24427      (or undefinition) comes from the command line.  These macros are defined
24428      before the first DW_MACINFO_start_file entry, and yet still need to be
24429      associated to the base file.
24430
24431      To determine the base file name, we scan the macro definitions until we
24432      reach the first DW_MACINFO_start_file entry.  We then initialize
24433      CURRENT_FILE accordingly so that any macro definition found before the
24434      first DW_MACINFO_start_file can still be associated to the base file.  */
24435
24436   mac_ptr = section->buffer + offset;
24437   mac_end = section->buffer + section->size;
24438
24439   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24440                                       &offset_size, section_is_gnu);
24441   if (mac_ptr == NULL)
24442     {
24443       /* We already issued a complaint.  */
24444       return;
24445     }
24446
24447   do
24448     {
24449       /* Do we at least have room for a macinfo type byte?  */
24450       if (mac_ptr >= mac_end)
24451         {
24452           /* Complaint is printed during the second pass as GDB will probably
24453              stop the first pass earlier upon finding
24454              DW_MACINFO_start_file.  */
24455           break;
24456         }
24457
24458       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24459       mac_ptr++;
24460
24461       /* Note that we rely on the fact that the corresponding GNU and
24462          DWARF constants are the same.  */
24463       switch (macinfo_type)
24464         {
24465           /* A zero macinfo type indicates the end of the macro
24466              information.  */
24467         case 0:
24468           break;
24469
24470         case DW_MACRO_define:
24471         case DW_MACRO_undef:
24472           /* Only skip the data by MAC_PTR.  */
24473           {
24474             unsigned int bytes_read;
24475
24476             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24477             mac_ptr += bytes_read;
24478             read_direct_string (abfd, mac_ptr, &bytes_read);
24479             mac_ptr += bytes_read;
24480           }
24481           break;
24482
24483         case DW_MACRO_start_file:
24484           {
24485             unsigned int bytes_read;
24486             int line, file;
24487
24488             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24489             mac_ptr += bytes_read;
24490             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24491             mac_ptr += bytes_read;
24492
24493             current_file = macro_start_file (file, line, current_file, lh);
24494           }
24495           break;
24496
24497         case DW_MACRO_end_file:
24498           /* No data to skip by MAC_PTR.  */
24499           break;
24500
24501         case DW_MACRO_define_strp:
24502         case DW_MACRO_undef_strp:
24503         case DW_MACRO_define_sup:
24504         case DW_MACRO_undef_sup:
24505           {
24506             unsigned int bytes_read;
24507
24508             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24509             mac_ptr += bytes_read;
24510             mac_ptr += offset_size;
24511           }
24512           break;
24513
24514         case DW_MACRO_import:
24515         case DW_MACRO_import_sup:
24516           /* Note that, according to the spec, a transparent include
24517              chain cannot call DW_MACRO_start_file.  So, we can just
24518              skip this opcode.  */
24519           mac_ptr += offset_size;
24520           break;
24521
24522         case DW_MACINFO_vendor_ext:
24523           /* Only skip the data by MAC_PTR.  */
24524           if (!section_is_gnu)
24525             {
24526               unsigned int bytes_read;
24527
24528               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24529               mac_ptr += bytes_read;
24530               read_direct_string (abfd, mac_ptr, &bytes_read);
24531               mac_ptr += bytes_read;
24532             }
24533           /* FALLTHROUGH */
24534
24535         default:
24536           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24537                                          mac_ptr, mac_end, abfd, offset_size,
24538                                          section);
24539           if (mac_ptr == NULL)
24540             return;
24541           break;
24542         }
24543     } while (macinfo_type != 0 && current_file == NULL);
24544
24545   /* Second pass: Process all entries.
24546
24547      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24548      command-line macro definitions/undefinitions.  This flag is unset when we
24549      reach the first DW_MACINFO_start_file entry.  */
24550
24551   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24552                                            htab_eq_pointer,
24553                                            NULL, xcalloc, xfree));
24554   mac_ptr = section->buffer + offset;
24555   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24556   *slot = (void *) mac_ptr;
24557   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
24558                             current_file, lh, section,
24559                             section_is_gnu, 0, offset_size,
24560                             include_hash.get ());
24561 }
24562
24563 /* Check if the attribute's form is a DW_FORM_block*
24564    if so return true else false.  */
24565
24566 static int
24567 attr_form_is_block (const struct attribute *attr)
24568 {
24569   return (attr == NULL ? 0 :
24570       attr->form == DW_FORM_block1
24571       || attr->form == DW_FORM_block2
24572       || attr->form == DW_FORM_block4
24573       || attr->form == DW_FORM_block
24574       || attr->form == DW_FORM_exprloc);
24575 }
24576
24577 /* Return non-zero if ATTR's value is a section offset --- classes
24578    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24579    You may use DW_UNSND (attr) to retrieve such offsets.
24580
24581    Section 7.5.4, "Attribute Encodings", explains that no attribute
24582    may have a value that belongs to more than one of these classes; it
24583    would be ambiguous if we did, because we use the same forms for all
24584    of them.  */
24585
24586 static int
24587 attr_form_is_section_offset (const struct attribute *attr)
24588 {
24589   return (attr->form == DW_FORM_data4
24590           || attr->form == DW_FORM_data8
24591           || attr->form == DW_FORM_sec_offset);
24592 }
24593
24594 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24595    zero otherwise.  When this function returns true, you can apply
24596    dwarf2_get_attr_constant_value to it.
24597
24598    However, note that for some attributes you must check
24599    attr_form_is_section_offset before using this test.  DW_FORM_data4
24600    and DW_FORM_data8 are members of both the constant class, and of
24601    the classes that contain offsets into other debug sections
24602    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24603    that, if an attribute's can be either a constant or one of the
24604    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24605    taken as section offsets, not constants.
24606
24607    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24608    cannot handle that.  */
24609
24610 static int
24611 attr_form_is_constant (const struct attribute *attr)
24612 {
24613   switch (attr->form)
24614     {
24615     case DW_FORM_sdata:
24616     case DW_FORM_udata:
24617     case DW_FORM_data1:
24618     case DW_FORM_data2:
24619     case DW_FORM_data4:
24620     case DW_FORM_data8:
24621     case DW_FORM_implicit_const:
24622       return 1;
24623     default:
24624       return 0;
24625     }
24626 }
24627
24628
24629 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24630    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24631
24632 static int
24633 attr_form_is_ref (const struct attribute *attr)
24634 {
24635   switch (attr->form)
24636     {
24637     case DW_FORM_ref_addr:
24638     case DW_FORM_ref1:
24639     case DW_FORM_ref2:
24640     case DW_FORM_ref4:
24641     case DW_FORM_ref8:
24642     case DW_FORM_ref_udata:
24643     case DW_FORM_GNU_ref_alt:
24644       return 1;
24645     default:
24646       return 0;
24647     }
24648 }
24649
24650 /* Return the .debug_loc section to use for CU.
24651    For DWO files use .debug_loc.dwo.  */
24652
24653 static struct dwarf2_section_info *
24654 cu_debug_loc_section (struct dwarf2_cu *cu)
24655 {
24656   if (cu->dwo_unit)
24657     {
24658       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24659       
24660       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24661     }
24662   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24663                                   : &dwarf2_per_objfile->loc);
24664 }
24665
24666 /* A helper function that fills in a dwarf2_loclist_baton.  */
24667
24668 static void
24669 fill_in_loclist_baton (struct dwarf2_cu *cu,
24670                        struct dwarf2_loclist_baton *baton,
24671                        const struct attribute *attr)
24672 {
24673   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24674
24675   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24676
24677   baton->per_cu = cu->per_cu;
24678   gdb_assert (baton->per_cu);
24679   /* We don't know how long the location list is, but make sure we
24680      don't run off the edge of the section.  */
24681   baton->size = section->size - DW_UNSND (attr);
24682   baton->data = section->buffer + DW_UNSND (attr);
24683   baton->base_address = cu->base_address;
24684   baton->from_dwo = cu->dwo_unit != NULL;
24685 }
24686
24687 static void
24688 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24689                              struct dwarf2_cu *cu, int is_block)
24690 {
24691   struct objfile *objfile = dwarf2_per_objfile->objfile;
24692   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24693
24694   if (attr_form_is_section_offset (attr)
24695       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24696          the section.  If so, fall through to the complaint in the
24697          other branch.  */
24698       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24699     {
24700       struct dwarf2_loclist_baton *baton;
24701
24702       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24703
24704       fill_in_loclist_baton (cu, baton, attr);
24705
24706       if (cu->base_known == 0)
24707         complaint (&symfile_complaints,
24708                    _("Location list used without "
24709                      "specifying the CU base address."));
24710
24711       SYMBOL_ACLASS_INDEX (sym) = (is_block
24712                                    ? dwarf2_loclist_block_index
24713                                    : dwarf2_loclist_index);
24714       SYMBOL_LOCATION_BATON (sym) = baton;
24715     }
24716   else
24717     {
24718       struct dwarf2_locexpr_baton *baton;
24719
24720       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24721       baton->per_cu = cu->per_cu;
24722       gdb_assert (baton->per_cu);
24723
24724       if (attr_form_is_block (attr))
24725         {
24726           /* Note that we're just copying the block's data pointer
24727              here, not the actual data.  We're still pointing into the
24728              info_buffer for SYM's objfile; right now we never release
24729              that buffer, but when we do clean up properly this may
24730              need to change.  */
24731           baton->size = DW_BLOCK (attr)->size;
24732           baton->data = DW_BLOCK (attr)->data;
24733         }
24734       else
24735         {
24736           dwarf2_invalid_attrib_class_complaint ("location description",
24737                                                  SYMBOL_NATURAL_NAME (sym));
24738           baton->size = 0;
24739         }
24740
24741       SYMBOL_ACLASS_INDEX (sym) = (is_block
24742                                    ? dwarf2_locexpr_block_index
24743                                    : dwarf2_locexpr_index);
24744       SYMBOL_LOCATION_BATON (sym) = baton;
24745     }
24746 }
24747
24748 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24749    came from a separate debuginfo file, then the master objfile is
24750    returned.  */
24751
24752 struct objfile *
24753 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24754 {
24755   struct objfile *objfile = per_cu->objfile;
24756
24757   /* Return the master objfile, so that we can report and look up the
24758      correct file containing this variable.  */
24759   if (objfile->separate_debug_objfile_backlink)
24760     objfile = objfile->separate_debug_objfile_backlink;
24761
24762   return objfile;
24763 }
24764
24765 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24766    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24767    CU_HEADERP first.  */
24768
24769 static const struct comp_unit_head *
24770 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24771                        struct dwarf2_per_cu_data *per_cu)
24772 {
24773   const gdb_byte *info_ptr;
24774
24775   if (per_cu->cu)
24776     return &per_cu->cu->header;
24777
24778   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24779
24780   memset (cu_headerp, 0, sizeof (*cu_headerp));
24781   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24782                        rcuh_kind::COMPILE);
24783
24784   return cu_headerp;
24785 }
24786
24787 /* Return the address size given in the compilation unit header for CU.  */
24788
24789 int
24790 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24791 {
24792   struct comp_unit_head cu_header_local;
24793   const struct comp_unit_head *cu_headerp;
24794
24795   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24796
24797   return cu_headerp->addr_size;
24798 }
24799
24800 /* Return the offset size given in the compilation unit header for CU.  */
24801
24802 int
24803 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24804 {
24805   struct comp_unit_head cu_header_local;
24806   const struct comp_unit_head *cu_headerp;
24807
24808   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24809
24810   return cu_headerp->offset_size;
24811 }
24812
24813 /* See its dwarf2loc.h declaration.  */
24814
24815 int
24816 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24817 {
24818   struct comp_unit_head cu_header_local;
24819   const struct comp_unit_head *cu_headerp;
24820
24821   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24822
24823   if (cu_headerp->version == 2)
24824     return cu_headerp->addr_size;
24825   else
24826     return cu_headerp->offset_size;
24827 }
24828
24829 /* Return the text offset of the CU.  The returned offset comes from
24830    this CU's objfile.  If this objfile came from a separate debuginfo
24831    file, then the offset may be different from the corresponding
24832    offset in the parent objfile.  */
24833
24834 CORE_ADDR
24835 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24836 {
24837   struct objfile *objfile = per_cu->objfile;
24838
24839   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24840 }
24841
24842 /* Return DWARF version number of PER_CU.  */
24843
24844 short
24845 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24846 {
24847   return per_cu->dwarf_version;
24848 }
24849
24850 /* Locate the .debug_info compilation unit from CU's objfile which contains
24851    the DIE at OFFSET.  Raises an error on failure.  */
24852
24853 static struct dwarf2_per_cu_data *
24854 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24855                                   unsigned int offset_in_dwz,
24856                                   struct objfile *objfile)
24857 {
24858   struct dwarf2_per_cu_data *this_cu;
24859   int low, high;
24860   const sect_offset *cu_off;
24861
24862   low = 0;
24863   high = dwarf2_per_objfile->n_comp_units - 1;
24864   while (high > low)
24865     {
24866       struct dwarf2_per_cu_data *mid_cu;
24867       int mid = low + (high - low) / 2;
24868
24869       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24870       cu_off = &mid_cu->sect_off;
24871       if (mid_cu->is_dwz > offset_in_dwz
24872           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24873         high = mid;
24874       else
24875         low = mid + 1;
24876     }
24877   gdb_assert (low == high);
24878   this_cu = dwarf2_per_objfile->all_comp_units[low];
24879   cu_off = &this_cu->sect_off;
24880   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24881     {
24882       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24883         error (_("Dwarf Error: could not find partial DIE containing "
24884                "offset 0x%x [in module %s]"),
24885                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
24886
24887       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24888                   <= sect_off);
24889       return dwarf2_per_objfile->all_comp_units[low-1];
24890     }
24891   else
24892     {
24893       this_cu = dwarf2_per_objfile->all_comp_units[low];
24894       if (low == dwarf2_per_objfile->n_comp_units - 1
24895           && sect_off >= this_cu->sect_off + this_cu->length)
24896         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
24897       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24898       return this_cu;
24899     }
24900 }
24901
24902 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24903
24904 static void
24905 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
24906 {
24907   memset (cu, 0, sizeof (*cu));
24908   per_cu->cu = cu;
24909   cu->per_cu = per_cu;
24910   cu->objfile = per_cu->objfile;
24911   obstack_init (&cu->comp_unit_obstack);
24912 }
24913
24914 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24915
24916 static void
24917 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24918                        enum language pretend_language)
24919 {
24920   struct attribute *attr;
24921
24922   /* Set the language we're debugging.  */
24923   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24924   if (attr)
24925     set_cu_language (DW_UNSND (attr), cu);
24926   else
24927     {
24928       cu->language = pretend_language;
24929       cu->language_defn = language_def (cu->language);
24930     }
24931
24932   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24933 }
24934
24935 /* Release one cached compilation unit, CU.  We unlink it from the tree
24936    of compilation units, but we don't remove it from the read_in_chain;
24937    the caller is responsible for that.
24938    NOTE: DATA is a void * because this function is also used as a
24939    cleanup routine.  */
24940
24941 static void
24942 free_heap_comp_unit (void *data)
24943 {
24944   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
24945
24946   gdb_assert (cu->per_cu != NULL);
24947   cu->per_cu->cu = NULL;
24948   cu->per_cu = NULL;
24949
24950   obstack_free (&cu->comp_unit_obstack, NULL);
24951
24952   xfree (cu);
24953 }
24954
24955 /* This cleanup function is passed the address of a dwarf2_cu on the stack
24956    when we're finished with it.  We can't free the pointer itself, but be
24957    sure to unlink it from the cache.  Also release any associated storage.  */
24958
24959 static void
24960 free_stack_comp_unit (void *data)
24961 {
24962   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
24963
24964   gdb_assert (cu->per_cu != NULL);
24965   cu->per_cu->cu = NULL;
24966   cu->per_cu = NULL;
24967
24968   obstack_free (&cu->comp_unit_obstack, NULL);
24969   cu->partial_dies = NULL;
24970 }
24971
24972 /* Free all cached compilation units.  */
24973
24974 static void
24975 free_cached_comp_units (void *data)
24976 {
24977   dwarf2_per_objfile->free_cached_comp_units ();
24978 }
24979
24980 /* Increase the age counter on each cached compilation unit, and free
24981    any that are too old.  */
24982
24983 static void
24984 age_cached_comp_units (void)
24985 {
24986   struct dwarf2_per_cu_data *per_cu, **last_chain;
24987
24988   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24989   per_cu = dwarf2_per_objfile->read_in_chain;
24990   while (per_cu != NULL)
24991     {
24992       per_cu->cu->last_used ++;
24993       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24994         dwarf2_mark (per_cu->cu);
24995       per_cu = per_cu->cu->read_in_chain;
24996     }
24997
24998   per_cu = dwarf2_per_objfile->read_in_chain;
24999   last_chain = &dwarf2_per_objfile->read_in_chain;
25000   while (per_cu != NULL)
25001     {
25002       struct dwarf2_per_cu_data *next_cu;
25003
25004       next_cu = per_cu->cu->read_in_chain;
25005
25006       if (!per_cu->cu->mark)
25007         {
25008           free_heap_comp_unit (per_cu->cu);
25009           *last_chain = next_cu;
25010         }
25011       else
25012         last_chain = &per_cu->cu->read_in_chain;
25013
25014       per_cu = next_cu;
25015     }
25016 }
25017
25018 /* Remove a single compilation unit from the cache.  */
25019
25020 static void
25021 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25022 {
25023   struct dwarf2_per_cu_data *per_cu, **last_chain;
25024
25025   per_cu = dwarf2_per_objfile->read_in_chain;
25026   last_chain = &dwarf2_per_objfile->read_in_chain;
25027   while (per_cu != NULL)
25028     {
25029       struct dwarf2_per_cu_data *next_cu;
25030
25031       next_cu = per_cu->cu->read_in_chain;
25032
25033       if (per_cu == target_per_cu)
25034         {
25035           free_heap_comp_unit (per_cu->cu);
25036           per_cu->cu = NULL;
25037           *last_chain = next_cu;
25038           break;
25039         }
25040       else
25041         last_chain = &per_cu->cu->read_in_chain;
25042
25043       per_cu = next_cu;
25044     }
25045 }
25046
25047 /* Release all extra memory associated with OBJFILE.  */
25048
25049 void
25050 dwarf2_free_objfile (struct objfile *objfile)
25051 {
25052   dwarf2_per_objfile
25053     = (struct dwarf2_per_objfile *) objfile_data (objfile,
25054                                                   dwarf2_objfile_data_key);
25055
25056   if (dwarf2_per_objfile == NULL)
25057     return;
25058
25059   dwarf2_per_objfile->~dwarf2_per_objfile ();
25060 }
25061
25062 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25063    We store these in a hash table separate from the DIEs, and preserve them
25064    when the DIEs are flushed out of cache.
25065
25066    The CU "per_cu" pointer is needed because offset alone is not enough to
25067    uniquely identify the type.  A file may have multiple .debug_types sections,
25068    or the type may come from a DWO file.  Furthermore, while it's more logical
25069    to use per_cu->section+offset, with Fission the section with the data is in
25070    the DWO file but we don't know that section at the point we need it.
25071    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25072    because we can enter the lookup routine, get_die_type_at_offset, from
25073    outside this file, and thus won't necessarily have PER_CU->cu.
25074    Fortunately, PER_CU is stable for the life of the objfile.  */
25075
25076 struct dwarf2_per_cu_offset_and_type
25077 {
25078   const struct dwarf2_per_cu_data *per_cu;
25079   sect_offset sect_off;
25080   struct type *type;
25081 };
25082
25083 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25084
25085 static hashval_t
25086 per_cu_offset_and_type_hash (const void *item)
25087 {
25088   const struct dwarf2_per_cu_offset_and_type *ofs
25089     = (const struct dwarf2_per_cu_offset_and_type *) item;
25090
25091   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25092 }
25093
25094 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25095
25096 static int
25097 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25098 {
25099   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25100     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25101   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25102     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25103
25104   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25105           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25106 }
25107
25108 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25109    table if necessary.  For convenience, return TYPE.
25110
25111    The DIEs reading must have careful ordering to:
25112     * Not cause infite loops trying to read in DIEs as a prerequisite for
25113       reading current DIE.
25114     * Not trying to dereference contents of still incompletely read in types
25115       while reading in other DIEs.
25116     * Enable referencing still incompletely read in types just by a pointer to
25117       the type without accessing its fields.
25118
25119    Therefore caller should follow these rules:
25120      * Try to fetch any prerequisite types we may need to build this DIE type
25121        before building the type and calling set_die_type.
25122      * After building type call set_die_type for current DIE as soon as
25123        possible before fetching more types to complete the current type.
25124      * Make the type as complete as possible before fetching more types.  */
25125
25126 static struct type *
25127 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25128 {
25129   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25130   struct objfile *objfile = cu->objfile;
25131   struct attribute *attr;
25132   struct dynamic_prop prop;
25133
25134   /* For Ada types, make sure that the gnat-specific data is always
25135      initialized (if not already set).  There are a few types where
25136      we should not be doing so, because the type-specific area is
25137      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25138      where the type-specific area is used to store the floatformat).
25139      But this is not a problem, because the gnat-specific information
25140      is actually not needed for these types.  */
25141   if (need_gnat_info (cu)
25142       && TYPE_CODE (type) != TYPE_CODE_FUNC
25143       && TYPE_CODE (type) != TYPE_CODE_FLT
25144       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25145       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25146       && TYPE_CODE (type) != TYPE_CODE_METHOD
25147       && !HAVE_GNAT_AUX_INFO (type))
25148     INIT_GNAT_SPECIFIC (type);
25149
25150   /* Read DW_AT_allocated and set in type.  */
25151   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25152   if (attr_form_is_block (attr))
25153     {
25154       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25155         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
25156     }
25157   else if (attr != NULL)
25158     {
25159       complaint (&symfile_complaints,
25160                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25161                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25162                  to_underlying (die->sect_off));
25163     }
25164
25165   /* Read DW_AT_associated and set in type.  */
25166   attr = dwarf2_attr (die, DW_AT_associated, cu);
25167   if (attr_form_is_block (attr))
25168     {
25169       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25170         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
25171     }
25172   else if (attr != NULL)
25173     {
25174       complaint (&symfile_complaints,
25175                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25176                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25177                  to_underlying (die->sect_off));
25178     }
25179
25180   /* Read DW_AT_data_location and set in type.  */
25181   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25182   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25183     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
25184
25185   if (dwarf2_per_objfile->die_type_hash == NULL)
25186     {
25187       dwarf2_per_objfile->die_type_hash =
25188         htab_create_alloc_ex (127,
25189                               per_cu_offset_and_type_hash,
25190                               per_cu_offset_and_type_eq,
25191                               NULL,
25192                               &objfile->objfile_obstack,
25193                               hashtab_obstack_allocate,
25194                               dummy_obstack_deallocate);
25195     }
25196
25197   ofs.per_cu = cu->per_cu;
25198   ofs.sect_off = die->sect_off;
25199   ofs.type = type;
25200   slot = (struct dwarf2_per_cu_offset_and_type **)
25201     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25202   if (*slot)
25203     complaint (&symfile_complaints,
25204                _("A problem internal to GDB: DIE 0x%x has type already set"),
25205                to_underlying (die->sect_off));
25206   *slot = XOBNEW (&objfile->objfile_obstack,
25207                   struct dwarf2_per_cu_offset_and_type);
25208   **slot = ofs;
25209   return type;
25210 }
25211
25212 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25213    or return NULL if the die does not have a saved type.  */
25214
25215 static struct type *
25216 get_die_type_at_offset (sect_offset sect_off,
25217                         struct dwarf2_per_cu_data *per_cu)
25218 {
25219   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25220
25221   if (dwarf2_per_objfile->die_type_hash == NULL)
25222     return NULL;
25223
25224   ofs.per_cu = per_cu;
25225   ofs.sect_off = sect_off;
25226   slot = ((struct dwarf2_per_cu_offset_and_type *)
25227           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25228   if (slot)
25229     return slot->type;
25230   else
25231     return NULL;
25232 }
25233
25234 /* Look up the type for DIE in CU in die_type_hash,
25235    or return NULL if DIE does not have a saved type.  */
25236
25237 static struct type *
25238 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25239 {
25240   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25241 }
25242
25243 /* Add a dependence relationship from CU to REF_PER_CU.  */
25244
25245 static void
25246 dwarf2_add_dependence (struct dwarf2_cu *cu,
25247                        struct dwarf2_per_cu_data *ref_per_cu)
25248 {
25249   void **slot;
25250
25251   if (cu->dependencies == NULL)
25252     cu->dependencies
25253       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25254                               NULL, &cu->comp_unit_obstack,
25255                               hashtab_obstack_allocate,
25256                               dummy_obstack_deallocate);
25257
25258   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25259   if (*slot == NULL)
25260     *slot = ref_per_cu;
25261 }
25262
25263 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25264    Set the mark field in every compilation unit in the
25265    cache that we must keep because we are keeping CU.  */
25266
25267 static int
25268 dwarf2_mark_helper (void **slot, void *data)
25269 {
25270   struct dwarf2_per_cu_data *per_cu;
25271
25272   per_cu = (struct dwarf2_per_cu_data *) *slot;
25273
25274   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25275      reading of the chain.  As such dependencies remain valid it is not much
25276      useful to track and undo them during QUIT cleanups.  */
25277   if (per_cu->cu == NULL)
25278     return 1;
25279
25280   if (per_cu->cu->mark)
25281     return 1;
25282   per_cu->cu->mark = 1;
25283
25284   if (per_cu->cu->dependencies != NULL)
25285     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25286
25287   return 1;
25288 }
25289
25290 /* Set the mark field in CU and in every other compilation unit in the
25291    cache that we must keep because we are keeping CU.  */
25292
25293 static void
25294 dwarf2_mark (struct dwarf2_cu *cu)
25295 {
25296   if (cu->mark)
25297     return;
25298   cu->mark = 1;
25299   if (cu->dependencies != NULL)
25300     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25301 }
25302
25303 static void
25304 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25305 {
25306   while (per_cu)
25307     {
25308       per_cu->cu->mark = 0;
25309       per_cu = per_cu->cu->read_in_chain;
25310     }
25311 }
25312
25313 /* Trivial hash function for partial_die_info: the hash value of a DIE
25314    is its offset in .debug_info for this objfile.  */
25315
25316 static hashval_t
25317 partial_die_hash (const void *item)
25318 {
25319   const struct partial_die_info *part_die
25320     = (const struct partial_die_info *) item;
25321
25322   return to_underlying (part_die->sect_off);
25323 }
25324
25325 /* Trivial comparison function for partial_die_info structures: two DIEs
25326    are equal if they have the same offset.  */
25327
25328 static int
25329 partial_die_eq (const void *item_lhs, const void *item_rhs)
25330 {
25331   const struct partial_die_info *part_die_lhs
25332     = (const struct partial_die_info *) item_lhs;
25333   const struct partial_die_info *part_die_rhs
25334     = (const struct partial_die_info *) item_rhs;
25335
25336   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25337 }
25338
25339 static struct cmd_list_element *set_dwarf_cmdlist;
25340 static struct cmd_list_element *show_dwarf_cmdlist;
25341
25342 static void
25343 set_dwarf_cmd (const char *args, int from_tty)
25344 {
25345   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25346              gdb_stdout);
25347 }
25348
25349 static void
25350 show_dwarf_cmd (const char *args, int from_tty)
25351 {
25352   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25353 }
25354
25355 /* Free data associated with OBJFILE, if necessary.  */
25356
25357 static void
25358 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25359 {
25360   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25361   int ix;
25362
25363   /* Make sure we don't accidentally use dwarf2_per_objfile while
25364      cleaning up.  */
25365   dwarf2_per_objfile = NULL;
25366
25367   for (ix = 0; ix < data->n_comp_units; ++ix)
25368    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25369
25370   for (ix = 0; ix < data->n_type_units; ++ix)
25371     VEC_free (dwarf2_per_cu_ptr,
25372               data->all_type_units[ix]->per_cu.imported_symtabs);
25373   xfree (data->all_type_units);
25374
25375   VEC_free (dwarf2_section_info_def, data->types);
25376
25377   if (data->dwo_files)
25378     free_dwo_files (data->dwo_files, objfile);
25379   if (data->dwp_file)
25380     gdb_bfd_unref (data->dwp_file->dbfd);
25381
25382   if (data->dwz_file && data->dwz_file->dwz_bfd)
25383     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25384
25385   if (data->index_table != NULL)
25386     data->index_table->~mapped_index ();
25387 }
25388
25389 \f
25390 /* The "save gdb-index" command.  */
25391
25392 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25393    error checking.  */
25394
25395 static void
25396 file_write (FILE *file, const void *data, size_t size)
25397 {
25398   if (fwrite (data, 1, size, file) != size)
25399     error (_("couldn't data write to file"));
25400 }
25401
25402 /* Write the contents of VEC to FILE, with error checking.  */
25403
25404 template<typename Elem, typename Alloc>
25405 static void
25406 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25407 {
25408   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25409 }
25410
25411 /* In-memory buffer to prepare data to be written later to a file.  */
25412 class data_buf
25413 {
25414 public:
25415   /* Copy DATA to the end of the buffer.  */
25416   template<typename T>
25417   void append_data (const T &data)
25418   {
25419     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25420                reinterpret_cast<const gdb_byte *> (&data + 1),
25421                grow (sizeof (data)));
25422   }
25423
25424   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25425      terminating zero is appended too.  */
25426   void append_cstr0 (const char *cstr)
25427   {
25428     const size_t size = strlen (cstr) + 1;
25429     std::copy (cstr, cstr + size, grow (size));
25430   }
25431
25432   /* Store INPUT as ULEB128 to the end of buffer.  */
25433   void append_unsigned_leb128 (ULONGEST input)
25434   {
25435     for (;;)
25436       {
25437         gdb_byte output = input & 0x7f;
25438         input >>= 7;
25439         if (input)
25440           output |= 0x80;
25441         append_data (output);
25442         if (input == 0)
25443           break;
25444       }
25445   }
25446
25447   /* Accept a host-format integer in VAL and append it to the buffer
25448      as a target-format integer which is LEN bytes long.  */
25449   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25450   {
25451     ::store_unsigned_integer (grow (len), len, byte_order, val);
25452   }
25453
25454   /* Return the size of the buffer.  */
25455   size_t size () const
25456   {
25457     return m_vec.size ();
25458   }
25459
25460   /* Return true iff the buffer is empty.  */
25461   bool empty () const
25462   {
25463     return m_vec.empty ();
25464   }
25465
25466   /* Write the buffer to FILE.  */
25467   void file_write (FILE *file) const
25468   {
25469     ::file_write (file, m_vec);
25470   }
25471
25472 private:
25473   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25474      the start of the new block.  */
25475   gdb_byte *grow (size_t size)
25476   {
25477     m_vec.resize (m_vec.size () + size);
25478     return &*m_vec.end () - size;
25479   }
25480
25481   gdb::byte_vector m_vec;
25482 };
25483
25484 /* An entry in the symbol table.  */
25485 struct symtab_index_entry
25486 {
25487   /* The name of the symbol.  */
25488   const char *name;
25489   /* The offset of the name in the constant pool.  */
25490   offset_type index_offset;
25491   /* A sorted vector of the indices of all the CUs that hold an object
25492      of this name.  */
25493   std::vector<offset_type> cu_indices;
25494 };
25495
25496 /* The symbol table.  This is a power-of-2-sized hash table.  */
25497 struct mapped_symtab
25498 {
25499   mapped_symtab ()
25500   {
25501     data.resize (1024);
25502   }
25503
25504   offset_type n_elements = 0;
25505   std::vector<symtab_index_entry> data;
25506 };
25507
25508 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25509    the slot.
25510    
25511    Function is used only during write_hash_table so no index format backward
25512    compatibility is needed.  */
25513
25514 static symtab_index_entry &
25515 find_slot (struct mapped_symtab *symtab, const char *name)
25516 {
25517   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25518
25519   index = hash & (symtab->data.size () - 1);
25520   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25521
25522   for (;;)
25523     {
25524       if (symtab->data[index].name == NULL
25525           || strcmp (name, symtab->data[index].name) == 0)
25526         return symtab->data[index];
25527       index = (index + step) & (symtab->data.size () - 1);
25528     }
25529 }
25530
25531 /* Expand SYMTAB's hash table.  */
25532
25533 static void
25534 hash_expand (struct mapped_symtab *symtab)
25535 {
25536   auto old_entries = std::move (symtab->data);
25537
25538   symtab->data.clear ();
25539   symtab->data.resize (old_entries.size () * 2);
25540
25541   for (auto &it : old_entries)
25542     if (it.name != NULL)
25543       {
25544         auto &ref = find_slot (symtab, it.name);
25545         ref = std::move (it);
25546       }
25547 }
25548
25549 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25550    CU_INDEX is the index of the CU in which the symbol appears.
25551    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25552
25553 static void
25554 add_index_entry (struct mapped_symtab *symtab, const char *name,
25555                  int is_static, gdb_index_symbol_kind kind,
25556                  offset_type cu_index)
25557 {
25558   offset_type cu_index_and_attrs;
25559
25560   ++symtab->n_elements;
25561   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25562     hash_expand (symtab);
25563
25564   symtab_index_entry &slot = find_slot (symtab, name);
25565   if (slot.name == NULL)
25566     {
25567       slot.name = name;
25568       /* index_offset is set later.  */
25569     }
25570
25571   cu_index_and_attrs = 0;
25572   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25573   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25574   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25575
25576   /* We don't want to record an index value twice as we want to avoid the
25577      duplication.
25578      We process all global symbols and then all static symbols
25579      (which would allow us to avoid the duplication by only having to check
25580      the last entry pushed), but a symbol could have multiple kinds in one CU.
25581      To keep things simple we don't worry about the duplication here and
25582      sort and uniqufy the list after we've processed all symbols.  */
25583   slot.cu_indices.push_back (cu_index_and_attrs);
25584 }
25585
25586 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25587
25588 static void
25589 uniquify_cu_indices (struct mapped_symtab *symtab)
25590 {
25591   for (auto &entry : symtab->data)
25592     {
25593       if (entry.name != NULL && !entry.cu_indices.empty ())
25594         {
25595           auto &cu_indices = entry.cu_indices;
25596           std::sort (cu_indices.begin (), cu_indices.end ());
25597           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25598           cu_indices.erase (from, cu_indices.end ());
25599         }
25600     }
25601 }
25602
25603 /* A form of 'const char *' suitable for container keys.  Only the
25604    pointer is stored.  The strings themselves are compared, not the
25605    pointers.  */
25606 class c_str_view
25607 {
25608 public:
25609   c_str_view (const char *cstr)
25610     : m_cstr (cstr)
25611   {}
25612
25613   bool operator== (const c_str_view &other) const
25614   {
25615     return strcmp (m_cstr, other.m_cstr) == 0;
25616   }
25617
25618   /* Return the underlying C string.  Note, the returned string is
25619      only a reference with lifetime of this object.  */
25620   const char *c_str () const
25621   {
25622     return m_cstr;
25623   }
25624
25625 private:
25626   friend class c_str_view_hasher;
25627   const char *const m_cstr;
25628 };
25629
25630 /* A std::unordered_map::hasher for c_str_view that uses the right
25631    hash function for strings in a mapped index.  */
25632 class c_str_view_hasher
25633 {
25634 public:
25635   size_t operator () (const c_str_view &x) const
25636   {
25637     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25638   }
25639 };
25640
25641 /* A std::unordered_map::hasher for std::vector<>.  */
25642 template<typename T>
25643 class vector_hasher
25644 {
25645 public:
25646   size_t operator () (const std::vector<T> &key) const
25647   {
25648     return iterative_hash (key.data (),
25649                            sizeof (key.front ()) * key.size (), 0);
25650   }
25651 };
25652
25653 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25654    constant pool entries going into the data buffer CPOOL.  */
25655
25656 static void
25657 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25658 {
25659   {
25660     /* Elements are sorted vectors of the indices of all the CUs that
25661        hold an object of this name.  */
25662     std::unordered_map<std::vector<offset_type>, offset_type,
25663                        vector_hasher<offset_type>>
25664       symbol_hash_table;
25665
25666     /* We add all the index vectors to the constant pool first, to
25667        ensure alignment is ok.  */
25668     for (symtab_index_entry &entry : symtab->data)
25669       {
25670         if (entry.name == NULL)
25671           continue;
25672         gdb_assert (entry.index_offset == 0);
25673
25674         /* Finding before inserting is faster than always trying to
25675            insert, because inserting always allocates a node, does the
25676            lookup, and then destroys the new node if another node
25677            already had the same key.  C++17 try_emplace will avoid
25678            this.  */
25679         const auto found
25680           = symbol_hash_table.find (entry.cu_indices);
25681         if (found != symbol_hash_table.end ())
25682           {
25683             entry.index_offset = found->second;
25684             continue;
25685           }
25686
25687         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25688         entry.index_offset = cpool.size ();
25689         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25690         for (const auto index : entry.cu_indices)
25691           cpool.append_data (MAYBE_SWAP (index));
25692       }
25693   }
25694
25695   /* Now write out the hash table.  */
25696   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25697   for (const auto &entry : symtab->data)
25698     {
25699       offset_type str_off, vec_off;
25700
25701       if (entry.name != NULL)
25702         {
25703           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25704           if (insertpair.second)
25705             cpool.append_cstr0 (entry.name);
25706           str_off = insertpair.first->second;
25707           vec_off = entry.index_offset;
25708         }
25709       else
25710         {
25711           /* While 0 is a valid constant pool index, it is not valid
25712              to have 0 for both offsets.  */
25713           str_off = 0;
25714           vec_off = 0;
25715         }
25716
25717       output.append_data (MAYBE_SWAP (str_off));
25718       output.append_data (MAYBE_SWAP (vec_off));
25719     }
25720 }
25721
25722 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
25723
25724 /* Helper struct for building the address table.  */
25725 struct addrmap_index_data
25726 {
25727   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
25728     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
25729   {}
25730
25731   struct objfile *objfile;
25732   data_buf &addr_vec;
25733   psym_index_map &cu_index_htab;
25734
25735   /* Non-zero if the previous_* fields are valid.
25736      We can't write an entry until we see the next entry (since it is only then
25737      that we know the end of the entry).  */
25738   int previous_valid;
25739   /* Index of the CU in the table of all CUs in the index file.  */
25740   unsigned int previous_cu_index;
25741   /* Start address of the CU.  */
25742   CORE_ADDR previous_cu_start;
25743 };
25744
25745 /* Write an address entry to ADDR_VEC.  */
25746
25747 static void
25748 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
25749                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
25750 {
25751   CORE_ADDR baseaddr;
25752
25753   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25754
25755   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
25756   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
25757   addr_vec.append_data (MAYBE_SWAP (cu_index));
25758 }
25759
25760 /* Worker function for traversing an addrmap to build the address table.  */
25761
25762 static int
25763 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
25764 {
25765   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
25766   struct partial_symtab *pst = (struct partial_symtab *) obj;
25767
25768   if (data->previous_valid)
25769     add_address_entry (data->objfile, data->addr_vec,
25770                        data->previous_cu_start, start_addr,
25771                        data->previous_cu_index);
25772
25773   data->previous_cu_start = start_addr;
25774   if (pst != NULL)
25775     {
25776       const auto it = data->cu_index_htab.find (pst);
25777       gdb_assert (it != data->cu_index_htab.cend ());
25778       data->previous_cu_index = it->second;
25779       data->previous_valid = 1;
25780     }
25781   else
25782     data->previous_valid = 0;
25783
25784   return 0;
25785 }
25786
25787 /* Write OBJFILE's address map to ADDR_VEC.
25788    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
25789    in the index file.  */
25790
25791 static void
25792 write_address_map (struct objfile *objfile, data_buf &addr_vec,
25793                    psym_index_map &cu_index_htab)
25794 {
25795   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
25796
25797   /* When writing the address table, we have to cope with the fact that
25798      the addrmap iterator only provides the start of a region; we have to
25799      wait until the next invocation to get the start of the next region.  */
25800
25801   addrmap_index_data.objfile = objfile;
25802   addrmap_index_data.previous_valid = 0;
25803
25804   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
25805                    &addrmap_index_data);
25806
25807   /* It's highly unlikely the last entry (end address = 0xff...ff)
25808      is valid, but we should still handle it.
25809      The end address is recorded as the start of the next region, but that
25810      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
25811      anyway.  */
25812   if (addrmap_index_data.previous_valid)
25813     add_address_entry (objfile, addr_vec,
25814                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
25815                        addrmap_index_data.previous_cu_index);
25816 }
25817
25818 /* Return the symbol kind of PSYM.  */
25819
25820 static gdb_index_symbol_kind
25821 symbol_kind (struct partial_symbol *psym)
25822 {
25823   domain_enum domain = PSYMBOL_DOMAIN (psym);
25824   enum address_class aclass = PSYMBOL_CLASS (psym);
25825
25826   switch (domain)
25827     {
25828     case VAR_DOMAIN:
25829       switch (aclass)
25830         {
25831         case LOC_BLOCK:
25832           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
25833         case LOC_TYPEDEF:
25834           return GDB_INDEX_SYMBOL_KIND_TYPE;
25835         case LOC_COMPUTED:
25836         case LOC_CONST_BYTES:
25837         case LOC_OPTIMIZED_OUT:
25838         case LOC_STATIC:
25839           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25840         case LOC_CONST:
25841           /* Note: It's currently impossible to recognize psyms as enum values
25842              short of reading the type info.  For now punt.  */
25843           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
25844         default:
25845           /* There are other LOC_FOO values that one might want to classify
25846              as variables, but dwarf2read.c doesn't currently use them.  */
25847           return GDB_INDEX_SYMBOL_KIND_OTHER;
25848         }
25849     case STRUCT_DOMAIN:
25850       return GDB_INDEX_SYMBOL_KIND_TYPE;
25851     default:
25852       return GDB_INDEX_SYMBOL_KIND_OTHER;
25853     }
25854 }
25855
25856 /* Add a list of partial symbols to SYMTAB.  */
25857
25858 static void
25859 write_psymbols (struct mapped_symtab *symtab,
25860                 std::unordered_set<partial_symbol *> &psyms_seen,
25861                 struct partial_symbol **psymp,
25862                 int count,
25863                 offset_type cu_index,
25864                 int is_static)
25865 {
25866   for (; count-- > 0; ++psymp)
25867     {
25868       struct partial_symbol *psym = *psymp;
25869
25870       if (SYMBOL_LANGUAGE (psym) == language_ada)
25871         error (_("Ada is not currently supported by the index"));
25872
25873       /* Only add a given psymbol once.  */
25874       if (psyms_seen.insert (psym).second)
25875         {
25876           gdb_index_symbol_kind kind = symbol_kind (psym);
25877
25878           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
25879                            is_static, kind, cu_index);
25880         }
25881     }
25882 }
25883
25884 /* A helper struct used when iterating over debug_types.  */
25885 struct signatured_type_index_data
25886 {
25887   signatured_type_index_data (data_buf &types_list_,
25888                               std::unordered_set<partial_symbol *> &psyms_seen_)
25889     : types_list (types_list_), psyms_seen (psyms_seen_)
25890   {}
25891
25892   struct objfile *objfile;
25893   struct mapped_symtab *symtab;
25894   data_buf &types_list;
25895   std::unordered_set<partial_symbol *> &psyms_seen;
25896   int cu_index;
25897 };
25898
25899 /* A helper function that writes a single signatured_type to an
25900    obstack.  */
25901
25902 static int
25903 write_one_signatured_type (void **slot, void *d)
25904 {
25905   struct signatured_type_index_data *info
25906     = (struct signatured_type_index_data *) d;
25907   struct signatured_type *entry = (struct signatured_type *) *slot;
25908   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
25909
25910   write_psymbols (info->symtab,
25911                   info->psyms_seen,
25912                   &info->objfile->global_psymbols[psymtab->globals_offset],
25913                   psymtab->n_global_syms, info->cu_index,
25914                   0);
25915   write_psymbols (info->symtab,
25916                   info->psyms_seen,
25917                   &info->objfile->static_psymbols[psymtab->statics_offset],
25918                   psymtab->n_static_syms, info->cu_index,
25919                   1);
25920
25921   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
25922                                 to_underlying (entry->per_cu.sect_off));
25923   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
25924                                 to_underlying (entry->type_offset_in_tu));
25925   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
25926
25927   ++info->cu_index;
25928
25929   return 1;
25930 }
25931
25932 /* Recurse into all "included" dependencies and count their symbols as
25933    if they appeared in this psymtab.  */
25934
25935 static void
25936 recursively_count_psymbols (struct partial_symtab *psymtab,
25937                             size_t &psyms_seen)
25938 {
25939   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
25940     if (psymtab->dependencies[i]->user != NULL)
25941       recursively_count_psymbols (psymtab->dependencies[i],
25942                                   psyms_seen);
25943
25944   psyms_seen += psymtab->n_global_syms;
25945   psyms_seen += psymtab->n_static_syms;
25946 }
25947
25948 /* Recurse into all "included" dependencies and write their symbols as
25949    if they appeared in this psymtab.  */
25950
25951 static void
25952 recursively_write_psymbols (struct objfile *objfile,
25953                             struct partial_symtab *psymtab,
25954                             struct mapped_symtab *symtab,
25955                             std::unordered_set<partial_symbol *> &psyms_seen,
25956                             offset_type cu_index)
25957 {
25958   int i;
25959
25960   for (i = 0; i < psymtab->number_of_dependencies; ++i)
25961     if (psymtab->dependencies[i]->user != NULL)
25962       recursively_write_psymbols (objfile, psymtab->dependencies[i],
25963                                   symtab, psyms_seen, cu_index);
25964
25965   write_psymbols (symtab,
25966                   psyms_seen,
25967                   &objfile->global_psymbols[psymtab->globals_offset],
25968                   psymtab->n_global_syms, cu_index,
25969                   0);
25970   write_psymbols (symtab,
25971                   psyms_seen,
25972                   &objfile->static_psymbols[psymtab->statics_offset],
25973                   psymtab->n_static_syms, cu_index,
25974                   1);
25975 }
25976
25977 /* DWARF-5 .debug_names builder.  */
25978 class debug_names
25979 {
25980 public:
25981   debug_names (bool is_dwarf64, bfd_endian dwarf5_byte_order)
25982     : m_dwarf5_byte_order (dwarf5_byte_order),
25983       m_dwarf32 (dwarf5_byte_order),
25984       m_dwarf64 (dwarf5_byte_order),
25985       m_dwarf (is_dwarf64
25986                ? static_cast<dwarf &> (m_dwarf64)
25987                : static_cast<dwarf &> (m_dwarf32)),
25988       m_name_table_string_offs (m_dwarf.name_table_string_offs),
25989       m_name_table_entry_offs (m_dwarf.name_table_entry_offs)
25990   {}
25991
25992   /* Insert one symbol.  */
25993   void insert (const partial_symbol *psym, int cu_index, bool is_static)
25994   {
25995     const int dwarf_tag = psymbol_tag (psym);
25996     if (dwarf_tag == 0)
25997       return;
25998     const char *const name = SYMBOL_SEARCH_NAME (psym);
25999     const auto insertpair
26000       = m_name_to_value_set.emplace (c_str_view (name),
26001                                      std::set<symbol_value> ());
26002     std::set<symbol_value> &value_set = insertpair.first->second;
26003     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static));
26004   }
26005
26006   /* Build all the tables.  All symbols must be already inserted.
26007      This function does not call file_write, caller has to do it
26008      afterwards.  */
26009   void build ()
26010   {
26011     /* Verify the build method has not be called twice.  */
26012     gdb_assert (m_abbrev_table.empty ());
26013     const size_t name_count = m_name_to_value_set.size ();
26014     m_bucket_table.resize
26015       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26016     m_hash_table.reserve (name_count);
26017     m_name_table_string_offs.reserve (name_count);
26018     m_name_table_entry_offs.reserve (name_count);
26019
26020     /* Map each hash of symbol to its name and value.  */
26021     struct hash_it_pair
26022     {
26023       uint32_t hash;
26024       decltype (m_name_to_value_set)::const_iterator it;
26025     };
26026     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26027     bucket_hash.resize (m_bucket_table.size ());
26028     for (decltype (m_name_to_value_set)::const_iterator it
26029            = m_name_to_value_set.cbegin ();
26030          it != m_name_to_value_set.cend ();
26031          ++it)
26032       {
26033         const char *const name = it->first.c_str ();
26034         const uint32_t hash = dwarf5_djb_hash (name);
26035         hash_it_pair hashitpair;
26036         hashitpair.hash = hash;
26037         hashitpair.it = it;
26038         auto &slot = bucket_hash[hash % bucket_hash.size()];
26039         slot.push_front (std::move (hashitpair));
26040       }
26041     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26042       {
26043         const std::forward_list<hash_it_pair> &hashitlist
26044           = bucket_hash[bucket_ix];
26045         if (hashitlist.empty ())
26046           continue;
26047         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26048         /* The hashes array is indexed starting at 1.  */
26049         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26050                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26051                                 m_hash_table.size () + 1);
26052         for (const hash_it_pair &hashitpair : hashitlist)
26053           {
26054             m_hash_table.push_back (0);
26055             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26056                                                         (&m_hash_table.back ()),
26057                                     sizeof (m_hash_table.back ()),
26058                                     m_dwarf5_byte_order, hashitpair.hash);
26059             const c_str_view &name = hashitpair.it->first;
26060             const std::set<symbol_value> &value_set = hashitpair.it->second;
26061             m_name_table_string_offs.push_back_reorder
26062               (m_debugstrlookup.lookup (name.c_str ()));
26063             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26064             gdb_assert (!value_set.empty ());
26065             for (const symbol_value &value : value_set)
26066               {
26067                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26068                                                         value.is_static)];
26069                 if (idx == 0)
26070                   {
26071                     idx = m_idx_next++;
26072                     m_abbrev_table.append_unsigned_leb128 (idx);
26073                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26074                     m_abbrev_table.append_unsigned_leb128 (DW_IDX_compile_unit);
26075                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26076                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26077                                                            ? DW_IDX_GNU_internal
26078                                                            : DW_IDX_GNU_external);
26079                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26080
26081                     /* Terminate attributes list.  */
26082                     m_abbrev_table.append_unsigned_leb128 (0);
26083                     m_abbrev_table.append_unsigned_leb128 (0);
26084                   }
26085
26086                 m_entry_pool.append_unsigned_leb128 (idx);
26087                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26088               }
26089
26090             /* Terminate the list of CUs.  */
26091             m_entry_pool.append_unsigned_leb128 (0);
26092           }
26093       }
26094     gdb_assert (m_hash_table.size () == name_count);
26095
26096     /* Terminate tags list.  */
26097     m_abbrev_table.append_unsigned_leb128 (0);
26098   }
26099
26100   /* Return .debug_names bucket count.  This must be called only after
26101      calling the build method.  */
26102   uint32_t bucket_count () const
26103   {
26104     /* Verify the build method has been already called.  */
26105     gdb_assert (!m_abbrev_table.empty ());
26106     const uint32_t retval = m_bucket_table.size ();
26107
26108     /* Check for overflow.  */
26109     gdb_assert (retval == m_bucket_table.size ());
26110     return retval;
26111   }
26112
26113   /* Return .debug_names names count.  This must be called only after
26114      calling the build method.  */
26115   uint32_t name_count () const
26116   {
26117     /* Verify the build method has been already called.  */
26118     gdb_assert (!m_abbrev_table.empty ());
26119     const uint32_t retval = m_hash_table.size ();
26120
26121     /* Check for overflow.  */
26122     gdb_assert (retval == m_hash_table.size ());
26123     return retval;
26124   }
26125
26126   /* Return number of bytes of .debug_names abbreviation table.  This
26127      must be called only after calling the build method.  */
26128   uint32_t abbrev_table_bytes () const
26129   {
26130     gdb_assert (!m_abbrev_table.empty ());
26131     return m_abbrev_table.size ();
26132   }
26133
26134   /* Recurse into all "included" dependencies and store their symbols
26135      as if they appeared in this psymtab.  */
26136   void recursively_write_psymbols
26137     (struct objfile *objfile,
26138      struct partial_symtab *psymtab,
26139      std::unordered_set<partial_symbol *> &psyms_seen,
26140      int cu_index)
26141   {
26142     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26143       if (psymtab->dependencies[i]->user != NULL)
26144         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26145                                     psyms_seen, cu_index);
26146
26147     write_psymbols (psyms_seen,
26148                     &objfile->global_psymbols[psymtab->globals_offset],
26149                     psymtab->n_global_syms, cu_index, false);
26150     write_psymbols (psyms_seen,
26151                     &objfile->static_psymbols[psymtab->statics_offset],
26152                     psymtab->n_static_syms, cu_index, true);
26153   }
26154
26155   /* Return number of bytes the .debug_names section will have.  This
26156      must be called only after calling the build method.  */
26157   size_t bytes () const
26158   {
26159     /* Verify the build method has been already called.  */
26160     gdb_assert (!m_abbrev_table.empty ());
26161     size_t expected_bytes = 0;
26162     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26163     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26164     expected_bytes += m_name_table_string_offs.bytes ();
26165     expected_bytes += m_name_table_entry_offs.bytes ();
26166     expected_bytes += m_abbrev_table.size ();
26167     expected_bytes += m_entry_pool.size ();
26168     return expected_bytes;
26169   }
26170
26171   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26172      FILE_STR.  This must be called only after calling the build
26173      method.  */
26174   void file_write (FILE *file_names, FILE *file_str) const
26175   {
26176     /* Verify the build method has been already called.  */
26177     gdb_assert (!m_abbrev_table.empty ());
26178     ::file_write (file_names, m_bucket_table);
26179     ::file_write (file_names, m_hash_table);
26180     m_name_table_string_offs.file_write (file_names);
26181     m_name_table_entry_offs.file_write (file_names);
26182     m_abbrev_table.file_write (file_names);
26183     m_entry_pool.file_write (file_names);
26184     m_debugstrlookup.file_write (file_str);
26185   }
26186
26187 private:
26188
26189   /* Storage for symbol names mapping them to their .debug_str section
26190      offsets.  */
26191   class debug_str_lookup
26192   {
26193   public:
26194
26195     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26196        All .debug_str section strings are automatically stored.  */
26197     debug_str_lookup ()
26198       : m_abfd (dwarf2_per_objfile->objfile->obfd)
26199     {
26200       dwarf2_read_section (dwarf2_per_objfile->objfile,
26201                            &dwarf2_per_objfile->str);
26202       if (dwarf2_per_objfile->str.buffer == NULL)
26203         return;
26204       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26205            data < (dwarf2_per_objfile->str.buffer
26206                    + dwarf2_per_objfile->str.size);)
26207         {
26208           const char *const s = reinterpret_cast<const char *> (data);
26209           const auto insertpair
26210             = m_str_table.emplace (c_str_view (s),
26211                                    data - dwarf2_per_objfile->str.buffer);
26212           if (!insertpair.second)
26213             complaint (&symfile_complaints,
26214                        _("Duplicate string \"%s\" in "
26215                          ".debug_str section [in module %s]"),
26216                        s, bfd_get_filename (m_abfd));
26217           data += strlen (s) + 1;
26218         }
26219     }
26220
26221     /* Return offset of symbol name S in the .debug_str section.  Add
26222        such symbol to the section's end if it does not exist there
26223        yet.  */
26224     size_t lookup (const char *s)
26225     {
26226       const auto it = m_str_table.find (c_str_view (s));
26227       if (it != m_str_table.end ())
26228         return it->second;
26229       const size_t offset = (dwarf2_per_objfile->str.size
26230                              + m_str_add_buf.size ());
26231       m_str_table.emplace (c_str_view (s), offset);
26232       m_str_add_buf.append_cstr0 (s);
26233       return offset;
26234     }
26235
26236     /* Append the end of the .debug_str section to FILE.  */
26237     void file_write (FILE *file) const
26238     {
26239       m_str_add_buf.file_write (file);
26240     }
26241
26242   private:
26243     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26244     bfd *const m_abfd;
26245
26246     /* Data to add at the end of .debug_str for new needed symbol names.  */
26247     data_buf m_str_add_buf;
26248   };
26249
26250   /* Container to map used DWARF tags to their .debug_names abbreviation
26251      tags.  */
26252   class index_key
26253   {
26254   public:
26255     index_key (int dwarf_tag_, bool is_static_)
26256       : dwarf_tag (dwarf_tag_), is_static (is_static_)
26257     {
26258     }
26259
26260     bool
26261     operator== (const index_key &other) const
26262     {
26263       return dwarf_tag == other.dwarf_tag && is_static == other.is_static;
26264     }
26265
26266     const int dwarf_tag;
26267     const bool is_static;
26268   };
26269
26270   /* Provide std::unordered_map::hasher for index_key.  */
26271   class index_key_hasher
26272   {
26273   public:
26274     size_t
26275     operator () (const index_key &key) const
26276     {
26277       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26278     }
26279   };
26280
26281   /* Parameters of one symbol entry.  */
26282   class symbol_value
26283   {
26284   public:
26285     const int dwarf_tag, cu_index;
26286     const bool is_static;
26287
26288     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_)
26289       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_)
26290     {}
26291
26292     bool
26293     operator< (const symbol_value &other) const
26294     {
26295 #define X(n) \
26296   do \
26297     { \
26298       if (n < other.n) \
26299         return true; \
26300       if (n > other.n) \
26301         return false; \
26302     } \
26303   while (0)
26304       X (dwarf_tag);
26305       X (is_static);
26306       X (cu_index);
26307 #undef X
26308       return false;
26309     }
26310   };
26311
26312   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26313      output.  */
26314   class offset_vec
26315   {
26316   protected:
26317     const bfd_endian dwarf5_byte_order;
26318   public:
26319     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26320       : dwarf5_byte_order (dwarf5_byte_order_)
26321     {}
26322
26323     /* Call std::vector::reserve for NELEM elements.  */
26324     virtual void reserve (size_t nelem) = 0;
26325
26326     /* Call std::vector::push_back with store_unsigned_integer byte
26327        reordering for ELEM.  */
26328     virtual void push_back_reorder (size_t elem) = 0;
26329
26330     /* Return expected output size in bytes.  */
26331     virtual size_t bytes () const = 0;
26332
26333     /* Write name table to FILE.  */
26334     virtual void file_write (FILE *file) const = 0;
26335   };
26336
26337   /* Template to unify DWARF-32 and DWARF-64 output.  */
26338   template<typename OffsetSize>
26339   class offset_vec_tmpl : public offset_vec
26340   {
26341   public:
26342     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26343       : offset_vec (dwarf5_byte_order_)
26344     {}
26345
26346     /* Implement offset_vec::reserve.  */
26347     void reserve (size_t nelem) override
26348     {
26349       m_vec.reserve (nelem);
26350     }
26351
26352     /* Implement offset_vec::push_back_reorder.  */
26353     void push_back_reorder (size_t elem) override
26354     {
26355       m_vec.push_back (elem);
26356       /* Check for overflow.  */
26357       gdb_assert (m_vec.back () == elem);
26358       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26359                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26360     }
26361
26362     /* Implement offset_vec::bytes.  */
26363     size_t bytes () const override
26364     {
26365       return m_vec.size () * sizeof (m_vec[0]);
26366     }
26367
26368     /* Implement offset_vec::file_write.  */
26369     void file_write (FILE *file) const override
26370     {
26371       ::file_write (file, m_vec);
26372     }
26373
26374   private:
26375     std::vector<OffsetSize> m_vec;
26376   };
26377
26378   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26379      respecting name table width.  */
26380   class dwarf
26381   {
26382   public:
26383     offset_vec &name_table_string_offs, &name_table_entry_offs;
26384
26385     dwarf (offset_vec &name_table_string_offs_,
26386            offset_vec &name_table_entry_offs_)
26387       : name_table_string_offs (name_table_string_offs_),
26388         name_table_entry_offs (name_table_entry_offs_)
26389     {
26390     }
26391   };
26392
26393   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26394      respecting name table width.  */
26395   template<typename OffsetSize>
26396   class dwarf_tmpl : public dwarf
26397   {
26398   public:
26399     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26400       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26401         m_name_table_string_offs (dwarf5_byte_order_),
26402         m_name_table_entry_offs (dwarf5_byte_order_)
26403     {}
26404
26405   private:
26406     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26407     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26408   };
26409
26410   /* Try to reconstruct original DWARF tag for given partial_symbol.
26411      This function is not DWARF-5 compliant but it is sufficient for
26412      GDB as a DWARF-5 index consumer.  */
26413   static int psymbol_tag (const struct partial_symbol *psym)
26414   {
26415     domain_enum domain = PSYMBOL_DOMAIN (psym);
26416     enum address_class aclass = PSYMBOL_CLASS (psym);
26417
26418     switch (domain)
26419       {
26420       case VAR_DOMAIN:
26421         switch (aclass)
26422           {
26423           case LOC_BLOCK:
26424             return DW_TAG_subprogram;
26425           case LOC_TYPEDEF:
26426             return DW_TAG_typedef;
26427           case LOC_COMPUTED:
26428           case LOC_CONST_BYTES:
26429           case LOC_OPTIMIZED_OUT:
26430           case LOC_STATIC:
26431             return DW_TAG_variable;
26432           case LOC_CONST:
26433             /* Note: It's currently impossible to recognize psyms as enum values
26434                short of reading the type info.  For now punt.  */
26435             return DW_TAG_variable;
26436           default:
26437             /* There are other LOC_FOO values that one might want to classify
26438                as variables, but dwarf2read.c doesn't currently use them.  */
26439             return DW_TAG_variable;
26440           }
26441       case STRUCT_DOMAIN:
26442         return DW_TAG_structure_type;
26443       default:
26444         return 0;
26445       }
26446   }
26447
26448   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26449   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26450                        struct partial_symbol **psymp, int count, int cu_index,
26451                        bool is_static)
26452   {
26453     for (; count-- > 0; ++psymp)
26454       {
26455         struct partial_symbol *psym = *psymp;
26456
26457         if (SYMBOL_LANGUAGE (psym) == language_ada)
26458           error (_("Ada is not currently supported by the index"));
26459
26460         /* Only add a given psymbol once.  */
26461         if (psyms_seen.insert (psym).second)
26462           insert (psym, cu_index, is_static);
26463       }
26464   }
26465
26466   /* Store value of each symbol.  */
26467   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26468     m_name_to_value_set;
26469
26470   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26471      order.  */
26472   std::vector<uint32_t> m_bucket_table;
26473   std::vector<uint32_t> m_hash_table;
26474
26475   const bfd_endian m_dwarf5_byte_order;
26476   dwarf_tmpl<uint32_t> m_dwarf32;
26477   dwarf_tmpl<uint64_t> m_dwarf64;
26478   dwarf &m_dwarf;
26479   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26480   debug_str_lookup m_debugstrlookup;
26481
26482   /* Map each used .debug_names abbreviation tag parameter to its
26483      index value.  */
26484   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26485
26486   /* Next unused .debug_names abbreviation tag for
26487      m_indexkey_to_idx.  */
26488   int m_idx_next = 1;
26489
26490   /* .debug_names abbreviation table.  */
26491   data_buf m_abbrev_table;
26492
26493   /* .debug_names entry pool.  */
26494   data_buf m_entry_pool;
26495 };
26496
26497 /* Return iff any of the needed offsets does not fit into 32-bit
26498    .debug_names section.  */
26499
26500 static bool
26501 check_dwarf64_offsets ()
26502 {
26503   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26504     {
26505       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26506
26507       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26508         return true;
26509     }
26510   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26511     {
26512       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26513       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26514
26515       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26516         return true;
26517     }
26518   return false;
26519 }
26520
26521 /* The psyms_seen set is potentially going to be largish (~40k
26522    elements when indexing a -g3 build of GDB itself).  Estimate the
26523    number of elements in order to avoid too many rehashes, which
26524    require rebuilding buckets and thus many trips to
26525    malloc/free.  */
26526
26527 static size_t
26528 psyms_seen_size ()
26529 {
26530   size_t psyms_count = 0;
26531   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26532     {
26533       struct dwarf2_per_cu_data *per_cu
26534         = dwarf2_per_objfile->all_comp_units[i];
26535       struct partial_symtab *psymtab = per_cu->v.psymtab;
26536
26537       if (psymtab != NULL && psymtab->user == NULL)
26538         recursively_count_psymbols (psymtab, psyms_count);
26539     }
26540   /* Generating an index for gdb itself shows a ratio of
26541      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26542   return psyms_count / 4;
26543 }
26544
26545 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26546    Return how many bytes were expected to be written into OUT_FILE.  */
26547
26548 static size_t
26549 write_gdbindex (struct objfile *objfile, FILE *out_file)
26550 {
26551   mapped_symtab symtab;
26552   data_buf cu_list;
26553
26554   /* While we're scanning CU's create a table that maps a psymtab pointer
26555      (which is what addrmap records) to its index (which is what is recorded
26556      in the index file).  This will later be needed to write the address
26557      table.  */
26558   psym_index_map cu_index_htab;
26559   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26560
26561   /* The CU list is already sorted, so we don't need to do additional
26562      work here.  Also, the debug_types entries do not appear in
26563      all_comp_units, but only in their own hash table.  */
26564
26565   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26566   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26567     {
26568       struct dwarf2_per_cu_data *per_cu
26569         = dwarf2_per_objfile->all_comp_units[i];
26570       struct partial_symtab *psymtab = per_cu->v.psymtab;
26571
26572       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26573          It may be referenced from a local scope but in such case it does not
26574          need to be present in .gdb_index.  */
26575       if (psymtab == NULL)
26576         continue;
26577
26578       if (psymtab->user == NULL)
26579         recursively_write_psymbols (objfile, psymtab, &symtab,
26580                                     psyms_seen, i);
26581
26582       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26583       gdb_assert (insertpair.second);
26584
26585       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26586                            to_underlying (per_cu->sect_off));
26587       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26588     }
26589
26590   /* Dump the address map.  */
26591   data_buf addr_vec;
26592   write_address_map (objfile, addr_vec, cu_index_htab);
26593
26594   /* Write out the .debug_type entries, if any.  */
26595   data_buf types_cu_list;
26596   if (dwarf2_per_objfile->signatured_types)
26597     {
26598       signatured_type_index_data sig_data (types_cu_list,
26599                                            psyms_seen);
26600
26601       sig_data.objfile = objfile;
26602       sig_data.symtab = &symtab;
26603       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26604       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26605                               write_one_signatured_type, &sig_data);
26606     }
26607
26608   /* Now that we've processed all symbols we can shrink their cu_indices
26609      lists.  */
26610   uniquify_cu_indices (&symtab);
26611
26612   data_buf symtab_vec, constant_pool;
26613   write_hash_table (&symtab, symtab_vec, constant_pool);
26614
26615   data_buf contents;
26616   const offset_type size_of_contents = 6 * sizeof (offset_type);
26617   offset_type total_len = size_of_contents;
26618
26619   /* The version number.  */
26620   contents.append_data (MAYBE_SWAP (8));
26621
26622   /* The offset of the CU list from the start of the file.  */
26623   contents.append_data (MAYBE_SWAP (total_len));
26624   total_len += cu_list.size ();
26625
26626   /* The offset of the types CU list from the start of the file.  */
26627   contents.append_data (MAYBE_SWAP (total_len));
26628   total_len += types_cu_list.size ();
26629
26630   /* The offset of the address table from the start of the file.  */
26631   contents.append_data (MAYBE_SWAP (total_len));
26632   total_len += addr_vec.size ();
26633
26634   /* The offset of the symbol table from the start of the file.  */
26635   contents.append_data (MAYBE_SWAP (total_len));
26636   total_len += symtab_vec.size ();
26637
26638   /* The offset of the constant pool from the start of the file.  */
26639   contents.append_data (MAYBE_SWAP (total_len));
26640   total_len += constant_pool.size ();
26641
26642   gdb_assert (contents.size () == size_of_contents);
26643
26644   contents.file_write (out_file);
26645   cu_list.file_write (out_file);
26646   types_cu_list.file_write (out_file);
26647   addr_vec.file_write (out_file);
26648   symtab_vec.file_write (out_file);
26649   constant_pool.file_write (out_file);
26650
26651   return total_len;
26652 }
26653
26654 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
26655 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
26656
26657 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
26658    needed addition to .debug_str section to OUT_FILE_STR.  Return how
26659    many bytes were expected to be written into OUT_FILE.  */
26660
26661 static size_t
26662 write_debug_names (struct objfile *objfile, FILE *out_file, FILE *out_file_str)
26663 {
26664   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets ();
26665   const int dwarf5_offset_size = dwarf5_is_dwarf64 ? 8 : 4;
26666   const enum bfd_endian dwarf5_byte_order
26667     = gdbarch_byte_order (get_objfile_arch (objfile));
26668
26669   /* The CU list is already sorted, so we don't need to do additional
26670      work here.  Also, the debug_types entries do not appear in
26671      all_comp_units, but only in their own hash table.  */
26672   data_buf cu_list;
26673   debug_names nametable (dwarf5_is_dwarf64, dwarf5_byte_order);
26674   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
26675   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26676     {
26677       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
26678       partial_symtab *psymtab = per_cu->v.psymtab;
26679
26680       /* CU of a shared file from 'dwz -m' may be unused by this main
26681          file.  It may be referenced from a local scope but in such
26682          case it does not need to be present in .debug_names.  */
26683       if (psymtab == NULL)
26684         continue;
26685
26686       if (psymtab->user == NULL)
26687         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
26688
26689       cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
26690                            to_underlying (per_cu->sect_off));
26691     }
26692   nametable.build ();
26693
26694   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
26695
26696   data_buf types_cu_list;
26697   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26698     {
26699       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26700       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26701
26702       types_cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
26703                                  to_underlying (per_cu.sect_off));
26704     }
26705
26706   const offset_type bytes_of_header
26707     = ((dwarf5_is_dwarf64 ? 12 : 4)
26708        + 2 + 2 + 7 * 4
26709        + sizeof (dwarf5_gdb_augmentation));
26710   size_t expected_bytes = 0;
26711   expected_bytes += bytes_of_header;
26712   expected_bytes += cu_list.size ();
26713   expected_bytes += types_cu_list.size ();
26714   expected_bytes += nametable.bytes ();
26715   data_buf header;
26716
26717   if (!dwarf5_is_dwarf64)
26718     {
26719       const uint64_t size64 = expected_bytes - 4;
26720       gdb_assert (size64 < 0xfffffff0);
26721       header.append_uint (4, dwarf5_byte_order, size64);
26722     }
26723   else
26724     {
26725       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
26726       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
26727     }
26728
26729   /* The version number.  */
26730   header.append_uint (2, dwarf5_byte_order, 5);
26731
26732   /* Padding.  */
26733   header.append_uint (2, dwarf5_byte_order, 0);
26734
26735   /* comp_unit_count - The number of CUs in the CU list.  */
26736   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
26737
26738   /* local_type_unit_count - The number of TUs in the local TU
26739      list.  */
26740   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
26741
26742   /* foreign_type_unit_count - The number of TUs in the foreign TU
26743      list.  */
26744   header.append_uint (4, dwarf5_byte_order, 0);
26745
26746   /* bucket_count - The number of hash buckets in the hash lookup
26747      table.  */
26748   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
26749
26750   /* name_count - The number of unique names in the index.  */
26751   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
26752
26753   /* abbrev_table_size - The size in bytes of the abbreviations
26754      table.  */
26755   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
26756
26757   /* augmentation_string_size - The size in bytes of the augmentation
26758      string.  This value is rounded up to a multiple of 4.  */
26759   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
26760   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
26761   header.append_data (dwarf5_gdb_augmentation);
26762
26763   gdb_assert (header.size () == bytes_of_header);
26764
26765   header.file_write (out_file);
26766   cu_list.file_write (out_file);
26767   types_cu_list.file_write (out_file);
26768   nametable.file_write (out_file, out_file_str);
26769
26770   return expected_bytes;
26771 }
26772
26773 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
26774    position is at the end of the file.  */
26775
26776 static void
26777 assert_file_size (FILE *file, const char *filename, size_t expected_size)
26778 {
26779   const auto file_size = ftell (file);
26780   if (file_size == -1)
26781     error (_("Can't get `%s' size"), filename);
26782   gdb_assert (file_size == expected_size);
26783 }
26784
26785 /* An index variant.  */
26786 enum dw_index_kind
26787 {
26788   /* GDB's own .gdb_index format.   */
26789   GDB_INDEX,
26790
26791   /* DWARF5 .debug_names.  */
26792   DEBUG_NAMES,
26793 };
26794
26795 /* Create an index file for OBJFILE in the directory DIR.  */
26796
26797 static void
26798 write_psymtabs_to_index (struct objfile *objfile, const char *dir,
26799                          dw_index_kind index_kind)
26800 {
26801   if (dwarf2_per_objfile->using_index)
26802     error (_("Cannot use an index to create the index"));
26803
26804   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
26805     error (_("Cannot make an index when the file has multiple .debug_types sections"));
26806
26807   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
26808     return;
26809
26810   struct stat st;
26811   if (stat (objfile_name (objfile), &st) < 0)
26812     perror_with_name (objfile_name (objfile));
26813
26814   std::string filename (std::string (dir) + SLASH_STRING
26815                         + lbasename (objfile_name (objfile))
26816                         + (index_kind == dw_index_kind::DEBUG_NAMES
26817                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
26818
26819   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
26820   if (!out_file)
26821     error (_("Can't open `%s' for writing"), filename.c_str ());
26822
26823   /* Order matters here; we want FILE to be closed before FILENAME is
26824      unlinked, because on MS-Windows one cannot delete a file that is
26825      still open.  (Don't call anything here that might throw until
26826      file_closer is created.)  */
26827   gdb::unlinker unlink_file (filename.c_str ());
26828   gdb_file_up close_out_file (out_file);
26829
26830   if (index_kind == dw_index_kind::DEBUG_NAMES)
26831     {
26832       std::string filename_str (std::string (dir) + SLASH_STRING
26833                                 + lbasename (objfile_name (objfile))
26834                                 + DEBUG_STR_SUFFIX);
26835       FILE *out_file_str
26836         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
26837       if (!out_file_str)
26838         error (_("Can't open `%s' for writing"), filename_str.c_str ());
26839       gdb::unlinker unlink_file_str (filename_str.c_str ());
26840       gdb_file_up close_out_file_str (out_file_str);
26841
26842       const size_t total_len
26843         = write_debug_names (objfile, out_file, out_file_str);
26844       assert_file_size (out_file, filename.c_str (), total_len);
26845
26846       /* We want to keep the file .debug_str file too.  */
26847       unlink_file_str.keep ();
26848     }
26849   else
26850     {
26851       const size_t total_len
26852         = write_gdbindex (objfile, out_file);
26853       assert_file_size (out_file, filename.c_str (), total_len);
26854     }
26855
26856   /* We want to keep the file.  */
26857   unlink_file.keep ();
26858 }
26859
26860 /* Implementation of the `save gdb-index' command.
26861    
26862    Note that the .gdb_index file format used by this command is
26863    documented in the GDB manual.  Any changes here must be documented
26864    there.  */
26865
26866 static void
26867 save_gdb_index_command (const char *arg, int from_tty)
26868 {
26869   struct objfile *objfile;
26870   const char dwarf5space[] = "-dwarf-5 ";
26871   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
26872
26873   if (!arg)
26874     arg = "";
26875
26876   arg = skip_spaces (arg);
26877   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
26878     {
26879       index_kind = dw_index_kind::DEBUG_NAMES;
26880       arg += strlen (dwarf5space);
26881       arg = skip_spaces (arg);
26882     }
26883
26884   if (!*arg)
26885     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
26886
26887   ALL_OBJFILES (objfile)
26888   {
26889     struct stat st;
26890
26891     /* If the objfile does not correspond to an actual file, skip it.  */
26892     if (stat (objfile_name (objfile), &st) < 0)
26893       continue;
26894
26895     dwarf2_per_objfile
26896       = (struct dwarf2_per_objfile *) objfile_data (objfile,
26897                                                     dwarf2_objfile_data_key);
26898     if (dwarf2_per_objfile)
26899       {
26900
26901         TRY
26902           {
26903             write_psymtabs_to_index (objfile, arg, index_kind);
26904           }
26905         CATCH (except, RETURN_MASK_ERROR)
26906           {
26907             exception_fprintf (gdb_stderr, except,
26908                                _("Error while writing index for `%s': "),
26909                                objfile_name (objfile));
26910           }
26911         END_CATCH
26912       }
26913   }
26914 }
26915
26916 \f
26917
26918 int dwarf_always_disassemble;
26919
26920 static void
26921 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
26922                                struct cmd_list_element *c, const char *value)
26923 {
26924   fprintf_filtered (file,
26925                     _("Whether to always disassemble "
26926                       "DWARF expressions is %s.\n"),
26927                     value);
26928 }
26929
26930 static void
26931 show_check_physname (struct ui_file *file, int from_tty,
26932                      struct cmd_list_element *c, const char *value)
26933 {
26934   fprintf_filtered (file,
26935                     _("Whether to check \"physname\" is %s.\n"),
26936                     value);
26937 }
26938
26939 void
26940 _initialize_dwarf2_read (void)
26941 {
26942   struct cmd_list_element *c;
26943
26944   dwarf2_objfile_data_key
26945     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
26946
26947   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
26948 Set DWARF specific variables.\n\
26949 Configure DWARF variables such as the cache size"),
26950                   &set_dwarf_cmdlist, "maintenance set dwarf ",
26951                   0/*allow-unknown*/, &maintenance_set_cmdlist);
26952
26953   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
26954 Show DWARF specific variables\n\
26955 Show DWARF variables such as the cache size"),
26956                   &show_dwarf_cmdlist, "maintenance show dwarf ",
26957                   0/*allow-unknown*/, &maintenance_show_cmdlist);
26958
26959   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
26960                             &dwarf_max_cache_age, _("\
26961 Set the upper bound on the age of cached DWARF compilation units."), _("\
26962 Show the upper bound on the age of cached DWARF compilation units."), _("\
26963 A higher limit means that cached compilation units will be stored\n\
26964 in memory longer, and more total memory will be used.  Zero disables\n\
26965 caching, which can slow down startup."),
26966                             NULL,
26967                             show_dwarf_max_cache_age,
26968                             &set_dwarf_cmdlist,
26969                             &show_dwarf_cmdlist);
26970
26971   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
26972                            &dwarf_always_disassemble, _("\
26973 Set whether `info address' always disassembles DWARF expressions."), _("\
26974 Show whether `info address' always disassembles DWARF expressions."), _("\
26975 When enabled, DWARF expressions are always printed in an assembly-like\n\
26976 syntax.  When disabled, expressions will be printed in a more\n\
26977 conversational style, when possible."),
26978                            NULL,
26979                            show_dwarf_always_disassemble,
26980                            &set_dwarf_cmdlist,
26981                            &show_dwarf_cmdlist);
26982
26983   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
26984 Set debugging of the DWARF reader."), _("\
26985 Show debugging of the DWARF reader."), _("\
26986 When enabled (non-zero), debugging messages are printed during DWARF\n\
26987 reading and symtab expansion.  A value of 1 (one) provides basic\n\
26988 information.  A value greater than 1 provides more verbose information."),
26989                             NULL,
26990                             NULL,
26991                             &setdebuglist, &showdebuglist);
26992
26993   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
26994 Set debugging of the DWARF DIE reader."), _("\
26995 Show debugging of the DWARF DIE reader."), _("\
26996 When enabled (non-zero), DIEs are dumped after they are read in.\n\
26997 The value is the maximum depth to print."),
26998                              NULL,
26999                              NULL,
27000                              &setdebuglist, &showdebuglist);
27001
27002   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27003 Set debugging of the dwarf line reader."), _("\
27004 Show debugging of the dwarf line reader."), _("\
27005 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27006 A value of 1 (one) provides basic information.\n\
27007 A value greater than 1 provides more verbose information."),
27008                              NULL,
27009                              NULL,
27010                              &setdebuglist, &showdebuglist);
27011
27012   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27013 Set cross-checking of \"physname\" code against demangler."), _("\
27014 Show cross-checking of \"physname\" code against demangler."), _("\
27015 When enabled, GDB's internal \"physname\" code is checked against\n\
27016 the demangler."),
27017                            NULL, show_check_physname,
27018                            &setdebuglist, &showdebuglist);
27019
27020   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27021                            no_class, &use_deprecated_index_sections, _("\
27022 Set whether to use deprecated gdb_index sections."), _("\
27023 Show whether to use deprecated gdb_index sections."), _("\
27024 When enabled, deprecated .gdb_index sections are used anyway.\n\
27025 Normally they are ignored either because of a missing feature or\n\
27026 performance issue.\n\
27027 Warning: This option must be enabled before gdb reads the file."),
27028                            NULL,
27029                            NULL,
27030                            &setlist, &showlist);
27031
27032   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27033                _("\
27034 Save a gdb-index file.\n\
27035 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27036 \n\
27037 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27038 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27039 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27040                &save_cmdlist);
27041   set_cmd_completer (c, filename_completer);
27042
27043   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27044                                                         &dwarf2_locexpr_funcs);
27045   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27046                                                         &dwarf2_loclist_funcs);
27047
27048   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27049                                         &dwarf2_block_frame_base_locexpr_funcs);
27050   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27051                                         &dwarf2_block_frame_base_loclist_funcs);
27052
27053 #if GDB_SELF_TEST
27054   selftests::register_test ("dw2_expand_symtabs_matching",
27055                             selftests::dw2_expand_symtabs_matching::run_test);
27056 #endif
27057 }