Record nested types
[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 "filename-seen-cache.h"
78 #include "producer.h"
79 #include <fcntl.h>
80 #include <sys/types.h>
81 #include <algorithm>
82 #include <unordered_set>
83 #include <unordered_map>
84 #include "selftest.h"
85
86 /* When == 1, print basic high level tracing messages.
87    When > 1, be more verbose.
88    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
89 static unsigned int dwarf_read_debug = 0;
90
91 /* When non-zero, dump DIEs after they are read in.  */
92 static unsigned int dwarf_die_debug = 0;
93
94 /* When non-zero, dump line number entries as they are read in.  */
95 static unsigned int dwarf_line_debug = 0;
96
97 /* When non-zero, cross-check physname against demangler.  */
98 static int check_physname = 0;
99
100 /* When non-zero, do not reject deprecated .gdb_index sections.  */
101 static int use_deprecated_index_sections = 0;
102
103 static const struct objfile_data *dwarf2_objfile_data_key;
104
105 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
106
107 static int dwarf2_locexpr_index;
108 static int dwarf2_loclist_index;
109 static int dwarf2_locexpr_block_index;
110 static int dwarf2_loclist_block_index;
111
112 /* A descriptor for dwarf sections.
113
114    S.ASECTION, SIZE are typically initialized when the objfile is first
115    scanned.  BUFFER, READIN are filled in later when the section is read.
116    If the section contained compressed data then SIZE is updated to record
117    the uncompressed size of the section.
118
119    DWP file format V2 introduces a wrinkle that is easiest to handle by
120    creating the concept of virtual sections contained within a real section.
121    In DWP V2 the sections of the input DWO files are concatenated together
122    into one section, but section offsets are kept relative to the original
123    input section.
124    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
125    the real section this "virtual" section is contained in, and BUFFER,SIZE
126    describe the virtual section.  */
127
128 struct dwarf2_section_info
129 {
130   union
131   {
132     /* If this is a real section, the bfd section.  */
133     asection *section;
134     /* If this is a virtual section, pointer to the containing ("real")
135        section.  */
136     struct dwarf2_section_info *containing_section;
137   } s;
138   /* Pointer to section data, only valid if readin.  */
139   const gdb_byte *buffer;
140   /* The size of the section, real or virtual.  */
141   bfd_size_type size;
142   /* If this is a virtual section, the offset in the real section.
143      Only valid if is_virtual.  */
144   bfd_size_type virtual_offset;
145   /* True if we have tried to read this section.  */
146   char readin;
147   /* True if this is a virtual section, False otherwise.
148      This specifies which of s.section and s.containing_section to use.  */
149   char is_virtual;
150 };
151
152 typedef struct dwarf2_section_info dwarf2_section_info_def;
153 DEF_VEC_O (dwarf2_section_info_def);
154
155 /* All offsets in the index are of this type.  It must be
156    architecture-independent.  */
157 typedef uint32_t offset_type;
158
159 DEF_VEC_I (offset_type);
160
161 /* Ensure only legit values are used.  */
162 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
163   do { \
164     gdb_assert ((unsigned int) (value) <= 1); \
165     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
166   } while (0)
167
168 /* Ensure only legit values are used.  */
169 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
172                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
173     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
174   } while (0)
175
176 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
177 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
178   do { \
179     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
180     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
181   } while (0)
182
183 #if WORDS_BIGENDIAN
184
185 /* Convert VALUE between big- and little-endian.  */
186
187 static offset_type
188 byte_swap (offset_type value)
189 {
190   offset_type result;
191
192   result = (value & 0xff) << 24;
193   result |= (value & 0xff00) << 8;
194   result |= (value & 0xff0000) >> 8;
195   result |= (value & 0xff000000) >> 24;
196   return result;
197 }
198
199 #define MAYBE_SWAP(V)  byte_swap (V)
200
201 #else
202 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
203 #endif /* WORDS_BIGENDIAN */
204
205 /* An index into a (C++) symbol name component in a symbol name as
206    recorded in the mapped_index's symbol table.  For each C++ symbol
207    in the symbol table, we record one entry for the start of each
208    component in the symbol in a table of name components, and then
209    sort the table, in order to be able to binary search symbol names,
210    ignoring leading namespaces, both completion and regular look up.
211    For example, for symbol "A::B::C", we'll have an entry that points
212    to "A::B::C", another that points to "B::C", and another for "C".
213    Note that function symbols in GDB index have no parameter
214    information, just the function/method names.  You can convert a
215    name_component to a "const char *" using the
216    'mapped_index::symbol_name_at(offset_type)' method.  */
217
218 struct name_component
219 {
220   /* Offset in the symbol name where the component starts.  Stored as
221      a (32-bit) offset instead of a pointer to save memory and improve
222      locality on 64-bit architectures.  */
223   offset_type name_offset;
224
225   /* The symbol's index in the symbol and constant pool tables of a
226      mapped_index.  */
227   offset_type idx;
228 };
229
230 /* A description of the mapped index.  The file format is described in
231    a comment by the code that writes the index.  */
232 struct mapped_index
233 {
234   /* Index data format version.  */
235   int version;
236
237   /* The total length of the buffer.  */
238   off_t total_size;
239
240   /* A pointer to the address table data.  */
241   const gdb_byte *address_table;
242
243   /* Size of the address table data in bytes.  */
244   offset_type address_table_size;
245
246   /* The symbol table, implemented as a hash table.  */
247   const offset_type *symbol_table;
248
249   /* Size in slots, each slot is 2 offset_types.  */
250   offset_type symbol_table_slots;
251
252   /* A pointer to the constant pool.  */
253   const char *constant_pool;
254
255   /* The name_component table (a sorted vector).  See name_component's
256      description above.  */
257   std::vector<name_component> name_components;
258
259   /* How NAME_COMPONENTS is sorted.  */
260   enum case_sensitivity name_components_casing;
261
262   /* Convenience method to get at the name of the symbol at IDX in the
263      symbol table.  */
264   const char *symbol_name_at (offset_type idx) const
265   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx]); }
266
267   /* Build the symbol name component sorted vector, if we haven't
268      yet.  */
269   void build_name_components ();
270
271   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
272      possible matches for LN_NO_PARAMS in the name component
273      vector.  */
274   std::pair<std::vector<name_component>::const_iterator,
275             std::vector<name_component>::const_iterator>
276     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
277 };
278
279 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
280 DEF_VEC_P (dwarf2_per_cu_ptr);
281
282 struct tu_stats
283 {
284   int nr_uniq_abbrev_tables;
285   int nr_symtabs;
286   int nr_symtab_sharers;
287   int nr_stmt_less_type_units;
288   int nr_all_type_units_reallocs;
289 };
290
291 /* Collection of data recorded per objfile.
292    This hangs off of dwarf2_objfile_data_key.  */
293
294 struct dwarf2_per_objfile
295 {
296   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
297      dwarf2 section names, or is NULL if the standard ELF names are
298      used.  */
299   dwarf2_per_objfile (struct objfile *objfile,
300                       const dwarf2_debug_sections *names);
301
302   ~dwarf2_per_objfile ();
303
304   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
305
306   /* Free all cached compilation units.  */
307   void free_cached_comp_units ();
308 private:
309   /* This function is mapped across the sections and remembers the
310      offset and size of each of the debugging sections we are
311      interested in.  */
312   void locate_sections (bfd *abfd, asection *sectp,
313                         const dwarf2_debug_sections &names);
314
315 public:
316   dwarf2_section_info info {};
317   dwarf2_section_info abbrev {};
318   dwarf2_section_info line {};
319   dwarf2_section_info loc {};
320   dwarf2_section_info loclists {};
321   dwarf2_section_info macinfo {};
322   dwarf2_section_info macro {};
323   dwarf2_section_info str {};
324   dwarf2_section_info line_str {};
325   dwarf2_section_info ranges {};
326   dwarf2_section_info rnglists {};
327   dwarf2_section_info addr {};
328   dwarf2_section_info frame {};
329   dwarf2_section_info eh_frame {};
330   dwarf2_section_info gdb_index {};
331
332   VEC (dwarf2_section_info_def) *types = NULL;
333
334   /* Back link.  */
335   struct objfile *objfile = NULL;
336
337   /* Table of all the compilation units.  This is used to locate
338      the target compilation unit of a particular reference.  */
339   struct dwarf2_per_cu_data **all_comp_units = NULL;
340
341   /* The number of compilation units in ALL_COMP_UNITS.  */
342   int n_comp_units = 0;
343
344   /* The number of .debug_types-related CUs.  */
345   int n_type_units = 0;
346
347   /* The number of elements allocated in all_type_units.
348      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
349   int n_allocated_type_units = 0;
350
351   /* The .debug_types-related CUs (TUs).
352      This is stored in malloc space because we may realloc it.  */
353   struct signatured_type **all_type_units = NULL;
354
355   /* Table of struct type_unit_group objects.
356      The hash key is the DW_AT_stmt_list value.  */
357   htab_t type_unit_groups {};
358
359   /* A table mapping .debug_types signatures to its signatured_type entry.
360      This is NULL if the .debug_types section hasn't been read in yet.  */
361   htab_t signatured_types {};
362
363   /* Type unit statistics, to see how well the scaling improvements
364      are doing.  */
365   struct tu_stats tu_stats {};
366
367   /* A chain of compilation units that are currently read in, so that
368      they can be freed later.  */
369   dwarf2_per_cu_data *read_in_chain = NULL;
370
371   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
372      This is NULL if the table hasn't been allocated yet.  */
373   htab_t dwo_files {};
374
375   /* True if we've checked for whether there is a DWP file.  */
376   bool dwp_checked = false;
377
378   /* The DWP file if there is one, or NULL.  */
379   struct dwp_file *dwp_file = NULL;
380
381   /* The shared '.dwz' file, if one exists.  This is used when the
382      original data was compressed using 'dwz -m'.  */
383   struct dwz_file *dwz_file = NULL;
384
385   /* A flag indicating whether this objfile has a section loaded at a
386      VMA of 0.  */
387   bool has_section_at_zero = false;
388
389   /* True if we are using the mapped index,
390      or we are faking it for OBJF_READNOW's sake.  */
391   bool using_index = false;
392
393   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
394   mapped_index *index_table = NULL;
395
396   /* When using index_table, this keeps track of all quick_file_names entries.
397      TUs typically share line table entries with a CU, so we maintain a
398      separate table of all line table entries to support the sharing.
399      Note that while there can be way more TUs than CUs, we've already
400      sorted all the TUs into "type unit groups", grouped by their
401      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
402      CU and its associated TU group if there is one.  */
403   htab_t quick_file_names_table {};
404
405   /* Set during partial symbol reading, to prevent queueing of full
406      symbols.  */
407   bool reading_partial_symbols = false;
408
409   /* Table mapping type DIEs to their struct type *.
410      This is NULL if not allocated yet.
411      The mapping is done via (CU/TU + DIE offset) -> type.  */
412   htab_t die_type_hash {};
413
414   /* The CUs we recently read.  */
415   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
416
417   /* Table containing line_header indexed by offset and offset_in_dwz.  */
418   htab_t line_header_hash {};
419
420   /* Table containing all filenames.  This is an optional because the
421      table is lazily constructed on first access.  */
422   gdb::optional<filename_seen_cache> filenames_cache;
423 };
424
425 static struct dwarf2_per_objfile *dwarf2_per_objfile;
426
427 /* Default names of the debugging sections.  */
428
429 /* Note that if the debugging section has been compressed, it might
430    have a name like .zdebug_info.  */
431
432 static const struct dwarf2_debug_sections dwarf2_elf_names =
433 {
434   { ".debug_info", ".zdebug_info" },
435   { ".debug_abbrev", ".zdebug_abbrev" },
436   { ".debug_line", ".zdebug_line" },
437   { ".debug_loc", ".zdebug_loc" },
438   { ".debug_loclists", ".zdebug_loclists" },
439   { ".debug_macinfo", ".zdebug_macinfo" },
440   { ".debug_macro", ".zdebug_macro" },
441   { ".debug_str", ".zdebug_str" },
442   { ".debug_line_str", ".zdebug_line_str" },
443   { ".debug_ranges", ".zdebug_ranges" },
444   { ".debug_rnglists", ".zdebug_rnglists" },
445   { ".debug_types", ".zdebug_types" },
446   { ".debug_addr", ".zdebug_addr" },
447   { ".debug_frame", ".zdebug_frame" },
448   { ".eh_frame", NULL },
449   { ".gdb_index", ".zgdb_index" },
450   23
451 };
452
453 /* List of DWO/DWP sections.  */
454
455 static const struct dwop_section_names
456 {
457   struct dwarf2_section_names abbrev_dwo;
458   struct dwarf2_section_names info_dwo;
459   struct dwarf2_section_names line_dwo;
460   struct dwarf2_section_names loc_dwo;
461   struct dwarf2_section_names loclists_dwo;
462   struct dwarf2_section_names macinfo_dwo;
463   struct dwarf2_section_names macro_dwo;
464   struct dwarf2_section_names str_dwo;
465   struct dwarf2_section_names str_offsets_dwo;
466   struct dwarf2_section_names types_dwo;
467   struct dwarf2_section_names cu_index;
468   struct dwarf2_section_names tu_index;
469 }
470 dwop_section_names =
471 {
472   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
473   { ".debug_info.dwo", ".zdebug_info.dwo" },
474   { ".debug_line.dwo", ".zdebug_line.dwo" },
475   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
476   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
477   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
478   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
479   { ".debug_str.dwo", ".zdebug_str.dwo" },
480   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
481   { ".debug_types.dwo", ".zdebug_types.dwo" },
482   { ".debug_cu_index", ".zdebug_cu_index" },
483   { ".debug_tu_index", ".zdebug_tu_index" },
484 };
485
486 /* local data types */
487
488 /* The data in a compilation unit header, after target2host
489    translation, looks like this.  */
490 struct comp_unit_head
491 {
492   unsigned int length;
493   short version;
494   unsigned char addr_size;
495   unsigned char signed_addr_p;
496   sect_offset abbrev_sect_off;
497
498   /* Size of file offsets; either 4 or 8.  */
499   unsigned int offset_size;
500
501   /* Size of the length field; either 4 or 12.  */
502   unsigned int initial_length_size;
503
504   enum dwarf_unit_type unit_type;
505
506   /* Offset to the first byte of this compilation unit header in the
507      .debug_info section, for resolving relative reference dies.  */
508   sect_offset sect_off;
509
510   /* Offset to first die in this cu from the start of the cu.
511      This will be the first byte following the compilation unit header.  */
512   cu_offset first_die_cu_offset;
513
514   /* 64-bit signature of this type unit - it is valid only for
515      UNIT_TYPE DW_UT_type.  */
516   ULONGEST signature;
517
518   /* For types, offset in the type's DIE of the type defined by this TU.  */
519   cu_offset type_cu_offset_in_tu;
520 };
521
522 /* Type used for delaying computation of method physnames.
523    See comments for compute_delayed_physnames.  */
524 struct delayed_method_info
525 {
526   /* The type to which the method is attached, i.e., its parent class.  */
527   struct type *type;
528
529   /* The index of the method in the type's function fieldlists.  */
530   int fnfield_index;
531
532   /* The index of the method in the fieldlist.  */
533   int index;
534
535   /* The name of the DIE.  */
536   const char *name;
537
538   /*  The DIE associated with this method.  */
539   struct die_info *die;
540 };
541
542 typedef struct delayed_method_info delayed_method_info;
543 DEF_VEC_O (delayed_method_info);
544
545 /* Internal state when decoding a particular compilation unit.  */
546 struct dwarf2_cu
547 {
548   /* The objfile containing this compilation unit.  */
549   struct objfile *objfile;
550
551   /* The header of the compilation unit.  */
552   struct comp_unit_head header;
553
554   /* Base address of this compilation unit.  */
555   CORE_ADDR base_address;
556
557   /* Non-zero if base_address has been set.  */
558   int base_known;
559
560   /* The language we are debugging.  */
561   enum language language;
562   const struct language_defn *language_defn;
563
564   const char *producer;
565
566   /* The generic symbol table building routines have separate lists for
567      file scope symbols and all all other scopes (local scopes).  So
568      we need to select the right one to pass to add_symbol_to_list().
569      We do it by keeping a pointer to the correct list in list_in_scope.
570
571      FIXME: The original dwarf code just treated the file scope as the
572      first local scope, and all other local scopes as nested local
573      scopes, and worked fine.  Check to see if we really need to
574      distinguish these in buildsym.c.  */
575   struct pending **list_in_scope;
576
577   /* The abbrev table for this CU.
578      Normally this points to the abbrev table in the objfile.
579      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
580   struct abbrev_table *abbrev_table;
581
582   /* Hash table holding all the loaded partial DIEs
583      with partial_die->offset.SECT_OFF as hash.  */
584   htab_t partial_dies;
585
586   /* Storage for things with the same lifetime as this read-in compilation
587      unit, including partial DIEs.  */
588   struct obstack comp_unit_obstack;
589
590   /* When multiple dwarf2_cu structures are living in memory, this field
591      chains them all together, so that they can be released efficiently.
592      We will probably also want a generation counter so that most-recently-used
593      compilation units are cached...  */
594   struct dwarf2_per_cu_data *read_in_chain;
595
596   /* Backlink to our per_cu entry.  */
597   struct dwarf2_per_cu_data *per_cu;
598
599   /* How many compilation units ago was this CU last referenced?  */
600   int last_used;
601
602   /* A hash table of DIE cu_offset for following references with
603      die_info->offset.sect_off as hash.  */
604   htab_t die_hash;
605
606   /* Full DIEs if read in.  */
607   struct die_info *dies;
608
609   /* A set of pointers to dwarf2_per_cu_data objects for compilation
610      units referenced by this one.  Only set during full symbol processing;
611      partial symbol tables do not have dependencies.  */
612   htab_t dependencies;
613
614   /* Header data from the line table, during full symbol processing.  */
615   struct line_header *line_header;
616   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
617      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
618      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
619      to the line header as long as this DIE is being processed.  See
620      process_die_scope.  */
621   die_info *line_header_die_owner;
622
623   /* A list of methods which need to have physnames computed
624      after all type information has been read.  */
625   VEC (delayed_method_info) *method_list;
626
627   /* To be copied to symtab->call_site_htab.  */
628   htab_t call_site_htab;
629
630   /* Non-NULL if this CU came from a DWO file.
631      There is an invariant here that is important to remember:
632      Except for attributes copied from the top level DIE in the "main"
633      (or "stub") file in preparation for reading the DWO file
634      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
635      Either there isn't a DWO file (in which case this is NULL and the point
636      is moot), or there is and either we're not going to read it (in which
637      case this is NULL) or there is and we are reading it (in which case this
638      is non-NULL).  */
639   struct dwo_unit *dwo_unit;
640
641   /* The DW_AT_addr_base attribute if present, zero otherwise
642      (zero is a valid value though).
643      Note this value comes from the Fission stub CU/TU's DIE.  */
644   ULONGEST addr_base;
645
646   /* The DW_AT_ranges_base attribute if present, zero otherwise
647      (zero is a valid value though).
648      Note this value comes from the Fission stub CU/TU's DIE.
649      Also note that the value is zero in the non-DWO case so this value can
650      be used without needing to know whether DWO files are in use or not.
651      N.B. This does not apply to DW_AT_ranges appearing in
652      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
653      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
654      DW_AT_ranges_base *would* have to be applied, and we'd have to care
655      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
656   ULONGEST ranges_base;
657
658   /* Mark used when releasing cached dies.  */
659   unsigned int mark : 1;
660
661   /* This CU references .debug_loc.  See the symtab->locations_valid field.
662      This test is imperfect as there may exist optimized debug code not using
663      any location list and still facing inlining issues if handled as
664      unoptimized code.  For a future better test see GCC PR other/32998.  */
665   unsigned int has_loclist : 1;
666
667   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
668      if all the producer_is_* fields are valid.  This information is cached
669      because profiling CU expansion showed excessive time spent in
670      producer_is_gxx_lt_4_6.  */
671   unsigned int checked_producer : 1;
672   unsigned int producer_is_gxx_lt_4_6 : 1;
673   unsigned int producer_is_gcc_lt_4_3 : 1;
674   unsigned int producer_is_icc_lt_14 : 1;
675
676   /* When set, the file that we're processing is known to have
677      debugging info for C++ namespaces.  GCC 3.3.x did not produce
678      this information, but later versions do.  */
679
680   unsigned int processing_has_namespace_info : 1;
681 };
682
683 /* Persistent data held for a compilation unit, even when not
684    processing it.  We put a pointer to this structure in the
685    read_symtab_private field of the psymtab.  */
686
687 struct dwarf2_per_cu_data
688 {
689   /* The start offset and length of this compilation unit.
690      NOTE: Unlike comp_unit_head.length, this length includes
691      initial_length_size.
692      If the DIE refers to a DWO file, this is always of the original die,
693      not the DWO file.  */
694   sect_offset sect_off;
695   unsigned int length;
696
697   /* DWARF standard version this data has been read from (such as 4 or 5).  */
698   short dwarf_version;
699
700   /* Flag indicating this compilation unit will be read in before
701      any of the current compilation units are processed.  */
702   unsigned int queued : 1;
703
704   /* This flag will be set when reading partial DIEs if we need to load
705      absolutely all DIEs for this compilation unit, instead of just the ones
706      we think are interesting.  It gets set if we look for a DIE in the
707      hash table and don't find it.  */
708   unsigned int load_all_dies : 1;
709
710   /* Non-zero if this CU is from .debug_types.
711      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
712      this is non-zero.  */
713   unsigned int is_debug_types : 1;
714
715   /* Non-zero if this CU is from the .dwz file.  */
716   unsigned int is_dwz : 1;
717
718   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
719      This flag is only valid if is_debug_types is true.
720      We can't read a CU directly from a DWO file: There are required
721      attributes in the stub.  */
722   unsigned int reading_dwo_directly : 1;
723
724   /* Non-zero if the TU has been read.
725      This is used to assist the "Stay in DWO Optimization" for Fission:
726      When reading a DWO, it's faster to read TUs from the DWO instead of
727      fetching them from random other DWOs (due to comdat folding).
728      If the TU has already been read, the optimization is unnecessary
729      (and unwise - we don't want to change where gdb thinks the TU lives
730      "midflight").
731      This flag is only valid if is_debug_types is true.  */
732   unsigned int tu_read : 1;
733
734   /* The section this CU/TU lives in.
735      If the DIE refers to a DWO file, this is always the original die,
736      not the DWO file.  */
737   struct dwarf2_section_info *section;
738
739   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
740      of the CU cache it gets reset to NULL again.  This is left as NULL for
741      dummy CUs (a CU header, but nothing else).  */
742   struct dwarf2_cu *cu;
743
744   /* The corresponding objfile.
745      Normally we can get the objfile from dwarf2_per_objfile.
746      However we can enter this file with just a "per_cu" handle.  */
747   struct objfile *objfile;
748
749   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
750      is active.  Otherwise, the 'psymtab' field is active.  */
751   union
752   {
753     /* The partial symbol table associated with this compilation unit,
754        or NULL for unread partial units.  */
755     struct partial_symtab *psymtab;
756
757     /* Data needed by the "quick" functions.  */
758     struct dwarf2_per_cu_quick_data *quick;
759   } v;
760
761   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
762      while reading psymtabs, used to compute the psymtab dependencies,
763      and then cleared.  Then it is filled in again while reading full
764      symbols, and only deleted when the objfile is destroyed.
765
766      This is also used to work around a difference between the way gold
767      generates .gdb_index version <=7 and the way gdb does.  Arguably this
768      is a gold bug.  For symbols coming from TUs, gold records in the index
769      the CU that includes the TU instead of the TU itself.  This breaks
770      dw2_lookup_symbol: It assumes that if the index says symbol X lives
771      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
772      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
773      we need to look in TU Z to find X.  Fortunately, this is akin to
774      DW_TAG_imported_unit, so we just use the same mechanism: For
775      .gdb_index version <=7 this also records the TUs that the CU referred
776      to.  Concurrently with this change gdb was modified to emit version 8
777      indices so we only pay a price for gold generated indices.
778      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
779   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
780 };
781
782 /* Entry in the signatured_types hash table.  */
783
784 struct signatured_type
785 {
786   /* The "per_cu" object of this type.
787      This struct is used iff per_cu.is_debug_types.
788      N.B.: This is the first member so that it's easy to convert pointers
789      between them.  */
790   struct dwarf2_per_cu_data per_cu;
791
792   /* The type's signature.  */
793   ULONGEST signature;
794
795   /* Offset in the TU of the type's DIE, as read from the TU header.
796      If this TU is a DWO stub and the definition lives in a DWO file
797      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
798   cu_offset type_offset_in_tu;
799
800   /* Offset in the section of the type's DIE.
801      If the definition lives in a DWO file, this is the offset in the
802      .debug_types.dwo section.
803      The value is zero until the actual value is known.
804      Zero is otherwise not a valid section offset.  */
805   sect_offset type_offset_in_section;
806
807   /* Type units are grouped by their DW_AT_stmt_list entry so that they
808      can share them.  This points to the containing symtab.  */
809   struct type_unit_group *type_unit_group;
810
811   /* The type.
812      The first time we encounter this type we fully read it in and install it
813      in the symbol tables.  Subsequent times we only need the type.  */
814   struct type *type;
815
816   /* Containing DWO unit.
817      This field is valid iff per_cu.reading_dwo_directly.  */
818   struct dwo_unit *dwo_unit;
819 };
820
821 typedef struct signatured_type *sig_type_ptr;
822 DEF_VEC_P (sig_type_ptr);
823
824 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
825    This includes type_unit_group and quick_file_names.  */
826
827 struct stmt_list_hash
828 {
829   /* The DWO unit this table is from or NULL if there is none.  */
830   struct dwo_unit *dwo_unit;
831
832   /* Offset in .debug_line or .debug_line.dwo.  */
833   sect_offset line_sect_off;
834 };
835
836 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
837    an object of this type.  */
838
839 struct type_unit_group
840 {
841   /* dwarf2read.c's main "handle" on a TU symtab.
842      To simplify things we create an artificial CU that "includes" all the
843      type units using this stmt_list so that the rest of the code still has
844      a "per_cu" handle on the symtab.
845      This PER_CU is recognized by having no section.  */
846 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
847   struct dwarf2_per_cu_data per_cu;
848
849   /* The TUs that share this DW_AT_stmt_list entry.
850      This is added to while parsing type units to build partial symtabs,
851      and is deleted afterwards and not used again.  */
852   VEC (sig_type_ptr) *tus;
853
854   /* The compunit symtab.
855      Type units in a group needn't all be defined in the same source file,
856      so we create an essentially anonymous symtab as the compunit symtab.  */
857   struct compunit_symtab *compunit_symtab;
858
859   /* The data used to construct the hash key.  */
860   struct stmt_list_hash hash;
861
862   /* The number of symtabs from the line header.
863      The value here must match line_header.num_file_names.  */
864   unsigned int num_symtabs;
865
866   /* The symbol tables for this TU (obtained from the files listed in
867      DW_AT_stmt_list).
868      WARNING: The order of entries here must match the order of entries
869      in the line header.  After the first TU using this type_unit_group, the
870      line header for the subsequent TUs is recreated from this.  This is done
871      because we need to use the same symtabs for each TU using the same
872      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
873      there's no guarantee the line header doesn't have duplicate entries.  */
874   struct symtab **symtabs;
875 };
876
877 /* These sections are what may appear in a (real or virtual) DWO file.  */
878
879 struct dwo_sections
880 {
881   struct dwarf2_section_info abbrev;
882   struct dwarf2_section_info line;
883   struct dwarf2_section_info loc;
884   struct dwarf2_section_info loclists;
885   struct dwarf2_section_info macinfo;
886   struct dwarf2_section_info macro;
887   struct dwarf2_section_info str;
888   struct dwarf2_section_info str_offsets;
889   /* In the case of a virtual DWO file, these two are unused.  */
890   struct dwarf2_section_info info;
891   VEC (dwarf2_section_info_def) *types;
892 };
893
894 /* CUs/TUs in DWP/DWO files.  */
895
896 struct dwo_unit
897 {
898   /* Backlink to the containing struct dwo_file.  */
899   struct dwo_file *dwo_file;
900
901   /* The "id" that distinguishes this CU/TU.
902      .debug_info calls this "dwo_id", .debug_types calls this "signature".
903      Since signatures came first, we stick with it for consistency.  */
904   ULONGEST signature;
905
906   /* The section this CU/TU lives in, in the DWO file.  */
907   struct dwarf2_section_info *section;
908
909   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
910   sect_offset sect_off;
911   unsigned int length;
912
913   /* For types, offset in the type's DIE of the type defined by this TU.  */
914   cu_offset type_offset_in_tu;
915 };
916
917 /* include/dwarf2.h defines the DWP section codes.
918    It defines a max value but it doesn't define a min value, which we
919    use for error checking, so provide one.  */
920
921 enum dwp_v2_section_ids
922 {
923   DW_SECT_MIN = 1
924 };
925
926 /* Data for one DWO file.
927
928    This includes virtual DWO files (a virtual DWO file is a DWO file as it
929    appears in a DWP file).  DWP files don't really have DWO files per se -
930    comdat folding of types "loses" the DWO file they came from, and from
931    a high level view DWP files appear to contain a mass of random types.
932    However, to maintain consistency with the non-DWP case we pretend DWP
933    files contain virtual DWO files, and we assign each TU with one virtual
934    DWO file (generally based on the line and abbrev section offsets -
935    a heuristic that seems to work in practice).  */
936
937 struct dwo_file
938 {
939   /* The DW_AT_GNU_dwo_name attribute.
940      For virtual DWO files the name is constructed from the section offsets
941      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
942      from related CU+TUs.  */
943   const char *dwo_name;
944
945   /* The DW_AT_comp_dir attribute.  */
946   const char *comp_dir;
947
948   /* The bfd, when the file is open.  Otherwise this is NULL.
949      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
950   bfd *dbfd;
951
952   /* The sections that make up this DWO file.
953      Remember that for virtual DWO files in DWP V2, these are virtual
954      sections (for lack of a better name).  */
955   struct dwo_sections sections;
956
957   /* The CUs in the file.
958      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
959      an extension to handle LLVM's Link Time Optimization output (where
960      multiple source files may be compiled into a single object/dwo pair). */
961   htab_t cus;
962
963   /* Table of TUs in the file.
964      Each element is a struct dwo_unit.  */
965   htab_t tus;
966 };
967
968 /* These sections are what may appear in a DWP file.  */
969
970 struct dwp_sections
971 {
972   /* These are used by both DWP version 1 and 2.  */
973   struct dwarf2_section_info str;
974   struct dwarf2_section_info cu_index;
975   struct dwarf2_section_info tu_index;
976
977   /* These are only used by DWP version 2 files.
978      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
979      sections are referenced by section number, and are not recorded here.
980      In DWP version 2 there is at most one copy of all these sections, each
981      section being (effectively) comprised of the concatenation of all of the
982      individual sections that exist in the version 1 format.
983      To keep the code simple we treat each of these concatenated pieces as a
984      section itself (a virtual section?).  */
985   struct dwarf2_section_info abbrev;
986   struct dwarf2_section_info info;
987   struct dwarf2_section_info line;
988   struct dwarf2_section_info loc;
989   struct dwarf2_section_info macinfo;
990   struct dwarf2_section_info macro;
991   struct dwarf2_section_info str_offsets;
992   struct dwarf2_section_info types;
993 };
994
995 /* These sections are what may appear in a virtual DWO file in DWP version 1.
996    A virtual DWO file is a DWO file as it appears in a DWP file.  */
997
998 struct virtual_v1_dwo_sections
999 {
1000   struct dwarf2_section_info abbrev;
1001   struct dwarf2_section_info line;
1002   struct dwarf2_section_info loc;
1003   struct dwarf2_section_info macinfo;
1004   struct dwarf2_section_info macro;
1005   struct dwarf2_section_info str_offsets;
1006   /* Each DWP hash table entry records one CU or one TU.
1007      That is recorded here, and copied to dwo_unit.section.  */
1008   struct dwarf2_section_info info_or_types;
1009 };
1010
1011 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1012    In version 2, the sections of the DWO files are concatenated together
1013    and stored in one section of that name.  Thus each ELF section contains
1014    several "virtual" sections.  */
1015
1016 struct virtual_v2_dwo_sections
1017 {
1018   bfd_size_type abbrev_offset;
1019   bfd_size_type abbrev_size;
1020
1021   bfd_size_type line_offset;
1022   bfd_size_type line_size;
1023
1024   bfd_size_type loc_offset;
1025   bfd_size_type loc_size;
1026
1027   bfd_size_type macinfo_offset;
1028   bfd_size_type macinfo_size;
1029
1030   bfd_size_type macro_offset;
1031   bfd_size_type macro_size;
1032
1033   bfd_size_type str_offsets_offset;
1034   bfd_size_type str_offsets_size;
1035
1036   /* Each DWP hash table entry records one CU or one TU.
1037      That is recorded here, and copied to dwo_unit.section.  */
1038   bfd_size_type info_or_types_offset;
1039   bfd_size_type info_or_types_size;
1040 };
1041
1042 /* Contents of DWP hash tables.  */
1043
1044 struct dwp_hash_table
1045 {
1046   uint32_t version, nr_columns;
1047   uint32_t nr_units, nr_slots;
1048   const gdb_byte *hash_table, *unit_table;
1049   union
1050   {
1051     struct
1052     {
1053       const gdb_byte *indices;
1054     } v1;
1055     struct
1056     {
1057       /* This is indexed by column number and gives the id of the section
1058          in that column.  */
1059 #define MAX_NR_V2_DWO_SECTIONS \
1060   (1 /* .debug_info or .debug_types */ \
1061    + 1 /* .debug_abbrev */ \
1062    + 1 /* .debug_line */ \
1063    + 1 /* .debug_loc */ \
1064    + 1 /* .debug_str_offsets */ \
1065    + 1 /* .debug_macro or .debug_macinfo */)
1066       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1067       const gdb_byte *offsets;
1068       const gdb_byte *sizes;
1069     } v2;
1070   } section_pool;
1071 };
1072
1073 /* Data for one DWP file.  */
1074
1075 struct dwp_file
1076 {
1077   /* Name of the file.  */
1078   const char *name;
1079
1080   /* File format version.  */
1081   int version;
1082
1083   /* The bfd.  */
1084   bfd *dbfd;
1085
1086   /* Section info for this file.  */
1087   struct dwp_sections sections;
1088
1089   /* Table of CUs in the file.  */
1090   const struct dwp_hash_table *cus;
1091
1092   /* Table of TUs in the file.  */
1093   const struct dwp_hash_table *tus;
1094
1095   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1096   htab_t loaded_cus;
1097   htab_t loaded_tus;
1098
1099   /* Table to map ELF section numbers to their sections.
1100      This is only needed for the DWP V1 file format.  */
1101   unsigned int num_sections;
1102   asection **elf_sections;
1103 };
1104
1105 /* This represents a '.dwz' file.  */
1106
1107 struct dwz_file
1108 {
1109   /* A dwz file can only contain a few sections.  */
1110   struct dwarf2_section_info abbrev;
1111   struct dwarf2_section_info info;
1112   struct dwarf2_section_info str;
1113   struct dwarf2_section_info line;
1114   struct dwarf2_section_info macro;
1115   struct dwarf2_section_info gdb_index;
1116
1117   /* The dwz's BFD.  */
1118   bfd *dwz_bfd;
1119 };
1120
1121 /* Struct used to pass misc. parameters to read_die_and_children, et
1122    al.  which are used for both .debug_info and .debug_types dies.
1123    All parameters here are unchanging for the life of the call.  This
1124    struct exists to abstract away the constant parameters of die reading.  */
1125
1126 struct die_reader_specs
1127 {
1128   /* The bfd of die_section.  */
1129   bfd* abfd;
1130
1131   /* The CU of the DIE we are parsing.  */
1132   struct dwarf2_cu *cu;
1133
1134   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1135   struct dwo_file *dwo_file;
1136
1137   /* The section the die comes from.
1138      This is either .debug_info or .debug_types, or the .dwo variants.  */
1139   struct dwarf2_section_info *die_section;
1140
1141   /* die_section->buffer.  */
1142   const gdb_byte *buffer;
1143
1144   /* The end of the buffer.  */
1145   const gdb_byte *buffer_end;
1146
1147   /* The value of the DW_AT_comp_dir attribute.  */
1148   const char *comp_dir;
1149 };
1150
1151 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1152 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1153                                       const gdb_byte *info_ptr,
1154                                       struct die_info *comp_unit_die,
1155                                       int has_children,
1156                                       void *data);
1157
1158 /* A 1-based directory index.  This is a strong typedef to prevent
1159    accidentally using a directory index as a 0-based index into an
1160    array/vector.  */
1161 enum class dir_index : unsigned int {};
1162
1163 /* Likewise, a 1-based file name index.  */
1164 enum class file_name_index : unsigned int {};
1165
1166 struct file_entry
1167 {
1168   file_entry () = default;
1169
1170   file_entry (const char *name_, dir_index d_index_,
1171               unsigned int mod_time_, unsigned int length_)
1172     : name (name_),
1173       d_index (d_index_),
1174       mod_time (mod_time_),
1175       length (length_)
1176   {}
1177
1178   /* Return the include directory at D_INDEX stored in LH.  Returns
1179      NULL if D_INDEX is out of bounds.  */
1180   const char *include_dir (const line_header *lh) const;
1181
1182   /* The file name.  Note this is an observing pointer.  The memory is
1183      owned by debug_line_buffer.  */
1184   const char *name {};
1185
1186   /* The directory index (1-based).  */
1187   dir_index d_index {};
1188
1189   unsigned int mod_time {};
1190
1191   unsigned int length {};
1192
1193   /* True if referenced by the Line Number Program.  */
1194   bool included_p {};
1195
1196   /* The associated symbol table, if any.  */
1197   struct symtab *symtab {};
1198 };
1199
1200 /* The line number information for a compilation unit (found in the
1201    .debug_line section) begins with a "statement program header",
1202    which contains the following information.  */
1203 struct line_header
1204 {
1205   line_header ()
1206     : offset_in_dwz {}
1207   {}
1208
1209   /* Add an entry to the include directory table.  */
1210   void add_include_dir (const char *include_dir);
1211
1212   /* Add an entry to the file name table.  */
1213   void add_file_name (const char *name, dir_index d_index,
1214                       unsigned int mod_time, unsigned int length);
1215
1216   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1217      is out of bounds.  */
1218   const char *include_dir_at (dir_index index) const
1219   {
1220     /* Convert directory index number (1-based) to vector index
1221        (0-based).  */
1222     size_t vec_index = to_underlying (index) - 1;
1223
1224     if (vec_index >= include_dirs.size ())
1225       return NULL;
1226     return include_dirs[vec_index];
1227   }
1228
1229   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1230      is out of bounds.  */
1231   file_entry *file_name_at (file_name_index index)
1232   {
1233     /* Convert file name index number (1-based) to vector index
1234        (0-based).  */
1235     size_t vec_index = to_underlying (index) - 1;
1236
1237     if (vec_index >= file_names.size ())
1238       return NULL;
1239     return &file_names[vec_index];
1240   }
1241
1242   /* Const version of the above.  */
1243   const file_entry *file_name_at (unsigned int index) const
1244   {
1245     if (index >= file_names.size ())
1246       return NULL;
1247     return &file_names[index];
1248   }
1249
1250   /* Offset of line number information in .debug_line section.  */
1251   sect_offset sect_off {};
1252
1253   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1254   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1255
1256   unsigned int total_length {};
1257   unsigned short version {};
1258   unsigned int header_length {};
1259   unsigned char minimum_instruction_length {};
1260   unsigned char maximum_ops_per_instruction {};
1261   unsigned char default_is_stmt {};
1262   int line_base {};
1263   unsigned char line_range {};
1264   unsigned char opcode_base {};
1265
1266   /* standard_opcode_lengths[i] is the number of operands for the
1267      standard opcode whose value is i.  This means that
1268      standard_opcode_lengths[0] is unused, and the last meaningful
1269      element is standard_opcode_lengths[opcode_base - 1].  */
1270   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1271
1272   /* The include_directories table.  Note these are observing
1273      pointers.  The memory is owned by debug_line_buffer.  */
1274   std::vector<const char *> include_dirs;
1275
1276   /* The file_names table.  */
1277   std::vector<file_entry> file_names;
1278
1279   /* The start and end of the statement program following this
1280      header.  These point into dwarf2_per_objfile->line_buffer.  */
1281   const gdb_byte *statement_program_start {}, *statement_program_end {};
1282 };
1283
1284 typedef std::unique_ptr<line_header> line_header_up;
1285
1286 const char *
1287 file_entry::include_dir (const line_header *lh) const
1288 {
1289   return lh->include_dir_at (d_index);
1290 }
1291
1292 /* When we construct a partial symbol table entry we only
1293    need this much information.  */
1294 struct partial_die_info
1295   {
1296     /* Offset of this DIE.  */
1297     sect_offset sect_off;
1298
1299     /* DWARF-2 tag for this DIE.  */
1300     ENUM_BITFIELD(dwarf_tag) tag : 16;
1301
1302     /* Assorted flags describing the data found in this DIE.  */
1303     unsigned int has_children : 1;
1304     unsigned int is_external : 1;
1305     unsigned int is_declaration : 1;
1306     unsigned int has_type : 1;
1307     unsigned int has_specification : 1;
1308     unsigned int has_pc_info : 1;
1309     unsigned int may_be_inlined : 1;
1310
1311     /* This DIE has been marked DW_AT_main_subprogram.  */
1312     unsigned int main_subprogram : 1;
1313
1314     /* Flag set if the SCOPE field of this structure has been
1315        computed.  */
1316     unsigned int scope_set : 1;
1317
1318     /* Flag set if the DIE has a byte_size attribute.  */
1319     unsigned int has_byte_size : 1;
1320
1321     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1322     unsigned int has_const_value : 1;
1323
1324     /* Flag set if any of the DIE's children are template arguments.  */
1325     unsigned int has_template_arguments : 1;
1326
1327     /* Flag set if fixup_partial_die has been called on this die.  */
1328     unsigned int fixup_called : 1;
1329
1330     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1331     unsigned int is_dwz : 1;
1332
1333     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1334     unsigned int spec_is_dwz : 1;
1335
1336     /* The name of this DIE.  Normally the value of DW_AT_name, but
1337        sometimes a default name for unnamed DIEs.  */
1338     const char *name;
1339
1340     /* The linkage name, if present.  */
1341     const char *linkage_name;
1342
1343     /* The scope to prepend to our children.  This is generally
1344        allocated on the comp_unit_obstack, so will disappear
1345        when this compilation unit leaves the cache.  */
1346     const char *scope;
1347
1348     /* Some data associated with the partial DIE.  The tag determines
1349        which field is live.  */
1350     union
1351     {
1352       /* The location description associated with this DIE, if any.  */
1353       struct dwarf_block *locdesc;
1354       /* The offset of an import, for DW_TAG_imported_unit.  */
1355       sect_offset sect_off;
1356     } d;
1357
1358     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1359     CORE_ADDR lowpc;
1360     CORE_ADDR highpc;
1361
1362     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1363        DW_AT_sibling, if any.  */
1364     /* NOTE: This member isn't strictly necessary, read_partial_die could
1365        return DW_AT_sibling values to its caller load_partial_dies.  */
1366     const gdb_byte *sibling;
1367
1368     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1369        DW_AT_specification (or DW_AT_abstract_origin or
1370        DW_AT_extension).  */
1371     sect_offset spec_offset;
1372
1373     /* Pointers to this DIE's parent, first child, and next sibling,
1374        if any.  */
1375     struct partial_die_info *die_parent, *die_child, *die_sibling;
1376   };
1377
1378 /* This data structure holds the information of an abbrev.  */
1379 struct abbrev_info
1380   {
1381     unsigned int number;        /* number identifying abbrev */
1382     enum dwarf_tag tag;         /* dwarf tag */
1383     unsigned short has_children;                /* boolean */
1384     unsigned short num_attrs;   /* number of attributes */
1385     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1386     struct abbrev_info *next;   /* next in chain */
1387   };
1388
1389 struct attr_abbrev
1390   {
1391     ENUM_BITFIELD(dwarf_attribute) name : 16;
1392     ENUM_BITFIELD(dwarf_form) form : 16;
1393
1394     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1395     LONGEST implicit_const;
1396   };
1397
1398 /* Size of abbrev_table.abbrev_hash_table.  */
1399 #define ABBREV_HASH_SIZE 121
1400
1401 /* Top level data structure to contain an abbreviation table.  */
1402
1403 struct abbrev_table
1404 {
1405   /* Where the abbrev table came from.
1406      This is used as a sanity check when the table is used.  */
1407   sect_offset sect_off;
1408
1409   /* Storage for the abbrev table.  */
1410   struct obstack abbrev_obstack;
1411
1412   /* Hash table of abbrevs.
1413      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1414      It could be statically allocated, but the previous code didn't so we
1415      don't either.  */
1416   struct abbrev_info **abbrevs;
1417 };
1418
1419 /* Attributes have a name and a value.  */
1420 struct attribute
1421   {
1422     ENUM_BITFIELD(dwarf_attribute) name : 16;
1423     ENUM_BITFIELD(dwarf_form) form : 15;
1424
1425     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1426        field should be in u.str (existing only for DW_STRING) but it is kept
1427        here for better struct attribute alignment.  */
1428     unsigned int string_is_canonical : 1;
1429
1430     union
1431       {
1432         const char *str;
1433         struct dwarf_block *blk;
1434         ULONGEST unsnd;
1435         LONGEST snd;
1436         CORE_ADDR addr;
1437         ULONGEST signature;
1438       }
1439     u;
1440   };
1441
1442 /* This data structure holds a complete die structure.  */
1443 struct die_info
1444   {
1445     /* DWARF-2 tag for this DIE.  */
1446     ENUM_BITFIELD(dwarf_tag) tag : 16;
1447
1448     /* Number of attributes */
1449     unsigned char num_attrs;
1450
1451     /* True if we're presently building the full type name for the
1452        type derived from this DIE.  */
1453     unsigned char building_fullname : 1;
1454
1455     /* True if this die is in process.  PR 16581.  */
1456     unsigned char in_process : 1;
1457
1458     /* Abbrev number */
1459     unsigned int abbrev;
1460
1461     /* Offset in .debug_info or .debug_types section.  */
1462     sect_offset sect_off;
1463
1464     /* The dies in a compilation unit form an n-ary tree.  PARENT
1465        points to this die's parent; CHILD points to the first child of
1466        this node; and all the children of a given node are chained
1467        together via their SIBLING fields.  */
1468     struct die_info *child;     /* Its first child, if any.  */
1469     struct die_info *sibling;   /* Its next sibling, if any.  */
1470     struct die_info *parent;    /* Its parent, if any.  */
1471
1472     /* An array of attributes, with NUM_ATTRS elements.  There may be
1473        zero, but it's not common and zero-sized arrays are not
1474        sufficiently portable C.  */
1475     struct attribute attrs[1];
1476   };
1477
1478 /* Get at parts of an attribute structure.  */
1479
1480 #define DW_STRING(attr)    ((attr)->u.str)
1481 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1482 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1483 #define DW_BLOCK(attr)     ((attr)->u.blk)
1484 #define DW_SND(attr)       ((attr)->u.snd)
1485 #define DW_ADDR(attr)      ((attr)->u.addr)
1486 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1487
1488 /* Blocks are a bunch of untyped bytes.  */
1489 struct dwarf_block
1490   {
1491     size_t size;
1492
1493     /* Valid only if SIZE is not zero.  */
1494     const gdb_byte *data;
1495   };
1496
1497 #ifndef ATTR_ALLOC_CHUNK
1498 #define ATTR_ALLOC_CHUNK 4
1499 #endif
1500
1501 /* Allocate fields for structs, unions and enums in this size.  */
1502 #ifndef DW_FIELD_ALLOC_CHUNK
1503 #define DW_FIELD_ALLOC_CHUNK 4
1504 #endif
1505
1506 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1507    but this would require a corresponding change in unpack_field_as_long
1508    and friends.  */
1509 static int bits_per_byte = 8;
1510
1511 struct nextfield
1512 {
1513   struct nextfield *next;
1514   int accessibility;
1515   int virtuality;
1516   struct field field;
1517 };
1518
1519 struct nextfnfield
1520 {
1521   struct nextfnfield *next;
1522   struct fn_field fnfield;
1523 };
1524
1525 struct fnfieldlist
1526 {
1527   const char *name;
1528   int length;
1529   struct nextfnfield *head;
1530 };
1531
1532 struct decl_field_list
1533 {
1534   struct decl_field field;
1535   struct decl_field_list *next;
1536 };
1537
1538 /* The routines that read and process dies for a C struct or C++ class
1539    pass lists of data member fields and lists of member function fields
1540    in an instance of a field_info structure, as defined below.  */
1541 struct field_info
1542   {
1543     /* List of data member and baseclasses fields.  */
1544     struct nextfield *fields, *baseclasses;
1545
1546     /* Number of fields (including baseclasses).  */
1547     int nfields;
1548
1549     /* Number of baseclasses.  */
1550     int nbaseclasses;
1551
1552     /* Set if the accesibility of one of the fields is not public.  */
1553     int non_public_fields;
1554
1555     /* Member function fieldlist array, contains name of possibly overloaded
1556        member function, number of overloaded member functions and a pointer
1557        to the head of the member function field chain.  */
1558     struct fnfieldlist *fnfieldlists;
1559
1560     /* Number of entries in the fnfieldlists array.  */
1561     int nfnfields;
1562
1563     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1564        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1565     struct decl_field_list *typedef_field_list;
1566     unsigned typedef_field_list_count;
1567
1568     /* Nested types defined by this class and the number of elements in this
1569        list.  */
1570     struct decl_field_list *nested_types_list;
1571     unsigned nested_types_list_count;
1572   };
1573
1574 /* One item on the queue of compilation units to read in full symbols
1575    for.  */
1576 struct dwarf2_queue_item
1577 {
1578   struct dwarf2_per_cu_data *per_cu;
1579   enum language pretend_language;
1580   struct dwarf2_queue_item *next;
1581 };
1582
1583 /* The current queue.  */
1584 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1585
1586 /* Loaded secondary compilation units are kept in memory until they
1587    have not been referenced for the processing of this many
1588    compilation units.  Set this to zero to disable caching.  Cache
1589    sizes of up to at least twenty will improve startup time for
1590    typical inter-CU-reference binaries, at an obvious memory cost.  */
1591 static int dwarf_max_cache_age = 5;
1592 static void
1593 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1594                           struct cmd_list_element *c, const char *value)
1595 {
1596   fprintf_filtered (file, _("The upper bound on the age of cached "
1597                             "DWARF compilation units is %s.\n"),
1598                     value);
1599 }
1600 \f
1601 /* local function prototypes */
1602
1603 static const char *get_section_name (const struct dwarf2_section_info *);
1604
1605 static const char *get_section_file_name (const struct dwarf2_section_info *);
1606
1607 static void dwarf2_find_base_address (struct die_info *die,
1608                                       struct dwarf2_cu *cu);
1609
1610 static struct partial_symtab *create_partial_symtab
1611   (struct dwarf2_per_cu_data *per_cu, const char *name);
1612
1613 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1614                                         const gdb_byte *info_ptr,
1615                                         struct die_info *type_unit_die,
1616                                         int has_children, void *data);
1617
1618 static void dwarf2_build_psymtabs_hard (struct objfile *);
1619
1620 static void scan_partial_symbols (struct partial_die_info *,
1621                                   CORE_ADDR *, CORE_ADDR *,
1622                                   int, struct dwarf2_cu *);
1623
1624 static void add_partial_symbol (struct partial_die_info *,
1625                                 struct dwarf2_cu *);
1626
1627 static void add_partial_namespace (struct partial_die_info *pdi,
1628                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1629                                    int set_addrmap, struct dwarf2_cu *cu);
1630
1631 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1632                                 CORE_ADDR *highpc, int set_addrmap,
1633                                 struct dwarf2_cu *cu);
1634
1635 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1636                                      struct dwarf2_cu *cu);
1637
1638 static void add_partial_subprogram (struct partial_die_info *pdi,
1639                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1640                                     int need_pc, struct dwarf2_cu *cu);
1641
1642 static void dwarf2_read_symtab (struct partial_symtab *,
1643                                 struct objfile *);
1644
1645 static void psymtab_to_symtab_1 (struct partial_symtab *);
1646
1647 static struct abbrev_info *abbrev_table_lookup_abbrev
1648   (const struct abbrev_table *, unsigned int);
1649
1650 static struct abbrev_table *abbrev_table_read_table
1651   (struct dwarf2_section_info *, sect_offset);
1652
1653 static void abbrev_table_free (struct abbrev_table *);
1654
1655 static void abbrev_table_free_cleanup (void *);
1656
1657 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1658                                  struct dwarf2_section_info *);
1659
1660 static void dwarf2_free_abbrev_table (void *);
1661
1662 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1663
1664 static struct partial_die_info *load_partial_dies
1665   (const struct die_reader_specs *, const gdb_byte *, int);
1666
1667 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1668                                          struct partial_die_info *,
1669                                          struct abbrev_info *,
1670                                          unsigned int,
1671                                          const gdb_byte *);
1672
1673 static struct partial_die_info *find_partial_die (sect_offset, int,
1674                                                   struct dwarf2_cu *);
1675
1676 static void fixup_partial_die (struct partial_die_info *,
1677                                struct dwarf2_cu *);
1678
1679 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1680                                        struct attribute *, struct attr_abbrev *,
1681                                        const gdb_byte *);
1682
1683 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1684
1685 static int read_1_signed_byte (bfd *, const gdb_byte *);
1686
1687 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1688
1689 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1690
1691 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1692
1693 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1694                                unsigned int *);
1695
1696 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1697
1698 static LONGEST read_checked_initial_length_and_offset
1699   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1700    unsigned int *, unsigned int *);
1701
1702 static LONGEST read_offset (bfd *, const gdb_byte *,
1703                             const struct comp_unit_head *,
1704                             unsigned int *);
1705
1706 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1707
1708 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1709                                        sect_offset);
1710
1711 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1712
1713 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1714
1715 static const char *read_indirect_string (bfd *, const gdb_byte *,
1716                                          const struct comp_unit_head *,
1717                                          unsigned int *);
1718
1719 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1720                                               const struct comp_unit_head *,
1721                                               unsigned int *);
1722
1723 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1724
1725 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1726
1727 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1728                                               const gdb_byte *,
1729                                               unsigned int *);
1730
1731 static const char *read_str_index (const struct die_reader_specs *reader,
1732                                    ULONGEST str_index);
1733
1734 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1735
1736 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1737                                       struct dwarf2_cu *);
1738
1739 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1740                                                 unsigned int);
1741
1742 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1743                                        struct dwarf2_cu *cu);
1744
1745 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1746                                struct dwarf2_cu *cu);
1747
1748 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1749
1750 static struct die_info *die_specification (struct die_info *die,
1751                                            struct dwarf2_cu **);
1752
1753 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1754                                                 struct dwarf2_cu *cu);
1755
1756 static void dwarf_decode_lines (struct line_header *, const char *,
1757                                 struct dwarf2_cu *, struct partial_symtab *,
1758                                 CORE_ADDR, int decode_mapping);
1759
1760 static void dwarf2_start_subfile (const char *, const char *);
1761
1762 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1763                                                     const char *, const char *,
1764                                                     CORE_ADDR);
1765
1766 static struct symbol *new_symbol (struct die_info *, struct type *,
1767                                   struct dwarf2_cu *);
1768
1769 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1770                                        struct dwarf2_cu *, struct symbol *);
1771
1772 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1773                                 struct dwarf2_cu *);
1774
1775 static void dwarf2_const_value_attr (const struct attribute *attr,
1776                                      struct type *type,
1777                                      const char *name,
1778                                      struct obstack *obstack,
1779                                      struct dwarf2_cu *cu, LONGEST *value,
1780                                      const gdb_byte **bytes,
1781                                      struct dwarf2_locexpr_baton **baton);
1782
1783 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1784
1785 static int need_gnat_info (struct dwarf2_cu *);
1786
1787 static struct type *die_descriptive_type (struct die_info *,
1788                                           struct dwarf2_cu *);
1789
1790 static void set_descriptive_type (struct type *, struct die_info *,
1791                                   struct dwarf2_cu *);
1792
1793 static struct type *die_containing_type (struct die_info *,
1794                                          struct dwarf2_cu *);
1795
1796 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1797                                      struct dwarf2_cu *);
1798
1799 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1800
1801 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1802
1803 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1804
1805 static char *typename_concat (struct obstack *obs, const char *prefix,
1806                               const char *suffix, int physname,
1807                               struct dwarf2_cu *cu);
1808
1809 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1810
1811 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1812
1813 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1814
1815 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1816
1817 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1818
1819 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1820
1821 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1822                                struct dwarf2_cu *, struct partial_symtab *);
1823
1824 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1825    values.  Keep the items ordered with increasing constraints compliance.  */
1826 enum pc_bounds_kind
1827 {
1828   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1829   PC_BOUNDS_NOT_PRESENT,
1830
1831   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1832      were present but they do not form a valid range of PC addresses.  */
1833   PC_BOUNDS_INVALID,
1834
1835   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1836   PC_BOUNDS_RANGES,
1837
1838   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1839   PC_BOUNDS_HIGH_LOW,
1840 };
1841
1842 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1843                                                  CORE_ADDR *, CORE_ADDR *,
1844                                                  struct dwarf2_cu *,
1845                                                  struct partial_symtab *);
1846
1847 static void get_scope_pc_bounds (struct die_info *,
1848                                  CORE_ADDR *, CORE_ADDR *,
1849                                  struct dwarf2_cu *);
1850
1851 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1852                                         CORE_ADDR, struct dwarf2_cu *);
1853
1854 static void dwarf2_add_field (struct field_info *, struct die_info *,
1855                               struct dwarf2_cu *);
1856
1857 static void dwarf2_attach_fields_to_type (struct field_info *,
1858                                           struct type *, struct dwarf2_cu *);
1859
1860 static void dwarf2_add_member_fn (struct field_info *,
1861                                   struct die_info *, struct type *,
1862                                   struct dwarf2_cu *);
1863
1864 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1865                                              struct type *,
1866                                              struct dwarf2_cu *);
1867
1868 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1869
1870 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1871
1872 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1873
1874 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1875
1876 static struct using_direct **using_directives (enum language);
1877
1878 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1879
1880 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1881
1882 static struct type *read_module_type (struct die_info *die,
1883                                       struct dwarf2_cu *cu);
1884
1885 static const char *namespace_name (struct die_info *die,
1886                                    int *is_anonymous, struct dwarf2_cu *);
1887
1888 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1889
1890 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1891
1892 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1893                                                        struct dwarf2_cu *);
1894
1895 static struct die_info *read_die_and_siblings_1
1896   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1897    struct die_info *);
1898
1899 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1900                                                const gdb_byte *info_ptr,
1901                                                const gdb_byte **new_info_ptr,
1902                                                struct die_info *parent);
1903
1904 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1905                                         struct die_info **, const gdb_byte *,
1906                                         int *, int);
1907
1908 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1909                                       struct die_info **, const gdb_byte *,
1910                                       int *);
1911
1912 static void process_die (struct die_info *, struct dwarf2_cu *);
1913
1914 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1915                                              struct obstack *);
1916
1917 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1918
1919 static const char *dwarf2_full_name (const char *name,
1920                                      struct die_info *die,
1921                                      struct dwarf2_cu *cu);
1922
1923 static const char *dwarf2_physname (const char *name, struct die_info *die,
1924                                     struct dwarf2_cu *cu);
1925
1926 static struct die_info *dwarf2_extension (struct die_info *die,
1927                                           struct dwarf2_cu **);
1928
1929 static const char *dwarf_tag_name (unsigned int);
1930
1931 static const char *dwarf_attr_name (unsigned int);
1932
1933 static const char *dwarf_form_name (unsigned int);
1934
1935 static const char *dwarf_bool_name (unsigned int);
1936
1937 static const char *dwarf_type_encoding_name (unsigned int);
1938
1939 static struct die_info *sibling_die (struct die_info *);
1940
1941 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1942
1943 static void dump_die_for_error (struct die_info *);
1944
1945 static void dump_die_1 (struct ui_file *, int level, int max_level,
1946                         struct die_info *);
1947
1948 /*static*/ void dump_die (struct die_info *, int max_level);
1949
1950 static void store_in_ref_table (struct die_info *,
1951                                 struct dwarf2_cu *);
1952
1953 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1954
1955 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1956
1957 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1958                                                const struct attribute *,
1959                                                struct dwarf2_cu **);
1960
1961 static struct die_info *follow_die_ref (struct die_info *,
1962                                         const struct attribute *,
1963                                         struct dwarf2_cu **);
1964
1965 static struct die_info *follow_die_sig (struct die_info *,
1966                                         const struct attribute *,
1967                                         struct dwarf2_cu **);
1968
1969 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1970                                          struct dwarf2_cu *);
1971
1972 static struct type *get_DW_AT_signature_type (struct die_info *,
1973                                               const struct attribute *,
1974                                               struct dwarf2_cu *);
1975
1976 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1977
1978 static void read_signatured_type (struct signatured_type *);
1979
1980 static int attr_to_dynamic_prop (const struct attribute *attr,
1981                                  struct die_info *die, struct dwarf2_cu *cu,
1982                                  struct dynamic_prop *prop);
1983
1984 /* memory allocation interface */
1985
1986 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1987
1988 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1989
1990 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1991
1992 static int attr_form_is_block (const struct attribute *);
1993
1994 static int attr_form_is_section_offset (const struct attribute *);
1995
1996 static int attr_form_is_constant (const struct attribute *);
1997
1998 static int attr_form_is_ref (const struct attribute *);
1999
2000 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2001                                    struct dwarf2_loclist_baton *baton,
2002                                    const struct attribute *attr);
2003
2004 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2005                                          struct symbol *sym,
2006                                          struct dwarf2_cu *cu,
2007                                          int is_block);
2008
2009 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2010                                      const gdb_byte *info_ptr,
2011                                      struct abbrev_info *abbrev);
2012
2013 static void free_stack_comp_unit (void *);
2014
2015 static hashval_t partial_die_hash (const void *item);
2016
2017 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2018
2019 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2020   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2021
2022 static void init_one_comp_unit (struct dwarf2_cu *cu,
2023                                 struct dwarf2_per_cu_data *per_cu);
2024
2025 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2026                                    struct die_info *comp_unit_die,
2027                                    enum language pretend_language);
2028
2029 static void free_heap_comp_unit (void *);
2030
2031 static void free_cached_comp_units (void *);
2032
2033 static void age_cached_comp_units (void);
2034
2035 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2036
2037 static struct type *set_die_type (struct die_info *, struct type *,
2038                                   struct dwarf2_cu *);
2039
2040 static void create_all_comp_units (struct objfile *);
2041
2042 static int create_all_type_units (struct objfile *);
2043
2044 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2045                                  enum language);
2046
2047 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2048                                     enum language);
2049
2050 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2051                                     enum language);
2052
2053 static void dwarf2_add_dependence (struct dwarf2_cu *,
2054                                    struct dwarf2_per_cu_data *);
2055
2056 static void dwarf2_mark (struct dwarf2_cu *);
2057
2058 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2059
2060 static struct type *get_die_type_at_offset (sect_offset,
2061                                             struct dwarf2_per_cu_data *);
2062
2063 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2064
2065 static void dwarf2_release_queue (void *dummy);
2066
2067 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2068                              enum language pretend_language);
2069
2070 static void process_queue (void);
2071
2072 /* The return type of find_file_and_directory.  Note, the enclosed
2073    string pointers are only valid while this object is valid.  */
2074
2075 struct file_and_directory
2076 {
2077   /* The filename.  This is never NULL.  */
2078   const char *name;
2079
2080   /* The compilation directory.  NULL if not known.  If we needed to
2081      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2082      points directly to the DW_AT_comp_dir string attribute owned by
2083      the obstack that owns the DIE.  */
2084   const char *comp_dir;
2085
2086   /* If we needed to build a new string for comp_dir, this is what
2087      owns the storage.  */
2088   std::string comp_dir_storage;
2089 };
2090
2091 static file_and_directory find_file_and_directory (struct die_info *die,
2092                                                    struct dwarf2_cu *cu);
2093
2094 static char *file_full_name (int file, struct line_header *lh,
2095                              const char *comp_dir);
2096
2097 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2098 enum class rcuh_kind { COMPILE, TYPE };
2099
2100 static const gdb_byte *read_and_check_comp_unit_head
2101   (struct comp_unit_head *header,
2102    struct dwarf2_section_info *section,
2103    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2104    rcuh_kind section_kind);
2105
2106 static void init_cutu_and_read_dies
2107   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2108    int use_existing_cu, int keep,
2109    die_reader_func_ftype *die_reader_func, void *data);
2110
2111 static void init_cutu_and_read_dies_simple
2112   (struct dwarf2_per_cu_data *this_cu,
2113    die_reader_func_ftype *die_reader_func, void *data);
2114
2115 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2116
2117 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2118
2119 static struct dwo_unit *lookup_dwo_unit_in_dwp
2120   (struct dwp_file *dwp_file, const char *comp_dir,
2121    ULONGEST signature, int is_debug_types);
2122
2123 static struct dwp_file *get_dwp_file (void);
2124
2125 static struct dwo_unit *lookup_dwo_comp_unit
2126   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2127
2128 static struct dwo_unit *lookup_dwo_type_unit
2129   (struct signatured_type *, const char *, const char *);
2130
2131 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2132
2133 static void free_dwo_file_cleanup (void *);
2134
2135 static void process_cu_includes (void);
2136
2137 static void check_producer (struct dwarf2_cu *cu);
2138
2139 static void free_line_header_voidp (void *arg);
2140 \f
2141 /* Various complaints about symbol reading that don't abort the process.  */
2142
2143 static void
2144 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2145 {
2146   complaint (&symfile_complaints,
2147              _("statement list doesn't fit in .debug_line section"));
2148 }
2149
2150 static void
2151 dwarf2_debug_line_missing_file_complaint (void)
2152 {
2153   complaint (&symfile_complaints,
2154              _(".debug_line section has line data without a file"));
2155 }
2156
2157 static void
2158 dwarf2_debug_line_missing_end_sequence_complaint (void)
2159 {
2160   complaint (&symfile_complaints,
2161              _(".debug_line section has line "
2162                "program sequence without an end"));
2163 }
2164
2165 static void
2166 dwarf2_complex_location_expr_complaint (void)
2167 {
2168   complaint (&symfile_complaints, _("location expression too complex"));
2169 }
2170
2171 static void
2172 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2173                                               int arg3)
2174 {
2175   complaint (&symfile_complaints,
2176              _("const value length mismatch for '%s', got %d, expected %d"),
2177              arg1, arg2, arg3);
2178 }
2179
2180 static void
2181 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2182 {
2183   complaint (&symfile_complaints,
2184              _("debug info runs off end of %s section"
2185                " [in module %s]"),
2186              get_section_name (section),
2187              get_section_file_name (section));
2188 }
2189
2190 static void
2191 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2192 {
2193   complaint (&symfile_complaints,
2194              _("macro debug info contains a "
2195                "malformed macro definition:\n`%s'"),
2196              arg1);
2197 }
2198
2199 static void
2200 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2201 {
2202   complaint (&symfile_complaints,
2203              _("invalid attribute class or form for '%s' in '%s'"),
2204              arg1, arg2);
2205 }
2206
2207 /* Hash function for line_header_hash.  */
2208
2209 static hashval_t
2210 line_header_hash (const struct line_header *ofs)
2211 {
2212   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2213 }
2214
2215 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2216
2217 static hashval_t
2218 line_header_hash_voidp (const void *item)
2219 {
2220   const struct line_header *ofs = (const struct line_header *) item;
2221
2222   return line_header_hash (ofs);
2223 }
2224
2225 /* Equality function for line_header_hash.  */
2226
2227 static int
2228 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2229 {
2230   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2231   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2232
2233   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2234           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2235 }
2236
2237 \f
2238
2239 /* Read the given attribute value as an address, taking the attribute's
2240    form into account.  */
2241
2242 static CORE_ADDR
2243 attr_value_as_address (struct attribute *attr)
2244 {
2245   CORE_ADDR addr;
2246
2247   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2248     {
2249       /* Aside from a few clearly defined exceptions, attributes that
2250          contain an address must always be in DW_FORM_addr form.
2251          Unfortunately, some compilers happen to be violating this
2252          requirement by encoding addresses using other forms, such
2253          as DW_FORM_data4 for example.  For those broken compilers,
2254          we try to do our best, without any guarantee of success,
2255          to interpret the address correctly.  It would also be nice
2256          to generate a complaint, but that would require us to maintain
2257          a list of legitimate cases where a non-address form is allowed,
2258          as well as update callers to pass in at least the CU's DWARF
2259          version.  This is more overhead than what we're willing to
2260          expand for a pretty rare case.  */
2261       addr = DW_UNSND (attr);
2262     }
2263   else
2264     addr = DW_ADDR (attr);
2265
2266   return addr;
2267 }
2268
2269 /* The suffix for an index file.  */
2270 #define INDEX_SUFFIX ".gdb-index"
2271
2272 /* See declaration.  */
2273
2274 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2275                                         const dwarf2_debug_sections *names)
2276   : objfile (objfile_)
2277 {
2278   if (names == NULL)
2279     names = &dwarf2_elf_names;
2280
2281   bfd *obfd = objfile->obfd;
2282
2283   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2284     locate_sections (obfd, sec, *names);
2285 }
2286
2287 dwarf2_per_objfile::~dwarf2_per_objfile ()
2288 {
2289   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2290   free_cached_comp_units ();
2291
2292   if (quick_file_names_table)
2293     htab_delete (quick_file_names_table);
2294
2295   if (line_header_hash)
2296     htab_delete (line_header_hash);
2297
2298   /* Everything else should be on the objfile obstack.  */
2299 }
2300
2301 /* See declaration.  */
2302
2303 void
2304 dwarf2_per_objfile::free_cached_comp_units ()
2305 {
2306   dwarf2_per_cu_data *per_cu = read_in_chain;
2307   dwarf2_per_cu_data **last_chain = &read_in_chain;
2308   while (per_cu != NULL)
2309     {
2310       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2311
2312       free_heap_comp_unit (per_cu->cu);
2313       *last_chain = next_cu;
2314       per_cu = next_cu;
2315     }
2316 }
2317
2318 /* Try to locate the sections we need for DWARF 2 debugging
2319    information and return true if we have enough to do something.
2320    NAMES points to the dwarf2 section names, or is NULL if the standard
2321    ELF names are used.  */
2322
2323 int
2324 dwarf2_has_info (struct objfile *objfile,
2325                  const struct dwarf2_debug_sections *names)
2326 {
2327   if (objfile->flags & OBJF_READNEVER)
2328     return 0;
2329
2330   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2331                         objfile_data (objfile, dwarf2_objfile_data_key));
2332   if (!dwarf2_per_objfile)
2333     {
2334       /* Initialize per-objfile state.  */
2335       struct dwarf2_per_objfile *data
2336         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2337
2338       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2339       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2340     }
2341   return (!dwarf2_per_objfile->info.is_virtual
2342           && dwarf2_per_objfile->info.s.section != NULL
2343           && !dwarf2_per_objfile->abbrev.is_virtual
2344           && dwarf2_per_objfile->abbrev.s.section != NULL);
2345 }
2346
2347 /* Return the containing section of virtual section SECTION.  */
2348
2349 static struct dwarf2_section_info *
2350 get_containing_section (const struct dwarf2_section_info *section)
2351 {
2352   gdb_assert (section->is_virtual);
2353   return section->s.containing_section;
2354 }
2355
2356 /* Return the bfd owner of SECTION.  */
2357
2358 static struct bfd *
2359 get_section_bfd_owner (const struct dwarf2_section_info *section)
2360 {
2361   if (section->is_virtual)
2362     {
2363       section = get_containing_section (section);
2364       gdb_assert (!section->is_virtual);
2365     }
2366   return section->s.section->owner;
2367 }
2368
2369 /* Return the bfd section of SECTION.
2370    Returns NULL if the section is not present.  */
2371
2372 static asection *
2373 get_section_bfd_section (const struct dwarf2_section_info *section)
2374 {
2375   if (section->is_virtual)
2376     {
2377       section = get_containing_section (section);
2378       gdb_assert (!section->is_virtual);
2379     }
2380   return section->s.section;
2381 }
2382
2383 /* Return the name of SECTION.  */
2384
2385 static const char *
2386 get_section_name (const struct dwarf2_section_info *section)
2387 {
2388   asection *sectp = get_section_bfd_section (section);
2389
2390   gdb_assert (sectp != NULL);
2391   return bfd_section_name (get_section_bfd_owner (section), sectp);
2392 }
2393
2394 /* Return the name of the file SECTION is in.  */
2395
2396 static const char *
2397 get_section_file_name (const struct dwarf2_section_info *section)
2398 {
2399   bfd *abfd = get_section_bfd_owner (section);
2400
2401   return bfd_get_filename (abfd);
2402 }
2403
2404 /* Return the id of SECTION.
2405    Returns 0 if SECTION doesn't exist.  */
2406
2407 static int
2408 get_section_id (const struct dwarf2_section_info *section)
2409 {
2410   asection *sectp = get_section_bfd_section (section);
2411
2412   if (sectp == NULL)
2413     return 0;
2414   return sectp->id;
2415 }
2416
2417 /* Return the flags of SECTION.
2418    SECTION (or containing section if this is a virtual section) must exist.  */
2419
2420 static int
2421 get_section_flags (const struct dwarf2_section_info *section)
2422 {
2423   asection *sectp = get_section_bfd_section (section);
2424
2425   gdb_assert (sectp != NULL);
2426   return bfd_get_section_flags (sectp->owner, sectp);
2427 }
2428
2429 /* When loading sections, we look either for uncompressed section or for
2430    compressed section names.  */
2431
2432 static int
2433 section_is_p (const char *section_name,
2434               const struct dwarf2_section_names *names)
2435 {
2436   if (names->normal != NULL
2437       && strcmp (section_name, names->normal) == 0)
2438     return 1;
2439   if (names->compressed != NULL
2440       && strcmp (section_name, names->compressed) == 0)
2441     return 1;
2442   return 0;
2443 }
2444
2445 /* See declaration.  */
2446
2447 void
2448 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2449                                      const dwarf2_debug_sections &names)
2450 {
2451   flagword aflag = bfd_get_section_flags (abfd, sectp);
2452
2453   if ((aflag & SEC_HAS_CONTENTS) == 0)
2454     {
2455     }
2456   else if (section_is_p (sectp->name, &names.info))
2457     {
2458       this->info.s.section = sectp;
2459       this->info.size = bfd_get_section_size (sectp);
2460     }
2461   else if (section_is_p (sectp->name, &names.abbrev))
2462     {
2463       this->abbrev.s.section = sectp;
2464       this->abbrev.size = bfd_get_section_size (sectp);
2465     }
2466   else if (section_is_p (sectp->name, &names.line))
2467     {
2468       this->line.s.section = sectp;
2469       this->line.size = bfd_get_section_size (sectp);
2470     }
2471   else if (section_is_p (sectp->name, &names.loc))
2472     {
2473       this->loc.s.section = sectp;
2474       this->loc.size = bfd_get_section_size (sectp);
2475     }
2476   else if (section_is_p (sectp->name, &names.loclists))
2477     {
2478       this->loclists.s.section = sectp;
2479       this->loclists.size = bfd_get_section_size (sectp);
2480     }
2481   else if (section_is_p (sectp->name, &names.macinfo))
2482     {
2483       this->macinfo.s.section = sectp;
2484       this->macinfo.size = bfd_get_section_size (sectp);
2485     }
2486   else if (section_is_p (sectp->name, &names.macro))
2487     {
2488       this->macro.s.section = sectp;
2489       this->macro.size = bfd_get_section_size (sectp);
2490     }
2491   else if (section_is_p (sectp->name, &names.str))
2492     {
2493       this->str.s.section = sectp;
2494       this->str.size = bfd_get_section_size (sectp);
2495     }
2496   else if (section_is_p (sectp->name, &names.line_str))
2497     {
2498       this->line_str.s.section = sectp;
2499       this->line_str.size = bfd_get_section_size (sectp);
2500     }
2501   else if (section_is_p (sectp->name, &names.addr))
2502     {
2503       this->addr.s.section = sectp;
2504       this->addr.size = bfd_get_section_size (sectp);
2505     }
2506   else if (section_is_p (sectp->name, &names.frame))
2507     {
2508       this->frame.s.section = sectp;
2509       this->frame.size = bfd_get_section_size (sectp);
2510     }
2511   else if (section_is_p (sectp->name, &names.eh_frame))
2512     {
2513       this->eh_frame.s.section = sectp;
2514       this->eh_frame.size = bfd_get_section_size (sectp);
2515     }
2516   else if (section_is_p (sectp->name, &names.ranges))
2517     {
2518       this->ranges.s.section = sectp;
2519       this->ranges.size = bfd_get_section_size (sectp);
2520     }
2521   else if (section_is_p (sectp->name, &names.rnglists))
2522     {
2523       this->rnglists.s.section = sectp;
2524       this->rnglists.size = bfd_get_section_size (sectp);
2525     }
2526   else if (section_is_p (sectp->name, &names.types))
2527     {
2528       struct dwarf2_section_info type_section;
2529
2530       memset (&type_section, 0, sizeof (type_section));
2531       type_section.s.section = sectp;
2532       type_section.size = bfd_get_section_size (sectp);
2533
2534       VEC_safe_push (dwarf2_section_info_def, this->types,
2535                      &type_section);
2536     }
2537   else if (section_is_p (sectp->name, &names.gdb_index))
2538     {
2539       this->gdb_index.s.section = sectp;
2540       this->gdb_index.size = bfd_get_section_size (sectp);
2541     }
2542
2543   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2544       && bfd_section_vma (abfd, sectp) == 0)
2545     this->has_section_at_zero = true;
2546 }
2547
2548 /* A helper function that decides whether a section is empty,
2549    or not present.  */
2550
2551 static int
2552 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2553 {
2554   if (section->is_virtual)
2555     return section->size == 0;
2556   return section->s.section == NULL || section->size == 0;
2557 }
2558
2559 /* Read the contents of the section INFO.
2560    OBJFILE is the main object file, but not necessarily the file where
2561    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2562    of the DWO file.
2563    If the section is compressed, uncompress it before returning.  */
2564
2565 static void
2566 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2567 {
2568   asection *sectp;
2569   bfd *abfd;
2570   gdb_byte *buf, *retbuf;
2571
2572   if (info->readin)
2573     return;
2574   info->buffer = NULL;
2575   info->readin = 1;
2576
2577   if (dwarf2_section_empty_p (info))
2578     return;
2579
2580   sectp = get_section_bfd_section (info);
2581
2582   /* If this is a virtual section we need to read in the real one first.  */
2583   if (info->is_virtual)
2584     {
2585       struct dwarf2_section_info *containing_section =
2586         get_containing_section (info);
2587
2588       gdb_assert (sectp != NULL);
2589       if ((sectp->flags & SEC_RELOC) != 0)
2590         {
2591           error (_("Dwarf Error: DWP format V2 with relocations is not"
2592                    " supported in section %s [in module %s]"),
2593                  get_section_name (info), get_section_file_name (info));
2594         }
2595       dwarf2_read_section (objfile, containing_section);
2596       /* Other code should have already caught virtual sections that don't
2597          fit.  */
2598       gdb_assert (info->virtual_offset + info->size
2599                   <= containing_section->size);
2600       /* If the real section is empty or there was a problem reading the
2601          section we shouldn't get here.  */
2602       gdb_assert (containing_section->buffer != NULL);
2603       info->buffer = containing_section->buffer + info->virtual_offset;
2604       return;
2605     }
2606
2607   /* If the section has relocations, we must read it ourselves.
2608      Otherwise we attach it to the BFD.  */
2609   if ((sectp->flags & SEC_RELOC) == 0)
2610     {
2611       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2612       return;
2613     }
2614
2615   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2616   info->buffer = buf;
2617
2618   /* When debugging .o files, we may need to apply relocations; see
2619      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2620      We never compress sections in .o files, so we only need to
2621      try this when the section is not compressed.  */
2622   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2623   if (retbuf != NULL)
2624     {
2625       info->buffer = retbuf;
2626       return;
2627     }
2628
2629   abfd = get_section_bfd_owner (info);
2630   gdb_assert (abfd != NULL);
2631
2632   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2633       || bfd_bread (buf, info->size, abfd) != info->size)
2634     {
2635       error (_("Dwarf Error: Can't read DWARF data"
2636                " in section %s [in module %s]"),
2637              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2638     }
2639 }
2640
2641 /* A helper function that returns the size of a section in a safe way.
2642    If you are positive that the section has been read before using the
2643    size, then it is safe to refer to the dwarf2_section_info object's
2644    "size" field directly.  In other cases, you must call this
2645    function, because for compressed sections the size field is not set
2646    correctly until the section has been read.  */
2647
2648 static bfd_size_type
2649 dwarf2_section_size (struct objfile *objfile,
2650                      struct dwarf2_section_info *info)
2651 {
2652   if (!info->readin)
2653     dwarf2_read_section (objfile, info);
2654   return info->size;
2655 }
2656
2657 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2658    SECTION_NAME.  */
2659
2660 void
2661 dwarf2_get_section_info (struct objfile *objfile,
2662                          enum dwarf2_section_enum sect,
2663                          asection **sectp, const gdb_byte **bufp,
2664                          bfd_size_type *sizep)
2665 {
2666   struct dwarf2_per_objfile *data
2667     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2668                                                   dwarf2_objfile_data_key);
2669   struct dwarf2_section_info *info;
2670
2671   /* We may see an objfile without any DWARF, in which case we just
2672      return nothing.  */
2673   if (data == NULL)
2674     {
2675       *sectp = NULL;
2676       *bufp = NULL;
2677       *sizep = 0;
2678       return;
2679     }
2680   switch (sect)
2681     {
2682     case DWARF2_DEBUG_FRAME:
2683       info = &data->frame;
2684       break;
2685     case DWARF2_EH_FRAME:
2686       info = &data->eh_frame;
2687       break;
2688     default:
2689       gdb_assert_not_reached ("unexpected section");
2690     }
2691
2692   dwarf2_read_section (objfile, info);
2693
2694   *sectp = get_section_bfd_section (info);
2695   *bufp = info->buffer;
2696   *sizep = info->size;
2697 }
2698
2699 /* A helper function to find the sections for a .dwz file.  */
2700
2701 static void
2702 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2703 {
2704   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2705
2706   /* Note that we only support the standard ELF names, because .dwz
2707      is ELF-only (at the time of writing).  */
2708   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2709     {
2710       dwz_file->abbrev.s.section = sectp;
2711       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2712     }
2713   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2714     {
2715       dwz_file->info.s.section = sectp;
2716       dwz_file->info.size = bfd_get_section_size (sectp);
2717     }
2718   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2719     {
2720       dwz_file->str.s.section = sectp;
2721       dwz_file->str.size = bfd_get_section_size (sectp);
2722     }
2723   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2724     {
2725       dwz_file->line.s.section = sectp;
2726       dwz_file->line.size = bfd_get_section_size (sectp);
2727     }
2728   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2729     {
2730       dwz_file->macro.s.section = sectp;
2731       dwz_file->macro.size = bfd_get_section_size (sectp);
2732     }
2733   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2734     {
2735       dwz_file->gdb_index.s.section = sectp;
2736       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2737     }
2738 }
2739
2740 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2741    there is no .gnu_debugaltlink section in the file.  Error if there
2742    is such a section but the file cannot be found.  */
2743
2744 static struct dwz_file *
2745 dwarf2_get_dwz_file (void)
2746 {
2747   const char *filename;
2748   struct dwz_file *result;
2749   bfd_size_type buildid_len_arg;
2750   size_t buildid_len;
2751   bfd_byte *buildid;
2752
2753   if (dwarf2_per_objfile->dwz_file != NULL)
2754     return dwarf2_per_objfile->dwz_file;
2755
2756   bfd_set_error (bfd_error_no_error);
2757   gdb::unique_xmalloc_ptr<char> data
2758     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2759                                   &buildid_len_arg, &buildid));
2760   if (data == NULL)
2761     {
2762       if (bfd_get_error () == bfd_error_no_error)
2763         return NULL;
2764       error (_("could not read '.gnu_debugaltlink' section: %s"),
2765              bfd_errmsg (bfd_get_error ()));
2766     }
2767
2768   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2769
2770   buildid_len = (size_t) buildid_len_arg;
2771
2772   filename = data.get ();
2773
2774   std::string abs_storage;
2775   if (!IS_ABSOLUTE_PATH (filename))
2776     {
2777       gdb::unique_xmalloc_ptr<char> abs
2778         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2779
2780       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2781       filename = abs_storage.c_str ();
2782     }
2783
2784   /* First try the file name given in the section.  If that doesn't
2785      work, try to use the build-id instead.  */
2786   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2787   if (dwz_bfd != NULL)
2788     {
2789       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2790         dwz_bfd.release ();
2791     }
2792
2793   if (dwz_bfd == NULL)
2794     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2795
2796   if (dwz_bfd == NULL)
2797     error (_("could not find '.gnu_debugaltlink' file for %s"),
2798            objfile_name (dwarf2_per_objfile->objfile));
2799
2800   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2801                            struct dwz_file);
2802   result->dwz_bfd = dwz_bfd.release ();
2803
2804   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2805
2806   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2807   dwarf2_per_objfile->dwz_file = result;
2808   return result;
2809 }
2810 \f
2811 /* DWARF quick_symbols_functions support.  */
2812
2813 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2814    unique line tables, so we maintain a separate table of all .debug_line
2815    derived entries to support the sharing.
2816    All the quick functions need is the list of file names.  We discard the
2817    line_header when we're done and don't need to record it here.  */
2818 struct quick_file_names
2819 {
2820   /* The data used to construct the hash key.  */
2821   struct stmt_list_hash hash;
2822
2823   /* The number of entries in file_names, real_names.  */
2824   unsigned int num_file_names;
2825
2826   /* The file names from the line table, after being run through
2827      file_full_name.  */
2828   const char **file_names;
2829
2830   /* The file names from the line table after being run through
2831      gdb_realpath.  These are computed lazily.  */
2832   const char **real_names;
2833 };
2834
2835 /* When using the index (and thus not using psymtabs), each CU has an
2836    object of this type.  This is used to hold information needed by
2837    the various "quick" methods.  */
2838 struct dwarf2_per_cu_quick_data
2839 {
2840   /* The file table.  This can be NULL if there was no file table
2841      or it's currently not read in.
2842      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2843   struct quick_file_names *file_names;
2844
2845   /* The corresponding symbol table.  This is NULL if symbols for this
2846      CU have not yet been read.  */
2847   struct compunit_symtab *compunit_symtab;
2848
2849   /* A temporary mark bit used when iterating over all CUs in
2850      expand_symtabs_matching.  */
2851   unsigned int mark : 1;
2852
2853   /* True if we've tried to read the file table and found there isn't one.
2854      There will be no point in trying to read it again next time.  */
2855   unsigned int no_file_data : 1;
2856 };
2857
2858 /* Utility hash function for a stmt_list_hash.  */
2859
2860 static hashval_t
2861 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2862 {
2863   hashval_t v = 0;
2864
2865   if (stmt_list_hash->dwo_unit != NULL)
2866     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2867   v += to_underlying (stmt_list_hash->line_sect_off);
2868   return v;
2869 }
2870
2871 /* Utility equality function for a stmt_list_hash.  */
2872
2873 static int
2874 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2875                     const struct stmt_list_hash *rhs)
2876 {
2877   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2878     return 0;
2879   if (lhs->dwo_unit != NULL
2880       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2881     return 0;
2882
2883   return lhs->line_sect_off == rhs->line_sect_off;
2884 }
2885
2886 /* Hash function for a quick_file_names.  */
2887
2888 static hashval_t
2889 hash_file_name_entry (const void *e)
2890 {
2891   const struct quick_file_names *file_data
2892     = (const struct quick_file_names *) e;
2893
2894   return hash_stmt_list_entry (&file_data->hash);
2895 }
2896
2897 /* Equality function for a quick_file_names.  */
2898
2899 static int
2900 eq_file_name_entry (const void *a, const void *b)
2901 {
2902   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2903   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2904
2905   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2906 }
2907
2908 /* Delete function for a quick_file_names.  */
2909
2910 static void
2911 delete_file_name_entry (void *e)
2912 {
2913   struct quick_file_names *file_data = (struct quick_file_names *) e;
2914   int i;
2915
2916   for (i = 0; i < file_data->num_file_names; ++i)
2917     {
2918       xfree ((void*) file_data->file_names[i]);
2919       if (file_data->real_names)
2920         xfree ((void*) file_data->real_names[i]);
2921     }
2922
2923   /* The space for the struct itself lives on objfile_obstack,
2924      so we don't free it here.  */
2925 }
2926
2927 /* Create a quick_file_names hash table.  */
2928
2929 static htab_t
2930 create_quick_file_names_table (unsigned int nr_initial_entries)
2931 {
2932   return htab_create_alloc (nr_initial_entries,
2933                             hash_file_name_entry, eq_file_name_entry,
2934                             delete_file_name_entry, xcalloc, xfree);
2935 }
2936
2937 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2938    have to be created afterwards.  You should call age_cached_comp_units after
2939    processing PER_CU->CU.  dw2_setup must have been already called.  */
2940
2941 static void
2942 load_cu (struct dwarf2_per_cu_data *per_cu)
2943 {
2944   if (per_cu->is_debug_types)
2945     load_full_type_unit (per_cu);
2946   else
2947     load_full_comp_unit (per_cu, language_minimal);
2948
2949   if (per_cu->cu == NULL)
2950     return;  /* Dummy CU.  */
2951
2952   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2953 }
2954
2955 /* Read in the symbols for PER_CU.  */
2956
2957 static void
2958 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2959 {
2960   struct cleanup *back_to;
2961
2962   /* Skip type_unit_groups, reading the type units they contain
2963      is handled elsewhere.  */
2964   if (IS_TYPE_UNIT_GROUP (per_cu))
2965     return;
2966
2967   back_to = make_cleanup (dwarf2_release_queue, NULL);
2968
2969   if (dwarf2_per_objfile->using_index
2970       ? per_cu->v.quick->compunit_symtab == NULL
2971       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2972     {
2973       queue_comp_unit (per_cu, language_minimal);
2974       load_cu (per_cu);
2975
2976       /* If we just loaded a CU from a DWO, and we're working with an index
2977          that may badly handle TUs, load all the TUs in that DWO as well.
2978          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2979       if (!per_cu->is_debug_types
2980           && per_cu->cu != NULL
2981           && per_cu->cu->dwo_unit != NULL
2982           && dwarf2_per_objfile->index_table != NULL
2983           && dwarf2_per_objfile->index_table->version <= 7
2984           /* DWP files aren't supported yet.  */
2985           && get_dwp_file () == NULL)
2986         queue_and_load_all_dwo_tus (per_cu);
2987     }
2988
2989   process_queue ();
2990
2991   /* Age the cache, releasing compilation units that have not
2992      been used recently.  */
2993   age_cached_comp_units ();
2994
2995   do_cleanups (back_to);
2996 }
2997
2998 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2999    the objfile from which this CU came.  Returns the resulting symbol
3000    table.  */
3001
3002 static struct compunit_symtab *
3003 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3004 {
3005   gdb_assert (dwarf2_per_objfile->using_index);
3006   if (!per_cu->v.quick->compunit_symtab)
3007     {
3008       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
3009       scoped_restore decrementer = increment_reading_symtab ();
3010       dw2_do_instantiate_symtab (per_cu);
3011       process_cu_includes ();
3012       do_cleanups (back_to);
3013     }
3014
3015   return per_cu->v.quick->compunit_symtab;
3016 }
3017
3018 /* Return the CU/TU given its index.
3019
3020    This is intended for loops like:
3021
3022    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3023                     + dwarf2_per_objfile->n_type_units); ++i)
3024      {
3025        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3026
3027        ...;
3028      }
3029 */
3030
3031 static struct dwarf2_per_cu_data *
3032 dw2_get_cutu (int index)
3033 {
3034   if (index >= dwarf2_per_objfile->n_comp_units)
3035     {
3036       index -= dwarf2_per_objfile->n_comp_units;
3037       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3038       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3039     }
3040
3041   return dwarf2_per_objfile->all_comp_units[index];
3042 }
3043
3044 /* Return the CU given its index.
3045    This differs from dw2_get_cutu in that it's for when you know INDEX
3046    refers to a CU.  */
3047
3048 static struct dwarf2_per_cu_data *
3049 dw2_get_cu (int index)
3050 {
3051   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3052
3053   return dwarf2_per_objfile->all_comp_units[index];
3054 }
3055
3056 /* A helper for create_cus_from_index that handles a given list of
3057    CUs.  */
3058
3059 static void
3060 create_cus_from_index_list (struct objfile *objfile,
3061                             const gdb_byte *cu_list, offset_type n_elements,
3062                             struct dwarf2_section_info *section,
3063                             int is_dwz,
3064                             int base_offset)
3065 {
3066   offset_type i;
3067
3068   for (i = 0; i < n_elements; i += 2)
3069     {
3070       gdb_static_assert (sizeof (ULONGEST) >= 8);
3071
3072       sect_offset sect_off
3073         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3074       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3075       cu_list += 2 * 8;
3076
3077       dwarf2_per_cu_data *the_cu
3078         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3079                           struct dwarf2_per_cu_data);
3080       the_cu->sect_off = sect_off;
3081       the_cu->length = length;
3082       the_cu->objfile = objfile;
3083       the_cu->section = section;
3084       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3085                                         struct dwarf2_per_cu_quick_data);
3086       the_cu->is_dwz = is_dwz;
3087       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3088     }
3089 }
3090
3091 /* Read the CU list from the mapped index, and use it to create all
3092    the CU objects for this objfile.  */
3093
3094 static void
3095 create_cus_from_index (struct objfile *objfile,
3096                        const gdb_byte *cu_list, offset_type cu_list_elements,
3097                        const gdb_byte *dwz_list, offset_type dwz_elements)
3098 {
3099   struct dwz_file *dwz;
3100
3101   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3102   dwarf2_per_objfile->all_comp_units =
3103     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3104                dwarf2_per_objfile->n_comp_units);
3105
3106   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3107                               &dwarf2_per_objfile->info, 0, 0);
3108
3109   if (dwz_elements == 0)
3110     return;
3111
3112   dwz = dwarf2_get_dwz_file ();
3113   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3114                               cu_list_elements / 2);
3115 }
3116
3117 /* Create the signatured type hash table from the index.  */
3118
3119 static void
3120 create_signatured_type_table_from_index (struct objfile *objfile,
3121                                          struct dwarf2_section_info *section,
3122                                          const gdb_byte *bytes,
3123                                          offset_type elements)
3124 {
3125   offset_type i;
3126   htab_t sig_types_hash;
3127
3128   dwarf2_per_objfile->n_type_units
3129     = dwarf2_per_objfile->n_allocated_type_units
3130     = elements / 3;
3131   dwarf2_per_objfile->all_type_units =
3132     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3133
3134   sig_types_hash = allocate_signatured_type_table (objfile);
3135
3136   for (i = 0; i < elements; i += 3)
3137     {
3138       struct signatured_type *sig_type;
3139       ULONGEST signature;
3140       void **slot;
3141       cu_offset type_offset_in_tu;
3142
3143       gdb_static_assert (sizeof (ULONGEST) >= 8);
3144       sect_offset sect_off
3145         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3146       type_offset_in_tu
3147         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3148                                                 BFD_ENDIAN_LITTLE);
3149       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3150       bytes += 3 * 8;
3151
3152       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3153                                  struct signatured_type);
3154       sig_type->signature = signature;
3155       sig_type->type_offset_in_tu = type_offset_in_tu;
3156       sig_type->per_cu.is_debug_types = 1;
3157       sig_type->per_cu.section = section;
3158       sig_type->per_cu.sect_off = sect_off;
3159       sig_type->per_cu.objfile = objfile;
3160       sig_type->per_cu.v.quick
3161         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3162                           struct dwarf2_per_cu_quick_data);
3163
3164       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3165       *slot = sig_type;
3166
3167       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3168     }
3169
3170   dwarf2_per_objfile->signatured_types = sig_types_hash;
3171 }
3172
3173 /* Read the address map data from the mapped index, and use it to
3174    populate the objfile's psymtabs_addrmap.  */
3175
3176 static void
3177 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3178 {
3179   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3180   const gdb_byte *iter, *end;
3181   struct addrmap *mutable_map;
3182   CORE_ADDR baseaddr;
3183
3184   auto_obstack temp_obstack;
3185
3186   mutable_map = addrmap_create_mutable (&temp_obstack);
3187
3188   iter = index->address_table;
3189   end = iter + index->address_table_size;
3190
3191   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3192
3193   while (iter < end)
3194     {
3195       ULONGEST hi, lo, cu_index;
3196       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3197       iter += 8;
3198       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3199       iter += 8;
3200       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3201       iter += 4;
3202
3203       if (lo > hi)
3204         {
3205           complaint (&symfile_complaints,
3206                      _(".gdb_index address table has invalid range (%s - %s)"),
3207                      hex_string (lo), hex_string (hi));
3208           continue;
3209         }
3210
3211       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3212         {
3213           complaint (&symfile_complaints,
3214                      _(".gdb_index address table has invalid CU number %u"),
3215                      (unsigned) cu_index);
3216           continue;
3217         }
3218
3219       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3220       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3221       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3222     }
3223
3224   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3225                                                     &objfile->objfile_obstack);
3226 }
3227
3228 /* The hash function for strings in the mapped index.  This is the same as
3229    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3230    implementation.  This is necessary because the hash function is tied to the
3231    format of the mapped index file.  The hash values do not have to match with
3232    SYMBOL_HASH_NEXT.
3233    
3234    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3235
3236 static hashval_t
3237 mapped_index_string_hash (int index_version, const void *p)
3238 {
3239   const unsigned char *str = (const unsigned char *) p;
3240   hashval_t r = 0;
3241   unsigned char c;
3242
3243   while ((c = *str++) != 0)
3244     {
3245       if (index_version >= 5)
3246         c = tolower (c);
3247       r = r * 67 + c - 113;
3248     }
3249
3250   return r;
3251 }
3252
3253 /* Find a slot in the mapped index INDEX for the object named NAME.
3254    If NAME is found, set *VEC_OUT to point to the CU vector in the
3255    constant pool and return true.  If NAME cannot be found, return
3256    false.  */
3257
3258 static bool
3259 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3260                           offset_type **vec_out)
3261 {
3262   offset_type hash;
3263   offset_type slot, step;
3264   int (*cmp) (const char *, const char *);
3265
3266   gdb::unique_xmalloc_ptr<char> without_params;
3267   if (current_language->la_language == language_cplus
3268       || current_language->la_language == language_fortran
3269       || current_language->la_language == language_d)
3270     {
3271       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3272          not contain any.  */
3273
3274       if (strchr (name, '(') != NULL)
3275         {
3276           without_params = cp_remove_params (name);
3277
3278           if (without_params != NULL)
3279             name = without_params.get ();
3280         }
3281     }
3282
3283   /* Index version 4 did not support case insensitive searches.  But the
3284      indices for case insensitive languages are built in lowercase, therefore
3285      simulate our NAME being searched is also lowercased.  */
3286   hash = mapped_index_string_hash ((index->version == 4
3287                                     && case_sensitivity == case_sensitive_off
3288                                     ? 5 : index->version),
3289                                    name);
3290
3291   slot = hash & (index->symbol_table_slots - 1);
3292   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3293   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3294
3295   for (;;)
3296     {
3297       /* Convert a slot number to an offset into the table.  */
3298       offset_type i = 2 * slot;
3299       const char *str;
3300       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3301         return false;
3302
3303       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3304       if (!cmp (name, str))
3305         {
3306           *vec_out = (offset_type *) (index->constant_pool
3307                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3308           return true;
3309         }
3310
3311       slot = (slot + step) & (index->symbol_table_slots - 1);
3312     }
3313 }
3314
3315 /* A helper function that reads the .gdb_index from SECTION and fills
3316    in MAP.  FILENAME is the name of the file containing the section;
3317    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3318    ok to use deprecated sections.
3319
3320    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3321    out parameters that are filled in with information about the CU and
3322    TU lists in the section.
3323
3324    Returns 1 if all went well, 0 otherwise.  */
3325
3326 static int
3327 read_index_from_section (struct objfile *objfile,
3328                          const char *filename,
3329                          int deprecated_ok,
3330                          struct dwarf2_section_info *section,
3331                          struct mapped_index *map,
3332                          const gdb_byte **cu_list,
3333                          offset_type *cu_list_elements,
3334                          const gdb_byte **types_list,
3335                          offset_type *types_list_elements)
3336 {
3337   const gdb_byte *addr;
3338   offset_type version;
3339   offset_type *metadata;
3340   int i;
3341
3342   if (dwarf2_section_empty_p (section))
3343     return 0;
3344
3345   /* Older elfutils strip versions could keep the section in the main
3346      executable while splitting it for the separate debug info file.  */
3347   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3348     return 0;
3349
3350   dwarf2_read_section (objfile, section);
3351
3352   addr = section->buffer;
3353   /* Version check.  */
3354   version = MAYBE_SWAP (*(offset_type *) addr);
3355   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3356      causes the index to behave very poorly for certain requests.  Version 3
3357      contained incomplete addrmap.  So, it seems better to just ignore such
3358      indices.  */
3359   if (version < 4)
3360     {
3361       static int warning_printed = 0;
3362       if (!warning_printed)
3363         {
3364           warning (_("Skipping obsolete .gdb_index section in %s."),
3365                    filename);
3366           warning_printed = 1;
3367         }
3368       return 0;
3369     }
3370   /* Index version 4 uses a different hash function than index version
3371      5 and later.
3372
3373      Versions earlier than 6 did not emit psymbols for inlined
3374      functions.  Using these files will cause GDB not to be able to
3375      set breakpoints on inlined functions by name, so we ignore these
3376      indices unless the user has done
3377      "set use-deprecated-index-sections on".  */
3378   if (version < 6 && !deprecated_ok)
3379     {
3380       static int warning_printed = 0;
3381       if (!warning_printed)
3382         {
3383           warning (_("\
3384 Skipping deprecated .gdb_index section in %s.\n\
3385 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3386 to use the section anyway."),
3387                    filename);
3388           warning_printed = 1;
3389         }
3390       return 0;
3391     }
3392   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3393      of the TU (for symbols coming from TUs),
3394      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3395      Plus gold-generated indices can have duplicate entries for global symbols,
3396      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3397      These are just performance bugs, and we can't distinguish gdb-generated
3398      indices from gold-generated ones, so issue no warning here.  */
3399
3400   /* Indexes with higher version than the one supported by GDB may be no
3401      longer backward compatible.  */
3402   if (version > 8)
3403     return 0;
3404
3405   map->version = version;
3406   map->total_size = section->size;
3407
3408   metadata = (offset_type *) (addr + sizeof (offset_type));
3409
3410   i = 0;
3411   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3412   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3413                        / 8);
3414   ++i;
3415
3416   *types_list = addr + MAYBE_SWAP (metadata[i]);
3417   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3418                            - MAYBE_SWAP (metadata[i]))
3419                           / 8);
3420   ++i;
3421
3422   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3423   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3424                              - MAYBE_SWAP (metadata[i]));
3425   ++i;
3426
3427   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3428   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3429                               - MAYBE_SWAP (metadata[i]))
3430                              / (2 * sizeof (offset_type)));
3431   ++i;
3432
3433   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3434
3435   return 1;
3436 }
3437
3438
3439 /* Read the index file.  If everything went ok, initialize the "quick"
3440    elements of all the CUs and return 1.  Otherwise, return 0.  */
3441
3442 static int
3443 dwarf2_read_index (struct objfile *objfile)
3444 {
3445   struct mapped_index local_map, *map;
3446   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3447   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3448   struct dwz_file *dwz;
3449
3450   if (!read_index_from_section (objfile, objfile_name (objfile),
3451                                 use_deprecated_index_sections,
3452                                 &dwarf2_per_objfile->gdb_index, &local_map,
3453                                 &cu_list, &cu_list_elements,
3454                                 &types_list, &types_list_elements))
3455     return 0;
3456
3457   /* Don't use the index if it's empty.  */
3458   if (local_map.symbol_table_slots == 0)
3459     return 0;
3460
3461   /* If there is a .dwz file, read it so we can get its CU list as
3462      well.  */
3463   dwz = dwarf2_get_dwz_file ();
3464   if (dwz != NULL)
3465     {
3466       struct mapped_index dwz_map;
3467       const gdb_byte *dwz_types_ignore;
3468       offset_type dwz_types_elements_ignore;
3469
3470       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3471                                     1,
3472                                     &dwz->gdb_index, &dwz_map,
3473                                     &dwz_list, &dwz_list_elements,
3474                                     &dwz_types_ignore,
3475                                     &dwz_types_elements_ignore))
3476         {
3477           warning (_("could not read '.gdb_index' section from %s; skipping"),
3478                    bfd_get_filename (dwz->dwz_bfd));
3479           return 0;
3480         }
3481     }
3482
3483   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3484                          dwz_list_elements);
3485
3486   if (types_list_elements)
3487     {
3488       struct dwarf2_section_info *section;
3489
3490       /* We can only handle a single .debug_types when we have an
3491          index.  */
3492       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3493         return 0;
3494
3495       section = VEC_index (dwarf2_section_info_def,
3496                            dwarf2_per_objfile->types, 0);
3497
3498       create_signatured_type_table_from_index (objfile, section, types_list,
3499                                                types_list_elements);
3500     }
3501
3502   create_addrmap_from_index (objfile, &local_map);
3503
3504   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3505   map = new (map) mapped_index ();
3506   *map = local_map;
3507
3508   dwarf2_per_objfile->index_table = map;
3509   dwarf2_per_objfile->using_index = 1;
3510   dwarf2_per_objfile->quick_file_names_table =
3511     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3512
3513   return 1;
3514 }
3515
3516 /* A helper for the "quick" functions which sets the global
3517    dwarf2_per_objfile according to OBJFILE.  */
3518
3519 static void
3520 dw2_setup (struct objfile *objfile)
3521 {
3522   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3523                         objfile_data (objfile, dwarf2_objfile_data_key));
3524   gdb_assert (dwarf2_per_objfile);
3525 }
3526
3527 /* die_reader_func for dw2_get_file_names.  */
3528
3529 static void
3530 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3531                            const gdb_byte *info_ptr,
3532                            struct die_info *comp_unit_die,
3533                            int has_children,
3534                            void *data)
3535 {
3536   struct dwarf2_cu *cu = reader->cu;
3537   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3538   struct objfile *objfile = dwarf2_per_objfile->objfile;
3539   struct dwarf2_per_cu_data *lh_cu;
3540   struct attribute *attr;
3541   int i;
3542   void **slot;
3543   struct quick_file_names *qfn;
3544
3545   gdb_assert (! this_cu->is_debug_types);
3546
3547   /* Our callers never want to match partial units -- instead they
3548      will match the enclosing full CU.  */
3549   if (comp_unit_die->tag == DW_TAG_partial_unit)
3550     {
3551       this_cu->v.quick->no_file_data = 1;
3552       return;
3553     }
3554
3555   lh_cu = this_cu;
3556   slot = NULL;
3557
3558   line_header_up lh;
3559   sect_offset line_offset {};
3560
3561   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3562   if (attr)
3563     {
3564       struct quick_file_names find_entry;
3565
3566       line_offset = (sect_offset) DW_UNSND (attr);
3567
3568       /* We may have already read in this line header (TU line header sharing).
3569          If we have we're done.  */
3570       find_entry.hash.dwo_unit = cu->dwo_unit;
3571       find_entry.hash.line_sect_off = line_offset;
3572       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3573                              &find_entry, INSERT);
3574       if (*slot != NULL)
3575         {
3576           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3577           return;
3578         }
3579
3580       lh = dwarf_decode_line_header (line_offset, cu);
3581     }
3582   if (lh == NULL)
3583     {
3584       lh_cu->v.quick->no_file_data = 1;
3585       return;
3586     }
3587
3588   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3589   qfn->hash.dwo_unit = cu->dwo_unit;
3590   qfn->hash.line_sect_off = line_offset;
3591   gdb_assert (slot != NULL);
3592   *slot = qfn;
3593
3594   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3595
3596   qfn->num_file_names = lh->file_names.size ();
3597   qfn->file_names =
3598     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3599   for (i = 0; i < lh->file_names.size (); ++i)
3600     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3601   qfn->real_names = NULL;
3602
3603   lh_cu->v.quick->file_names = qfn;
3604 }
3605
3606 /* A helper for the "quick" functions which attempts to read the line
3607    table for THIS_CU.  */
3608
3609 static struct quick_file_names *
3610 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3611 {
3612   /* This should never be called for TUs.  */
3613   gdb_assert (! this_cu->is_debug_types);
3614   /* Nor type unit groups.  */
3615   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3616
3617   if (this_cu->v.quick->file_names != NULL)
3618     return this_cu->v.quick->file_names;
3619   /* If we know there is no line data, no point in looking again.  */
3620   if (this_cu->v.quick->no_file_data)
3621     return NULL;
3622
3623   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3624
3625   if (this_cu->v.quick->no_file_data)
3626     return NULL;
3627   return this_cu->v.quick->file_names;
3628 }
3629
3630 /* A helper for the "quick" functions which computes and caches the
3631    real path for a given file name from the line table.  */
3632
3633 static const char *
3634 dw2_get_real_path (struct objfile *objfile,
3635                    struct quick_file_names *qfn, int index)
3636 {
3637   if (qfn->real_names == NULL)
3638     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3639                                       qfn->num_file_names, const char *);
3640
3641   if (qfn->real_names[index] == NULL)
3642     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3643
3644   return qfn->real_names[index];
3645 }
3646
3647 static struct symtab *
3648 dw2_find_last_source_symtab (struct objfile *objfile)
3649 {
3650   struct compunit_symtab *cust;
3651   int index;
3652
3653   dw2_setup (objfile);
3654   index = dwarf2_per_objfile->n_comp_units - 1;
3655   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3656   if (cust == NULL)
3657     return NULL;
3658   return compunit_primary_filetab (cust);
3659 }
3660
3661 /* Traversal function for dw2_forget_cached_source_info.  */
3662
3663 static int
3664 dw2_free_cached_file_names (void **slot, void *info)
3665 {
3666   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3667
3668   if (file_data->real_names)
3669     {
3670       int i;
3671
3672       for (i = 0; i < file_data->num_file_names; ++i)
3673         {
3674           xfree ((void*) file_data->real_names[i]);
3675           file_data->real_names[i] = NULL;
3676         }
3677     }
3678
3679   return 1;
3680 }
3681
3682 static void
3683 dw2_forget_cached_source_info (struct objfile *objfile)
3684 {
3685   dw2_setup (objfile);
3686
3687   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3688                           dw2_free_cached_file_names, NULL);
3689 }
3690
3691 /* Helper function for dw2_map_symtabs_matching_filename that expands
3692    the symtabs and calls the iterator.  */
3693
3694 static int
3695 dw2_map_expand_apply (struct objfile *objfile,
3696                       struct dwarf2_per_cu_data *per_cu,
3697                       const char *name, const char *real_path,
3698                       gdb::function_view<bool (symtab *)> callback)
3699 {
3700   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3701
3702   /* Don't visit already-expanded CUs.  */
3703   if (per_cu->v.quick->compunit_symtab)
3704     return 0;
3705
3706   /* This may expand more than one symtab, and we want to iterate over
3707      all of them.  */
3708   dw2_instantiate_symtab (per_cu);
3709
3710   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3711                                     last_made, callback);
3712 }
3713
3714 /* Implementation of the map_symtabs_matching_filename method.  */
3715
3716 static bool
3717 dw2_map_symtabs_matching_filename
3718   (struct objfile *objfile, const char *name, const char *real_path,
3719    gdb::function_view<bool (symtab *)> callback)
3720 {
3721   int i;
3722   const char *name_basename = lbasename (name);
3723
3724   dw2_setup (objfile);
3725
3726   /* The rule is CUs specify all the files, including those used by
3727      any TU, so there's no need to scan TUs here.  */
3728
3729   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3730     {
3731       int j;
3732       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3733       struct quick_file_names *file_data;
3734
3735       /* We only need to look at symtabs not already expanded.  */
3736       if (per_cu->v.quick->compunit_symtab)
3737         continue;
3738
3739       file_data = dw2_get_file_names (per_cu);
3740       if (file_data == NULL)
3741         continue;
3742
3743       for (j = 0; j < file_data->num_file_names; ++j)
3744         {
3745           const char *this_name = file_data->file_names[j];
3746           const char *this_real_name;
3747
3748           if (compare_filenames_for_search (this_name, name))
3749             {
3750               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3751                                         callback))
3752                 return true;
3753               continue;
3754             }
3755
3756           /* Before we invoke realpath, which can get expensive when many
3757              files are involved, do a quick comparison of the basenames.  */
3758           if (! basenames_may_differ
3759               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3760             continue;
3761
3762           this_real_name = dw2_get_real_path (objfile, file_data, j);
3763           if (compare_filenames_for_search (this_real_name, name))
3764             {
3765               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3766                                         callback))
3767                 return true;
3768               continue;
3769             }
3770
3771           if (real_path != NULL)
3772             {
3773               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3774               gdb_assert (IS_ABSOLUTE_PATH (name));
3775               if (this_real_name != NULL
3776                   && FILENAME_CMP (real_path, this_real_name) == 0)
3777                 {
3778                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3779                                             callback))
3780                     return true;
3781                   continue;
3782                 }
3783             }
3784         }
3785     }
3786
3787   return false;
3788 }
3789
3790 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3791
3792 struct dw2_symtab_iterator
3793 {
3794   /* The internalized form of .gdb_index.  */
3795   struct mapped_index *index;
3796   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3797   int want_specific_block;
3798   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3799      Unused if !WANT_SPECIFIC_BLOCK.  */
3800   int block_index;
3801   /* The kind of symbol we're looking for.  */
3802   domain_enum domain;
3803   /* The list of CUs from the index entry of the symbol,
3804      or NULL if not found.  */
3805   offset_type *vec;
3806   /* The next element in VEC to look at.  */
3807   int next;
3808   /* The number of elements in VEC, or zero if there is no match.  */
3809   int length;
3810   /* Have we seen a global version of the symbol?
3811      If so we can ignore all further global instances.
3812      This is to work around gold/15646, inefficient gold-generated
3813      indices.  */
3814   int global_seen;
3815 };
3816
3817 /* Initialize the index symtab iterator ITER.
3818    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3819    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3820
3821 static void
3822 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3823                       struct mapped_index *index,
3824                       int want_specific_block,
3825                       int block_index,
3826                       domain_enum domain,
3827                       const char *name)
3828 {
3829   iter->index = index;
3830   iter->want_specific_block = want_specific_block;
3831   iter->block_index = block_index;
3832   iter->domain = domain;
3833   iter->next = 0;
3834   iter->global_seen = 0;
3835
3836   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3837     iter->length = MAYBE_SWAP (*iter->vec);
3838   else
3839     {
3840       iter->vec = NULL;
3841       iter->length = 0;
3842     }
3843 }
3844
3845 /* Return the next matching CU or NULL if there are no more.  */
3846
3847 static struct dwarf2_per_cu_data *
3848 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3849 {
3850   for ( ; iter->next < iter->length; ++iter->next)
3851     {
3852       offset_type cu_index_and_attrs =
3853         MAYBE_SWAP (iter->vec[iter->next + 1]);
3854       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3855       struct dwarf2_per_cu_data *per_cu;
3856       int want_static = iter->block_index != GLOBAL_BLOCK;
3857       /* This value is only valid for index versions >= 7.  */
3858       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3859       gdb_index_symbol_kind symbol_kind =
3860         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3861       /* Only check the symbol attributes if they're present.
3862          Indices prior to version 7 don't record them,
3863          and indices >= 7 may elide them for certain symbols
3864          (gold does this).  */
3865       int attrs_valid =
3866         (iter->index->version >= 7
3867          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3868
3869       /* Don't crash on bad data.  */
3870       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3871                        + dwarf2_per_objfile->n_type_units))
3872         {
3873           complaint (&symfile_complaints,
3874                      _(".gdb_index entry has bad CU index"
3875                        " [in module %s]"),
3876                      objfile_name (dwarf2_per_objfile->objfile));
3877           continue;
3878         }
3879
3880       per_cu = dw2_get_cutu (cu_index);
3881
3882       /* Skip if already read in.  */
3883       if (per_cu->v.quick->compunit_symtab)
3884         continue;
3885
3886       /* Check static vs global.  */
3887       if (attrs_valid)
3888         {
3889           if (iter->want_specific_block
3890               && want_static != is_static)
3891             continue;
3892           /* Work around gold/15646.  */
3893           if (!is_static && iter->global_seen)
3894             continue;
3895           if (!is_static)
3896             iter->global_seen = 1;
3897         }
3898
3899       /* Only check the symbol's kind if it has one.  */
3900       if (attrs_valid)
3901         {
3902           switch (iter->domain)
3903             {
3904             case VAR_DOMAIN:
3905               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3906                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3907                   /* Some types are also in VAR_DOMAIN.  */
3908                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3909                 continue;
3910               break;
3911             case STRUCT_DOMAIN:
3912               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3913                 continue;
3914               break;
3915             case LABEL_DOMAIN:
3916               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3917                 continue;
3918               break;
3919             default:
3920               break;
3921             }
3922         }
3923
3924       ++iter->next;
3925       return per_cu;
3926     }
3927
3928   return NULL;
3929 }
3930
3931 static struct compunit_symtab *
3932 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3933                    const char *name, domain_enum domain)
3934 {
3935   struct compunit_symtab *stab_best = NULL;
3936   struct mapped_index *index;
3937
3938   dw2_setup (objfile);
3939
3940   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3941
3942   index = dwarf2_per_objfile->index_table;
3943
3944   /* index is NULL if OBJF_READNOW.  */
3945   if (index)
3946     {
3947       struct dw2_symtab_iterator iter;
3948       struct dwarf2_per_cu_data *per_cu;
3949
3950       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3951
3952       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3953         {
3954           struct symbol *sym, *with_opaque = NULL;
3955           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3956           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3957           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3958
3959           sym = block_find_symbol (block, name, domain,
3960                                    block_find_non_opaque_type_preferred,
3961                                    &with_opaque);
3962
3963           /* Some caution must be observed with overloaded functions
3964              and methods, since the index will not contain any overload
3965              information (but NAME might contain it).  */
3966
3967           if (sym != NULL
3968               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3969             return stab;
3970           if (with_opaque != NULL
3971               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3972             stab_best = stab;
3973
3974           /* Keep looking through other CUs.  */
3975         }
3976     }
3977
3978   return stab_best;
3979 }
3980
3981 static void
3982 dw2_print_stats (struct objfile *objfile)
3983 {
3984   int i, total, count;
3985
3986   dw2_setup (objfile);
3987   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3988   count = 0;
3989   for (i = 0; i < total; ++i)
3990     {
3991       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3992
3993       if (!per_cu->v.quick->compunit_symtab)
3994         ++count;
3995     }
3996   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3997   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3998 }
3999
4000 /* This dumps minimal information about the index.
4001    It is called via "mt print objfiles".
4002    One use is to verify .gdb_index has been loaded by the
4003    gdb.dwarf2/gdb-index.exp testcase.  */
4004
4005 static void
4006 dw2_dump (struct objfile *objfile)
4007 {
4008   dw2_setup (objfile);
4009   gdb_assert (dwarf2_per_objfile->using_index);
4010   printf_filtered (".gdb_index:");
4011   if (dwarf2_per_objfile->index_table != NULL)
4012     {
4013       printf_filtered (" version %d\n",
4014                        dwarf2_per_objfile->index_table->version);
4015     }
4016   else
4017     printf_filtered (" faked for \"readnow\"\n");
4018   printf_filtered ("\n");
4019 }
4020
4021 static void
4022 dw2_relocate (struct objfile *objfile,
4023               const struct section_offsets *new_offsets,
4024               const struct section_offsets *delta)
4025 {
4026   /* There's nothing to relocate here.  */
4027 }
4028
4029 static void
4030 dw2_expand_symtabs_for_function (struct objfile *objfile,
4031                                  const char *func_name)
4032 {
4033   struct mapped_index *index;
4034
4035   dw2_setup (objfile);
4036
4037   index = dwarf2_per_objfile->index_table;
4038
4039   /* index is NULL if OBJF_READNOW.  */
4040   if (index)
4041     {
4042       struct dw2_symtab_iterator iter;
4043       struct dwarf2_per_cu_data *per_cu;
4044
4045       /* Note: It doesn't matter what we pass for block_index here.  */
4046       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4047                             func_name);
4048
4049       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4050         dw2_instantiate_symtab (per_cu);
4051     }
4052 }
4053
4054 static void
4055 dw2_expand_all_symtabs (struct objfile *objfile)
4056 {
4057   int i;
4058
4059   dw2_setup (objfile);
4060
4061   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4062                    + dwarf2_per_objfile->n_type_units); ++i)
4063     {
4064       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4065
4066       dw2_instantiate_symtab (per_cu);
4067     }
4068 }
4069
4070 static void
4071 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4072                                   const char *fullname)
4073 {
4074   int i;
4075
4076   dw2_setup (objfile);
4077
4078   /* We don't need to consider type units here.
4079      This is only called for examining code, e.g. expand_line_sal.
4080      There can be an order of magnitude (or more) more type units
4081      than comp units, and we avoid them if we can.  */
4082
4083   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4084     {
4085       int j;
4086       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4087       struct quick_file_names *file_data;
4088
4089       /* We only need to look at symtabs not already expanded.  */
4090       if (per_cu->v.quick->compunit_symtab)
4091         continue;
4092
4093       file_data = dw2_get_file_names (per_cu);
4094       if (file_data == NULL)
4095         continue;
4096
4097       for (j = 0; j < file_data->num_file_names; ++j)
4098         {
4099           const char *this_fullname = file_data->file_names[j];
4100
4101           if (filename_cmp (this_fullname, fullname) == 0)
4102             {
4103               dw2_instantiate_symtab (per_cu);
4104               break;
4105             }
4106         }
4107     }
4108 }
4109
4110 static void
4111 dw2_map_matching_symbols (struct objfile *objfile,
4112                           const char * name, domain_enum domain,
4113                           int global,
4114                           int (*callback) (struct block *,
4115                                            struct symbol *, void *),
4116                           void *data, symbol_name_match_type match,
4117                           symbol_compare_ftype *ordered_compare)
4118 {
4119   /* Currently unimplemented; used for Ada.  The function can be called if the
4120      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4121      does not look for non-Ada symbols this function should just return.  */
4122 }
4123
4124 /* Symbol name matcher for .gdb_index names.
4125
4126    Symbol names in .gdb_index have a few particularities:
4127
4128    - There's no indication of which is the language of each symbol.
4129
4130      Since each language has its own symbol name matching algorithm,
4131      and we don't know which language is the right one, we must match
4132      each symbol against all languages.  This would be a potential
4133      performance problem if it were not mitigated by the
4134      mapped_index::name_components lookup table, which significantly
4135      reduces the number of times we need to call into this matcher,
4136      making it a non-issue.
4137
4138    - Symbol names in the index have no overload (parameter)
4139      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4140      appear as "foo" in the index, for example.
4141
4142      This means that the lookup names passed to the symbol name
4143      matcher functions must have no parameter information either
4144      because (e.g.) symbol search name "foo" does not match
4145      lookup-name "foo(int)" [while swapping search name for lookup
4146      name would match].
4147 */
4148 class gdb_index_symbol_name_matcher
4149 {
4150 public:
4151   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4152   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4153
4154   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4155      Returns true if any matcher matches.  */
4156   bool matches (const char *symbol_name);
4157
4158 private:
4159   /* A reference to the lookup name we're matching against.  */
4160   const lookup_name_info &m_lookup_name;
4161
4162   /* A vector holding all the different symbol name matchers, for all
4163      languages.  */
4164   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4165 };
4166
4167 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4168   (const lookup_name_info &lookup_name)
4169     : m_lookup_name (lookup_name)
4170 {
4171   /* Prepare the vector of comparison functions upfront, to avoid
4172      doing the same work for each symbol.  Care is taken to avoid
4173      matching with the same matcher more than once if/when multiple
4174      languages use the same matcher function.  */
4175   auto &matchers = m_symbol_name_matcher_funcs;
4176   matchers.reserve (nr_languages);
4177
4178   matchers.push_back (default_symbol_name_matcher);
4179
4180   for (int i = 0; i < nr_languages; i++)
4181     {
4182       const language_defn *lang = language_def ((enum language) i);
4183       if (lang->la_get_symbol_name_matcher != NULL)
4184         {
4185           symbol_name_matcher_ftype *name_matcher
4186             = lang->la_get_symbol_name_matcher (m_lookup_name);
4187
4188           /* Don't insert the same comparison routine more than once.
4189              Note that we do this linear walk instead of a cheaper
4190              sorted insert, or use a std::set or something like that,
4191              because relative order of function addresses is not
4192              stable.  This is not a problem in practice because the
4193              number of supported languages is low, and the cost here
4194              is tiny compared to the number of searches we'll do
4195              afterwards using this object.  */
4196           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4197               == matchers.end ())
4198             matchers.push_back (name_matcher);
4199         }
4200     }
4201 }
4202
4203 bool
4204 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4205 {
4206   for (auto matches_name : m_symbol_name_matcher_funcs)
4207     if (matches_name (symbol_name, m_lookup_name, NULL))
4208       return true;
4209
4210   return false;
4211 }
4212
4213 /* Starting from a search name, return the string that finds the upper
4214    bound of all strings that start with SEARCH_NAME in a sorted name
4215    list.  Returns the empty string to indicate that the upper bound is
4216    the end of the list.  */
4217
4218 static std::string
4219 make_sort_after_prefix_name (const char *search_name)
4220 {
4221   /* When looking to complete "func", we find the upper bound of all
4222      symbols that start with "func" by looking for where we'd insert
4223      the closest string that would follow "func" in lexicographical
4224      order.  Usually, that's "func"-with-last-character-incremented,
4225      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4226      will be UTF-8 multi-byte sequences, but we can't be certain.
4227      Especially mind the 0xff character, which is a valid character in
4228      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4229      rule out compilers allowing it in identifiers.  Note that
4230      conveniently, strcmp/strcasecmp are specified to compare
4231      characters interpreted as unsigned char.  So what we do is treat
4232      the whole string as a base 256 number composed of a sequence of
4233      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4234      to 0, and carries 1 to the following more-significant position.
4235      If the very first character in SEARCH_NAME ends up incremented
4236      and carries/overflows, then the upper bound is the end of the
4237      list.  The string after the empty string is also the empty
4238      string.
4239
4240      Some examples of this operation:
4241
4242        SEARCH_NAME  => "+1" RESULT
4243
4244        "abc"              => "abd"
4245        "ab\xff"           => "ac"
4246        "\xff" "a" "\xff"  => "\xff" "b"
4247        "\xff"             => ""
4248        "\xff\xff"         => ""
4249        ""                 => ""
4250
4251      Then, with these symbols for example:
4252
4253       func
4254       func1
4255       fund
4256
4257      completing "func" looks for symbols between "func" and
4258      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4259      which finds "func" and "func1", but not "fund".
4260
4261      And with:
4262
4263       funcÿ     (Latin1 'ÿ' [0xff])
4264       funcÿ1
4265       fund
4266
4267      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4268      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4269
4270      And with:
4271
4272       ÿÿ        (Latin1 'ÿ' [0xff])
4273       ÿÿ1
4274
4275      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4276      the end of the list.
4277   */
4278   std::string after = search_name;
4279   while (!after.empty () && (unsigned char) after.back () == 0xff)
4280     after.pop_back ();
4281   if (!after.empty ())
4282     after.back () = (unsigned char) after.back () + 1;
4283   return after;
4284 }
4285
4286 /* See declaration.  */
4287
4288 std::pair<std::vector<name_component>::const_iterator,
4289           std::vector<name_component>::const_iterator>
4290 mapped_index::find_name_components_bounds
4291   (const lookup_name_info &lookup_name_without_params) const
4292 {
4293   auto *name_cmp
4294     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4295
4296   const char *cplus
4297     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4298
4299   /* Comparison function object for lower_bound that matches against a
4300      given symbol name.  */
4301   auto lookup_compare_lower = [&] (const name_component &elem,
4302                                    const char *name)
4303     {
4304       const char *elem_qualified = this->symbol_name_at (elem.idx);
4305       const char *elem_name = elem_qualified + elem.name_offset;
4306       return name_cmp (elem_name, name) < 0;
4307     };
4308
4309   /* Comparison function object for upper_bound that matches against a
4310      given symbol name.  */
4311   auto lookup_compare_upper = [&] (const char *name,
4312                                    const name_component &elem)
4313     {
4314       const char *elem_qualified = this->symbol_name_at (elem.idx);
4315       const char *elem_name = elem_qualified + elem.name_offset;
4316       return name_cmp (name, elem_name) < 0;
4317     };
4318
4319   auto begin = this->name_components.begin ();
4320   auto end = this->name_components.end ();
4321
4322   /* Find the lower bound.  */
4323   auto lower = [&] ()
4324     {
4325       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4326         return begin;
4327       else
4328         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4329     } ();
4330
4331   /* Find the upper bound.  */
4332   auto upper = [&] ()
4333     {
4334       if (lookup_name_without_params.completion_mode ())
4335         {
4336           /* In completion mode, we want UPPER to point past all
4337              symbols names that have the same prefix.  I.e., with
4338              these symbols, and completing "func":
4339
4340               function        << lower bound
4341               function1
4342               other_function  << upper bound
4343
4344              We find the upper bound by looking for the insertion
4345              point of "func"-with-last-character-incremented,
4346              i.e. "fund".  */
4347           std::string after = make_sort_after_prefix_name (cplus);
4348           if (after.empty ())
4349             return end;
4350           return std::lower_bound (lower, end, after.c_str (),
4351                                    lookup_compare_lower);
4352         }
4353       else
4354         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4355     } ();
4356
4357   return {lower, upper};
4358 }
4359
4360 /* See declaration.  */
4361
4362 void
4363 mapped_index::build_name_components ()
4364 {
4365   if (!this->name_components.empty ())
4366     return;
4367
4368   this->name_components_casing = case_sensitivity;
4369   auto *name_cmp
4370     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4371
4372   /* The code below only knows how to break apart components of C++
4373      symbol names (and other languages that use '::' as
4374      namespace/module separator).  If we add support for wild matching
4375      to some language that uses some other operator (E.g., Ada, Go and
4376      D use '.'), then we'll need to try splitting the symbol name
4377      according to that language too.  Note that Ada does support wild
4378      matching, but doesn't currently support .gdb_index.  */
4379   for (size_t iter = 0; iter < this->symbol_table_slots; ++iter)
4380     {
4381       offset_type idx = 2 * iter;
4382
4383       if (this->symbol_table[idx] == 0
4384           && this->symbol_table[idx + 1] == 0)
4385         continue;
4386
4387       const char *name = this->symbol_name_at (idx);
4388
4389       /* Add each name component to the name component table.  */
4390       unsigned int previous_len = 0;
4391       for (unsigned int current_len = cp_find_first_component (name);
4392            name[current_len] != '\0';
4393            current_len += cp_find_first_component (name + current_len))
4394         {
4395           gdb_assert (name[current_len] == ':');
4396           this->name_components.push_back ({previous_len, idx});
4397           /* Skip the '::'.  */
4398           current_len += 2;
4399           previous_len = current_len;
4400         }
4401       this->name_components.push_back ({previous_len, idx});
4402     }
4403
4404   /* Sort name_components elements by name.  */
4405   auto name_comp_compare = [&] (const name_component &left,
4406                                 const name_component &right)
4407     {
4408       const char *left_qualified = this->symbol_name_at (left.idx);
4409       const char *right_qualified = this->symbol_name_at (right.idx);
4410
4411       const char *left_name = left_qualified + left.name_offset;
4412       const char *right_name = right_qualified + right.name_offset;
4413
4414       return name_cmp (left_name, right_name) < 0;
4415     };
4416
4417   std::sort (this->name_components.begin (),
4418              this->name_components.end (),
4419              name_comp_compare);
4420 }
4421
4422 /* Helper for dw2_expand_symtabs_matching that works with a
4423    mapped_index instead of the containing objfile.  This is split to a
4424    separate function in order to be able to unit test the
4425    name_components matching using a mock mapped_index.  For each
4426    symbol name that matches, calls MATCH_CALLBACK, passing it the
4427    symbol's index in the mapped_index symbol table.  */
4428
4429 static void
4430 dw2_expand_symtabs_matching_symbol
4431   (mapped_index &index,
4432    const lookup_name_info &lookup_name_in,
4433    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4434    enum search_domain kind,
4435    gdb::function_view<void (offset_type)> match_callback)
4436 {
4437   lookup_name_info lookup_name_without_params
4438     = lookup_name_in.make_ignore_params ();
4439   gdb_index_symbol_name_matcher lookup_name_matcher
4440     (lookup_name_without_params);
4441
4442   /* Build the symbol name component sorted vector, if we haven't
4443      yet.  */
4444   index.build_name_components ();
4445
4446   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4447
4448   /* Now for each symbol name in range, check to see if we have a name
4449      match, and if so, call the MATCH_CALLBACK callback.  */
4450
4451   /* The same symbol may appear more than once in the range though.
4452      E.g., if we're looking for symbols that complete "w", and we have
4453      a symbol named "w1::w2", we'll find the two name components for
4454      that same symbol in the range.  To be sure we only call the
4455      callback once per symbol, we first collect the symbol name
4456      indexes that matched in a temporary vector and ignore
4457      duplicates.  */
4458   std::vector<offset_type> matches;
4459   matches.reserve (std::distance (bounds.first, bounds.second));
4460
4461   for (; bounds.first != bounds.second; ++bounds.first)
4462     {
4463       const char *qualified = index.symbol_name_at (bounds.first->idx);
4464
4465       if (!lookup_name_matcher.matches (qualified)
4466           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4467         continue;
4468
4469       matches.push_back (bounds.first->idx);
4470     }
4471
4472   std::sort (matches.begin (), matches.end ());
4473
4474   /* Finally call the callback, once per match.  */
4475   ULONGEST prev = -1;
4476   for (offset_type idx : matches)
4477     {
4478       if (prev != idx)
4479         {
4480           match_callback (idx);
4481           prev = idx;
4482         }
4483     }
4484
4485   /* Above we use a type wider than idx's for 'prev', since 0 and
4486      (offset_type)-1 are both possible values.  */
4487   static_assert (sizeof (prev) > sizeof (offset_type), "");
4488 }
4489
4490 #if GDB_SELF_TEST
4491
4492 namespace selftests { namespace dw2_expand_symtabs_matching {
4493
4494 /* A wrapper around mapped_index that builds a mock mapped_index, from
4495    the symbol list passed as parameter to the constructor.  */
4496 class mock_mapped_index
4497 {
4498 public:
4499   template<size_t N>
4500   mock_mapped_index (const char *(&symbols)[N])
4501     : mock_mapped_index (symbols, N)
4502   {}
4503
4504   /* Access the built index.  */
4505   mapped_index &index ()
4506   { return m_index; }
4507
4508   /* Disable copy.  */
4509   mock_mapped_index(const mock_mapped_index &) = delete;
4510   void operator= (const mock_mapped_index &) = delete;
4511
4512 private:
4513   mock_mapped_index (const char **symbols, size_t symbols_size)
4514   {
4515     /* No string can live at offset zero.  Add a dummy entry.  */
4516     obstack_grow_str0 (&m_constant_pool, "");
4517
4518     for (size_t i = 0; i < symbols_size; i++)
4519       {
4520         const char *sym = symbols[i];
4521         size_t offset = obstack_object_size (&m_constant_pool);
4522         obstack_grow_str0 (&m_constant_pool, sym);
4523         m_symbol_table.push_back (offset);
4524         m_symbol_table.push_back (0);
4525       };
4526
4527     m_index.constant_pool = (const char *) obstack_base (&m_constant_pool);
4528     m_index.symbol_table = m_symbol_table.data ();
4529     m_index.symbol_table_slots = m_symbol_table.size () / 2;
4530   }
4531
4532 public:
4533   /* The built mapped_index.  */
4534   mapped_index m_index{};
4535
4536   /* The storage that the built mapped_index uses for symbol and
4537      constant pool tables.  */
4538   std::vector<offset_type> m_symbol_table;
4539   auto_obstack m_constant_pool;
4540 };
4541
4542 /* Convenience function that converts a NULL pointer to a "<null>"
4543    string, to pass to print routines.  */
4544
4545 static const char *
4546 string_or_null (const char *str)
4547 {
4548   return str != NULL ? str : "<null>";
4549 }
4550
4551 /* Check if a lookup_name_info built from
4552    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4553    index.  EXPECTED_LIST is the list of expected matches, in expected
4554    matching order.  If no match expected, then an empty list is
4555    specified.  Returns true on success.  On failure prints a warning
4556    indicating the file:line that failed, and returns false.  */
4557
4558 static bool
4559 check_match (const char *file, int line,
4560              mock_mapped_index &mock_index,
4561              const char *name, symbol_name_match_type match_type,
4562              bool completion_mode,
4563              std::initializer_list<const char *> expected_list)
4564 {
4565   lookup_name_info lookup_name (name, match_type, completion_mode);
4566
4567   bool matched = true;
4568
4569   auto mismatch = [&] (const char *expected_str,
4570                        const char *got)
4571   {
4572     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4573                "expected=\"%s\", got=\"%s\"\n"),
4574              file, line,
4575              (match_type == symbol_name_match_type::FULL
4576               ? "FULL" : "WILD"),
4577              name, string_or_null (expected_str), string_or_null (got));
4578     matched = false;
4579   };
4580
4581   auto expected_it = expected_list.begin ();
4582   auto expected_end = expected_list.end ();
4583
4584   dw2_expand_symtabs_matching_symbol (mock_index.index (), lookup_name,
4585                                       NULL, ALL_DOMAIN,
4586                                       [&] (offset_type idx)
4587   {
4588     const char *matched_name = mock_index.index ().symbol_name_at (idx);
4589     const char *expected_str
4590       = expected_it == expected_end ? NULL : *expected_it++;
4591
4592     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4593       mismatch (expected_str, matched_name);
4594   });
4595
4596   const char *expected_str
4597   = expected_it == expected_end ? NULL : *expected_it++;
4598   if (expected_str != NULL)
4599     mismatch (expected_str, NULL);
4600
4601   return matched;
4602 }
4603
4604 /* The symbols added to the mock mapped_index for testing (in
4605    canonical form).  */
4606 static const char *test_symbols[] = {
4607   "function",
4608   "std::bar",
4609   "std::zfunction",
4610   "std::zfunction2",
4611   "w1::w2",
4612   "ns::foo<char*>",
4613   "ns::foo<int>",
4614   "ns::foo<long>",
4615   "ns2::tmpl<int>::foo2",
4616   "(anonymous namespace)::A::B::C",
4617
4618   /* These are used to check that the increment-last-char in the
4619      matching algorithm for completion doesn't match "t1_fund" when
4620      completing "t1_func".  */
4621   "t1_func",
4622   "t1_func1",
4623   "t1_fund",
4624   "t1_fund1",
4625
4626   /* A UTF-8 name with multi-byte sequences to make sure that
4627      cp-name-parser understands this as a single identifier ("função"
4628      is "function" in PT).  */
4629   u8"u8função",
4630
4631   /* \377 (0xff) is Latin1 'ÿ'.  */
4632   "yfunc\377",
4633
4634   /* \377 (0xff) is Latin1 'ÿ'.  */
4635   "\377",
4636   "\377\377123",
4637
4638   /* A name with all sorts of complications.  Starts with "z" to make
4639      it easier for the completion tests below.  */
4640 #define Z_SYM_NAME \
4641   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4642     "::tuple<(anonymous namespace)::ui*, " \
4643     "std::default_delete<(anonymous namespace)::ui>, void>"
4644
4645   Z_SYM_NAME
4646 };
4647
4648 /* Returns true if the mapped_index::find_name_component_bounds method
4649    finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME, in
4650    completion mode.  */
4651
4652 static bool
4653 check_find_bounds_finds (mapped_index &index,
4654                          const char *search_name,
4655                          gdb::array_view<const char *> expected_syms)
4656 {
4657   lookup_name_info lookup_name (search_name,
4658                                 symbol_name_match_type::FULL, true);
4659
4660   auto bounds = index.find_name_components_bounds (lookup_name);
4661
4662   size_t distance = std::distance (bounds.first, bounds.second);
4663   if (distance != expected_syms.size ())
4664     return false;
4665
4666   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4667     {
4668       auto nc_elem = bounds.first + exp_elem;
4669       const char *qualified = index.symbol_name_at (nc_elem->idx);
4670       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4671         return false;
4672     }
4673
4674   return true;
4675 }
4676
4677 /* Test the lower-level mapped_index::find_name_component_bounds
4678    method.  */
4679
4680 static void
4681 test_mapped_index_find_name_component_bounds ()
4682 {
4683   mock_mapped_index mock_index (test_symbols);
4684
4685   mock_index.index ().build_name_components ();
4686
4687   /* Test the lower-level mapped_index::find_name_component_bounds
4688      method in completion mode.  */
4689   {
4690     static const char *expected_syms[] = {
4691       "t1_func",
4692       "t1_func1",
4693     };
4694
4695     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4696                                          "t1_func", expected_syms));
4697   }
4698
4699   /* Check that the increment-last-char in the name matching algorithm
4700      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4701   {
4702     static const char *expected_syms1[] = {
4703       "\377",
4704       "\377\377123",
4705     };
4706     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4707                                          "\377", expected_syms1));
4708
4709     static const char *expected_syms2[] = {
4710       "\377\377123",
4711     };
4712     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4713                                          "\377\377", expected_syms2));
4714   }
4715 }
4716
4717 /* Test dw2_expand_symtabs_matching_symbol.  */
4718
4719 static void
4720 test_dw2_expand_symtabs_matching_symbol ()
4721 {
4722   mock_mapped_index mock_index (test_symbols);
4723
4724   /* We let all tests run until the end even if some fails, for debug
4725      convenience.  */
4726   bool any_mismatch = false;
4727
4728   /* Create the expected symbols list (an initializer_list).  Needed
4729      because lists have commas, and we need to pass them to CHECK,
4730      which is a macro.  */
4731 #define EXPECT(...) { __VA_ARGS__ }
4732
4733   /* Wrapper for check_match that passes down the current
4734      __FILE__/__LINE__.  */
4735 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4736   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4737                                 mock_index,                             \
4738                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4739                                 EXPECTED_LIST)
4740
4741   /* Identity checks.  */
4742   for (const char *sym : test_symbols)
4743     {
4744       /* Should be able to match all existing symbols.  */
4745       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4746                    EXPECT (sym));
4747
4748       /* Should be able to match all existing symbols with
4749          parameters.  */
4750       std::string with_params = std::string (sym) + "(int)";
4751       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4752                    EXPECT (sym));
4753
4754       /* Should be able to match all existing symbols with
4755          parameters and qualifiers.  */
4756       with_params = std::string (sym) + " ( int ) const";
4757       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4758                    EXPECT (sym));
4759
4760       /* This should really find sym, but cp-name-parser.y doesn't
4761          know about lvalue/rvalue qualifiers yet.  */
4762       with_params = std::string (sym) + " ( int ) &&";
4763       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4764                    {});
4765     }
4766
4767   /* Check that the name matching algorithm for completion doesn't get
4768      confused with Latin1 'ÿ' / 0xff.  */
4769   {
4770     static const char str[] = "\377";
4771     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4772                  EXPECT ("\377", "\377\377123"));
4773   }
4774
4775   /* Check that the increment-last-char in the matching algorithm for
4776      completion doesn't match "t1_fund" when completing "t1_func".  */
4777   {
4778     static const char str[] = "t1_func";
4779     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4780                  EXPECT ("t1_func", "t1_func1"));
4781   }
4782
4783   /* Check that completion mode works at each prefix of the expected
4784      symbol name.  */
4785   {
4786     static const char str[] = "function(int)";
4787     size_t len = strlen (str);
4788     std::string lookup;
4789
4790     for (size_t i = 1; i < len; i++)
4791       {
4792         lookup.assign (str, i);
4793         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4794                      EXPECT ("function"));
4795       }
4796   }
4797
4798   /* While "w" is a prefix of both components, the match function
4799      should still only be called once.  */
4800   {
4801     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4802                  EXPECT ("w1::w2"));
4803     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4804                  EXPECT ("w1::w2"));
4805   }
4806
4807   /* Same, with a "complicated" symbol.  */
4808   {
4809     static const char str[] = Z_SYM_NAME;
4810     size_t len = strlen (str);
4811     std::string lookup;
4812
4813     for (size_t i = 1; i < len; i++)
4814       {
4815         lookup.assign (str, i);
4816         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4817                      EXPECT (Z_SYM_NAME));
4818       }
4819   }
4820
4821   /* In FULL mode, an incomplete symbol doesn't match.  */
4822   {
4823     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4824                  {});
4825   }
4826
4827   /* A complete symbol with parameters matches any overload, since the
4828      index has no overload info.  */
4829   {
4830     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4831                  EXPECT ("std::zfunction", "std::zfunction2"));
4832     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4833                  EXPECT ("std::zfunction", "std::zfunction2"));
4834     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4835                  EXPECT ("std::zfunction", "std::zfunction2"));
4836   }
4837
4838   /* Check that whitespace is ignored appropriately.  A symbol with a
4839      template argument list. */
4840   {
4841     static const char expected[] = "ns::foo<int>";
4842     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4843                  EXPECT (expected));
4844     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4845                  EXPECT (expected));
4846   }
4847
4848   /* Check that whitespace is ignored appropriately.  A symbol with a
4849      template argument list that includes a pointer.  */
4850   {
4851     static const char expected[] = "ns::foo<char*>";
4852     /* Try both completion and non-completion modes.  */
4853     static const bool completion_mode[2] = {false, true};
4854     for (size_t i = 0; i < 2; i++)
4855       {
4856         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4857                      completion_mode[i], EXPECT (expected));
4858         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4859                      completion_mode[i], EXPECT (expected));
4860
4861         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4862                      completion_mode[i], EXPECT (expected));
4863         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4864                      completion_mode[i], EXPECT (expected));
4865       }
4866   }
4867
4868   {
4869     /* Check method qualifiers are ignored.  */
4870     static const char expected[] = "ns::foo<char*>";
4871     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4872                  symbol_name_match_type::FULL, true, EXPECT (expected));
4873     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4874                  symbol_name_match_type::FULL, true, EXPECT (expected));
4875     CHECK_MATCH ("foo < char * >  ( int ) const",
4876                  symbol_name_match_type::WILD, true, EXPECT (expected));
4877     CHECK_MATCH ("foo < char * >  ( int ) &&",
4878                  symbol_name_match_type::WILD, true, EXPECT (expected));
4879   }
4880
4881   /* Test lookup names that don't match anything.  */
4882   {
4883     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4884                  {});
4885
4886     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4887                  {});
4888   }
4889
4890   /* Some wild matching tests, exercising "(anonymous namespace)",
4891      which should not be confused with a parameter list.  */
4892   {
4893     static const char *syms[] = {
4894       "A::B::C",
4895       "B::C",
4896       "C",
4897       "A :: B :: C ( int )",
4898       "B :: C ( int )",
4899       "C ( int )",
4900     };
4901
4902     for (const char *s : syms)
4903       {
4904         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4905                      EXPECT ("(anonymous namespace)::A::B::C"));
4906       }
4907   }
4908
4909   {
4910     static const char expected[] = "ns2::tmpl<int>::foo2";
4911     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4912                  EXPECT (expected));
4913     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4914                  EXPECT (expected));
4915   }
4916
4917   SELF_CHECK (!any_mismatch);
4918
4919 #undef EXPECT
4920 #undef CHECK_MATCH
4921 }
4922
4923 static void
4924 run_test ()
4925 {
4926   test_mapped_index_find_name_component_bounds ();
4927   test_dw2_expand_symtabs_matching_symbol ();
4928 }
4929
4930 }} // namespace selftests::dw2_expand_symtabs_matching
4931
4932 #endif /* GDB_SELF_TEST */
4933
4934 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4935    matched, to expand corresponding CUs that were marked.  IDX is the
4936    index of the symbol name that matched.  */
4937
4938 static void
4939 dw2_expand_marked_cus
4940   (mapped_index &index, offset_type idx,
4941    struct objfile *objfile,
4942    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4943    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4944    search_domain kind)
4945 {
4946   offset_type *vec, vec_len, vec_idx;
4947   bool global_seen = false;
4948
4949   vec = (offset_type *) (index.constant_pool
4950                          + MAYBE_SWAP (index.symbol_table[idx + 1]));
4951   vec_len = MAYBE_SWAP (vec[0]);
4952   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4953     {
4954       struct dwarf2_per_cu_data *per_cu;
4955       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4956       /* This value is only valid for index versions >= 7.  */
4957       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4958       gdb_index_symbol_kind symbol_kind =
4959         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4960       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4961       /* Only check the symbol attributes if they're present.
4962          Indices prior to version 7 don't record them,
4963          and indices >= 7 may elide them for certain symbols
4964          (gold does this).  */
4965       int attrs_valid =
4966         (index.version >= 7
4967          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4968
4969       /* Work around gold/15646.  */
4970       if (attrs_valid)
4971         {
4972           if (!is_static && global_seen)
4973             continue;
4974           if (!is_static)
4975             global_seen = true;
4976         }
4977
4978       /* Only check the symbol's kind if it has one.  */
4979       if (attrs_valid)
4980         {
4981           switch (kind)
4982             {
4983             case VARIABLES_DOMAIN:
4984               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4985                 continue;
4986               break;
4987             case FUNCTIONS_DOMAIN:
4988               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4989                 continue;
4990               break;
4991             case TYPES_DOMAIN:
4992               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4993                 continue;
4994               break;
4995             default:
4996               break;
4997             }
4998         }
4999
5000       /* Don't crash on bad data.  */
5001       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5002                        + dwarf2_per_objfile->n_type_units))
5003         {
5004           complaint (&symfile_complaints,
5005                      _(".gdb_index entry has bad CU index"
5006                        " [in module %s]"), objfile_name (objfile));
5007           continue;
5008         }
5009
5010       per_cu = dw2_get_cutu (cu_index);
5011       if (file_matcher == NULL || per_cu->v.quick->mark)
5012         {
5013           int symtab_was_null =
5014             (per_cu->v.quick->compunit_symtab == NULL);
5015
5016           dw2_instantiate_symtab (per_cu);
5017
5018           if (expansion_notify != NULL
5019               && symtab_was_null
5020               && per_cu->v.quick->compunit_symtab != NULL)
5021             expansion_notify (per_cu->v.quick->compunit_symtab);
5022         }
5023     }
5024 }
5025
5026 static void
5027 dw2_expand_symtabs_matching
5028   (struct objfile *objfile,
5029    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5030    const lookup_name_info &lookup_name,
5031    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5032    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5033    enum search_domain kind)
5034 {
5035   int i;
5036
5037   dw2_setup (objfile);
5038
5039   /* index_table is NULL if OBJF_READNOW.  */
5040   if (!dwarf2_per_objfile->index_table)
5041     return;
5042
5043   if (file_matcher != NULL)
5044     {
5045       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5046                                                 htab_eq_pointer,
5047                                                 NULL, xcalloc, xfree));
5048       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5049                                                     htab_eq_pointer,
5050                                                     NULL, xcalloc, xfree));
5051
5052       /* The rule is CUs specify all the files, including those used by
5053          any TU, so there's no need to scan TUs here.  */
5054
5055       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5056         {
5057           int j;
5058           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5059           struct quick_file_names *file_data;
5060           void **slot;
5061
5062           QUIT;
5063
5064           per_cu->v.quick->mark = 0;
5065
5066           /* We only need to look at symtabs not already expanded.  */
5067           if (per_cu->v.quick->compunit_symtab)
5068             continue;
5069
5070           file_data = dw2_get_file_names (per_cu);
5071           if (file_data == NULL)
5072             continue;
5073
5074           if (htab_find (visited_not_found.get (), file_data) != NULL)
5075             continue;
5076           else if (htab_find (visited_found.get (), file_data) != NULL)
5077             {
5078               per_cu->v.quick->mark = 1;
5079               continue;
5080             }
5081
5082           for (j = 0; j < file_data->num_file_names; ++j)
5083             {
5084               const char *this_real_name;
5085
5086               if (file_matcher (file_data->file_names[j], false))
5087                 {
5088                   per_cu->v.quick->mark = 1;
5089                   break;
5090                 }
5091
5092               /* Before we invoke realpath, which can get expensive when many
5093                  files are involved, do a quick comparison of the basenames.  */
5094               if (!basenames_may_differ
5095                   && !file_matcher (lbasename (file_data->file_names[j]),
5096                                     true))
5097                 continue;
5098
5099               this_real_name = dw2_get_real_path (objfile, file_data, j);
5100               if (file_matcher (this_real_name, false))
5101                 {
5102                   per_cu->v.quick->mark = 1;
5103                   break;
5104                 }
5105             }
5106
5107           slot = htab_find_slot (per_cu->v.quick->mark
5108                                  ? visited_found.get ()
5109                                  : visited_not_found.get (),
5110                                  file_data, INSERT);
5111           *slot = file_data;
5112         }
5113     }
5114
5115   mapped_index &index = *dwarf2_per_objfile->index_table;
5116
5117   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5118                                       symbol_matcher,
5119                                       kind, [&] (offset_type idx)
5120     {
5121       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
5122                              expansion_notify, kind);
5123     });
5124 }
5125
5126 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5127    symtab.  */
5128
5129 static struct compunit_symtab *
5130 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5131                                           CORE_ADDR pc)
5132 {
5133   int i;
5134
5135   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5136       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5137     return cust;
5138
5139   if (cust->includes == NULL)
5140     return NULL;
5141
5142   for (i = 0; cust->includes[i]; ++i)
5143     {
5144       struct compunit_symtab *s = cust->includes[i];
5145
5146       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5147       if (s != NULL)
5148         return s;
5149     }
5150
5151   return NULL;
5152 }
5153
5154 static struct compunit_symtab *
5155 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5156                                   struct bound_minimal_symbol msymbol,
5157                                   CORE_ADDR pc,
5158                                   struct obj_section *section,
5159                                   int warn_if_readin)
5160 {
5161   struct dwarf2_per_cu_data *data;
5162   struct compunit_symtab *result;
5163
5164   dw2_setup (objfile);
5165
5166   if (!objfile->psymtabs_addrmap)
5167     return NULL;
5168
5169   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5170                                                      pc);
5171   if (!data)
5172     return NULL;
5173
5174   if (warn_if_readin && data->v.quick->compunit_symtab)
5175     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5176              paddress (get_objfile_arch (objfile), pc));
5177
5178   result
5179     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5180                                                 pc);
5181   gdb_assert (result != NULL);
5182   return result;
5183 }
5184
5185 static void
5186 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5187                           void *data, int need_fullname)
5188 {
5189   dw2_setup (objfile);
5190
5191   if (!dwarf2_per_objfile->filenames_cache)
5192     {
5193       dwarf2_per_objfile->filenames_cache.emplace ();
5194
5195       htab_up visited (htab_create_alloc (10,
5196                                           htab_hash_pointer, htab_eq_pointer,
5197                                           NULL, xcalloc, xfree));
5198
5199       /* The rule is CUs specify all the files, including those used
5200          by any TU, so there's no need to scan TUs here.  We can
5201          ignore file names coming from already-expanded CUs.  */
5202
5203       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5204         {
5205           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5206
5207           if (per_cu->v.quick->compunit_symtab)
5208             {
5209               void **slot = htab_find_slot (visited.get (),
5210                                             per_cu->v.quick->file_names,
5211                                             INSERT);
5212
5213               *slot = per_cu->v.quick->file_names;
5214             }
5215         }
5216
5217       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5218         {
5219           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5220           struct quick_file_names *file_data;
5221           void **slot;
5222
5223           /* We only need to look at symtabs not already expanded.  */
5224           if (per_cu->v.quick->compunit_symtab)
5225             continue;
5226
5227           file_data = dw2_get_file_names (per_cu);
5228           if (file_data == NULL)
5229             continue;
5230
5231           slot = htab_find_slot (visited.get (), file_data, INSERT);
5232           if (*slot)
5233             {
5234               /* Already visited.  */
5235               continue;
5236             }
5237           *slot = file_data;
5238
5239           for (int j = 0; j < file_data->num_file_names; ++j)
5240             {
5241               const char *filename = file_data->file_names[j];
5242               dwarf2_per_objfile->filenames_cache->seen (filename);
5243             }
5244         }
5245     }
5246
5247   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5248     {
5249       gdb::unique_xmalloc_ptr<char> this_real_name;
5250
5251       if (need_fullname)
5252         this_real_name = gdb_realpath (filename);
5253       (*fun) (filename, this_real_name.get (), data);
5254     });
5255 }
5256
5257 static int
5258 dw2_has_symbols (struct objfile *objfile)
5259 {
5260   return 1;
5261 }
5262
5263 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5264 {
5265   dw2_has_symbols,
5266   dw2_find_last_source_symtab,
5267   dw2_forget_cached_source_info,
5268   dw2_map_symtabs_matching_filename,
5269   dw2_lookup_symbol,
5270   dw2_print_stats,
5271   dw2_dump,
5272   dw2_relocate,
5273   dw2_expand_symtabs_for_function,
5274   dw2_expand_all_symtabs,
5275   dw2_expand_symtabs_with_fullname,
5276   dw2_map_matching_symbols,
5277   dw2_expand_symtabs_matching,
5278   dw2_find_pc_sect_compunit_symtab,
5279   NULL,
5280   dw2_map_symbol_filenames
5281 };
5282
5283 /* Initialize for reading DWARF for this objfile.  Return 0 if this
5284    file will use psymtabs, or 1 if using the GNU index.  */
5285
5286 int
5287 dwarf2_initialize_objfile (struct objfile *objfile)
5288 {
5289   /* If we're about to read full symbols, don't bother with the
5290      indices.  In this case we also don't care if some other debug
5291      format is making psymtabs, because they are all about to be
5292      expanded anyway.  */
5293   if ((objfile->flags & OBJF_READNOW))
5294     {
5295       int i;
5296
5297       dwarf2_per_objfile->using_index = 1;
5298       create_all_comp_units (objfile);
5299       create_all_type_units (objfile);
5300       dwarf2_per_objfile->quick_file_names_table =
5301         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5302
5303       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
5304                        + dwarf2_per_objfile->n_type_units); ++i)
5305         {
5306           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5307
5308           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5309                                             struct dwarf2_per_cu_quick_data);
5310         }
5311
5312       /* Return 1 so that gdb sees the "quick" functions.  However,
5313          these functions will be no-ops because we will have expanded
5314          all symtabs.  */
5315       return 1;
5316     }
5317
5318   if (dwarf2_read_index (objfile))
5319     return 1;
5320
5321   return 0;
5322 }
5323
5324 \f
5325
5326 /* Build a partial symbol table.  */
5327
5328 void
5329 dwarf2_build_psymtabs (struct objfile *objfile)
5330 {
5331
5332   if (objfile->global_psymbols.capacity () == 0
5333       && objfile->static_psymbols.capacity () == 0)
5334     init_psymbol_list (objfile, 1024);
5335
5336   TRY
5337     {
5338       /* This isn't really ideal: all the data we allocate on the
5339          objfile's obstack is still uselessly kept around.  However,
5340          freeing it seems unsafe.  */
5341       psymtab_discarder psymtabs (objfile);
5342       dwarf2_build_psymtabs_hard (objfile);
5343       psymtabs.keep ();
5344     }
5345   CATCH (except, RETURN_MASK_ERROR)
5346     {
5347       exception_print (gdb_stderr, except);
5348     }
5349   END_CATCH
5350 }
5351
5352 /* Return the total length of the CU described by HEADER.  */
5353
5354 static unsigned int
5355 get_cu_length (const struct comp_unit_head *header)
5356 {
5357   return header->initial_length_size + header->length;
5358 }
5359
5360 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
5361
5362 static inline bool
5363 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
5364 {
5365   sect_offset bottom = cu_header->sect_off;
5366   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
5367
5368   return sect_off >= bottom && sect_off < top;
5369 }
5370
5371 /* Find the base address of the compilation unit for range lists and
5372    location lists.  It will normally be specified by DW_AT_low_pc.
5373    In DWARF-3 draft 4, the base address could be overridden by
5374    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
5375    compilation units with discontinuous ranges.  */
5376
5377 static void
5378 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
5379 {
5380   struct attribute *attr;
5381
5382   cu->base_known = 0;
5383   cu->base_address = 0;
5384
5385   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
5386   if (attr)
5387     {
5388       cu->base_address = attr_value_as_address (attr);
5389       cu->base_known = 1;
5390     }
5391   else
5392     {
5393       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
5394       if (attr)
5395         {
5396           cu->base_address = attr_value_as_address (attr);
5397           cu->base_known = 1;
5398         }
5399     }
5400 }
5401
5402 /* Read in the comp unit header information from the debug_info at info_ptr.
5403    Use rcuh_kind::COMPILE as the default type if not known by the caller.
5404    NOTE: This leaves members offset, first_die_offset to be filled in
5405    by the caller.  */
5406
5407 static const gdb_byte *
5408 read_comp_unit_head (struct comp_unit_head *cu_header,
5409                      const gdb_byte *info_ptr,
5410                      struct dwarf2_section_info *section,
5411                      rcuh_kind section_kind)
5412 {
5413   int signed_addr;
5414   unsigned int bytes_read;
5415   const char *filename = get_section_file_name (section);
5416   bfd *abfd = get_section_bfd_owner (section);
5417
5418   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
5419   cu_header->initial_length_size = bytes_read;
5420   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
5421   info_ptr += bytes_read;
5422   cu_header->version = read_2_bytes (abfd, info_ptr);
5423   info_ptr += 2;
5424   if (cu_header->version < 5)
5425     switch (section_kind)
5426       {
5427       case rcuh_kind::COMPILE:
5428         cu_header->unit_type = DW_UT_compile;
5429         break;
5430       case rcuh_kind::TYPE:
5431         cu_header->unit_type = DW_UT_type;
5432         break;
5433       default:
5434         internal_error (__FILE__, __LINE__,
5435                         _("read_comp_unit_head: invalid section_kind"));
5436       }
5437   else
5438     {
5439       cu_header->unit_type = static_cast<enum dwarf_unit_type>
5440                                                  (read_1_byte (abfd, info_ptr));
5441       info_ptr += 1;
5442       switch (cu_header->unit_type)
5443         {
5444         case DW_UT_compile:
5445           if (section_kind != rcuh_kind::COMPILE)
5446             error (_("Dwarf Error: wrong unit_type in compilation unit header "
5447                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
5448                    filename);
5449           break;
5450         case DW_UT_type:
5451           section_kind = rcuh_kind::TYPE;
5452           break;
5453         default:
5454           error (_("Dwarf Error: wrong unit_type in compilation unit header "
5455                  "(is %d, should be %d or %d) [in module %s]"),
5456                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
5457         }
5458
5459       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5460       info_ptr += 1;
5461     }
5462   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
5463                                                           cu_header,
5464                                                           &bytes_read);
5465   info_ptr += bytes_read;
5466   if (cu_header->version < 5)
5467     {
5468       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5469       info_ptr += 1;
5470     }
5471   signed_addr = bfd_get_sign_extend_vma (abfd);
5472   if (signed_addr < 0)
5473     internal_error (__FILE__, __LINE__,
5474                     _("read_comp_unit_head: dwarf from non elf file"));
5475   cu_header->signed_addr_p = signed_addr;
5476
5477   if (section_kind == rcuh_kind::TYPE)
5478     {
5479       LONGEST type_offset;
5480
5481       cu_header->signature = read_8_bytes (abfd, info_ptr);
5482       info_ptr += 8;
5483
5484       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
5485       info_ptr += bytes_read;
5486       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
5487       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
5488         error (_("Dwarf Error: Too big type_offset in compilation unit "
5489                "header (is %s) [in module %s]"), plongest (type_offset),
5490                filename);
5491     }
5492
5493   return info_ptr;
5494 }
5495
5496 /* Helper function that returns the proper abbrev section for
5497    THIS_CU.  */
5498
5499 static struct dwarf2_section_info *
5500 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
5501 {
5502   struct dwarf2_section_info *abbrev;
5503
5504   if (this_cu->is_dwz)
5505     abbrev = &dwarf2_get_dwz_file ()->abbrev;
5506   else
5507     abbrev = &dwarf2_per_objfile->abbrev;
5508
5509   return abbrev;
5510 }
5511
5512 /* Subroutine of read_and_check_comp_unit_head and
5513    read_and_check_type_unit_head to simplify them.
5514    Perform various error checking on the header.  */
5515
5516 static void
5517 error_check_comp_unit_head (struct comp_unit_head *header,
5518                             struct dwarf2_section_info *section,
5519                             struct dwarf2_section_info *abbrev_section)
5520 {
5521   const char *filename = get_section_file_name (section);
5522
5523   if (header->version < 2 || header->version > 5)
5524     error (_("Dwarf Error: wrong version in compilation unit header "
5525            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
5526            filename);
5527
5528   if (to_underlying (header->abbrev_sect_off)
5529       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
5530     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
5531            "(offset 0x%x + 6) [in module %s]"),
5532            to_underlying (header->abbrev_sect_off),
5533            to_underlying (header->sect_off),
5534            filename);
5535
5536   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
5537      avoid potential 32-bit overflow.  */
5538   if (((ULONGEST) header->sect_off + get_cu_length (header))
5539       > section->size)
5540     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
5541            "(offset 0x%x + 0) [in module %s]"),
5542            header->length, to_underlying (header->sect_off),
5543            filename);
5544 }
5545
5546 /* Read in a CU/TU header and perform some basic error checking.
5547    The contents of the header are stored in HEADER.
5548    The result is a pointer to the start of the first DIE.  */
5549
5550 static const gdb_byte *
5551 read_and_check_comp_unit_head (struct comp_unit_head *header,
5552                                struct dwarf2_section_info *section,
5553                                struct dwarf2_section_info *abbrev_section,
5554                                const gdb_byte *info_ptr,
5555                                rcuh_kind section_kind)
5556 {
5557   const gdb_byte *beg_of_comp_unit = info_ptr;
5558
5559   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
5560
5561   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
5562
5563   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
5564
5565   error_check_comp_unit_head (header, section, abbrev_section);
5566
5567   return info_ptr;
5568 }
5569
5570 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5571
5572 static sect_offset
5573 read_abbrev_offset (struct dwarf2_section_info *section,
5574                     sect_offset sect_off)
5575 {
5576   bfd *abfd = get_section_bfd_owner (section);
5577   const gdb_byte *info_ptr;
5578   unsigned int initial_length_size, offset_size;
5579   uint16_t version;
5580
5581   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
5582   info_ptr = section->buffer + to_underlying (sect_off);
5583   read_initial_length (abfd, info_ptr, &initial_length_size);
5584   offset_size = initial_length_size == 4 ? 4 : 8;
5585   info_ptr += initial_length_size;
5586
5587   version = read_2_bytes (abfd, info_ptr);
5588   info_ptr += 2;
5589   if (version >= 5)
5590     {
5591       /* Skip unit type and address size.  */
5592       info_ptr += 2;
5593     }
5594
5595   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
5596 }
5597
5598 /* Allocate a new partial symtab for file named NAME and mark this new
5599    partial symtab as being an include of PST.  */
5600
5601 static void
5602 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
5603                                struct objfile *objfile)
5604 {
5605   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
5606
5607   if (!IS_ABSOLUTE_PATH (subpst->filename))
5608     {
5609       /* It shares objfile->objfile_obstack.  */
5610       subpst->dirname = pst->dirname;
5611     }
5612
5613   subpst->textlow = 0;
5614   subpst->texthigh = 0;
5615
5616   subpst->dependencies
5617     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
5618   subpst->dependencies[0] = pst;
5619   subpst->number_of_dependencies = 1;
5620
5621   subpst->globals_offset = 0;
5622   subpst->n_global_syms = 0;
5623   subpst->statics_offset = 0;
5624   subpst->n_static_syms = 0;
5625   subpst->compunit_symtab = NULL;
5626   subpst->read_symtab = pst->read_symtab;
5627   subpst->readin = 0;
5628
5629   /* No private part is necessary for include psymtabs.  This property
5630      can be used to differentiate between such include psymtabs and
5631      the regular ones.  */
5632   subpst->read_symtab_private = NULL;
5633 }
5634
5635 /* Read the Line Number Program data and extract the list of files
5636    included by the source file represented by PST.  Build an include
5637    partial symtab for each of these included files.  */
5638
5639 static void
5640 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5641                                struct die_info *die,
5642                                struct partial_symtab *pst)
5643 {
5644   line_header_up lh;
5645   struct attribute *attr;
5646
5647   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5648   if (attr)
5649     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
5650   if (lh == NULL)
5651     return;  /* No linetable, so no includes.  */
5652
5653   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
5654   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
5655 }
5656
5657 static hashval_t
5658 hash_signatured_type (const void *item)
5659 {
5660   const struct signatured_type *sig_type
5661     = (const struct signatured_type *) item;
5662
5663   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5664   return sig_type->signature;
5665 }
5666
5667 static int
5668 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5669 {
5670   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5671   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5672
5673   return lhs->signature == rhs->signature;
5674 }
5675
5676 /* Allocate a hash table for signatured types.  */
5677
5678 static htab_t
5679 allocate_signatured_type_table (struct objfile *objfile)
5680 {
5681   return htab_create_alloc_ex (41,
5682                                hash_signatured_type,
5683                                eq_signatured_type,
5684                                NULL,
5685                                &objfile->objfile_obstack,
5686                                hashtab_obstack_allocate,
5687                                dummy_obstack_deallocate);
5688 }
5689
5690 /* A helper function to add a signatured type CU to a table.  */
5691
5692 static int
5693 add_signatured_type_cu_to_table (void **slot, void *datum)
5694 {
5695   struct signatured_type *sigt = (struct signatured_type *) *slot;
5696   struct signatured_type ***datap = (struct signatured_type ***) datum;
5697
5698   **datap = sigt;
5699   ++*datap;
5700
5701   return 1;
5702 }
5703
5704 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5705    and fill them into TYPES_HTAB.  It will process only type units,
5706    therefore DW_UT_type.  */
5707
5708 static void
5709 create_debug_type_hash_table (struct dwo_file *dwo_file,
5710                               dwarf2_section_info *section, htab_t &types_htab,
5711                               rcuh_kind section_kind)
5712 {
5713   struct objfile *objfile = dwarf2_per_objfile->objfile;
5714   struct dwarf2_section_info *abbrev_section;
5715   bfd *abfd;
5716   const gdb_byte *info_ptr, *end_ptr;
5717
5718   abbrev_section = (dwo_file != NULL
5719                     ? &dwo_file->sections.abbrev
5720                     : &dwarf2_per_objfile->abbrev);
5721
5722   if (dwarf_read_debug)
5723     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
5724                         get_section_name (section),
5725                         get_section_file_name (abbrev_section));
5726
5727   dwarf2_read_section (objfile, section);
5728   info_ptr = section->buffer;
5729
5730   if (info_ptr == NULL)
5731     return;
5732
5733   /* We can't set abfd until now because the section may be empty or
5734      not present, in which case the bfd is unknown.  */
5735   abfd = get_section_bfd_owner (section);
5736
5737   /* We don't use init_cutu_and_read_dies_simple, or some such, here
5738      because we don't need to read any dies: the signature is in the
5739      header.  */
5740
5741   end_ptr = info_ptr + section->size;
5742   while (info_ptr < end_ptr)
5743     {
5744       struct signatured_type *sig_type;
5745       struct dwo_unit *dwo_tu;
5746       void **slot;
5747       const gdb_byte *ptr = info_ptr;
5748       struct comp_unit_head header;
5749       unsigned int length;
5750
5751       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5752
5753       /* Initialize it due to a false compiler warning.  */
5754       header.signature = -1;
5755       header.type_cu_offset_in_tu = (cu_offset) -1;
5756
5757       /* We need to read the type's signature in order to build the hash
5758          table, but we don't need anything else just yet.  */
5759
5760       ptr = read_and_check_comp_unit_head (&header, section,
5761                                            abbrev_section, ptr, section_kind);
5762
5763       length = get_cu_length (&header);
5764
5765       /* Skip dummy type units.  */
5766       if (ptr >= info_ptr + length
5767           || peek_abbrev_code (abfd, ptr) == 0
5768           || header.unit_type != DW_UT_type)
5769         {
5770           info_ptr += length;
5771           continue;
5772         }
5773
5774       if (types_htab == NULL)
5775         {
5776           if (dwo_file)
5777             types_htab = allocate_dwo_unit_table (objfile);
5778           else
5779             types_htab = allocate_signatured_type_table (objfile);
5780         }
5781
5782       if (dwo_file)
5783         {
5784           sig_type = NULL;
5785           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5786                                    struct dwo_unit);
5787           dwo_tu->dwo_file = dwo_file;
5788           dwo_tu->signature = header.signature;
5789           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5790           dwo_tu->section = section;
5791           dwo_tu->sect_off = sect_off;
5792           dwo_tu->length = length;
5793         }
5794       else
5795         {
5796           /* N.B.: type_offset is not usable if this type uses a DWO file.
5797              The real type_offset is in the DWO file.  */
5798           dwo_tu = NULL;
5799           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5800                                      struct signatured_type);
5801           sig_type->signature = header.signature;
5802           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
5803           sig_type->per_cu.objfile = objfile;
5804           sig_type->per_cu.is_debug_types = 1;
5805           sig_type->per_cu.section = section;
5806           sig_type->per_cu.sect_off = sect_off;
5807           sig_type->per_cu.length = length;
5808         }
5809
5810       slot = htab_find_slot (types_htab,
5811                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
5812                              INSERT);
5813       gdb_assert (slot != NULL);
5814       if (*slot != NULL)
5815         {
5816           sect_offset dup_sect_off;
5817
5818           if (dwo_file)
5819             {
5820               const struct dwo_unit *dup_tu
5821                 = (const struct dwo_unit *) *slot;
5822
5823               dup_sect_off = dup_tu->sect_off;
5824             }
5825           else
5826             {
5827               const struct signatured_type *dup_tu
5828                 = (const struct signatured_type *) *slot;
5829
5830               dup_sect_off = dup_tu->per_cu.sect_off;
5831             }
5832
5833           complaint (&symfile_complaints,
5834                      _("debug type entry at offset 0x%x is duplicate to"
5835                        " the entry at offset 0x%x, signature %s"),
5836                      to_underlying (sect_off), to_underlying (dup_sect_off),
5837                      hex_string (header.signature));
5838         }
5839       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
5840
5841       if (dwarf_read_debug > 1)
5842         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
5843                             to_underlying (sect_off),
5844                             hex_string (header.signature));
5845
5846       info_ptr += length;
5847     }
5848 }
5849
5850 /* Create the hash table of all entries in the .debug_types
5851    (or .debug_types.dwo) section(s).
5852    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
5853    otherwise it is NULL.
5854
5855    The result is a pointer to the hash table or NULL if there are no types.
5856
5857    Note: This function processes DWO files only, not DWP files.  */
5858
5859 static void
5860 create_debug_types_hash_table (struct dwo_file *dwo_file,
5861                                VEC (dwarf2_section_info_def) *types,
5862                                htab_t &types_htab)
5863 {
5864   int ix;
5865   struct dwarf2_section_info *section;
5866
5867   if (VEC_empty (dwarf2_section_info_def, types))
5868     return;
5869
5870   for (ix = 0;
5871        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5872        ++ix)
5873     create_debug_type_hash_table (dwo_file, section, types_htab,
5874                                   rcuh_kind::TYPE);
5875 }
5876
5877 /* Create the hash table of all entries in the .debug_types section,
5878    and initialize all_type_units.
5879    The result is zero if there is an error (e.g. missing .debug_types section),
5880    otherwise non-zero.  */
5881
5882 static int
5883 create_all_type_units (struct objfile *objfile)
5884 {
5885   htab_t types_htab = NULL;
5886   struct signatured_type **iter;
5887
5888   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5889                                 rcuh_kind::COMPILE);
5890   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5891   if (types_htab == NULL)
5892     {
5893       dwarf2_per_objfile->signatured_types = NULL;
5894       return 0;
5895     }
5896
5897   dwarf2_per_objfile->signatured_types = types_htab;
5898
5899   dwarf2_per_objfile->n_type_units
5900     = dwarf2_per_objfile->n_allocated_type_units
5901     = htab_elements (types_htab);
5902   dwarf2_per_objfile->all_type_units =
5903     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5904   iter = &dwarf2_per_objfile->all_type_units[0];
5905   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5906   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5907               == dwarf2_per_objfile->n_type_units);
5908
5909   return 1;
5910 }
5911
5912 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5913    If SLOT is non-NULL, it is the entry to use in the hash table.
5914    Otherwise we find one.  */
5915
5916 static struct signatured_type *
5917 add_type_unit (ULONGEST sig, void **slot)
5918 {
5919   struct objfile *objfile = dwarf2_per_objfile->objfile;
5920   int n_type_units = dwarf2_per_objfile->n_type_units;
5921   struct signatured_type *sig_type;
5922
5923   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5924   ++n_type_units;
5925   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5926     {
5927       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5928         dwarf2_per_objfile->n_allocated_type_units = 1;
5929       dwarf2_per_objfile->n_allocated_type_units *= 2;
5930       dwarf2_per_objfile->all_type_units
5931         = XRESIZEVEC (struct signatured_type *,
5932                       dwarf2_per_objfile->all_type_units,
5933                       dwarf2_per_objfile->n_allocated_type_units);
5934       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5935     }
5936   dwarf2_per_objfile->n_type_units = n_type_units;
5937
5938   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5939                              struct signatured_type);
5940   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5941   sig_type->signature = sig;
5942   sig_type->per_cu.is_debug_types = 1;
5943   if (dwarf2_per_objfile->using_index)
5944     {
5945       sig_type->per_cu.v.quick =
5946         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5947                         struct dwarf2_per_cu_quick_data);
5948     }
5949
5950   if (slot == NULL)
5951     {
5952       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5953                              sig_type, INSERT);
5954     }
5955   gdb_assert (*slot == NULL);
5956   *slot = sig_type;
5957   /* The rest of sig_type must be filled in by the caller.  */
5958   return sig_type;
5959 }
5960
5961 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5962    Fill in SIG_ENTRY with DWO_ENTRY.  */
5963
5964 static void
5965 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5966                                   struct signatured_type *sig_entry,
5967                                   struct dwo_unit *dwo_entry)
5968 {
5969   /* Make sure we're not clobbering something we don't expect to.  */
5970   gdb_assert (! sig_entry->per_cu.queued);
5971   gdb_assert (sig_entry->per_cu.cu == NULL);
5972   if (dwarf2_per_objfile->using_index)
5973     {
5974       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5975       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5976     }
5977   else
5978       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5979   gdb_assert (sig_entry->signature == dwo_entry->signature);
5980   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5981   gdb_assert (sig_entry->type_unit_group == NULL);
5982   gdb_assert (sig_entry->dwo_unit == NULL);
5983
5984   sig_entry->per_cu.section = dwo_entry->section;
5985   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5986   sig_entry->per_cu.length = dwo_entry->length;
5987   sig_entry->per_cu.reading_dwo_directly = 1;
5988   sig_entry->per_cu.objfile = objfile;
5989   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5990   sig_entry->dwo_unit = dwo_entry;
5991 }
5992
5993 /* Subroutine of lookup_signatured_type.
5994    If we haven't read the TU yet, create the signatured_type data structure
5995    for a TU to be read in directly from a DWO file, bypassing the stub.
5996    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5997    using .gdb_index, then when reading a CU we want to stay in the DWO file
5998    containing that CU.  Otherwise we could end up reading several other DWO
5999    files (due to comdat folding) to process the transitive closure of all the
6000    mentioned TUs, and that can be slow.  The current DWO file will have every
6001    type signature that it needs.
6002    We only do this for .gdb_index because in the psymtab case we already have
6003    to read all the DWOs to build the type unit groups.  */
6004
6005 static struct signatured_type *
6006 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6007 {
6008   struct objfile *objfile = dwarf2_per_objfile->objfile;
6009   struct dwo_file *dwo_file;
6010   struct dwo_unit find_dwo_entry, *dwo_entry;
6011   struct signatured_type find_sig_entry, *sig_entry;
6012   void **slot;
6013
6014   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6015
6016   /* If TU skeletons have been removed then we may not have read in any
6017      TUs yet.  */
6018   if (dwarf2_per_objfile->signatured_types == NULL)
6019     {
6020       dwarf2_per_objfile->signatured_types
6021         = allocate_signatured_type_table (objfile);
6022     }
6023
6024   /* We only ever need to read in one copy of a signatured type.
6025      Use the global signatured_types array to do our own comdat-folding
6026      of types.  If this is the first time we're reading this TU, and
6027      the TU has an entry in .gdb_index, replace the recorded data from
6028      .gdb_index with this TU.  */
6029
6030   find_sig_entry.signature = sig;
6031   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6032                          &find_sig_entry, INSERT);
6033   sig_entry = (struct signatured_type *) *slot;
6034
6035   /* We can get here with the TU already read, *or* in the process of being
6036      read.  Don't reassign the global entry to point to this DWO if that's
6037      the case.  Also note that if the TU is already being read, it may not
6038      have come from a DWO, the program may be a mix of Fission-compiled
6039      code and non-Fission-compiled code.  */
6040
6041   /* Have we already tried to read this TU?
6042      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6043      needn't exist in the global table yet).  */
6044   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6045     return sig_entry;
6046
6047   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6048      dwo_unit of the TU itself.  */
6049   dwo_file = cu->dwo_unit->dwo_file;
6050
6051   /* Ok, this is the first time we're reading this TU.  */
6052   if (dwo_file->tus == NULL)
6053     return NULL;
6054   find_dwo_entry.signature = sig;
6055   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6056   if (dwo_entry == NULL)
6057     return NULL;
6058
6059   /* If the global table doesn't have an entry for this TU, add one.  */
6060   if (sig_entry == NULL)
6061     sig_entry = add_type_unit (sig, slot);
6062
6063   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
6064   sig_entry->per_cu.tu_read = 1;
6065   return sig_entry;
6066 }
6067
6068 /* Subroutine of lookup_signatured_type.
6069    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6070    then try the DWP file.  If the TU stub (skeleton) has been removed then
6071    it won't be in .gdb_index.  */
6072
6073 static struct signatured_type *
6074 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6075 {
6076   struct objfile *objfile = dwarf2_per_objfile->objfile;
6077   struct dwp_file *dwp_file = get_dwp_file ();
6078   struct dwo_unit *dwo_entry;
6079   struct signatured_type find_sig_entry, *sig_entry;
6080   void **slot;
6081
6082   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6083   gdb_assert (dwp_file != NULL);
6084
6085   /* If TU skeletons have been removed then we may not have read in any
6086      TUs yet.  */
6087   if (dwarf2_per_objfile->signatured_types == NULL)
6088     {
6089       dwarf2_per_objfile->signatured_types
6090         = allocate_signatured_type_table (objfile);
6091     }
6092
6093   find_sig_entry.signature = sig;
6094   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6095                          &find_sig_entry, INSERT);
6096   sig_entry = (struct signatured_type *) *slot;
6097
6098   /* Have we already tried to read this TU?
6099      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6100      needn't exist in the global table yet).  */
6101   if (sig_entry != NULL)
6102     return sig_entry;
6103
6104   if (dwp_file->tus == NULL)
6105     return NULL;
6106   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
6107                                       sig, 1 /* is_debug_types */);
6108   if (dwo_entry == NULL)
6109     return NULL;
6110
6111   sig_entry = add_type_unit (sig, slot);
6112   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
6113
6114   return sig_entry;
6115 }
6116
6117 /* Lookup a signature based type for DW_FORM_ref_sig8.
6118    Returns NULL if signature SIG is not present in the table.
6119    It is up to the caller to complain about this.  */
6120
6121 static struct signatured_type *
6122 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6123 {
6124   if (cu->dwo_unit
6125       && dwarf2_per_objfile->using_index)
6126     {
6127       /* We're in a DWO/DWP file, and we're using .gdb_index.
6128          These cases require special processing.  */
6129       if (get_dwp_file () == NULL)
6130         return lookup_dwo_signatured_type (cu, sig);
6131       else
6132         return lookup_dwp_signatured_type (cu, sig);
6133     }
6134   else
6135     {
6136       struct signatured_type find_entry, *entry;
6137
6138       if (dwarf2_per_objfile->signatured_types == NULL)
6139         return NULL;
6140       find_entry.signature = sig;
6141       entry = ((struct signatured_type *)
6142                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
6143       return entry;
6144     }
6145 }
6146 \f
6147 /* Low level DIE reading support.  */
6148
6149 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6150
6151 static void
6152 init_cu_die_reader (struct die_reader_specs *reader,
6153                     struct dwarf2_cu *cu,
6154                     struct dwarf2_section_info *section,
6155                     struct dwo_file *dwo_file)
6156 {
6157   gdb_assert (section->readin && section->buffer != NULL);
6158   reader->abfd = get_section_bfd_owner (section);
6159   reader->cu = cu;
6160   reader->dwo_file = dwo_file;
6161   reader->die_section = section;
6162   reader->buffer = section->buffer;
6163   reader->buffer_end = section->buffer + section->size;
6164   reader->comp_dir = NULL;
6165 }
6166
6167 /* Subroutine of init_cutu_and_read_dies to simplify it.
6168    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6169    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
6170    already.
6171
6172    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6173    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6174    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6175    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6176    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6177    STUB_COMP_DIR may be non-NULL.
6178    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
6179    are filled in with the info of the DIE from the DWO file.
6180    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
6181    provided an abbrev table to use.
6182    The result is non-zero if a valid (non-dummy) DIE was found.  */
6183
6184 static int
6185 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
6186                         struct dwo_unit *dwo_unit,
6187                         int abbrev_table_provided,
6188                         struct die_info *stub_comp_unit_die,
6189                         const char *stub_comp_dir,
6190                         struct die_reader_specs *result_reader,
6191                         const gdb_byte **result_info_ptr,
6192                         struct die_info **result_comp_unit_die,
6193                         int *result_has_children)
6194 {
6195   struct objfile *objfile = dwarf2_per_objfile->objfile;
6196   struct dwarf2_cu *cu = this_cu->cu;
6197   struct dwarf2_section_info *section;
6198   bfd *abfd;
6199   const gdb_byte *begin_info_ptr, *info_ptr;
6200   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6201   int i,num_extra_attrs;
6202   struct dwarf2_section_info *dwo_abbrev_section;
6203   struct attribute *attr;
6204   struct die_info *comp_unit_die;
6205
6206   /* At most one of these may be provided.  */
6207   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6208
6209   /* These attributes aren't processed until later:
6210      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6211      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6212      referenced later.  However, these attributes are found in the stub
6213      which we won't have later.  In order to not impose this complication
6214      on the rest of the code, we read them here and copy them to the
6215      DWO CU/TU die.  */
6216
6217   stmt_list = NULL;
6218   low_pc = NULL;
6219   high_pc = NULL;
6220   ranges = NULL;
6221   comp_dir = NULL;
6222
6223   if (stub_comp_unit_die != NULL)
6224     {
6225       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6226          DWO file.  */
6227       if (! this_cu->is_debug_types)
6228         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6229       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6230       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6231       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6232       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6233
6234       /* There should be a DW_AT_addr_base attribute here (if needed).
6235          We need the value before we can process DW_FORM_GNU_addr_index.  */
6236       cu->addr_base = 0;
6237       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
6238       if (attr)
6239         cu->addr_base = DW_UNSND (attr);
6240
6241       /* There should be a DW_AT_ranges_base attribute here (if needed).
6242          We need the value before we can process DW_AT_ranges.  */
6243       cu->ranges_base = 0;
6244       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
6245       if (attr)
6246         cu->ranges_base = DW_UNSND (attr);
6247     }
6248   else if (stub_comp_dir != NULL)
6249     {
6250       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6251       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
6252       comp_dir->name = DW_AT_comp_dir;
6253       comp_dir->form = DW_FORM_string;
6254       DW_STRING_IS_CANONICAL (comp_dir) = 0;
6255       DW_STRING (comp_dir) = stub_comp_dir;
6256     }
6257
6258   /* Set up for reading the DWO CU/TU.  */
6259   cu->dwo_unit = dwo_unit;
6260   section = dwo_unit->section;
6261   dwarf2_read_section (objfile, section);
6262   abfd = get_section_bfd_owner (section);
6263   begin_info_ptr = info_ptr = (section->buffer
6264                                + to_underlying (dwo_unit->sect_off));
6265   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6266   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
6267
6268   if (this_cu->is_debug_types)
6269     {
6270       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
6271
6272       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6273                                                 dwo_abbrev_section,
6274                                                 info_ptr, rcuh_kind::TYPE);
6275       /* This is not an assert because it can be caused by bad debug info.  */
6276       if (sig_type->signature != cu->header.signature)
6277         {
6278           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
6279                    " TU at offset 0x%x [in module %s]"),
6280                  hex_string (sig_type->signature),
6281                  hex_string (cu->header.signature),
6282                  to_underlying (dwo_unit->sect_off),
6283                  bfd_get_filename (abfd));
6284         }
6285       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6286       /* For DWOs coming from DWP files, we don't know the CU length
6287          nor the type's offset in the TU until now.  */
6288       dwo_unit->length = get_cu_length (&cu->header);
6289       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6290
6291       /* Establish the type offset that can be used to lookup the type.
6292          For DWO files, we don't know it until now.  */
6293       sig_type->type_offset_in_section
6294         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6295     }
6296   else
6297     {
6298       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6299                                                 dwo_abbrev_section,
6300                                                 info_ptr, rcuh_kind::COMPILE);
6301       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6302       /* For DWOs coming from DWP files, we don't know the CU length
6303          until now.  */
6304       dwo_unit->length = get_cu_length (&cu->header);
6305     }
6306
6307   /* Replace the CU's original abbrev table with the DWO's.
6308      Reminder: We can't read the abbrev table until we've read the header.  */
6309   if (abbrev_table_provided)
6310     {
6311       /* Don't free the provided abbrev table, the caller of
6312          init_cutu_and_read_dies owns it.  */
6313       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6314       /* Ensure the DWO abbrev table gets freed.  */
6315       make_cleanup (dwarf2_free_abbrev_table, cu);
6316     }
6317   else
6318     {
6319       dwarf2_free_abbrev_table (cu);
6320       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6321       /* Leave any existing abbrev table cleanup as is.  */
6322     }
6323
6324   /* Read in the die, but leave space to copy over the attributes
6325      from the stub.  This has the benefit of simplifying the rest of
6326      the code - all the work to maintain the illusion of a single
6327      DW_TAG_{compile,type}_unit DIE is done here.  */
6328   num_extra_attrs = ((stmt_list != NULL)
6329                      + (low_pc != NULL)
6330                      + (high_pc != NULL)
6331                      + (ranges != NULL)
6332                      + (comp_dir != NULL));
6333   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6334                               result_has_children, num_extra_attrs);
6335
6336   /* Copy over the attributes from the stub to the DIE we just read in.  */
6337   comp_unit_die = *result_comp_unit_die;
6338   i = comp_unit_die->num_attrs;
6339   if (stmt_list != NULL)
6340     comp_unit_die->attrs[i++] = *stmt_list;
6341   if (low_pc != NULL)
6342     comp_unit_die->attrs[i++] = *low_pc;
6343   if (high_pc != NULL)
6344     comp_unit_die->attrs[i++] = *high_pc;
6345   if (ranges != NULL)
6346     comp_unit_die->attrs[i++] = *ranges;
6347   if (comp_dir != NULL)
6348     comp_unit_die->attrs[i++] = *comp_dir;
6349   comp_unit_die->num_attrs += num_extra_attrs;
6350
6351   if (dwarf_die_debug)
6352     {
6353       fprintf_unfiltered (gdb_stdlog,
6354                           "Read die from %s@0x%x of %s:\n",
6355                           get_section_name (section),
6356                           (unsigned) (begin_info_ptr - section->buffer),
6357                           bfd_get_filename (abfd));
6358       dump_die (comp_unit_die, dwarf_die_debug);
6359     }
6360
6361   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
6362      TUs by skipping the stub and going directly to the entry in the DWO file.
6363      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
6364      to get it via circuitous means.  Blech.  */
6365   if (comp_dir != NULL)
6366     result_reader->comp_dir = DW_STRING (comp_dir);
6367
6368   /* Skip dummy compilation units.  */
6369   if (info_ptr >= begin_info_ptr + dwo_unit->length
6370       || peek_abbrev_code (abfd, info_ptr) == 0)
6371     return 0;
6372
6373   *result_info_ptr = info_ptr;
6374   return 1;
6375 }
6376
6377 /* Subroutine of init_cutu_and_read_dies to simplify it.
6378    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
6379    Returns NULL if the specified DWO unit cannot be found.  */
6380
6381 static struct dwo_unit *
6382 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
6383                  struct die_info *comp_unit_die)
6384 {
6385   struct dwarf2_cu *cu = this_cu->cu;
6386   ULONGEST signature;
6387   struct dwo_unit *dwo_unit;
6388   const char *comp_dir, *dwo_name;
6389
6390   gdb_assert (cu != NULL);
6391
6392   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
6393   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6394   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6395
6396   if (this_cu->is_debug_types)
6397     {
6398       struct signatured_type *sig_type;
6399
6400       /* Since this_cu is the first member of struct signatured_type,
6401          we can go from a pointer to one to a pointer to the other.  */
6402       sig_type = (struct signatured_type *) this_cu;
6403       signature = sig_type->signature;
6404       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
6405     }
6406   else
6407     {
6408       struct attribute *attr;
6409
6410       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6411       if (! attr)
6412         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
6413                  " [in module %s]"),
6414                dwo_name, objfile_name (this_cu->objfile));
6415       signature = DW_UNSND (attr);
6416       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
6417                                        signature);
6418     }
6419
6420   return dwo_unit;
6421 }
6422
6423 /* Subroutine of init_cutu_and_read_dies to simplify it.
6424    See it for a description of the parameters.
6425    Read a TU directly from a DWO file, bypassing the stub.
6426
6427    Note: This function could be a little bit simpler if we shared cleanups
6428    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
6429    to do, so we keep this function self-contained.  Or we could move this
6430    into our caller, but it's complex enough already.  */
6431
6432 static void
6433 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
6434                            int use_existing_cu, int keep,
6435                            die_reader_func_ftype *die_reader_func,
6436                            void *data)
6437 {
6438   struct dwarf2_cu *cu;
6439   struct signatured_type *sig_type;
6440   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6441   struct die_reader_specs reader;
6442   const gdb_byte *info_ptr;
6443   struct die_info *comp_unit_die;
6444   int has_children;
6445
6446   /* Verify we can do the following downcast, and that we have the
6447      data we need.  */
6448   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
6449   sig_type = (struct signatured_type *) this_cu;
6450   gdb_assert (sig_type->dwo_unit != NULL);
6451
6452   cleanups = make_cleanup (null_cleanup, NULL);
6453
6454   if (use_existing_cu && this_cu->cu != NULL)
6455     {
6456       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
6457       cu = this_cu->cu;
6458       /* There's no need to do the rereading_dwo_cu handling that
6459          init_cutu_and_read_dies does since we don't read the stub.  */
6460     }
6461   else
6462     {
6463       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6464       gdb_assert (this_cu->cu == NULL);
6465       cu = XNEW (struct dwarf2_cu);
6466       init_one_comp_unit (cu, this_cu);
6467       /* If an error occurs while loading, release our storage.  */
6468       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6469     }
6470
6471   /* A future optimization, if needed, would be to use an existing
6472      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
6473      could share abbrev tables.  */
6474
6475   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
6476                               0 /* abbrev_table_provided */,
6477                               NULL /* stub_comp_unit_die */,
6478                               sig_type->dwo_unit->dwo_file->comp_dir,
6479                               &reader, &info_ptr,
6480                               &comp_unit_die, &has_children) == 0)
6481     {
6482       /* Dummy die.  */
6483       do_cleanups (cleanups);
6484       return;
6485     }
6486
6487   /* All the "real" work is done here.  */
6488   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6489
6490   /* This duplicates the code in init_cutu_and_read_dies,
6491      but the alternative is making the latter more complex.
6492      This function is only for the special case of using DWO files directly:
6493      no point in overly complicating the general case just to handle this.  */
6494   if (free_cu_cleanup != NULL)
6495     {
6496       if (keep)
6497         {
6498           /* We've successfully allocated this compilation unit.  Let our
6499              caller clean it up when finished with it.  */
6500           discard_cleanups (free_cu_cleanup);
6501
6502           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6503              So we have to manually free the abbrev table.  */
6504           dwarf2_free_abbrev_table (cu);
6505
6506           /* Link this CU into read_in_chain.  */
6507           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6508           dwarf2_per_objfile->read_in_chain = this_cu;
6509         }
6510       else
6511         do_cleanups (free_cu_cleanup);
6512     }
6513
6514   do_cleanups (cleanups);
6515 }
6516
6517 /* Initialize a CU (or TU) and read its DIEs.
6518    If the CU defers to a DWO file, read the DWO file as well.
6519
6520    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
6521    Otherwise the table specified in the comp unit header is read in and used.
6522    This is an optimization for when we already have the abbrev table.
6523
6524    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
6525    Otherwise, a new CU is allocated with xmalloc.
6526
6527    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
6528    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
6529
6530    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6531    linker) then DIE_READER_FUNC will not get called.  */
6532
6533 static void
6534 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
6535                          struct abbrev_table *abbrev_table,
6536                          int use_existing_cu, int keep,
6537                          die_reader_func_ftype *die_reader_func,
6538                          void *data)
6539 {
6540   struct objfile *objfile = dwarf2_per_objfile->objfile;
6541   struct dwarf2_section_info *section = this_cu->section;
6542   bfd *abfd = get_section_bfd_owner (section);
6543   struct dwarf2_cu *cu;
6544   const gdb_byte *begin_info_ptr, *info_ptr;
6545   struct die_reader_specs reader;
6546   struct die_info *comp_unit_die;
6547   int has_children;
6548   struct attribute *attr;
6549   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6550   struct signatured_type *sig_type = NULL;
6551   struct dwarf2_section_info *abbrev_section;
6552   /* Non-zero if CU currently points to a DWO file and we need to
6553      reread it.  When this happens we need to reread the skeleton die
6554      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6555   int rereading_dwo_cu = 0;
6556
6557   if (dwarf_die_debug)
6558     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6559                         this_cu->is_debug_types ? "type" : "comp",
6560                         to_underlying (this_cu->sect_off));
6561
6562   if (use_existing_cu)
6563     gdb_assert (keep);
6564
6565   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6566      file (instead of going through the stub), short-circuit all of this.  */
6567   if (this_cu->reading_dwo_directly)
6568     {
6569       /* Narrow down the scope of possibilities to have to understand.  */
6570       gdb_assert (this_cu->is_debug_types);
6571       gdb_assert (abbrev_table == NULL);
6572       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
6573                                  die_reader_func, data);
6574       return;
6575     }
6576
6577   cleanups = make_cleanup (null_cleanup, NULL);
6578
6579   /* This is cheap if the section is already read in.  */
6580   dwarf2_read_section (objfile, section);
6581
6582   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6583
6584   abbrev_section = get_abbrev_section_for_cu (this_cu);
6585
6586   if (use_existing_cu && this_cu->cu != NULL)
6587     {
6588       cu = this_cu->cu;
6589       /* If this CU is from a DWO file we need to start over, we need to
6590          refetch the attributes from the skeleton CU.
6591          This could be optimized by retrieving those attributes from when we
6592          were here the first time: the previous comp_unit_die was stored in
6593          comp_unit_obstack.  But there's no data yet that we need this
6594          optimization.  */
6595       if (cu->dwo_unit != NULL)
6596         rereading_dwo_cu = 1;
6597     }
6598   else
6599     {
6600       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6601       gdb_assert (this_cu->cu == NULL);
6602       cu = XNEW (struct dwarf2_cu);
6603       init_one_comp_unit (cu, this_cu);
6604       /* If an error occurs while loading, release our storage.  */
6605       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6606     }
6607
6608   /* Get the header.  */
6609   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6610     {
6611       /* We already have the header, there's no need to read it in again.  */
6612       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6613     }
6614   else
6615     {
6616       if (this_cu->is_debug_types)
6617         {
6618           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6619                                                     abbrev_section, info_ptr,
6620                                                     rcuh_kind::TYPE);
6621
6622           /* Since per_cu is the first member of struct signatured_type,
6623              we can go from a pointer to one to a pointer to the other.  */
6624           sig_type = (struct signatured_type *) this_cu;
6625           gdb_assert (sig_type->signature == cu->header.signature);
6626           gdb_assert (sig_type->type_offset_in_tu
6627                       == cu->header.type_cu_offset_in_tu);
6628           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6629
6630           /* LENGTH has not been set yet for type units if we're
6631              using .gdb_index.  */
6632           this_cu->length = get_cu_length (&cu->header);
6633
6634           /* Establish the type offset that can be used to lookup the type.  */
6635           sig_type->type_offset_in_section =
6636             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6637
6638           this_cu->dwarf_version = cu->header.version;
6639         }
6640       else
6641         {
6642           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6643                                                     abbrev_section,
6644                                                     info_ptr,
6645                                                     rcuh_kind::COMPILE);
6646
6647           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6648           gdb_assert (this_cu->length == get_cu_length (&cu->header));
6649           this_cu->dwarf_version = cu->header.version;
6650         }
6651     }
6652
6653   /* Skip dummy compilation units.  */
6654   if (info_ptr >= begin_info_ptr + this_cu->length
6655       || peek_abbrev_code (abfd, info_ptr) == 0)
6656     {
6657       do_cleanups (cleanups);
6658       return;
6659     }
6660
6661   /* If we don't have them yet, read the abbrevs for this compilation unit.
6662      And if we need to read them now, make sure they're freed when we're
6663      done.  Note that it's important that if the CU had an abbrev table
6664      on entry we don't free it when we're done: Somewhere up the call stack
6665      it may be in use.  */
6666   if (abbrev_table != NULL)
6667     {
6668       gdb_assert (cu->abbrev_table == NULL);
6669       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6670       cu->abbrev_table = abbrev_table;
6671     }
6672   else if (cu->abbrev_table == NULL)
6673     {
6674       dwarf2_read_abbrevs (cu, abbrev_section);
6675       make_cleanup (dwarf2_free_abbrev_table, cu);
6676     }
6677   else if (rereading_dwo_cu)
6678     {
6679       dwarf2_free_abbrev_table (cu);
6680       dwarf2_read_abbrevs (cu, abbrev_section);
6681     }
6682
6683   /* Read the top level CU/TU die.  */
6684   init_cu_die_reader (&reader, cu, section, NULL);
6685   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6686
6687   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6688      from the DWO file.
6689      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6690      DWO CU, that this test will fail (the attribute will not be present).  */
6691   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6692   if (attr)
6693     {
6694       struct dwo_unit *dwo_unit;
6695       struct die_info *dwo_comp_unit_die;
6696
6697       if (has_children)
6698         {
6699           complaint (&symfile_complaints,
6700                      _("compilation unit with DW_AT_GNU_dwo_name"
6701                        " has children (offset 0x%x) [in module %s]"),
6702                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
6703         }
6704       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
6705       if (dwo_unit != NULL)
6706         {
6707           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
6708                                       abbrev_table != NULL,
6709                                       comp_unit_die, NULL,
6710                                       &reader, &info_ptr,
6711                                       &dwo_comp_unit_die, &has_children) == 0)
6712             {
6713               /* Dummy die.  */
6714               do_cleanups (cleanups);
6715               return;
6716             }
6717           comp_unit_die = dwo_comp_unit_die;
6718         }
6719       else
6720         {
6721           /* Yikes, we couldn't find the rest of the DIE, we only have
6722              the stub.  A complaint has already been logged.  There's
6723              not much more we can do except pass on the stub DIE to
6724              die_reader_func.  We don't want to throw an error on bad
6725              debug info.  */
6726         }
6727     }
6728
6729   /* All of the above is setup for this call.  Yikes.  */
6730   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6731
6732   /* Done, clean up.  */
6733   if (free_cu_cleanup != NULL)
6734     {
6735       if (keep)
6736         {
6737           /* We've successfully allocated this compilation unit.  Let our
6738              caller clean it up when finished with it.  */
6739           discard_cleanups (free_cu_cleanup);
6740
6741           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6742              So we have to manually free the abbrev table.  */
6743           dwarf2_free_abbrev_table (cu);
6744
6745           /* Link this CU into read_in_chain.  */
6746           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6747           dwarf2_per_objfile->read_in_chain = this_cu;
6748         }
6749       else
6750         do_cleanups (free_cu_cleanup);
6751     }
6752
6753   do_cleanups (cleanups);
6754 }
6755
6756 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
6757    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
6758    to have already done the lookup to find the DWO file).
6759
6760    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6761    THIS_CU->is_debug_types, but nothing else.
6762
6763    We fill in THIS_CU->length.
6764
6765    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6766    linker) then DIE_READER_FUNC will not get called.
6767
6768    THIS_CU->cu is always freed when done.
6769    This is done in order to not leave THIS_CU->cu in a state where we have
6770    to care whether it refers to the "main" CU or the DWO CU.  */
6771
6772 static void
6773 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
6774                                    struct dwo_file *dwo_file,
6775                                    die_reader_func_ftype *die_reader_func,
6776                                    void *data)
6777 {
6778   struct objfile *objfile = dwarf2_per_objfile->objfile;
6779   struct dwarf2_section_info *section = this_cu->section;
6780   bfd *abfd = get_section_bfd_owner (section);
6781   struct dwarf2_section_info *abbrev_section;
6782   struct dwarf2_cu cu;
6783   const gdb_byte *begin_info_ptr, *info_ptr;
6784   struct die_reader_specs reader;
6785   struct cleanup *cleanups;
6786   struct die_info *comp_unit_die;
6787   int has_children;
6788
6789   if (dwarf_die_debug)
6790     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6791                         this_cu->is_debug_types ? "type" : "comp",
6792                         to_underlying (this_cu->sect_off));
6793
6794   gdb_assert (this_cu->cu == NULL);
6795
6796   abbrev_section = (dwo_file != NULL
6797                     ? &dwo_file->sections.abbrev
6798                     : get_abbrev_section_for_cu (this_cu));
6799
6800   /* This is cheap if the section is already read in.  */
6801   dwarf2_read_section (objfile, section);
6802
6803   init_one_comp_unit (&cu, this_cu);
6804
6805   cleanups = make_cleanup (free_stack_comp_unit, &cu);
6806
6807   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6808   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
6809                                             abbrev_section, info_ptr,
6810                                             (this_cu->is_debug_types
6811                                              ? rcuh_kind::TYPE
6812                                              : rcuh_kind::COMPILE));
6813
6814   this_cu->length = get_cu_length (&cu.header);
6815
6816   /* Skip dummy compilation units.  */
6817   if (info_ptr >= begin_info_ptr + this_cu->length
6818       || peek_abbrev_code (abfd, info_ptr) == 0)
6819     {
6820       do_cleanups (cleanups);
6821       return;
6822     }
6823
6824   dwarf2_read_abbrevs (&cu, abbrev_section);
6825   make_cleanup (dwarf2_free_abbrev_table, &cu);
6826
6827   init_cu_die_reader (&reader, &cu, section, dwo_file);
6828   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6829
6830   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6831
6832   do_cleanups (cleanups);
6833 }
6834
6835 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
6836    does not lookup the specified DWO file.
6837    This cannot be used to read DWO files.
6838
6839    THIS_CU->cu is always freed when done.
6840    This is done in order to not leave THIS_CU->cu in a state where we have
6841    to care whether it refers to the "main" CU or the DWO CU.
6842    We can revisit this if the data shows there's a performance issue.  */
6843
6844 static void
6845 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
6846                                 die_reader_func_ftype *die_reader_func,
6847                                 void *data)
6848 {
6849   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
6850 }
6851 \f
6852 /* Type Unit Groups.
6853
6854    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6855    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6856    so that all types coming from the same compilation (.o file) are grouped
6857    together.  A future step could be to put the types in the same symtab as
6858    the CU the types ultimately came from.  */
6859
6860 static hashval_t
6861 hash_type_unit_group (const void *item)
6862 {
6863   const struct type_unit_group *tu_group
6864     = (const struct type_unit_group *) item;
6865
6866   return hash_stmt_list_entry (&tu_group->hash);
6867 }
6868
6869 static int
6870 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6871 {
6872   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6873   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6874
6875   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6876 }
6877
6878 /* Allocate a hash table for type unit groups.  */
6879
6880 static htab_t
6881 allocate_type_unit_groups_table (void)
6882 {
6883   return htab_create_alloc_ex (3,
6884                                hash_type_unit_group,
6885                                eq_type_unit_group,
6886                                NULL,
6887                                &dwarf2_per_objfile->objfile->objfile_obstack,
6888                                hashtab_obstack_allocate,
6889                                dummy_obstack_deallocate);
6890 }
6891
6892 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6893    partial symtabs.  We combine several TUs per psymtab to not let the size
6894    of any one psymtab grow too big.  */
6895 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6896 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6897
6898 /* Helper routine for get_type_unit_group.
6899    Create the type_unit_group object used to hold one or more TUs.  */
6900
6901 static struct type_unit_group *
6902 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6903 {
6904   struct objfile *objfile = dwarf2_per_objfile->objfile;
6905   struct dwarf2_per_cu_data *per_cu;
6906   struct type_unit_group *tu_group;
6907
6908   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6909                              struct type_unit_group);
6910   per_cu = &tu_group->per_cu;
6911   per_cu->objfile = objfile;
6912
6913   if (dwarf2_per_objfile->using_index)
6914     {
6915       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6916                                         struct dwarf2_per_cu_quick_data);
6917     }
6918   else
6919     {
6920       unsigned int line_offset = to_underlying (line_offset_struct);
6921       struct partial_symtab *pst;
6922       char *name;
6923
6924       /* Give the symtab a useful name for debug purposes.  */
6925       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6926         name = xstrprintf ("<type_units_%d>",
6927                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6928       else
6929         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6930
6931       pst = create_partial_symtab (per_cu, name);
6932       pst->anonymous = 1;
6933
6934       xfree (name);
6935     }
6936
6937   tu_group->hash.dwo_unit = cu->dwo_unit;
6938   tu_group->hash.line_sect_off = line_offset_struct;
6939
6940   return tu_group;
6941 }
6942
6943 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6944    STMT_LIST is a DW_AT_stmt_list attribute.  */
6945
6946 static struct type_unit_group *
6947 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6948 {
6949   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6950   struct type_unit_group *tu_group;
6951   void **slot;
6952   unsigned int line_offset;
6953   struct type_unit_group type_unit_group_for_lookup;
6954
6955   if (dwarf2_per_objfile->type_unit_groups == NULL)
6956     {
6957       dwarf2_per_objfile->type_unit_groups =
6958         allocate_type_unit_groups_table ();
6959     }
6960
6961   /* Do we need to create a new group, or can we use an existing one?  */
6962
6963   if (stmt_list)
6964     {
6965       line_offset = DW_UNSND (stmt_list);
6966       ++tu_stats->nr_symtab_sharers;
6967     }
6968   else
6969     {
6970       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6971          We can do various things here like create one group per TU or
6972          spread them over multiple groups to split up the expansion work.
6973          To avoid worst case scenarios (too many groups or too large groups)
6974          we, umm, group them in bunches.  */
6975       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6976                      | (tu_stats->nr_stmt_less_type_units
6977                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6978       ++tu_stats->nr_stmt_less_type_units;
6979     }
6980
6981   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6982   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6983   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6984                          &type_unit_group_for_lookup, INSERT);
6985   if (*slot != NULL)
6986     {
6987       tu_group = (struct type_unit_group *) *slot;
6988       gdb_assert (tu_group != NULL);
6989     }
6990   else
6991     {
6992       sect_offset line_offset_struct = (sect_offset) line_offset;
6993       tu_group = create_type_unit_group (cu, line_offset_struct);
6994       *slot = tu_group;
6995       ++tu_stats->nr_symtabs;
6996     }
6997
6998   return tu_group;
6999 }
7000 \f
7001 /* Partial symbol tables.  */
7002
7003 /* Create a psymtab named NAME and assign it to PER_CU.
7004
7005    The caller must fill in the following details:
7006    dirname, textlow, texthigh.  */
7007
7008 static struct partial_symtab *
7009 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7010 {
7011   struct objfile *objfile = per_cu->objfile;
7012   struct partial_symtab *pst;
7013
7014   pst = start_psymtab_common (objfile, name, 0,
7015                               objfile->global_psymbols,
7016                               objfile->static_psymbols);
7017
7018   pst->psymtabs_addrmap_supported = 1;
7019
7020   /* This is the glue that links PST into GDB's symbol API.  */
7021   pst->read_symtab_private = per_cu;
7022   pst->read_symtab = dwarf2_read_symtab;
7023   per_cu->v.psymtab = pst;
7024
7025   return pst;
7026 }
7027
7028 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7029    type.  */
7030
7031 struct process_psymtab_comp_unit_data
7032 {
7033   /* True if we are reading a DW_TAG_partial_unit.  */
7034
7035   int want_partial_unit;
7036
7037   /* The "pretend" language that is used if the CU doesn't declare a
7038      language.  */
7039
7040   enum language pretend_language;
7041 };
7042
7043 /* die_reader_func for process_psymtab_comp_unit.  */
7044
7045 static void
7046 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7047                                   const gdb_byte *info_ptr,
7048                                   struct die_info *comp_unit_die,
7049                                   int has_children,
7050                                   void *data)
7051 {
7052   struct dwarf2_cu *cu = reader->cu;
7053   struct objfile *objfile = cu->objfile;
7054   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7055   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7056   CORE_ADDR baseaddr;
7057   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7058   struct partial_symtab *pst;
7059   enum pc_bounds_kind cu_bounds_kind;
7060   const char *filename;
7061   struct process_psymtab_comp_unit_data *info
7062     = (struct process_psymtab_comp_unit_data *) data;
7063
7064   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7065     return;
7066
7067   gdb_assert (! per_cu->is_debug_types);
7068
7069   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7070
7071   cu->list_in_scope = &file_symbols;
7072
7073   /* Allocate a new partial symbol table structure.  */
7074   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7075   if (filename == NULL)
7076     filename = "";
7077
7078   pst = create_partial_symtab (per_cu, filename);
7079
7080   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7081   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7082
7083   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7084
7085   dwarf2_find_base_address (comp_unit_die, cu);
7086
7087   /* Possibly set the default values of LOWPC and HIGHPC from
7088      `DW_AT_ranges'.  */
7089   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7090                                          &best_highpc, cu, pst);
7091   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7092     /* Store the contiguous range if it is not empty; it can be empty for
7093        CUs with no code.  */
7094     addrmap_set_empty (objfile->psymtabs_addrmap,
7095                        gdbarch_adjust_dwarf2_addr (gdbarch,
7096                                                    best_lowpc + baseaddr),
7097                        gdbarch_adjust_dwarf2_addr (gdbarch,
7098                                                    best_highpc + baseaddr) - 1,
7099                        pst);
7100
7101   /* Check if comp unit has_children.
7102      If so, read the rest of the partial symbols from this comp unit.
7103      If not, there's no more debug_info for this comp unit.  */
7104   if (has_children)
7105     {
7106       struct partial_die_info *first_die;
7107       CORE_ADDR lowpc, highpc;
7108
7109       lowpc = ((CORE_ADDR) -1);
7110       highpc = ((CORE_ADDR) 0);
7111
7112       first_die = load_partial_dies (reader, info_ptr, 1);
7113
7114       scan_partial_symbols (first_die, &lowpc, &highpc,
7115                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7116
7117       /* If we didn't find a lowpc, set it to highpc to avoid
7118          complaints from `maint check'.  */
7119       if (lowpc == ((CORE_ADDR) -1))
7120         lowpc = highpc;
7121
7122       /* If the compilation unit didn't have an explicit address range,
7123          then use the information extracted from its child dies.  */
7124       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7125         {
7126           best_lowpc = lowpc;
7127           best_highpc = highpc;
7128         }
7129     }
7130   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7131   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7132
7133   end_psymtab_common (objfile, pst);
7134
7135   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7136     {
7137       int i;
7138       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7139       struct dwarf2_per_cu_data *iter;
7140
7141       /* Fill in 'dependencies' here; we fill in 'users' in a
7142          post-pass.  */
7143       pst->number_of_dependencies = len;
7144       pst->dependencies =
7145         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7146       for (i = 0;
7147            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7148                         i, iter);
7149            ++i)
7150         pst->dependencies[i] = iter->v.psymtab;
7151
7152       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7153     }
7154
7155   /* Get the list of files included in the current compilation unit,
7156      and build a psymtab for each of them.  */
7157   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7158
7159   if (dwarf_read_debug)
7160     {
7161       struct gdbarch *gdbarch = get_objfile_arch (objfile);
7162
7163       fprintf_unfiltered (gdb_stdlog,
7164                           "Psymtab for %s unit @0x%x: %s - %s"
7165                           ", %d global, %d static syms\n",
7166                           per_cu->is_debug_types ? "type" : "comp",
7167                           to_underlying (per_cu->sect_off),
7168                           paddress (gdbarch, pst->textlow),
7169                           paddress (gdbarch, pst->texthigh),
7170                           pst->n_global_syms, pst->n_static_syms);
7171     }
7172 }
7173
7174 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7175    Process compilation unit THIS_CU for a psymtab.  */
7176
7177 static void
7178 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
7179                            int want_partial_unit,
7180                            enum language pretend_language)
7181 {
7182   /* If this compilation unit was already read in, free the
7183      cached copy in order to read it in again.  This is
7184      necessary because we skipped some symbols when we first
7185      read in the compilation unit (see load_partial_dies).
7186      This problem could be avoided, but the benefit is unclear.  */
7187   if (this_cu->cu != NULL)
7188     free_one_cached_comp_unit (this_cu);
7189
7190   if (this_cu->is_debug_types)
7191     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
7192                              NULL);
7193   else
7194     {
7195       process_psymtab_comp_unit_data info;
7196       info.want_partial_unit = want_partial_unit;
7197       info.pretend_language = pretend_language;
7198       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
7199                                process_psymtab_comp_unit_reader, &info);
7200     }
7201
7202   /* Age out any secondary CUs.  */
7203   age_cached_comp_units ();
7204 }
7205
7206 /* Reader function for build_type_psymtabs.  */
7207
7208 static void
7209 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7210                             const gdb_byte *info_ptr,
7211                             struct die_info *type_unit_die,
7212                             int has_children,
7213                             void *data)
7214 {
7215   struct objfile *objfile = dwarf2_per_objfile->objfile;
7216   struct dwarf2_cu *cu = reader->cu;
7217   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7218   struct signatured_type *sig_type;
7219   struct type_unit_group *tu_group;
7220   struct attribute *attr;
7221   struct partial_die_info *first_die;
7222   CORE_ADDR lowpc, highpc;
7223   struct partial_symtab *pst;
7224
7225   gdb_assert (data == NULL);
7226   gdb_assert (per_cu->is_debug_types);
7227   sig_type = (struct signatured_type *) per_cu;
7228
7229   if (! has_children)
7230     return;
7231
7232   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
7233   tu_group = get_type_unit_group (cu, attr);
7234
7235   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
7236
7237   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7238   cu->list_in_scope = &file_symbols;
7239   pst = create_partial_symtab (per_cu, "");
7240   pst->anonymous = 1;
7241
7242   first_die = load_partial_dies (reader, info_ptr, 1);
7243
7244   lowpc = (CORE_ADDR) -1;
7245   highpc = (CORE_ADDR) 0;
7246   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7247
7248   end_psymtab_common (objfile, pst);
7249 }
7250
7251 /* Struct used to sort TUs by their abbreviation table offset.  */
7252
7253 struct tu_abbrev_offset
7254 {
7255   struct signatured_type *sig_type;
7256   sect_offset abbrev_offset;
7257 };
7258
7259 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
7260
7261 static int
7262 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
7263 {
7264   const struct tu_abbrev_offset * const *a
7265     = (const struct tu_abbrev_offset * const*) ap;
7266   const struct tu_abbrev_offset * const *b
7267     = (const struct tu_abbrev_offset * const*) bp;
7268   sect_offset aoff = (*a)->abbrev_offset;
7269   sect_offset boff = (*b)->abbrev_offset;
7270
7271   return (aoff > boff) - (aoff < boff);
7272 }
7273
7274 /* Efficiently read all the type units.
7275    This does the bulk of the work for build_type_psymtabs.
7276
7277    The efficiency is because we sort TUs by the abbrev table they use and
7278    only read each abbrev table once.  In one program there are 200K TUs
7279    sharing 8K abbrev tables.
7280
7281    The main purpose of this function is to support building the
7282    dwarf2_per_objfile->type_unit_groups table.
7283    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7284    can collapse the search space by grouping them by stmt_list.
7285    The savings can be significant, in the same program from above the 200K TUs
7286    share 8K stmt_list tables.
7287
7288    FUNC is expected to call get_type_unit_group, which will create the
7289    struct type_unit_group if necessary and add it to
7290    dwarf2_per_objfile->type_unit_groups.  */
7291
7292 static void
7293 build_type_psymtabs_1 (void)
7294 {
7295   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7296   struct cleanup *cleanups;
7297   struct abbrev_table *abbrev_table;
7298   sect_offset abbrev_offset;
7299   struct tu_abbrev_offset *sorted_by_abbrev;
7300   int i;
7301
7302   /* It's up to the caller to not call us multiple times.  */
7303   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
7304
7305   if (dwarf2_per_objfile->n_type_units == 0)
7306     return;
7307
7308   /* TUs typically share abbrev tables, and there can be way more TUs than
7309      abbrev tables.  Sort by abbrev table to reduce the number of times we
7310      read each abbrev table in.
7311      Alternatives are to punt or to maintain a cache of abbrev tables.
7312      This is simpler and efficient enough for now.
7313
7314      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7315      symtab to use).  Typically TUs with the same abbrev offset have the same
7316      stmt_list value too so in practice this should work well.
7317
7318      The basic algorithm here is:
7319
7320       sort TUs by abbrev table
7321       for each TU with same abbrev table:
7322         read abbrev table if first user
7323         read TU top level DIE
7324           [IWBN if DWO skeletons had DW_AT_stmt_list]
7325         call FUNC  */
7326
7327   if (dwarf_read_debug)
7328     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
7329
7330   /* Sort in a separate table to maintain the order of all_type_units
7331      for .gdb_index: TU indices directly index all_type_units.  */
7332   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
7333                               dwarf2_per_objfile->n_type_units);
7334   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7335     {
7336       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
7337
7338       sorted_by_abbrev[i].sig_type = sig_type;
7339       sorted_by_abbrev[i].abbrev_offset =
7340         read_abbrev_offset (sig_type->per_cu.section,
7341                             sig_type->per_cu.sect_off);
7342     }
7343   cleanups = make_cleanup (xfree, sorted_by_abbrev);
7344   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
7345          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
7346
7347   abbrev_offset = (sect_offset) ~(unsigned) 0;
7348   abbrev_table = NULL;
7349   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
7350
7351   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7352     {
7353       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
7354
7355       /* Switch to the next abbrev table if necessary.  */
7356       if (abbrev_table == NULL
7357           || tu->abbrev_offset != abbrev_offset)
7358         {
7359           if (abbrev_table != NULL)
7360             {
7361               abbrev_table_free (abbrev_table);
7362               /* Reset to NULL in case abbrev_table_read_table throws
7363                  an error: abbrev_table_free_cleanup will get called.  */
7364               abbrev_table = NULL;
7365             }
7366           abbrev_offset = tu->abbrev_offset;
7367           abbrev_table =
7368             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
7369                                      abbrev_offset);
7370           ++tu_stats->nr_uniq_abbrev_tables;
7371         }
7372
7373       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
7374                                build_type_psymtabs_reader, NULL);
7375     }
7376
7377   do_cleanups (cleanups);
7378 }
7379
7380 /* Print collected type unit statistics.  */
7381
7382 static void
7383 print_tu_stats (void)
7384 {
7385   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7386
7387   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
7388   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
7389                       dwarf2_per_objfile->n_type_units);
7390   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
7391                       tu_stats->nr_uniq_abbrev_tables);
7392   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
7393                       tu_stats->nr_symtabs);
7394   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
7395                       tu_stats->nr_symtab_sharers);
7396   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
7397                       tu_stats->nr_stmt_less_type_units);
7398   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
7399                       tu_stats->nr_all_type_units_reallocs);
7400 }
7401
7402 /* Traversal function for build_type_psymtabs.  */
7403
7404 static int
7405 build_type_psymtab_dependencies (void **slot, void *info)
7406 {
7407   struct objfile *objfile = dwarf2_per_objfile->objfile;
7408   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7409   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
7410   struct partial_symtab *pst = per_cu->v.psymtab;
7411   int len = VEC_length (sig_type_ptr, tu_group->tus);
7412   struct signatured_type *iter;
7413   int i;
7414
7415   gdb_assert (len > 0);
7416   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
7417
7418   pst->number_of_dependencies = len;
7419   pst->dependencies =
7420     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7421   for (i = 0;
7422        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
7423        ++i)
7424     {
7425       gdb_assert (iter->per_cu.is_debug_types);
7426       pst->dependencies[i] = iter->per_cu.v.psymtab;
7427       iter->type_unit_group = tu_group;
7428     }
7429
7430   VEC_free (sig_type_ptr, tu_group->tus);
7431
7432   return 1;
7433 }
7434
7435 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7436    Build partial symbol tables for the .debug_types comp-units.  */
7437
7438 static void
7439 build_type_psymtabs (struct objfile *objfile)
7440 {
7441   if (! create_all_type_units (objfile))
7442     return;
7443
7444   build_type_psymtabs_1 ();
7445 }
7446
7447 /* Traversal function for process_skeletonless_type_unit.
7448    Read a TU in a DWO file and build partial symbols for it.  */
7449
7450 static int
7451 process_skeletonless_type_unit (void **slot, void *info)
7452 {
7453   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7454   struct objfile *objfile = (struct objfile *) info;
7455   struct signatured_type find_entry, *entry;
7456
7457   /* If this TU doesn't exist in the global table, add it and read it in.  */
7458
7459   if (dwarf2_per_objfile->signatured_types == NULL)
7460     {
7461       dwarf2_per_objfile->signatured_types
7462         = allocate_signatured_type_table (objfile);
7463     }
7464
7465   find_entry.signature = dwo_unit->signature;
7466   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
7467                          INSERT);
7468   /* If we've already seen this type there's nothing to do.  What's happening
7469      is we're doing our own version of comdat-folding here.  */
7470   if (*slot != NULL)
7471     return 1;
7472
7473   /* This does the job that create_all_type_units would have done for
7474      this TU.  */
7475   entry = add_type_unit (dwo_unit->signature, slot);
7476   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
7477   *slot = entry;
7478
7479   /* This does the job that build_type_psymtabs_1 would have done.  */
7480   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
7481                            build_type_psymtabs_reader, NULL);
7482
7483   return 1;
7484 }
7485
7486 /* Traversal function for process_skeletonless_type_units.  */
7487
7488 static int
7489 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
7490 {
7491   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7492
7493   if (dwo_file->tus != NULL)
7494     {
7495       htab_traverse_noresize (dwo_file->tus,
7496                               process_skeletonless_type_unit, info);
7497     }
7498
7499   return 1;
7500 }
7501
7502 /* Scan all TUs of DWO files, verifying we've processed them.
7503    This is needed in case a TU was emitted without its skeleton.
7504    Note: This can't be done until we know what all the DWO files are.  */
7505
7506 static void
7507 process_skeletonless_type_units (struct objfile *objfile)
7508 {
7509   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
7510   if (get_dwp_file () == NULL
7511       && dwarf2_per_objfile->dwo_files != NULL)
7512     {
7513       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
7514                               process_dwo_file_for_skeletonless_type_units,
7515                               objfile);
7516     }
7517 }
7518
7519 /* Compute the 'user' field for each psymtab in OBJFILE.  */
7520
7521 static void
7522 set_partial_user (struct objfile *objfile)
7523 {
7524   int i;
7525
7526   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7527     {
7528       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7529       struct partial_symtab *pst = per_cu->v.psymtab;
7530       int j;
7531
7532       if (pst == NULL)
7533         continue;
7534
7535       for (j = 0; j < pst->number_of_dependencies; ++j)
7536         {
7537           /* Set the 'user' field only if it is not already set.  */
7538           if (pst->dependencies[j]->user == NULL)
7539             pst->dependencies[j]->user = pst;
7540         }
7541     }
7542 }
7543
7544 /* Build the partial symbol table by doing a quick pass through the
7545    .debug_info and .debug_abbrev sections.  */
7546
7547 static void
7548 dwarf2_build_psymtabs_hard (struct objfile *objfile)
7549 {
7550   struct cleanup *back_to;
7551   int i;
7552
7553   if (dwarf_read_debug)
7554     {
7555       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
7556                           objfile_name (objfile));
7557     }
7558
7559   dwarf2_per_objfile->reading_partial_symbols = 1;
7560
7561   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
7562
7563   /* Any cached compilation units will be linked by the per-objfile
7564      read_in_chain.  Make sure to free them when we're done.  */
7565   back_to = make_cleanup (free_cached_comp_units, NULL);
7566
7567   build_type_psymtabs (objfile);
7568
7569   create_all_comp_units (objfile);
7570
7571   /* Create a temporary address map on a temporary obstack.  We later
7572      copy this to the final obstack.  */
7573   auto_obstack temp_obstack;
7574
7575   scoped_restore save_psymtabs_addrmap
7576     = make_scoped_restore (&objfile->psymtabs_addrmap,
7577                            addrmap_create_mutable (&temp_obstack));
7578
7579   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7580     {
7581       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7582
7583       process_psymtab_comp_unit (per_cu, 0, language_minimal);
7584     }
7585
7586   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7587   process_skeletonless_type_units (objfile);
7588
7589   /* Now that all TUs have been processed we can fill in the dependencies.  */
7590   if (dwarf2_per_objfile->type_unit_groups != NULL)
7591     {
7592       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
7593                               build_type_psymtab_dependencies, NULL);
7594     }
7595
7596   if (dwarf_read_debug)
7597     print_tu_stats ();
7598
7599   set_partial_user (objfile);
7600
7601   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
7602                                                     &objfile->objfile_obstack);
7603   /* At this point we want to keep the address map.  */
7604   save_psymtabs_addrmap.release ();
7605
7606   do_cleanups (back_to);
7607
7608   if (dwarf_read_debug)
7609     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
7610                         objfile_name (objfile));
7611 }
7612
7613 /* die_reader_func for load_partial_comp_unit.  */
7614
7615 static void
7616 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
7617                                const gdb_byte *info_ptr,
7618                                struct die_info *comp_unit_die,
7619                                int has_children,
7620                                void *data)
7621 {
7622   struct dwarf2_cu *cu = reader->cu;
7623
7624   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
7625
7626   /* Check if comp unit has_children.
7627      If so, read the rest of the partial symbols from this comp unit.
7628      If not, there's no more debug_info for this comp unit.  */
7629   if (has_children)
7630     load_partial_dies (reader, info_ptr, 0);
7631 }
7632
7633 /* Load the partial DIEs for a secondary CU into memory.
7634    This is also used when rereading a primary CU with load_all_dies.  */
7635
7636 static void
7637 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
7638 {
7639   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7640                            load_partial_comp_unit_reader, NULL);
7641 }
7642
7643 static void
7644 read_comp_units_from_section (struct objfile *objfile,
7645                               struct dwarf2_section_info *section,
7646                               struct dwarf2_section_info *abbrev_section,
7647                               unsigned int is_dwz,
7648                               int *n_allocated,
7649                               int *n_comp_units,
7650                               struct dwarf2_per_cu_data ***all_comp_units)
7651 {
7652   const gdb_byte *info_ptr;
7653
7654   if (dwarf_read_debug)
7655     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
7656                         get_section_name (section),
7657                         get_section_file_name (section));
7658
7659   dwarf2_read_section (objfile, section);
7660
7661   info_ptr = section->buffer;
7662
7663   while (info_ptr < section->buffer + section->size)
7664     {
7665       struct dwarf2_per_cu_data *this_cu;
7666
7667       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7668
7669       comp_unit_head cu_header;
7670       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
7671                                      info_ptr, rcuh_kind::COMPILE);
7672
7673       /* Save the compilation unit for later lookup.  */
7674       if (cu_header.unit_type != DW_UT_type)
7675         {
7676           this_cu = XOBNEW (&objfile->objfile_obstack,
7677                             struct dwarf2_per_cu_data);
7678           memset (this_cu, 0, sizeof (*this_cu));
7679         }
7680       else
7681         {
7682           auto sig_type = XOBNEW (&objfile->objfile_obstack,
7683                                   struct signatured_type);
7684           memset (sig_type, 0, sizeof (*sig_type));
7685           sig_type->signature = cu_header.signature;
7686           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7687           this_cu = &sig_type->per_cu;
7688         }
7689       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
7690       this_cu->sect_off = sect_off;
7691       this_cu->length = cu_header.length + cu_header.initial_length_size;
7692       this_cu->is_dwz = is_dwz;
7693       this_cu->objfile = objfile;
7694       this_cu->section = section;
7695
7696       if (*n_comp_units == *n_allocated)
7697         {
7698           *n_allocated *= 2;
7699           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
7700                                         *all_comp_units, *n_allocated);
7701         }
7702       (*all_comp_units)[*n_comp_units] = this_cu;
7703       ++*n_comp_units;
7704
7705       info_ptr = info_ptr + this_cu->length;
7706     }
7707 }
7708
7709 /* Create a list of all compilation units in OBJFILE.
7710    This is only done for -readnow and building partial symtabs.  */
7711
7712 static void
7713 create_all_comp_units (struct objfile *objfile)
7714 {
7715   int n_allocated;
7716   int n_comp_units;
7717   struct dwarf2_per_cu_data **all_comp_units;
7718   struct dwz_file *dwz;
7719
7720   n_comp_units = 0;
7721   n_allocated = 10;
7722   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
7723
7724   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
7725                                 &dwarf2_per_objfile->abbrev, 0,
7726                                 &n_allocated, &n_comp_units, &all_comp_units);
7727
7728   dwz = dwarf2_get_dwz_file ();
7729   if (dwz != NULL)
7730     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
7731                                   &n_allocated, &n_comp_units,
7732                                   &all_comp_units);
7733
7734   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
7735                                                   struct dwarf2_per_cu_data *,
7736                                                   n_comp_units);
7737   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
7738           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
7739   xfree (all_comp_units);
7740   dwarf2_per_objfile->n_comp_units = n_comp_units;
7741 }
7742
7743 /* Process all loaded DIEs for compilation unit CU, starting at
7744    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7745    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7746    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7747    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7748
7749 static void
7750 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7751                       CORE_ADDR *highpc, int set_addrmap,
7752                       struct dwarf2_cu *cu)
7753 {
7754   struct partial_die_info *pdi;
7755
7756   /* Now, march along the PDI's, descending into ones which have
7757      interesting children but skipping the children of the other ones,
7758      until we reach the end of the compilation unit.  */
7759
7760   pdi = first_die;
7761
7762   while (pdi != NULL)
7763     {
7764       fixup_partial_die (pdi, cu);
7765
7766       /* Anonymous namespaces or modules have no name but have interesting
7767          children, so we need to look at them.  Ditto for anonymous
7768          enums.  */
7769
7770       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
7771           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7772           || pdi->tag == DW_TAG_imported_unit)
7773         {
7774           switch (pdi->tag)
7775             {
7776             case DW_TAG_subprogram:
7777               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7778               break;
7779             case DW_TAG_constant:
7780             case DW_TAG_variable:
7781             case DW_TAG_typedef:
7782             case DW_TAG_union_type:
7783               if (!pdi->is_declaration)
7784                 {
7785                   add_partial_symbol (pdi, cu);
7786                 }
7787               break;
7788             case DW_TAG_class_type:
7789             case DW_TAG_interface_type:
7790             case DW_TAG_structure_type:
7791               if (!pdi->is_declaration)
7792                 {
7793                   add_partial_symbol (pdi, cu);
7794                 }
7795               if (cu->language == language_rust && pdi->has_children)
7796                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7797                                       set_addrmap, cu);
7798               break;
7799             case DW_TAG_enumeration_type:
7800               if (!pdi->is_declaration)
7801                 add_partial_enumeration (pdi, cu);
7802               break;
7803             case DW_TAG_base_type:
7804             case DW_TAG_subrange_type:
7805               /* File scope base type definitions are added to the partial
7806                  symbol table.  */
7807               add_partial_symbol (pdi, cu);
7808               break;
7809             case DW_TAG_namespace:
7810               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7811               break;
7812             case DW_TAG_module:
7813               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7814               break;
7815             case DW_TAG_imported_unit:
7816               {
7817                 struct dwarf2_per_cu_data *per_cu;
7818
7819                 /* For now we don't handle imported units in type units.  */
7820                 if (cu->per_cu->is_debug_types)
7821                   {
7822                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7823                              " supported in type units [in module %s]"),
7824                            objfile_name (cu->objfile));
7825                   }
7826
7827                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
7828                                                            pdi->is_dwz,
7829                                                            cu->objfile);
7830
7831                 /* Go read the partial unit, if needed.  */
7832                 if (per_cu->v.psymtab == NULL)
7833                   process_psymtab_comp_unit (per_cu, 1, cu->language);
7834
7835                 VEC_safe_push (dwarf2_per_cu_ptr,
7836                                cu->per_cu->imported_symtabs, per_cu);
7837               }
7838               break;
7839             case DW_TAG_imported_declaration:
7840               add_partial_symbol (pdi, cu);
7841               break;
7842             default:
7843               break;
7844             }
7845         }
7846
7847       /* If the die has a sibling, skip to the sibling.  */
7848
7849       pdi = pdi->die_sibling;
7850     }
7851 }
7852
7853 /* Functions used to compute the fully scoped name of a partial DIE.
7854
7855    Normally, this is simple.  For C++, the parent DIE's fully scoped
7856    name is concatenated with "::" and the partial DIE's name.
7857    Enumerators are an exception; they use the scope of their parent
7858    enumeration type, i.e. the name of the enumeration type is not
7859    prepended to the enumerator.
7860
7861    There are two complexities.  One is DW_AT_specification; in this
7862    case "parent" means the parent of the target of the specification,
7863    instead of the direct parent of the DIE.  The other is compilers
7864    which do not emit DW_TAG_namespace; in this case we try to guess
7865    the fully qualified name of structure types from their members'
7866    linkage names.  This must be done using the DIE's children rather
7867    than the children of any DW_AT_specification target.  We only need
7868    to do this for structures at the top level, i.e. if the target of
7869    any DW_AT_specification (if any; otherwise the DIE itself) does not
7870    have a parent.  */
7871
7872 /* Compute the scope prefix associated with PDI's parent, in
7873    compilation unit CU.  The result will be allocated on CU's
7874    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7875    field.  NULL is returned if no prefix is necessary.  */
7876 static const char *
7877 partial_die_parent_scope (struct partial_die_info *pdi,
7878                           struct dwarf2_cu *cu)
7879 {
7880   const char *grandparent_scope;
7881   struct partial_die_info *parent, *real_pdi;
7882
7883   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7884      then this means the parent of the specification DIE.  */
7885
7886   real_pdi = pdi;
7887   while (real_pdi->has_specification)
7888     real_pdi = find_partial_die (real_pdi->spec_offset,
7889                                  real_pdi->spec_is_dwz, cu);
7890
7891   parent = real_pdi->die_parent;
7892   if (parent == NULL)
7893     return NULL;
7894
7895   if (parent->scope_set)
7896     return parent->scope;
7897
7898   fixup_partial_die (parent, cu);
7899
7900   grandparent_scope = partial_die_parent_scope (parent, cu);
7901
7902   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7903      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7904      Work around this problem here.  */
7905   if (cu->language == language_cplus
7906       && parent->tag == DW_TAG_namespace
7907       && strcmp (parent->name, "::") == 0
7908       && grandparent_scope == NULL)
7909     {
7910       parent->scope = NULL;
7911       parent->scope_set = 1;
7912       return NULL;
7913     }
7914
7915   if (pdi->tag == DW_TAG_enumerator)
7916     /* Enumerators should not get the name of the enumeration as a prefix.  */
7917     parent->scope = grandparent_scope;
7918   else if (parent->tag == DW_TAG_namespace
7919       || parent->tag == DW_TAG_module
7920       || parent->tag == DW_TAG_structure_type
7921       || parent->tag == DW_TAG_class_type
7922       || parent->tag == DW_TAG_interface_type
7923       || parent->tag == DW_TAG_union_type
7924       || parent->tag == DW_TAG_enumeration_type)
7925     {
7926       if (grandparent_scope == NULL)
7927         parent->scope = parent->name;
7928       else
7929         parent->scope = typename_concat (&cu->comp_unit_obstack,
7930                                          grandparent_scope,
7931                                          parent->name, 0, cu);
7932     }
7933   else
7934     {
7935       /* FIXME drow/2004-04-01: What should we be doing with
7936          function-local names?  For partial symbols, we should probably be
7937          ignoring them.  */
7938       complaint (&symfile_complaints,
7939                  _("unhandled containing DIE tag %d for DIE at %d"),
7940                  parent->tag, to_underlying (pdi->sect_off));
7941       parent->scope = grandparent_scope;
7942     }
7943
7944   parent->scope_set = 1;
7945   return parent->scope;
7946 }
7947
7948 /* Return the fully scoped name associated with PDI, from compilation unit
7949    CU.  The result will be allocated with malloc.  */
7950
7951 static char *
7952 partial_die_full_name (struct partial_die_info *pdi,
7953                        struct dwarf2_cu *cu)
7954 {
7955   const char *parent_scope;
7956
7957   /* If this is a template instantiation, we can not work out the
7958      template arguments from partial DIEs.  So, unfortunately, we have
7959      to go through the full DIEs.  At least any work we do building
7960      types here will be reused if full symbols are loaded later.  */
7961   if (pdi->has_template_arguments)
7962     {
7963       fixup_partial_die (pdi, cu);
7964
7965       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7966         {
7967           struct die_info *die;
7968           struct attribute attr;
7969           struct dwarf2_cu *ref_cu = cu;
7970
7971           /* DW_FORM_ref_addr is using section offset.  */
7972           attr.name = (enum dwarf_attribute) 0;
7973           attr.form = DW_FORM_ref_addr;
7974           attr.u.unsnd = to_underlying (pdi->sect_off);
7975           die = follow_die_ref (NULL, &attr, &ref_cu);
7976
7977           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7978         }
7979     }
7980
7981   parent_scope = partial_die_parent_scope (pdi, cu);
7982   if (parent_scope == NULL)
7983     return NULL;
7984   else
7985     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7986 }
7987
7988 static void
7989 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7990 {
7991   struct objfile *objfile = cu->objfile;
7992   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7993   CORE_ADDR addr = 0;
7994   const char *actual_name = NULL;
7995   CORE_ADDR baseaddr;
7996   char *built_actual_name;
7997
7998   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7999
8000   built_actual_name = partial_die_full_name (pdi, cu);
8001   if (built_actual_name != NULL)
8002     actual_name = built_actual_name;
8003
8004   if (actual_name == NULL)
8005     actual_name = pdi->name;
8006
8007   switch (pdi->tag)
8008     {
8009     case DW_TAG_subprogram:
8010       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8011       if (pdi->is_external || cu->language == language_ada)
8012         {
8013           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8014              of the global scope.  But in Ada, we want to be able to access
8015              nested procedures globally.  So all Ada subprograms are stored
8016              in the global scope.  */
8017           add_psymbol_to_list (actual_name, strlen (actual_name),
8018                                built_actual_name != NULL,
8019                                VAR_DOMAIN, LOC_BLOCK,
8020                                &objfile->global_psymbols,
8021                                addr, cu->language, objfile);
8022         }
8023       else
8024         {
8025           add_psymbol_to_list (actual_name, strlen (actual_name),
8026                                built_actual_name != NULL,
8027                                VAR_DOMAIN, LOC_BLOCK,
8028                                &objfile->static_psymbols,
8029                                addr, cu->language, objfile);
8030         }
8031
8032       if (pdi->main_subprogram && actual_name != NULL)
8033         set_objfile_main_name (objfile, actual_name, cu->language);
8034       break;
8035     case DW_TAG_constant:
8036       {
8037         std::vector<partial_symbol *> *list;
8038
8039         if (pdi->is_external)
8040           list = &objfile->global_psymbols;
8041         else
8042           list = &objfile->static_psymbols;
8043         add_psymbol_to_list (actual_name, strlen (actual_name),
8044                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8045                              list, 0, cu->language, objfile);
8046       }
8047       break;
8048     case DW_TAG_variable:
8049       if (pdi->d.locdesc)
8050         addr = decode_locdesc (pdi->d.locdesc, cu);
8051
8052       if (pdi->d.locdesc
8053           && addr == 0
8054           && !dwarf2_per_objfile->has_section_at_zero)
8055         {
8056           /* A global or static variable may also have been stripped
8057              out by the linker if unused, in which case its address
8058              will be nullified; do not add such variables into partial
8059              symbol table then.  */
8060         }
8061       else if (pdi->is_external)
8062         {
8063           /* Global Variable.
8064              Don't enter into the minimal symbol tables as there is
8065              a minimal symbol table entry from the ELF symbols already.
8066              Enter into partial symbol table if it has a location
8067              descriptor or a type.
8068              If the location descriptor is missing, new_symbol will create
8069              a LOC_UNRESOLVED symbol, the address of the variable will then
8070              be determined from the minimal symbol table whenever the variable
8071              is referenced.
8072              The address for the partial symbol table entry is not
8073              used by GDB, but it comes in handy for debugging partial symbol
8074              table building.  */
8075
8076           if (pdi->d.locdesc || pdi->has_type)
8077             add_psymbol_to_list (actual_name, strlen (actual_name),
8078                                  built_actual_name != NULL,
8079                                  VAR_DOMAIN, LOC_STATIC,
8080                                  &objfile->global_psymbols,
8081                                  addr + baseaddr,
8082                                  cu->language, objfile);
8083         }
8084       else
8085         {
8086           int has_loc = pdi->d.locdesc != NULL;
8087
8088           /* Static Variable.  Skip symbols whose value we cannot know (those
8089              without location descriptors or constant values).  */
8090           if (!has_loc && !pdi->has_const_value)
8091             {
8092               xfree (built_actual_name);
8093               return;
8094             }
8095
8096           add_psymbol_to_list (actual_name, strlen (actual_name),
8097                                built_actual_name != NULL,
8098                                VAR_DOMAIN, LOC_STATIC,
8099                                &objfile->static_psymbols,
8100                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8101                                cu->language, objfile);
8102         }
8103       break;
8104     case DW_TAG_typedef:
8105     case DW_TAG_base_type:
8106     case DW_TAG_subrange_type:
8107       add_psymbol_to_list (actual_name, strlen (actual_name),
8108                            built_actual_name != NULL,
8109                            VAR_DOMAIN, LOC_TYPEDEF,
8110                            &objfile->static_psymbols,
8111                            0, cu->language, objfile);
8112       break;
8113     case DW_TAG_imported_declaration:
8114     case DW_TAG_namespace:
8115       add_psymbol_to_list (actual_name, strlen (actual_name),
8116                            built_actual_name != NULL,
8117                            VAR_DOMAIN, LOC_TYPEDEF,
8118                            &objfile->global_psymbols,
8119                            0, cu->language, objfile);
8120       break;
8121     case DW_TAG_module:
8122       add_psymbol_to_list (actual_name, strlen (actual_name),
8123                            built_actual_name != NULL,
8124                            MODULE_DOMAIN, LOC_TYPEDEF,
8125                            &objfile->global_psymbols,
8126                            0, cu->language, objfile);
8127       break;
8128     case DW_TAG_class_type:
8129     case DW_TAG_interface_type:
8130     case DW_TAG_structure_type:
8131     case DW_TAG_union_type:
8132     case DW_TAG_enumeration_type:
8133       /* Skip external references.  The DWARF standard says in the section
8134          about "Structure, Union, and Class Type Entries": "An incomplete
8135          structure, union or class type is represented by a structure,
8136          union or class entry that does not have a byte size attribute
8137          and that has a DW_AT_declaration attribute."  */
8138       if (!pdi->has_byte_size && pdi->is_declaration)
8139         {
8140           xfree (built_actual_name);
8141           return;
8142         }
8143
8144       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8145          static vs. global.  */
8146       add_psymbol_to_list (actual_name, strlen (actual_name),
8147                            built_actual_name != NULL,
8148                            STRUCT_DOMAIN, LOC_TYPEDEF,
8149                            cu->language == language_cplus
8150                            ? &objfile->global_psymbols
8151                            : &objfile->static_psymbols,
8152                            0, cu->language, objfile);
8153
8154       break;
8155     case DW_TAG_enumerator:
8156       add_psymbol_to_list (actual_name, strlen (actual_name),
8157                            built_actual_name != NULL,
8158                            VAR_DOMAIN, LOC_CONST,
8159                            cu->language == language_cplus
8160                            ? &objfile->global_psymbols
8161                            : &objfile->static_psymbols,
8162                            0, cu->language, objfile);
8163       break;
8164     default:
8165       break;
8166     }
8167
8168   xfree (built_actual_name);
8169 }
8170
8171 /* Read a partial die corresponding to a namespace; also, add a symbol
8172    corresponding to that namespace to the symbol table.  NAMESPACE is
8173    the name of the enclosing namespace.  */
8174
8175 static void
8176 add_partial_namespace (struct partial_die_info *pdi,
8177                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8178                        int set_addrmap, struct dwarf2_cu *cu)
8179 {
8180   /* Add a symbol for the namespace.  */
8181
8182   add_partial_symbol (pdi, cu);
8183
8184   /* Now scan partial symbols in that namespace.  */
8185
8186   if (pdi->has_children)
8187     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8188 }
8189
8190 /* Read a partial die corresponding to a Fortran module.  */
8191
8192 static void
8193 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8194                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8195 {
8196   /* Add a symbol for the namespace.  */
8197
8198   add_partial_symbol (pdi, cu);
8199
8200   /* Now scan partial symbols in that module.  */
8201
8202   if (pdi->has_children)
8203     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8204 }
8205
8206 /* Read a partial die corresponding to a subprogram and create a partial
8207    symbol for that subprogram.  When the CU language allows it, this
8208    routine also defines a partial symbol for each nested subprogram
8209    that this subprogram contains.  If SET_ADDRMAP is true, record the
8210    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
8211    and highest PC values found in PDI.
8212
8213    PDI may also be a lexical block, in which case we simply search
8214    recursively for subprograms defined inside that lexical block.
8215    Again, this is only performed when the CU language allows this
8216    type of definitions.  */
8217
8218 static void
8219 add_partial_subprogram (struct partial_die_info *pdi,
8220                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8221                         int set_addrmap, struct dwarf2_cu *cu)
8222 {
8223   if (pdi->tag == DW_TAG_subprogram)
8224     {
8225       if (pdi->has_pc_info)
8226         {
8227           if (pdi->lowpc < *lowpc)
8228             *lowpc = pdi->lowpc;
8229           if (pdi->highpc > *highpc)
8230             *highpc = pdi->highpc;
8231           if (set_addrmap)
8232             {
8233               struct objfile *objfile = cu->objfile;
8234               struct gdbarch *gdbarch = get_objfile_arch (objfile);
8235               CORE_ADDR baseaddr;
8236               CORE_ADDR highpc;
8237               CORE_ADDR lowpc;
8238
8239               baseaddr = ANOFFSET (objfile->section_offsets,
8240                                    SECT_OFF_TEXT (objfile));
8241               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
8242                                                   pdi->lowpc + baseaddr);
8243               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
8244                                                    pdi->highpc + baseaddr);
8245               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
8246                                  cu->per_cu->v.psymtab);
8247             }
8248         }
8249
8250       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8251         {
8252           if (!pdi->is_declaration)
8253             /* Ignore subprogram DIEs that do not have a name, they are
8254                illegal.  Do not emit a complaint at this point, we will
8255                do so when we convert this psymtab into a symtab.  */
8256             if (pdi->name)
8257               add_partial_symbol (pdi, cu);
8258         }
8259     }
8260
8261   if (! pdi->has_children)
8262     return;
8263
8264   if (cu->language == language_ada)
8265     {
8266       pdi = pdi->die_child;
8267       while (pdi != NULL)
8268         {
8269           fixup_partial_die (pdi, cu);
8270           if (pdi->tag == DW_TAG_subprogram
8271               || pdi->tag == DW_TAG_lexical_block)
8272             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8273           pdi = pdi->die_sibling;
8274         }
8275     }
8276 }
8277
8278 /* Read a partial die corresponding to an enumeration type.  */
8279
8280 static void
8281 add_partial_enumeration (struct partial_die_info *enum_pdi,
8282                          struct dwarf2_cu *cu)
8283 {
8284   struct partial_die_info *pdi;
8285
8286   if (enum_pdi->name != NULL)
8287     add_partial_symbol (enum_pdi, cu);
8288
8289   pdi = enum_pdi->die_child;
8290   while (pdi)
8291     {
8292       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
8293         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
8294       else
8295         add_partial_symbol (pdi, cu);
8296       pdi = pdi->die_sibling;
8297     }
8298 }
8299
8300 /* Return the initial uleb128 in the die at INFO_PTR.  */
8301
8302 static unsigned int
8303 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8304 {
8305   unsigned int bytes_read;
8306
8307   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8308 }
8309
8310 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
8311    Return the corresponding abbrev, or NULL if the number is zero (indicating
8312    an empty DIE).  In either case *BYTES_READ will be set to the length of
8313    the initial number.  */
8314
8315 static struct abbrev_info *
8316 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
8317                  struct dwarf2_cu *cu)
8318 {
8319   bfd *abfd = cu->objfile->obfd;
8320   unsigned int abbrev_number;
8321   struct abbrev_info *abbrev;
8322
8323   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8324
8325   if (abbrev_number == 0)
8326     return NULL;
8327
8328   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
8329   if (!abbrev)
8330     {
8331       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8332                " at offset 0x%x [in module %s]"),
8333              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8334              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
8335     }
8336
8337   return abbrev;
8338 }
8339
8340 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8341    Returns a pointer to the end of a series of DIEs, terminated by an empty
8342    DIE.  Any children of the skipped DIEs will also be skipped.  */
8343
8344 static const gdb_byte *
8345 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8346 {
8347   struct dwarf2_cu *cu = reader->cu;
8348   struct abbrev_info *abbrev;
8349   unsigned int bytes_read;
8350
8351   while (1)
8352     {
8353       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
8354       if (abbrev == NULL)
8355         return info_ptr + bytes_read;
8356       else
8357         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8358     }
8359 }
8360
8361 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8362    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8363    abbrev corresponding to that skipped uleb128 should be passed in
8364    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8365    children.  */
8366
8367 static const gdb_byte *
8368 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8369               struct abbrev_info *abbrev)
8370 {
8371   unsigned int bytes_read;
8372   struct attribute attr;
8373   bfd *abfd = reader->abfd;
8374   struct dwarf2_cu *cu = reader->cu;
8375   const gdb_byte *buffer = reader->buffer;
8376   const gdb_byte *buffer_end = reader->buffer_end;
8377   unsigned int form, i;
8378
8379   for (i = 0; i < abbrev->num_attrs; i++)
8380     {
8381       /* The only abbrev we care about is DW_AT_sibling.  */
8382       if (abbrev->attrs[i].name == DW_AT_sibling)
8383         {
8384           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
8385           if (attr.form == DW_FORM_ref_addr)
8386             complaint (&symfile_complaints,
8387                        _("ignoring absolute DW_AT_sibling"));
8388           else
8389             {
8390               sect_offset off = dwarf2_get_ref_die_offset (&attr);
8391               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8392
8393               if (sibling_ptr < info_ptr)
8394                 complaint (&symfile_complaints,
8395                            _("DW_AT_sibling points backwards"));
8396               else if (sibling_ptr > reader->buffer_end)
8397                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
8398               else
8399                 return sibling_ptr;
8400             }
8401         }
8402
8403       /* If it isn't DW_AT_sibling, skip this attribute.  */
8404       form = abbrev->attrs[i].form;
8405     skip_attribute:
8406       switch (form)
8407         {
8408         case DW_FORM_ref_addr:
8409           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8410              and later it is offset sized.  */
8411           if (cu->header.version == 2)
8412             info_ptr += cu->header.addr_size;
8413           else
8414             info_ptr += cu->header.offset_size;
8415           break;
8416         case DW_FORM_GNU_ref_alt:
8417           info_ptr += cu->header.offset_size;
8418           break;
8419         case DW_FORM_addr:
8420           info_ptr += cu->header.addr_size;
8421           break;
8422         case DW_FORM_data1:
8423         case DW_FORM_ref1:
8424         case DW_FORM_flag:
8425           info_ptr += 1;
8426           break;
8427         case DW_FORM_flag_present:
8428         case DW_FORM_implicit_const:
8429           break;
8430         case DW_FORM_data2:
8431         case DW_FORM_ref2:
8432           info_ptr += 2;
8433           break;
8434         case DW_FORM_data4:
8435         case DW_FORM_ref4:
8436           info_ptr += 4;
8437           break;
8438         case DW_FORM_data8:
8439         case DW_FORM_ref8:
8440         case DW_FORM_ref_sig8:
8441           info_ptr += 8;
8442           break;
8443         case DW_FORM_data16:
8444           info_ptr += 16;
8445           break;
8446         case DW_FORM_string:
8447           read_direct_string (abfd, info_ptr, &bytes_read);
8448           info_ptr += bytes_read;
8449           break;
8450         case DW_FORM_sec_offset:
8451         case DW_FORM_strp:
8452         case DW_FORM_GNU_strp_alt:
8453           info_ptr += cu->header.offset_size;
8454           break;
8455         case DW_FORM_exprloc:
8456         case DW_FORM_block:
8457           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8458           info_ptr += bytes_read;
8459           break;
8460         case DW_FORM_block1:
8461           info_ptr += 1 + read_1_byte (abfd, info_ptr);
8462           break;
8463         case DW_FORM_block2:
8464           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8465           break;
8466         case DW_FORM_block4:
8467           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8468           break;
8469         case DW_FORM_sdata:
8470         case DW_FORM_udata:
8471         case DW_FORM_ref_udata:
8472         case DW_FORM_GNU_addr_index:
8473         case DW_FORM_GNU_str_index:
8474           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
8475           break;
8476         case DW_FORM_indirect:
8477           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8478           info_ptr += bytes_read;
8479           /* We need to continue parsing from here, so just go back to
8480              the top.  */
8481           goto skip_attribute;
8482
8483         default:
8484           error (_("Dwarf Error: Cannot handle %s "
8485                    "in DWARF reader [in module %s]"),
8486                  dwarf_form_name (form),
8487                  bfd_get_filename (abfd));
8488         }
8489     }
8490
8491   if (abbrev->has_children)
8492     return skip_children (reader, info_ptr);
8493   else
8494     return info_ptr;
8495 }
8496
8497 /* Locate ORIG_PDI's sibling.
8498    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
8499
8500 static const gdb_byte *
8501 locate_pdi_sibling (const struct die_reader_specs *reader,
8502                     struct partial_die_info *orig_pdi,
8503                     const gdb_byte *info_ptr)
8504 {
8505   /* Do we know the sibling already?  */
8506
8507   if (orig_pdi->sibling)
8508     return orig_pdi->sibling;
8509
8510   /* Are there any children to deal with?  */
8511
8512   if (!orig_pdi->has_children)
8513     return info_ptr;
8514
8515   /* Skip the children the long way.  */
8516
8517   return skip_children (reader, info_ptr);
8518 }
8519
8520 /* Expand this partial symbol table into a full symbol table.  SELF is
8521    not NULL.  */
8522
8523 static void
8524 dwarf2_read_symtab (struct partial_symtab *self,
8525                     struct objfile *objfile)
8526 {
8527   if (self->readin)
8528     {
8529       warning (_("bug: psymtab for %s is already read in."),
8530                self->filename);
8531     }
8532   else
8533     {
8534       if (info_verbose)
8535         {
8536           printf_filtered (_("Reading in symbols for %s..."),
8537                            self->filename);
8538           gdb_flush (gdb_stdout);
8539         }
8540
8541       /* Restore our global data.  */
8542       dwarf2_per_objfile
8543         = (struct dwarf2_per_objfile *) objfile_data (objfile,
8544                                                       dwarf2_objfile_data_key);
8545
8546       /* If this psymtab is constructed from a debug-only objfile, the
8547          has_section_at_zero flag will not necessarily be correct.  We
8548          can get the correct value for this flag by looking at the data
8549          associated with the (presumably stripped) associated objfile.  */
8550       if (objfile->separate_debug_objfile_backlink)
8551         {
8552           struct dwarf2_per_objfile *dpo_backlink
8553             = ((struct dwarf2_per_objfile *)
8554                objfile_data (objfile->separate_debug_objfile_backlink,
8555                              dwarf2_objfile_data_key));
8556
8557           dwarf2_per_objfile->has_section_at_zero
8558             = dpo_backlink->has_section_at_zero;
8559         }
8560
8561       dwarf2_per_objfile->reading_partial_symbols = 0;
8562
8563       psymtab_to_symtab_1 (self);
8564
8565       /* Finish up the debug error message.  */
8566       if (info_verbose)
8567         printf_filtered (_("done.\n"));
8568     }
8569
8570   process_cu_includes ();
8571 }
8572 \f
8573 /* Reading in full CUs.  */
8574
8575 /* Add PER_CU to the queue.  */
8576
8577 static void
8578 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
8579                  enum language pretend_language)
8580 {
8581   struct dwarf2_queue_item *item;
8582
8583   per_cu->queued = 1;
8584   item = XNEW (struct dwarf2_queue_item);
8585   item->per_cu = per_cu;
8586   item->pretend_language = pretend_language;
8587   item->next = NULL;
8588
8589   if (dwarf2_queue == NULL)
8590     dwarf2_queue = item;
8591   else
8592     dwarf2_queue_tail->next = item;
8593
8594   dwarf2_queue_tail = item;
8595 }
8596
8597 /* If PER_CU is not yet queued, add it to the queue.
8598    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8599    dependency.
8600    The result is non-zero if PER_CU was queued, otherwise the result is zero
8601    meaning either PER_CU is already queued or it is already loaded.
8602
8603    N.B. There is an invariant here that if a CU is queued then it is loaded.
8604    The caller is required to load PER_CU if we return non-zero.  */
8605
8606 static int
8607 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8608                        struct dwarf2_per_cu_data *per_cu,
8609                        enum language pretend_language)
8610 {
8611   /* We may arrive here during partial symbol reading, if we need full
8612      DIEs to process an unusual case (e.g. template arguments).  Do
8613      not queue PER_CU, just tell our caller to load its DIEs.  */
8614   if (dwarf2_per_objfile->reading_partial_symbols)
8615     {
8616       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
8617         return 1;
8618       return 0;
8619     }
8620
8621   /* Mark the dependence relation so that we don't flush PER_CU
8622      too early.  */
8623   if (dependent_cu != NULL)
8624     dwarf2_add_dependence (dependent_cu, per_cu);
8625
8626   /* If it's already on the queue, we have nothing to do.  */
8627   if (per_cu->queued)
8628     return 0;
8629
8630   /* If the compilation unit is already loaded, just mark it as
8631      used.  */
8632   if (per_cu->cu != NULL)
8633     {
8634       per_cu->cu->last_used = 0;
8635       return 0;
8636     }
8637
8638   /* Add it to the queue.  */
8639   queue_comp_unit (per_cu, pretend_language);
8640
8641   return 1;
8642 }
8643
8644 /* Process the queue.  */
8645
8646 static void
8647 process_queue (void)
8648 {
8649   struct dwarf2_queue_item *item, *next_item;
8650
8651   if (dwarf_read_debug)
8652     {
8653       fprintf_unfiltered (gdb_stdlog,
8654                           "Expanding one or more symtabs of objfile %s ...\n",
8655                           objfile_name (dwarf2_per_objfile->objfile));
8656     }
8657
8658   /* The queue starts out with one item, but following a DIE reference
8659      may load a new CU, adding it to the end of the queue.  */
8660   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
8661     {
8662       if ((dwarf2_per_objfile->using_index
8663            ? !item->per_cu->v.quick->compunit_symtab
8664            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
8665           /* Skip dummy CUs.  */
8666           && item->per_cu->cu != NULL)
8667         {
8668           struct dwarf2_per_cu_data *per_cu = item->per_cu;
8669           unsigned int debug_print_threshold;
8670           char buf[100];
8671
8672           if (per_cu->is_debug_types)
8673             {
8674               struct signatured_type *sig_type =
8675                 (struct signatured_type *) per_cu;
8676
8677               sprintf (buf, "TU %s at offset 0x%x",
8678                        hex_string (sig_type->signature),
8679                        to_underlying (per_cu->sect_off));
8680               /* There can be 100s of TUs.
8681                  Only print them in verbose mode.  */
8682               debug_print_threshold = 2;
8683             }
8684           else
8685             {
8686               sprintf (buf, "CU at offset 0x%x",
8687                        to_underlying (per_cu->sect_off));
8688               debug_print_threshold = 1;
8689             }
8690
8691           if (dwarf_read_debug >= debug_print_threshold)
8692             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
8693
8694           if (per_cu->is_debug_types)
8695             process_full_type_unit (per_cu, item->pretend_language);
8696           else
8697             process_full_comp_unit (per_cu, item->pretend_language);
8698
8699           if (dwarf_read_debug >= debug_print_threshold)
8700             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
8701         }
8702
8703       item->per_cu->queued = 0;
8704       next_item = item->next;
8705       xfree (item);
8706     }
8707
8708   dwarf2_queue_tail = NULL;
8709
8710   if (dwarf_read_debug)
8711     {
8712       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
8713                           objfile_name (dwarf2_per_objfile->objfile));
8714     }
8715 }
8716
8717 /* Free all allocated queue entries.  This function only releases anything if
8718    an error was thrown; if the queue was processed then it would have been
8719    freed as we went along.  */
8720
8721 static void
8722 dwarf2_release_queue (void *dummy)
8723 {
8724   struct dwarf2_queue_item *item, *last;
8725
8726   item = dwarf2_queue;
8727   while (item)
8728     {
8729       /* Anything still marked queued is likely to be in an
8730          inconsistent state, so discard it.  */
8731       if (item->per_cu->queued)
8732         {
8733           if (item->per_cu->cu != NULL)
8734             free_one_cached_comp_unit (item->per_cu);
8735           item->per_cu->queued = 0;
8736         }
8737
8738       last = item;
8739       item = item->next;
8740       xfree (last);
8741     }
8742
8743   dwarf2_queue = dwarf2_queue_tail = NULL;
8744 }
8745
8746 /* Read in full symbols for PST, and anything it depends on.  */
8747
8748 static void
8749 psymtab_to_symtab_1 (struct partial_symtab *pst)
8750 {
8751   struct dwarf2_per_cu_data *per_cu;
8752   int i;
8753
8754   if (pst->readin)
8755     return;
8756
8757   for (i = 0; i < pst->number_of_dependencies; i++)
8758     if (!pst->dependencies[i]->readin
8759         && pst->dependencies[i]->user == NULL)
8760       {
8761         /* Inform about additional files that need to be read in.  */
8762         if (info_verbose)
8763           {
8764             /* FIXME: i18n: Need to make this a single string.  */
8765             fputs_filtered (" ", gdb_stdout);
8766             wrap_here ("");
8767             fputs_filtered ("and ", gdb_stdout);
8768             wrap_here ("");
8769             printf_filtered ("%s...", pst->dependencies[i]->filename);
8770             wrap_here ("");     /* Flush output.  */
8771             gdb_flush (gdb_stdout);
8772           }
8773         psymtab_to_symtab_1 (pst->dependencies[i]);
8774       }
8775
8776   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
8777
8778   if (per_cu == NULL)
8779     {
8780       /* It's an include file, no symbols to read for it.
8781          Everything is in the parent symtab.  */
8782       pst->readin = 1;
8783       return;
8784     }
8785
8786   dw2_do_instantiate_symtab (per_cu);
8787 }
8788
8789 /* Trivial hash function for die_info: the hash value of a DIE
8790    is its offset in .debug_info for this objfile.  */
8791
8792 static hashval_t
8793 die_hash (const void *item)
8794 {
8795   const struct die_info *die = (const struct die_info *) item;
8796
8797   return to_underlying (die->sect_off);
8798 }
8799
8800 /* Trivial comparison function for die_info structures: two DIEs
8801    are equal if they have the same offset.  */
8802
8803 static int
8804 die_eq (const void *item_lhs, const void *item_rhs)
8805 {
8806   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8807   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8808
8809   return die_lhs->sect_off == die_rhs->sect_off;
8810 }
8811
8812 /* die_reader_func for load_full_comp_unit.
8813    This is identical to read_signatured_type_reader,
8814    but is kept separate for now.  */
8815
8816 static void
8817 load_full_comp_unit_reader (const struct die_reader_specs *reader,
8818                             const gdb_byte *info_ptr,
8819                             struct die_info *comp_unit_die,
8820                             int has_children,
8821                             void *data)
8822 {
8823   struct dwarf2_cu *cu = reader->cu;
8824   enum language *language_ptr = (enum language *) data;
8825
8826   gdb_assert (cu->die_hash == NULL);
8827   cu->die_hash =
8828     htab_create_alloc_ex (cu->header.length / 12,
8829                           die_hash,
8830                           die_eq,
8831                           NULL,
8832                           &cu->comp_unit_obstack,
8833                           hashtab_obstack_allocate,
8834                           dummy_obstack_deallocate);
8835
8836   if (has_children)
8837     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
8838                                                   &info_ptr, comp_unit_die);
8839   cu->dies = comp_unit_die;
8840   /* comp_unit_die is not stored in die_hash, no need.  */
8841
8842   /* We try not to read any attributes in this function, because not
8843      all CUs needed for references have been loaded yet, and symbol
8844      table processing isn't initialized.  But we have to set the CU language,
8845      or we won't be able to build types correctly.
8846      Similarly, if we do not read the producer, we can not apply
8847      producer-specific interpretation.  */
8848   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8849 }
8850
8851 /* Load the DIEs associated with PER_CU into memory.  */
8852
8853 static void
8854 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8855                      enum language pretend_language)
8856 {
8857   gdb_assert (! this_cu->is_debug_types);
8858
8859   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8860                            load_full_comp_unit_reader, &pretend_language);
8861 }
8862
8863 /* Add a DIE to the delayed physname list.  */
8864
8865 static void
8866 add_to_method_list (struct type *type, int fnfield_index, int index,
8867                     const char *name, struct die_info *die,
8868                     struct dwarf2_cu *cu)
8869 {
8870   struct delayed_method_info mi;
8871   mi.type = type;
8872   mi.fnfield_index = fnfield_index;
8873   mi.index = index;
8874   mi.name = name;
8875   mi.die = die;
8876   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8877 }
8878
8879 /* A cleanup for freeing the delayed method list.  */
8880
8881 static void
8882 free_delayed_list (void *ptr)
8883 {
8884   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8885   if (cu->method_list != NULL)
8886     {
8887       VEC_free (delayed_method_info, cu->method_list);
8888       cu->method_list = NULL;
8889     }
8890 }
8891
8892 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8893    "const" / "volatile".  If so, decrements LEN by the length of the
8894    modifier and return true.  Otherwise return false.  */
8895
8896 template<size_t N>
8897 static bool
8898 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8899 {
8900   size_t mod_len = sizeof (mod) - 1;
8901   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8902     {
8903       len -= mod_len;
8904       return true;
8905     }
8906   return false;
8907 }
8908
8909 /* Compute the physnames of any methods on the CU's method list.
8910
8911    The computation of method physnames is delayed in order to avoid the
8912    (bad) condition that one of the method's formal parameters is of an as yet
8913    incomplete type.  */
8914
8915 static void
8916 compute_delayed_physnames (struct dwarf2_cu *cu)
8917 {
8918   int i;
8919   struct delayed_method_info *mi;
8920
8921   /* Only C++ delays computing physnames.  */
8922   if (VEC_empty (delayed_method_info, cu->method_list))
8923     return;
8924   gdb_assert (cu->language == language_cplus);
8925
8926   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8927     {
8928       const char *physname;
8929       struct fn_fieldlist *fn_flp
8930         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8931       physname = dwarf2_physname (mi->name, mi->die, cu);
8932       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8933         = physname ? physname : "";
8934
8935       /* Since there's no tag to indicate whether a method is a
8936          const/volatile overload, extract that information out of the
8937          demangled name.  */
8938       if (physname != NULL)
8939         {
8940           size_t len = strlen (physname);
8941
8942           while (1)
8943             {
8944               if (physname[len] == ')') /* shortcut */
8945                 break;
8946               else if (check_modifier (physname, len, " const"))
8947                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8948               else if (check_modifier (physname, len, " volatile"))
8949                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8950               else
8951                 break;
8952             }
8953         }
8954     }
8955 }
8956
8957 /* Go objects should be embedded in a DW_TAG_module DIE,
8958    and it's not clear if/how imported objects will appear.
8959    To keep Go support simple until that's worked out,
8960    go back through what we've read and create something usable.
8961    We could do this while processing each DIE, and feels kinda cleaner,
8962    but that way is more invasive.
8963    This is to, for example, allow the user to type "p var" or "b main"
8964    without having to specify the package name, and allow lookups
8965    of module.object to work in contexts that use the expression
8966    parser.  */
8967
8968 static void
8969 fixup_go_packaging (struct dwarf2_cu *cu)
8970 {
8971   char *package_name = NULL;
8972   struct pending *list;
8973   int i;
8974
8975   for (list = global_symbols; list != NULL; list = list->next)
8976     {
8977       for (i = 0; i < list->nsyms; ++i)
8978         {
8979           struct symbol *sym = list->symbol[i];
8980
8981           if (SYMBOL_LANGUAGE (sym) == language_go
8982               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8983             {
8984               char *this_package_name = go_symbol_package_name (sym);
8985
8986               if (this_package_name == NULL)
8987                 continue;
8988               if (package_name == NULL)
8989                 package_name = this_package_name;
8990               else
8991                 {
8992                   if (strcmp (package_name, this_package_name) != 0)
8993                     complaint (&symfile_complaints,
8994                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8995                                (symbol_symtab (sym) != NULL
8996                                 ? symtab_to_filename_for_display
8997                                     (symbol_symtab (sym))
8998                                 : objfile_name (cu->objfile)),
8999                                this_package_name, package_name);
9000                   xfree (this_package_name);
9001                 }
9002             }
9003         }
9004     }
9005
9006   if (package_name != NULL)
9007     {
9008       struct objfile *objfile = cu->objfile;
9009       const char *saved_package_name
9010         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9011                                         package_name,
9012                                         strlen (package_name));
9013       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9014                                      saved_package_name);
9015       struct symbol *sym;
9016
9017       TYPE_TAG_NAME (type) = TYPE_NAME (type);
9018
9019       sym = allocate_symbol (objfile);
9020       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9021       SYMBOL_SET_NAMES (sym, saved_package_name,
9022                         strlen (saved_package_name), 0, objfile);
9023       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9024          e.g., "main" finds the "main" module and not C's main().  */
9025       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9026       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9027       SYMBOL_TYPE (sym) = type;
9028
9029       add_symbol_to_list (sym, &global_symbols);
9030
9031       xfree (package_name);
9032     }
9033 }
9034
9035 /* Return the symtab for PER_CU.  This works properly regardless of
9036    whether we're using the index or psymtabs.  */
9037
9038 static struct compunit_symtab *
9039 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
9040 {
9041   return (dwarf2_per_objfile->using_index
9042           ? per_cu->v.quick->compunit_symtab
9043           : per_cu->v.psymtab->compunit_symtab);
9044 }
9045
9046 /* A helper function for computing the list of all symbol tables
9047    included by PER_CU.  */
9048
9049 static void
9050 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
9051                                 htab_t all_children, htab_t all_type_symtabs,
9052                                 struct dwarf2_per_cu_data *per_cu,
9053                                 struct compunit_symtab *immediate_parent)
9054 {
9055   void **slot;
9056   int ix;
9057   struct compunit_symtab *cust;
9058   struct dwarf2_per_cu_data *iter;
9059
9060   slot = htab_find_slot (all_children, per_cu, INSERT);
9061   if (*slot != NULL)
9062     {
9063       /* This inclusion and its children have been processed.  */
9064       return;
9065     }
9066
9067   *slot = per_cu;
9068   /* Only add a CU if it has a symbol table.  */
9069   cust = get_compunit_symtab (per_cu);
9070   if (cust != NULL)
9071     {
9072       /* If this is a type unit only add its symbol table if we haven't
9073          seen it yet (type unit per_cu's can share symtabs).  */
9074       if (per_cu->is_debug_types)
9075         {
9076           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9077           if (*slot == NULL)
9078             {
9079               *slot = cust;
9080               VEC_safe_push (compunit_symtab_ptr, *result, cust);
9081               if (cust->user == NULL)
9082                 cust->user = immediate_parent;
9083             }
9084         }
9085       else
9086         {
9087           VEC_safe_push (compunit_symtab_ptr, *result, cust);
9088           if (cust->user == NULL)
9089             cust->user = immediate_parent;
9090         }
9091     }
9092
9093   for (ix = 0;
9094        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
9095        ++ix)
9096     {
9097       recursively_compute_inclusions (result, all_children,
9098                                       all_type_symtabs, iter, cust);
9099     }
9100 }
9101
9102 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9103    PER_CU.  */
9104
9105 static void
9106 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
9107 {
9108   gdb_assert (! per_cu->is_debug_types);
9109
9110   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
9111     {
9112       int ix, len;
9113       struct dwarf2_per_cu_data *per_cu_iter;
9114       struct compunit_symtab *compunit_symtab_iter;
9115       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
9116       htab_t all_children, all_type_symtabs;
9117       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
9118
9119       /* If we don't have a symtab, we can just skip this case.  */
9120       if (cust == NULL)
9121         return;
9122
9123       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9124                                         NULL, xcalloc, xfree);
9125       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9126                                             NULL, xcalloc, xfree);
9127
9128       for (ix = 0;
9129            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
9130                         ix, per_cu_iter);
9131            ++ix)
9132         {
9133           recursively_compute_inclusions (&result_symtabs, all_children,
9134                                           all_type_symtabs, per_cu_iter,
9135                                           cust);
9136         }
9137
9138       /* Now we have a transitive closure of all the included symtabs.  */
9139       len = VEC_length (compunit_symtab_ptr, result_symtabs);
9140       cust->includes
9141         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
9142                      struct compunit_symtab *, len + 1);
9143       for (ix = 0;
9144            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
9145                         compunit_symtab_iter);
9146            ++ix)
9147         cust->includes[ix] = compunit_symtab_iter;
9148       cust->includes[len] = NULL;
9149
9150       VEC_free (compunit_symtab_ptr, result_symtabs);
9151       htab_delete (all_children);
9152       htab_delete (all_type_symtabs);
9153     }
9154 }
9155
9156 /* Compute the 'includes' field for the symtabs of all the CUs we just
9157    read.  */
9158
9159 static void
9160 process_cu_includes (void)
9161 {
9162   int ix;
9163   struct dwarf2_per_cu_data *iter;
9164
9165   for (ix = 0;
9166        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
9167                     ix, iter);
9168        ++ix)
9169     {
9170       if (! iter->is_debug_types)
9171         compute_compunit_symtab_includes (iter);
9172     }
9173
9174   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
9175 }
9176
9177 /* Generate full symbol information for PER_CU, whose DIEs have
9178    already been loaded into memory.  */
9179
9180 static void
9181 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
9182                         enum language pretend_language)
9183 {
9184   struct dwarf2_cu *cu = per_cu->cu;
9185   struct objfile *objfile = per_cu->objfile;
9186   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9187   CORE_ADDR lowpc, highpc;
9188   struct compunit_symtab *cust;
9189   struct cleanup *delayed_list_cleanup;
9190   CORE_ADDR baseaddr;
9191   struct block *static_block;
9192   CORE_ADDR addr;
9193
9194   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9195
9196   buildsym_init ();
9197   scoped_free_pendings free_pending;
9198   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
9199
9200   cu->list_in_scope = &file_symbols;
9201
9202   cu->language = pretend_language;
9203   cu->language_defn = language_def (cu->language);
9204
9205   /* Do line number decoding in read_file_scope () */
9206   process_die (cu->dies, cu);
9207
9208   /* For now fudge the Go package.  */
9209   if (cu->language == language_go)
9210     fixup_go_packaging (cu);
9211
9212   /* Now that we have processed all the DIEs in the CU, all the types 
9213      should be complete, and it should now be safe to compute all of the
9214      physnames.  */
9215   compute_delayed_physnames (cu);
9216   do_cleanups (delayed_list_cleanup);
9217
9218   /* Some compilers don't define a DW_AT_high_pc attribute for the
9219      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9220      it, by scanning the DIE's below the compilation unit.  */
9221   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9222
9223   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
9224   static_block = end_symtab_get_static_block (addr, 0, 1);
9225
9226   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
9227      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
9228      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
9229      addrmap to help ensure it has an accurate map of pc values belonging to
9230      this comp unit.  */
9231   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
9232
9233   cust = end_symtab_from_static_block (static_block,
9234                                        SECT_OFF_TEXT (objfile), 0);
9235
9236   if (cust != NULL)
9237     {
9238       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
9239
9240       /* Set symtab language to language from DW_AT_language.  If the
9241          compilation is from a C file generated by language preprocessors, do
9242          not set the language if it was already deduced by start_subfile.  */
9243       if (!(cu->language == language_c
9244             && COMPUNIT_FILETABS (cust)->language != language_unknown))
9245         COMPUNIT_FILETABS (cust)->language = cu->language;
9246
9247       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
9248          produce DW_AT_location with location lists but it can be possibly
9249          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
9250          there were bugs in prologue debug info, fixed later in GCC-4.5
9251          by "unwind info for epilogues" patch (which is not directly related).
9252
9253          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
9254          needed, it would be wrong due to missing DW_AT_producer there.
9255
9256          Still one can confuse GDB by using non-standard GCC compilation
9257          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
9258          */ 
9259       if (cu->has_loclist && gcc_4_minor >= 5)
9260         cust->locations_valid = 1;
9261
9262       if (gcc_4_minor >= 5)
9263         cust->epilogue_unwind_valid = 1;
9264
9265       cust->call_site_htab = cu->call_site_htab;
9266     }
9267
9268   if (dwarf2_per_objfile->using_index)
9269     per_cu->v.quick->compunit_symtab = cust;
9270   else
9271     {
9272       struct partial_symtab *pst = per_cu->v.psymtab;
9273       pst->compunit_symtab = cust;
9274       pst->readin = 1;
9275     }
9276
9277   /* Push it for inclusion processing later.  */
9278   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
9279 }
9280
9281 /* Generate full symbol information for type unit PER_CU, whose DIEs have
9282    already been loaded into memory.  */
9283
9284 static void
9285 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
9286                         enum language pretend_language)
9287 {
9288   struct dwarf2_cu *cu = per_cu->cu;
9289   struct objfile *objfile = per_cu->objfile;
9290   struct compunit_symtab *cust;
9291   struct cleanup *delayed_list_cleanup;
9292   struct signatured_type *sig_type;
9293
9294   gdb_assert (per_cu->is_debug_types);
9295   sig_type = (struct signatured_type *) per_cu;
9296
9297   buildsym_init ();
9298   scoped_free_pendings free_pending;
9299   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
9300
9301   cu->list_in_scope = &file_symbols;
9302
9303   cu->language = pretend_language;
9304   cu->language_defn = language_def (cu->language);
9305
9306   /* The symbol tables are set up in read_type_unit_scope.  */
9307   process_die (cu->dies, cu);
9308
9309   /* For now fudge the Go package.  */
9310   if (cu->language == language_go)
9311     fixup_go_packaging (cu);
9312
9313   /* Now that we have processed all the DIEs in the CU, all the types 
9314      should be complete, and it should now be safe to compute all of the
9315      physnames.  */
9316   compute_delayed_physnames (cu);
9317   do_cleanups (delayed_list_cleanup);
9318
9319   /* TUs share symbol tables.
9320      If this is the first TU to use this symtab, complete the construction
9321      of it with end_expandable_symtab.  Otherwise, complete the addition of
9322      this TU's symbols to the existing symtab.  */
9323   if (sig_type->type_unit_group->compunit_symtab == NULL)
9324     {
9325       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
9326       sig_type->type_unit_group->compunit_symtab = cust;
9327
9328       if (cust != NULL)
9329         {
9330           /* Set symtab language to language from DW_AT_language.  If the
9331              compilation is from a C file generated by language preprocessors,
9332              do not set the language if it was already deduced by
9333              start_subfile.  */
9334           if (!(cu->language == language_c
9335                 && COMPUNIT_FILETABS (cust)->language != language_c))
9336             COMPUNIT_FILETABS (cust)->language = cu->language;
9337         }
9338     }
9339   else
9340     {
9341       augment_type_symtab ();
9342       cust = sig_type->type_unit_group->compunit_symtab;
9343     }
9344
9345   if (dwarf2_per_objfile->using_index)
9346     per_cu->v.quick->compunit_symtab = cust;
9347   else
9348     {
9349       struct partial_symtab *pst = per_cu->v.psymtab;
9350       pst->compunit_symtab = cust;
9351       pst->readin = 1;
9352     }
9353 }
9354
9355 /* Process an imported unit DIE.  */
9356
9357 static void
9358 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
9359 {
9360   struct attribute *attr;
9361
9362   /* For now we don't handle imported units in type units.  */
9363   if (cu->per_cu->is_debug_types)
9364     {
9365       error (_("Dwarf Error: DW_TAG_imported_unit is not"
9366                " supported in type units [in module %s]"),
9367              objfile_name (cu->objfile));
9368     }
9369
9370   attr = dwarf2_attr (die, DW_AT_import, cu);
9371   if (attr != NULL)
9372     {
9373       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9374       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
9375       dwarf2_per_cu_data *per_cu
9376         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
9377
9378       /* If necessary, add it to the queue and load its DIEs.  */
9379       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
9380         load_full_comp_unit (per_cu, cu->language);
9381
9382       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
9383                      per_cu);
9384     }
9385 }
9386
9387 /* RAII object that represents a process_die scope: i.e.,
9388    starts/finishes processing a DIE.  */
9389 class process_die_scope
9390 {
9391 public:
9392   process_die_scope (die_info *die, dwarf2_cu *cu)
9393     : m_die (die), m_cu (cu)
9394   {
9395     /* We should only be processing DIEs not already in process.  */
9396     gdb_assert (!m_die->in_process);
9397     m_die->in_process = true;
9398   }
9399
9400   ~process_die_scope ()
9401   {
9402     m_die->in_process = false;
9403
9404     /* If we're done processing the DIE for the CU that owns the line
9405        header, we don't need the line header anymore.  */
9406     if (m_cu->line_header_die_owner == m_die)
9407       {
9408         delete m_cu->line_header;
9409         m_cu->line_header = NULL;
9410         m_cu->line_header_die_owner = NULL;
9411       }
9412   }
9413
9414 private:
9415   die_info *m_die;
9416   dwarf2_cu *m_cu;
9417 };
9418
9419 /* Process a die and its children.  */
9420
9421 static void
9422 process_die (struct die_info *die, struct dwarf2_cu *cu)
9423 {
9424   process_die_scope scope (die, cu);
9425
9426   switch (die->tag)
9427     {
9428     case DW_TAG_padding:
9429       break;
9430     case DW_TAG_compile_unit:
9431     case DW_TAG_partial_unit:
9432       read_file_scope (die, cu);
9433       break;
9434     case DW_TAG_type_unit:
9435       read_type_unit_scope (die, cu);
9436       break;
9437     case DW_TAG_subprogram:
9438     case DW_TAG_inlined_subroutine:
9439       read_func_scope (die, cu);
9440       break;
9441     case DW_TAG_lexical_block:
9442     case DW_TAG_try_block:
9443     case DW_TAG_catch_block:
9444       read_lexical_block_scope (die, cu);
9445       break;
9446     case DW_TAG_call_site:
9447     case DW_TAG_GNU_call_site:
9448       read_call_site_scope (die, cu);
9449       break;
9450     case DW_TAG_class_type:
9451     case DW_TAG_interface_type:
9452     case DW_TAG_structure_type:
9453     case DW_TAG_union_type:
9454       process_structure_scope (die, cu);
9455       break;
9456     case DW_TAG_enumeration_type:
9457       process_enumeration_scope (die, cu);
9458       break;
9459
9460     /* These dies have a type, but processing them does not create
9461        a symbol or recurse to process the children.  Therefore we can
9462        read them on-demand through read_type_die.  */
9463     case DW_TAG_subroutine_type:
9464     case DW_TAG_set_type:
9465     case DW_TAG_array_type:
9466     case DW_TAG_pointer_type:
9467     case DW_TAG_ptr_to_member_type:
9468     case DW_TAG_reference_type:
9469     case DW_TAG_rvalue_reference_type:
9470     case DW_TAG_string_type:
9471       break;
9472
9473     case DW_TAG_base_type:
9474     case DW_TAG_subrange_type:
9475     case DW_TAG_typedef:
9476       /* Add a typedef symbol for the type definition, if it has a
9477          DW_AT_name.  */
9478       new_symbol (die, read_type_die (die, cu), cu);
9479       break;
9480     case DW_TAG_common_block:
9481       read_common_block (die, cu);
9482       break;
9483     case DW_TAG_common_inclusion:
9484       break;
9485     case DW_TAG_namespace:
9486       cu->processing_has_namespace_info = 1;
9487       read_namespace (die, cu);
9488       break;
9489     case DW_TAG_module:
9490       cu->processing_has_namespace_info = 1;
9491       read_module (die, cu);
9492       break;
9493     case DW_TAG_imported_declaration:
9494       cu->processing_has_namespace_info = 1;
9495       if (read_namespace_alias (die, cu))
9496         break;
9497       /* The declaration is not a global namespace alias: fall through.  */
9498     case DW_TAG_imported_module:
9499       cu->processing_has_namespace_info = 1;
9500       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
9501                                  || cu->language != language_fortran))
9502         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
9503                    dwarf_tag_name (die->tag));
9504       read_import_statement (die, cu);
9505       break;
9506
9507     case DW_TAG_imported_unit:
9508       process_imported_unit_die (die, cu);
9509       break;
9510
9511     case DW_TAG_variable:
9512       read_variable (die, cu);
9513       break;
9514
9515     default:
9516       new_symbol (die, NULL, cu);
9517       break;
9518     }
9519 }
9520 \f
9521 /* DWARF name computation.  */
9522
9523 /* A helper function for dwarf2_compute_name which determines whether DIE
9524    needs to have the name of the scope prepended to the name listed in the
9525    die.  */
9526
9527 static int
9528 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
9529 {
9530   struct attribute *attr;
9531
9532   switch (die->tag)
9533     {
9534     case DW_TAG_namespace:
9535     case DW_TAG_typedef:
9536     case DW_TAG_class_type:
9537     case DW_TAG_interface_type:
9538     case DW_TAG_structure_type:
9539     case DW_TAG_union_type:
9540     case DW_TAG_enumeration_type:
9541     case DW_TAG_enumerator:
9542     case DW_TAG_subprogram:
9543     case DW_TAG_inlined_subroutine:
9544     case DW_TAG_member:
9545     case DW_TAG_imported_declaration:
9546       return 1;
9547
9548     case DW_TAG_variable:
9549     case DW_TAG_constant:
9550       /* We only need to prefix "globally" visible variables.  These include
9551          any variable marked with DW_AT_external or any variable that
9552          lives in a namespace.  [Variables in anonymous namespaces
9553          require prefixing, but they are not DW_AT_external.]  */
9554
9555       if (dwarf2_attr (die, DW_AT_specification, cu))
9556         {
9557           struct dwarf2_cu *spec_cu = cu;
9558
9559           return die_needs_namespace (die_specification (die, &spec_cu),
9560                                       spec_cu);
9561         }
9562
9563       attr = dwarf2_attr (die, DW_AT_external, cu);
9564       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9565           && die->parent->tag != DW_TAG_module)
9566         return 0;
9567       /* A variable in a lexical block of some kind does not need a
9568          namespace, even though in C++ such variables may be external
9569          and have a mangled name.  */
9570       if (die->parent->tag ==  DW_TAG_lexical_block
9571           || die->parent->tag ==  DW_TAG_try_block
9572           || die->parent->tag ==  DW_TAG_catch_block
9573           || die->parent->tag == DW_TAG_subprogram)
9574         return 0;
9575       return 1;
9576
9577     default:
9578       return 0;
9579     }
9580 }
9581
9582 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9583    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9584    defined for the given DIE.  */
9585
9586 static struct attribute *
9587 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9588 {
9589   struct attribute *attr;
9590
9591   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9592   if (attr == NULL)
9593     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9594
9595   return attr;
9596 }
9597
9598 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9599    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9600    defined for the given DIE.  */
9601
9602 static const char *
9603 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9604 {
9605   const char *linkage_name;
9606
9607   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9608   if (linkage_name == NULL)
9609     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9610
9611   return linkage_name;
9612 }
9613
9614 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9615    compute the physname for the object, which include a method's:
9616    - formal parameters (C++),
9617    - receiver type (Go),
9618
9619    The term "physname" is a bit confusing.
9620    For C++, for example, it is the demangled name.
9621    For Go, for example, it's the mangled name.
9622
9623    For Ada, return the DIE's linkage name rather than the fully qualified
9624    name.  PHYSNAME is ignored..
9625
9626    The result is allocated on the objfile_obstack and canonicalized.  */
9627
9628 static const char *
9629 dwarf2_compute_name (const char *name,
9630                      struct die_info *die, struct dwarf2_cu *cu,
9631                      int physname)
9632 {
9633   struct objfile *objfile = cu->objfile;
9634
9635   if (name == NULL)
9636     name = dwarf2_name (die, cu);
9637
9638   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9639      but otherwise compute it by typename_concat inside GDB.
9640      FIXME: Actually this is not really true, or at least not always true.
9641      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
9642      Fortran names because there is no mangling standard.  So new_symbol_full
9643      will set the demangled name to the result of dwarf2_full_name, and it is
9644      the demangled name that GDB uses if it exists.  */
9645   if (cu->language == language_ada
9646       || (cu->language == language_fortran && physname))
9647     {
9648       /* For Ada unit, we prefer the linkage name over the name, as
9649          the former contains the exported name, which the user expects
9650          to be able to reference.  Ideally, we want the user to be able
9651          to reference this entity using either natural or linkage name,
9652          but we haven't started looking at this enhancement yet.  */
9653       const char *linkage_name = dw2_linkage_name (die, cu);
9654
9655       if (linkage_name != NULL)
9656         return linkage_name;
9657     }
9658
9659   /* These are the only languages we know how to qualify names in.  */
9660   if (name != NULL
9661       && (cu->language == language_cplus
9662           || cu->language == language_fortran || cu->language == language_d
9663           || cu->language == language_rust))
9664     {
9665       if (die_needs_namespace (die, cu))
9666         {
9667           const char *prefix;
9668           const char *canonical_name = NULL;
9669
9670           string_file buf;
9671
9672           prefix = determine_prefix (die, cu);
9673           if (*prefix != '\0')
9674             {
9675               char *prefixed_name = typename_concat (NULL, prefix, name,
9676                                                      physname, cu);
9677
9678               buf.puts (prefixed_name);
9679               xfree (prefixed_name);
9680             }
9681           else
9682             buf.puts (name);
9683
9684           /* Template parameters may be specified in the DIE's DW_AT_name, or
9685              as children with DW_TAG_template_type_param or
9686              DW_TAG_value_type_param.  If the latter, add them to the name
9687              here.  If the name already has template parameters, then
9688              skip this step; some versions of GCC emit both, and
9689              it is more efficient to use the pre-computed name.
9690
9691              Something to keep in mind about this process: it is very
9692              unlikely, or in some cases downright impossible, to produce
9693              something that will match the mangled name of a function.
9694              If the definition of the function has the same debug info,
9695              we should be able to match up with it anyway.  But fallbacks
9696              using the minimal symbol, for instance to find a method
9697              implemented in a stripped copy of libstdc++, will not work.
9698              If we do not have debug info for the definition, we will have to
9699              match them up some other way.
9700
9701              When we do name matching there is a related problem with function
9702              templates; two instantiated function templates are allowed to
9703              differ only by their return types, which we do not add here.  */
9704
9705           if (cu->language == language_cplus && strchr (name, '<') == NULL)
9706             {
9707               struct attribute *attr;
9708               struct die_info *child;
9709               int first = 1;
9710
9711               die->building_fullname = 1;
9712
9713               for (child = die->child; child != NULL; child = child->sibling)
9714                 {
9715                   struct type *type;
9716                   LONGEST value;
9717                   const gdb_byte *bytes;
9718                   struct dwarf2_locexpr_baton *baton;
9719                   struct value *v;
9720
9721                   if (child->tag != DW_TAG_template_type_param
9722                       && child->tag != DW_TAG_template_value_param)
9723                     continue;
9724
9725                   if (first)
9726                     {
9727                       buf.puts ("<");
9728                       first = 0;
9729                     }
9730                   else
9731                     buf.puts (", ");
9732
9733                   attr = dwarf2_attr (child, DW_AT_type, cu);
9734                   if (attr == NULL)
9735                     {
9736                       complaint (&symfile_complaints,
9737                                  _("template parameter missing DW_AT_type"));
9738                       buf.puts ("UNKNOWN_TYPE");
9739                       continue;
9740                     }
9741                   type = die_type (child, cu);
9742
9743                   if (child->tag == DW_TAG_template_type_param)
9744                     {
9745                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
9746                       continue;
9747                     }
9748
9749                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
9750                   if (attr == NULL)
9751                     {
9752                       complaint (&symfile_complaints,
9753                                  _("template parameter missing "
9754                                    "DW_AT_const_value"));
9755                       buf.puts ("UNKNOWN_VALUE");
9756                       continue;
9757                     }
9758
9759                   dwarf2_const_value_attr (attr, type, name,
9760                                            &cu->comp_unit_obstack, cu,
9761                                            &value, &bytes, &baton);
9762
9763                   if (TYPE_NOSIGN (type))
9764                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
9765                        changed, this can use value_print instead.  */
9766                     c_printchar (value, type, &buf);
9767                   else
9768                     {
9769                       struct value_print_options opts;
9770
9771                       if (baton != NULL)
9772                         v = dwarf2_evaluate_loc_desc (type, NULL,
9773                                                       baton->data,
9774                                                       baton->size,
9775                                                       baton->per_cu);
9776                       else if (bytes != NULL)
9777                         {
9778                           v = allocate_value (type);
9779                           memcpy (value_contents_writeable (v), bytes,
9780                                   TYPE_LENGTH (type));
9781                         }
9782                       else
9783                         v = value_from_longest (type, value);
9784
9785                       /* Specify decimal so that we do not depend on
9786                          the radix.  */
9787                       get_formatted_print_options (&opts, 'd');
9788                       opts.raw = 1;
9789                       value_print (v, &buf, &opts);
9790                       release_value (v);
9791                       value_free (v);
9792                     }
9793                 }
9794
9795               die->building_fullname = 0;
9796
9797               if (!first)
9798                 {
9799                   /* Close the argument list, with a space if necessary
9800                      (nested templates).  */
9801                   if (!buf.empty () && buf.string ().back () == '>')
9802                     buf.puts (" >");
9803                   else
9804                     buf.puts (">");
9805                 }
9806             }
9807
9808           /* For C++ methods, append formal parameter type
9809              information, if PHYSNAME.  */
9810
9811           if (physname && die->tag == DW_TAG_subprogram
9812               && cu->language == language_cplus)
9813             {
9814               struct type *type = read_type_die (die, cu);
9815
9816               c_type_print_args (type, &buf, 1, cu->language,
9817                                  &type_print_raw_options);
9818
9819               if (cu->language == language_cplus)
9820                 {
9821                   /* Assume that an artificial first parameter is
9822                      "this", but do not crash if it is not.  RealView
9823                      marks unnamed (and thus unused) parameters as
9824                      artificial; there is no way to differentiate
9825                      the two cases.  */
9826                   if (TYPE_NFIELDS (type) > 0
9827                       && TYPE_FIELD_ARTIFICIAL (type, 0)
9828                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
9829                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
9830                                                                         0))))
9831                     buf.puts (" const");
9832                 }
9833             }
9834
9835           const std::string &intermediate_name = buf.string ();
9836
9837           if (cu->language == language_cplus)
9838             canonical_name
9839               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
9840                                           &objfile->per_bfd->storage_obstack);
9841
9842           /* If we only computed INTERMEDIATE_NAME, or if
9843              INTERMEDIATE_NAME is already canonical, then we need to
9844              copy it to the appropriate obstack.  */
9845           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9846             name = ((const char *)
9847                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
9848                                    intermediate_name.c_str (),
9849                                    intermediate_name.length ()));
9850           else
9851             name = canonical_name;
9852         }
9853     }
9854
9855   return name;
9856 }
9857
9858 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9859    If scope qualifiers are appropriate they will be added.  The result
9860    will be allocated on the storage_obstack, or NULL if the DIE does
9861    not have a name.  NAME may either be from a previous call to
9862    dwarf2_name or NULL.
9863
9864    The output string will be canonicalized (if C++).  */
9865
9866 static const char *
9867 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9868 {
9869   return dwarf2_compute_name (name, die, cu, 0);
9870 }
9871
9872 /* Construct a physname for the given DIE in CU.  NAME may either be
9873    from a previous call to dwarf2_name or NULL.  The result will be
9874    allocated on the objfile_objstack or NULL if the DIE does not have a
9875    name.
9876
9877    The output string will be canonicalized (if C++).  */
9878
9879 static const char *
9880 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9881 {
9882   struct objfile *objfile = cu->objfile;
9883   const char *retval, *mangled = NULL, *canon = NULL;
9884   int need_copy = 1;
9885
9886   /* In this case dwarf2_compute_name is just a shortcut not building anything
9887      on its own.  */
9888   if (!die_needs_namespace (die, cu))
9889     return dwarf2_compute_name (name, die, cu, 1);
9890
9891   mangled = dw2_linkage_name (die, cu);
9892
9893   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9894      See https://github.com/rust-lang/rust/issues/32925.  */
9895   if (cu->language == language_rust && mangled != NULL
9896       && strchr (mangled, '{') != NULL)
9897     mangled = NULL;
9898
9899   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9900      has computed.  */
9901   gdb::unique_xmalloc_ptr<char> demangled;
9902   if (mangled != NULL)
9903     {
9904       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9905          type.  It is easier for GDB users to search for such functions as
9906          `name(params)' than `long name(params)'.  In such case the minimal
9907          symbol names do not match the full symbol names but for template
9908          functions there is never a need to look up their definition from their
9909          declaration so the only disadvantage remains the minimal symbol
9910          variant `long name(params)' does not have the proper inferior type.
9911          */
9912
9913       if (cu->language == language_go)
9914         {
9915           /* This is a lie, but we already lie to the caller new_symbol_full.
9916              new_symbol_full assumes we return the mangled name.
9917              This just undoes that lie until things are cleaned up.  */
9918         }
9919       else
9920         {
9921           demangled.reset (gdb_demangle (mangled,
9922                                          (DMGL_PARAMS | DMGL_ANSI
9923                                           | DMGL_RET_DROP)));
9924         }
9925       if (demangled)
9926         canon = demangled.get ();
9927       else
9928         {
9929           canon = mangled;
9930           need_copy = 0;
9931         }
9932     }
9933
9934   if (canon == NULL || check_physname)
9935     {
9936       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9937
9938       if (canon != NULL && strcmp (physname, canon) != 0)
9939         {
9940           /* It may not mean a bug in GDB.  The compiler could also
9941              compute DW_AT_linkage_name incorrectly.  But in such case
9942              GDB would need to be bug-to-bug compatible.  */
9943
9944           complaint (&symfile_complaints,
9945                      _("Computed physname <%s> does not match demangled <%s> "
9946                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9947                      physname, canon, mangled, to_underlying (die->sect_off),
9948                      objfile_name (objfile));
9949
9950           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9951              is available here - over computed PHYSNAME.  It is safer
9952              against both buggy GDB and buggy compilers.  */
9953
9954           retval = canon;
9955         }
9956       else
9957         {
9958           retval = physname;
9959           need_copy = 0;
9960         }
9961     }
9962   else
9963     retval = canon;
9964
9965   if (need_copy)
9966     retval = ((const char *)
9967               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9968                              retval, strlen (retval)));
9969
9970   return retval;
9971 }
9972
9973 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9974    a new symbol for it.
9975
9976    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9977
9978 static int
9979 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9980 {
9981   struct attribute *attr;
9982
9983   /* If the die does not have a name, this is not a namespace
9984      alias.  */
9985   attr = dwarf2_attr (die, DW_AT_name, cu);
9986   if (attr != NULL)
9987     {
9988       int num;
9989       struct die_info *d = die;
9990       struct dwarf2_cu *imported_cu = cu;
9991
9992       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9993          keep inspecting DIEs until we hit the underlying import.  */
9994 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9995       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9996         {
9997           attr = dwarf2_attr (d, DW_AT_import, cu);
9998           if (attr == NULL)
9999             break;
10000
10001           d = follow_die_ref (d, attr, &imported_cu);
10002           if (d->tag != DW_TAG_imported_declaration)
10003             break;
10004         }
10005
10006       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10007         {
10008           complaint (&symfile_complaints,
10009                      _("DIE at 0x%x has too many recursively imported "
10010                        "declarations"), to_underlying (d->sect_off));
10011           return 0;
10012         }
10013
10014       if (attr != NULL)
10015         {
10016           struct type *type;
10017           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10018
10019           type = get_die_type_at_offset (sect_off, cu->per_cu);
10020           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
10021             {
10022               /* This declaration is a global namespace alias.  Add
10023                  a symbol for it whose type is the aliased namespace.  */
10024               new_symbol (die, type, cu);
10025               return 1;
10026             }
10027         }
10028     }
10029
10030   return 0;
10031 }
10032
10033 /* Return the using directives repository (global or local?) to use in the
10034    current context for LANGUAGE.
10035
10036    For Ada, imported declarations can materialize renamings, which *may* be
10037    global.  However it is impossible (for now?) in DWARF to distinguish
10038    "external" imported declarations and "static" ones.  As all imported
10039    declarations seem to be static in all other languages, make them all CU-wide
10040    global only in Ada.  */
10041
10042 static struct using_direct **
10043 using_directives (enum language language)
10044 {
10045   if (language == language_ada && context_stack_depth == 0)
10046     return &global_using_directives;
10047   else
10048     return &local_using_directives;
10049 }
10050
10051 /* Read the import statement specified by the given die and record it.  */
10052
10053 static void
10054 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10055 {
10056   struct objfile *objfile = cu->objfile;
10057   struct attribute *import_attr;
10058   struct die_info *imported_die, *child_die;
10059   struct dwarf2_cu *imported_cu;
10060   const char *imported_name;
10061   const char *imported_name_prefix;
10062   const char *canonical_name;
10063   const char *import_alias;
10064   const char *imported_declaration = NULL;
10065   const char *import_prefix;
10066   std::vector<const char *> excludes;
10067
10068   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10069   if (import_attr == NULL)
10070     {
10071       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
10072                  dwarf_tag_name (die->tag));
10073       return;
10074     }
10075
10076   imported_cu = cu;
10077   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10078   imported_name = dwarf2_name (imported_die, imported_cu);
10079   if (imported_name == NULL)
10080     {
10081       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10082
10083         The import in the following code:
10084         namespace A
10085           {
10086             typedef int B;
10087           }
10088
10089         int main ()
10090           {
10091             using A::B;
10092             B b;
10093             return b;
10094           }
10095
10096         ...
10097          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10098             <52>   DW_AT_decl_file   : 1
10099             <53>   DW_AT_decl_line   : 6
10100             <54>   DW_AT_import      : <0x75>
10101          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10102             <59>   DW_AT_name        : B
10103             <5b>   DW_AT_decl_file   : 1
10104             <5c>   DW_AT_decl_line   : 2
10105             <5d>   DW_AT_type        : <0x6e>
10106         ...
10107          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10108             <76>   DW_AT_byte_size   : 4
10109             <77>   DW_AT_encoding    : 5        (signed)
10110
10111         imports the wrong die ( 0x75 instead of 0x58 ).
10112         This case will be ignored until the gcc bug is fixed.  */
10113       return;
10114     }
10115
10116   /* Figure out the local name after import.  */
10117   import_alias = dwarf2_name (die, cu);
10118
10119   /* Figure out where the statement is being imported to.  */
10120   import_prefix = determine_prefix (die, cu);
10121
10122   /* Figure out what the scope of the imported die is and prepend it
10123      to the name of the imported die.  */
10124   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10125
10126   if (imported_die->tag != DW_TAG_namespace
10127       && imported_die->tag != DW_TAG_module)
10128     {
10129       imported_declaration = imported_name;
10130       canonical_name = imported_name_prefix;
10131     }
10132   else if (strlen (imported_name_prefix) > 0)
10133     canonical_name = obconcat (&objfile->objfile_obstack,
10134                                imported_name_prefix,
10135                                (cu->language == language_d ? "." : "::"),
10136                                imported_name, (char *) NULL);
10137   else
10138     canonical_name = imported_name;
10139
10140   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
10141     for (child_die = die->child; child_die && child_die->tag;
10142          child_die = sibling_die (child_die))
10143       {
10144         /* DWARF-4: A Fortran use statement with a “rename list” may be
10145            represented by an imported module entry with an import attribute
10146            referring to the module and owned entries corresponding to those
10147            entities that are renamed as part of being imported.  */
10148
10149         if (child_die->tag != DW_TAG_imported_declaration)
10150           {
10151             complaint (&symfile_complaints,
10152                        _("child DW_TAG_imported_declaration expected "
10153                          "- DIE at 0x%x [in module %s]"),
10154                        to_underlying (child_die->sect_off), objfile_name (objfile));
10155             continue;
10156           }
10157
10158         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10159         if (import_attr == NULL)
10160           {
10161             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
10162                        dwarf_tag_name (child_die->tag));
10163             continue;
10164           }
10165
10166         imported_cu = cu;
10167         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10168                                               &imported_cu);
10169         imported_name = dwarf2_name (imported_die, imported_cu);
10170         if (imported_name == NULL)
10171           {
10172             complaint (&symfile_complaints,
10173                        _("child DW_TAG_imported_declaration has unknown "
10174                          "imported name - DIE at 0x%x [in module %s]"),
10175                        to_underlying (child_die->sect_off), objfile_name (objfile));
10176             continue;
10177           }
10178
10179         excludes.push_back (imported_name);
10180
10181         process_die (child_die, cu);
10182       }
10183
10184   add_using_directive (using_directives (cu->language),
10185                        import_prefix,
10186                        canonical_name,
10187                        import_alias,
10188                        imported_declaration,
10189                        excludes,
10190                        0,
10191                        &objfile->objfile_obstack);
10192 }
10193
10194 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10195    types, but gives them a size of zero.  Starting with version 14,
10196    ICC is compatible with GCC.  */
10197
10198 static int
10199 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10200 {
10201   if (!cu->checked_producer)
10202     check_producer (cu);
10203
10204   return cu->producer_is_icc_lt_14;
10205 }
10206
10207 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
10208    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
10209    this, it was first present in GCC release 4.3.0.  */
10210
10211 static int
10212 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
10213 {
10214   if (!cu->checked_producer)
10215     check_producer (cu);
10216
10217   return cu->producer_is_gcc_lt_4_3;
10218 }
10219
10220 static file_and_directory
10221 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
10222 {
10223   file_and_directory res;
10224
10225   /* Find the filename.  Do not use dwarf2_name here, since the filename
10226      is not a source language identifier.  */
10227   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
10228   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
10229
10230   if (res.comp_dir == NULL
10231       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
10232       && IS_ABSOLUTE_PATH (res.name))
10233     {
10234       res.comp_dir_storage = ldirname (res.name);
10235       if (!res.comp_dir_storage.empty ())
10236         res.comp_dir = res.comp_dir_storage.c_str ();
10237     }
10238   if (res.comp_dir != NULL)
10239     {
10240       /* Irix 6.2 native cc prepends <machine>.: to the compilation
10241          directory, get rid of it.  */
10242       const char *cp = strchr (res.comp_dir, ':');
10243
10244       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
10245         res.comp_dir = cp + 1;
10246     }
10247
10248   if (res.name == NULL)
10249     res.name = "<unknown>";
10250
10251   return res;
10252 }
10253
10254 /* Handle DW_AT_stmt_list for a compilation unit.
10255    DIE is the DW_TAG_compile_unit die for CU.
10256    COMP_DIR is the compilation directory.  LOWPC is passed to
10257    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
10258
10259 static void
10260 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
10261                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
10262 {
10263   struct objfile *objfile = dwarf2_per_objfile->objfile;
10264   struct attribute *attr;
10265   struct line_header line_header_local;
10266   hashval_t line_header_local_hash;
10267   void **slot;
10268   int decode_mapping;
10269
10270   gdb_assert (! cu->per_cu->is_debug_types);
10271
10272   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10273   if (attr == NULL)
10274     return;
10275
10276   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10277
10278   /* The line header hash table is only created if needed (it exists to
10279      prevent redundant reading of the line table for partial_units).
10280      If we're given a partial_unit, we'll need it.  If we're given a
10281      compile_unit, then use the line header hash table if it's already
10282      created, but don't create one just yet.  */
10283
10284   if (dwarf2_per_objfile->line_header_hash == NULL
10285       && die->tag == DW_TAG_partial_unit)
10286     {
10287       dwarf2_per_objfile->line_header_hash
10288         = htab_create_alloc_ex (127, line_header_hash_voidp,
10289                                 line_header_eq_voidp,
10290                                 free_line_header_voidp,
10291                                 &objfile->objfile_obstack,
10292                                 hashtab_obstack_allocate,
10293                                 dummy_obstack_deallocate);
10294     }
10295
10296   line_header_local.sect_off = line_offset;
10297   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
10298   line_header_local_hash = line_header_hash (&line_header_local);
10299   if (dwarf2_per_objfile->line_header_hash != NULL)
10300     {
10301       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10302                                        &line_header_local,
10303                                        line_header_local_hash, NO_INSERT);
10304
10305       /* For DW_TAG_compile_unit we need info like symtab::linetable which
10306          is not present in *SLOT (since if there is something in *SLOT then
10307          it will be for a partial_unit).  */
10308       if (die->tag == DW_TAG_partial_unit && slot != NULL)
10309         {
10310           gdb_assert (*slot != NULL);
10311           cu->line_header = (struct line_header *) *slot;
10312           return;
10313         }
10314     }
10315
10316   /* dwarf_decode_line_header does not yet provide sufficient information.
10317      We always have to call also dwarf_decode_lines for it.  */
10318   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
10319   if (lh == NULL)
10320     return;
10321
10322   cu->line_header = lh.release ();
10323   cu->line_header_die_owner = die;
10324
10325   if (dwarf2_per_objfile->line_header_hash == NULL)
10326     slot = NULL;
10327   else
10328     {
10329       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10330                                        &line_header_local,
10331                                        line_header_local_hash, INSERT);
10332       gdb_assert (slot != NULL);
10333     }
10334   if (slot != NULL && *slot == NULL)
10335     {
10336       /* This newly decoded line number information unit will be owned
10337          by line_header_hash hash table.  */
10338       *slot = cu->line_header;
10339       cu->line_header_die_owner = NULL;
10340     }
10341   else
10342     {
10343       /* We cannot free any current entry in (*slot) as that struct line_header
10344          may be already used by multiple CUs.  Create only temporary decoded
10345          line_header for this CU - it may happen at most once for each line
10346          number information unit.  And if we're not using line_header_hash
10347          then this is what we want as well.  */
10348       gdb_assert (die->tag != DW_TAG_partial_unit);
10349     }
10350   decode_mapping = (die->tag != DW_TAG_partial_unit);
10351   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
10352                       decode_mapping);
10353
10354 }
10355
10356 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
10357
10358 static void
10359 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
10360 {
10361   struct objfile *objfile = dwarf2_per_objfile->objfile;
10362   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10363   CORE_ADDR lowpc = ((CORE_ADDR) -1);
10364   CORE_ADDR highpc = ((CORE_ADDR) 0);
10365   struct attribute *attr;
10366   struct die_info *child_die;
10367   CORE_ADDR baseaddr;
10368
10369   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10370
10371   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
10372
10373   /* If we didn't find a lowpc, set it to highpc to avoid complaints
10374      from finish_block.  */
10375   if (lowpc == ((CORE_ADDR) -1))
10376     lowpc = highpc;
10377   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
10378
10379   file_and_directory fnd = find_file_and_directory (die, cu);
10380
10381   prepare_one_comp_unit (cu, die, cu->language);
10382
10383   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
10384      standardised yet.  As a workaround for the language detection we fall
10385      back to the DW_AT_producer string.  */
10386   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
10387     cu->language = language_opencl;
10388
10389   /* Similar hack for Go.  */
10390   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
10391     set_cu_language (DW_LANG_Go, cu);
10392
10393   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
10394
10395   /* Decode line number information if present.  We do this before
10396      processing child DIEs, so that the line header table is available
10397      for DW_AT_decl_file.  */
10398   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
10399
10400   /* Process all dies in compilation unit.  */
10401   if (die->child != NULL)
10402     {
10403       child_die = die->child;
10404       while (child_die && child_die->tag)
10405         {
10406           process_die (child_die, cu);
10407           child_die = sibling_die (child_die);
10408         }
10409     }
10410
10411   /* Decode macro information, if present.  Dwarf 2 macro information
10412      refers to information in the line number info statement program
10413      header, so we can only read it if we've read the header
10414      successfully.  */
10415   attr = dwarf2_attr (die, DW_AT_macros, cu);
10416   if (attr == NULL)
10417     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
10418   if (attr && cu->line_header)
10419     {
10420       if (dwarf2_attr (die, DW_AT_macro_info, cu))
10421         complaint (&symfile_complaints,
10422                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
10423
10424       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
10425     }
10426   else
10427     {
10428       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
10429       if (attr && cu->line_header)
10430         {
10431           unsigned int macro_offset = DW_UNSND (attr);
10432
10433           dwarf_decode_macros (cu, macro_offset, 0);
10434         }
10435     }
10436 }
10437
10438 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
10439    Create the set of symtabs used by this TU, or if this TU is sharing
10440    symtabs with another TU and the symtabs have already been created
10441    then restore those symtabs in the line header.
10442    We don't need the pc/line-number mapping for type units.  */
10443
10444 static void
10445 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
10446 {
10447   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
10448   struct type_unit_group *tu_group;
10449   int first_time;
10450   struct attribute *attr;
10451   unsigned int i;
10452   struct signatured_type *sig_type;
10453
10454   gdb_assert (per_cu->is_debug_types);
10455   sig_type = (struct signatured_type *) per_cu;
10456
10457   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10458
10459   /* If we're using .gdb_index (includes -readnow) then
10460      per_cu->type_unit_group may not have been set up yet.  */
10461   if (sig_type->type_unit_group == NULL)
10462     sig_type->type_unit_group = get_type_unit_group (cu, attr);
10463   tu_group = sig_type->type_unit_group;
10464
10465   /* If we've already processed this stmt_list there's no real need to
10466      do it again, we could fake it and just recreate the part we need
10467      (file name,index -> symtab mapping).  If data shows this optimization
10468      is useful we can do it then.  */
10469   first_time = tu_group->compunit_symtab == NULL;
10470
10471   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
10472      debug info.  */
10473   line_header_up lh;
10474   if (attr != NULL)
10475     {
10476       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10477       lh = dwarf_decode_line_header (line_offset, cu);
10478     }
10479   if (lh == NULL)
10480     {
10481       if (first_time)
10482         dwarf2_start_symtab (cu, "", NULL, 0);
10483       else
10484         {
10485           gdb_assert (tu_group->symtabs == NULL);
10486           restart_symtab (tu_group->compunit_symtab, "", 0);
10487         }
10488       return;
10489     }
10490
10491   cu->line_header = lh.release ();
10492   cu->line_header_die_owner = die;
10493
10494   if (first_time)
10495     {
10496       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
10497
10498       /* Note: We don't assign tu_group->compunit_symtab yet because we're
10499          still initializing it, and our caller (a few levels up)
10500          process_full_type_unit still needs to know if this is the first
10501          time.  */
10502
10503       tu_group->num_symtabs = cu->line_header->file_names.size ();
10504       tu_group->symtabs = XNEWVEC (struct symtab *,
10505                                    cu->line_header->file_names.size ());
10506
10507       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10508         {
10509           file_entry &fe = cu->line_header->file_names[i];
10510
10511           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
10512
10513           if (current_subfile->symtab == NULL)
10514             {
10515               /* NOTE: start_subfile will recognize when it's been
10516                  passed a file it has already seen.  So we can't
10517                  assume there's a simple mapping from
10518                  cu->line_header->file_names to subfiles, plus
10519                  cu->line_header->file_names may contain dups.  */
10520               current_subfile->symtab
10521                 = allocate_symtab (cust, current_subfile->name);
10522             }
10523
10524           fe.symtab = current_subfile->symtab;
10525           tu_group->symtabs[i] = fe.symtab;
10526         }
10527     }
10528   else
10529     {
10530       restart_symtab (tu_group->compunit_symtab, "", 0);
10531
10532       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10533         {
10534           file_entry &fe = cu->line_header->file_names[i];
10535
10536           fe.symtab = tu_group->symtabs[i];
10537         }
10538     }
10539
10540   /* The main symtab is allocated last.  Type units don't have DW_AT_name
10541      so they don't have a "real" (so to speak) symtab anyway.
10542      There is later code that will assign the main symtab to all symbols
10543      that don't have one.  We need to handle the case of a symbol with a
10544      missing symtab (DW_AT_decl_file) anyway.  */
10545 }
10546
10547 /* Process DW_TAG_type_unit.
10548    For TUs we want to skip the first top level sibling if it's not the
10549    actual type being defined by this TU.  In this case the first top
10550    level sibling is there to provide context only.  */
10551
10552 static void
10553 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10554 {
10555   struct die_info *child_die;
10556
10557   prepare_one_comp_unit (cu, die, language_minimal);
10558
10559   /* Initialize (or reinitialize) the machinery for building symtabs.
10560      We do this before processing child DIEs, so that the line header table
10561      is available for DW_AT_decl_file.  */
10562   setup_type_unit_groups (die, cu);
10563
10564   if (die->child != NULL)
10565     {
10566       child_die = die->child;
10567       while (child_die && child_die->tag)
10568         {
10569           process_die (child_die, cu);
10570           child_die = sibling_die (child_die);
10571         }
10572     }
10573 }
10574 \f
10575 /* DWO/DWP files.
10576
10577    http://gcc.gnu.org/wiki/DebugFission
10578    http://gcc.gnu.org/wiki/DebugFissionDWP
10579
10580    To simplify handling of both DWO files ("object" files with the DWARF info)
10581    and DWP files (a file with the DWOs packaged up into one file), we treat
10582    DWP files as having a collection of virtual DWO files.  */
10583
10584 static hashval_t
10585 hash_dwo_file (const void *item)
10586 {
10587   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10588   hashval_t hash;
10589
10590   hash = htab_hash_string (dwo_file->dwo_name);
10591   if (dwo_file->comp_dir != NULL)
10592     hash += htab_hash_string (dwo_file->comp_dir);
10593   return hash;
10594 }
10595
10596 static int
10597 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10598 {
10599   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10600   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10601
10602   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10603     return 0;
10604   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10605     return lhs->comp_dir == rhs->comp_dir;
10606   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10607 }
10608
10609 /* Allocate a hash table for DWO files.  */
10610
10611 static htab_t
10612 allocate_dwo_file_hash_table (void)
10613 {
10614   struct objfile *objfile = dwarf2_per_objfile->objfile;
10615
10616   return htab_create_alloc_ex (41,
10617                                hash_dwo_file,
10618                                eq_dwo_file,
10619                                NULL,
10620                                &objfile->objfile_obstack,
10621                                hashtab_obstack_allocate,
10622                                dummy_obstack_deallocate);
10623 }
10624
10625 /* Lookup DWO file DWO_NAME.  */
10626
10627 static void **
10628 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
10629 {
10630   struct dwo_file find_entry;
10631   void **slot;
10632
10633   if (dwarf2_per_objfile->dwo_files == NULL)
10634     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
10635
10636   memset (&find_entry, 0, sizeof (find_entry));
10637   find_entry.dwo_name = dwo_name;
10638   find_entry.comp_dir = comp_dir;
10639   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
10640
10641   return slot;
10642 }
10643
10644 static hashval_t
10645 hash_dwo_unit (const void *item)
10646 {
10647   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10648
10649   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10650   return dwo_unit->signature;
10651 }
10652
10653 static int
10654 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10655 {
10656   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10657   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10658
10659   /* The signature is assumed to be unique within the DWO file.
10660      So while object file CU dwo_id's always have the value zero,
10661      that's OK, assuming each object file DWO file has only one CU,
10662      and that's the rule for now.  */
10663   return lhs->signature == rhs->signature;
10664 }
10665
10666 /* Allocate a hash table for DWO CUs,TUs.
10667    There is one of these tables for each of CUs,TUs for each DWO file.  */
10668
10669 static htab_t
10670 allocate_dwo_unit_table (struct objfile *objfile)
10671 {
10672   /* Start out with a pretty small number.
10673      Generally DWO files contain only one CU and maybe some TUs.  */
10674   return htab_create_alloc_ex (3,
10675                                hash_dwo_unit,
10676                                eq_dwo_unit,
10677                                NULL,
10678                                &objfile->objfile_obstack,
10679                                hashtab_obstack_allocate,
10680                                dummy_obstack_deallocate);
10681 }
10682
10683 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
10684
10685 struct create_dwo_cu_data
10686 {
10687   struct dwo_file *dwo_file;
10688   struct dwo_unit dwo_unit;
10689 };
10690
10691 /* die_reader_func for create_dwo_cu.  */
10692
10693 static void
10694 create_dwo_cu_reader (const struct die_reader_specs *reader,
10695                       const gdb_byte *info_ptr,
10696                       struct die_info *comp_unit_die,
10697                       int has_children,
10698                       void *datap)
10699 {
10700   struct dwarf2_cu *cu = reader->cu;
10701   sect_offset sect_off = cu->per_cu->sect_off;
10702   struct dwarf2_section_info *section = cu->per_cu->section;
10703   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
10704   struct dwo_file *dwo_file = data->dwo_file;
10705   struct dwo_unit *dwo_unit = &data->dwo_unit;
10706   struct attribute *attr;
10707
10708   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
10709   if (attr == NULL)
10710     {
10711       complaint (&symfile_complaints,
10712                  _("Dwarf Error: debug entry at offset 0x%x is missing"
10713                    " its dwo_id [in module %s]"),
10714                  to_underlying (sect_off), dwo_file->dwo_name);
10715       return;
10716     }
10717
10718   dwo_unit->dwo_file = dwo_file;
10719   dwo_unit->signature = DW_UNSND (attr);
10720   dwo_unit->section = section;
10721   dwo_unit->sect_off = sect_off;
10722   dwo_unit->length = cu->per_cu->length;
10723
10724   if (dwarf_read_debug)
10725     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
10726                         to_underlying (sect_off),
10727                         hex_string (dwo_unit->signature));
10728 }
10729
10730 /* Create the dwo_units for the CUs in a DWO_FILE.
10731    Note: This function processes DWO files only, not DWP files.  */
10732
10733 static void
10734 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
10735                        htab_t &cus_htab)
10736 {
10737   struct objfile *objfile = dwarf2_per_objfile->objfile;
10738   const gdb_byte *info_ptr, *end_ptr;
10739
10740   dwarf2_read_section (objfile, &section);
10741   info_ptr = section.buffer;
10742
10743   if (info_ptr == NULL)
10744     return;
10745
10746   if (dwarf_read_debug)
10747     {
10748       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
10749                           get_section_name (&section),
10750                           get_section_file_name (&section));
10751     }
10752
10753   end_ptr = info_ptr + section.size;
10754   while (info_ptr < end_ptr)
10755     {
10756       struct dwarf2_per_cu_data per_cu;
10757       struct create_dwo_cu_data create_dwo_cu_data;
10758       struct dwo_unit *dwo_unit;
10759       void **slot;
10760       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10761
10762       memset (&create_dwo_cu_data.dwo_unit, 0,
10763               sizeof (create_dwo_cu_data.dwo_unit));
10764       memset (&per_cu, 0, sizeof (per_cu));
10765       per_cu.objfile = objfile;
10766       per_cu.is_debug_types = 0;
10767       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10768       per_cu.section = &section;
10769       create_dwo_cu_data.dwo_file = &dwo_file;
10770
10771       init_cutu_and_read_dies_no_follow (
10772           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
10773       info_ptr += per_cu.length;
10774
10775       // If the unit could not be parsed, skip it.
10776       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
10777         continue;
10778
10779       if (cus_htab == NULL)
10780         cus_htab = allocate_dwo_unit_table (objfile);
10781
10782       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10783       *dwo_unit = create_dwo_cu_data.dwo_unit;
10784       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
10785       gdb_assert (slot != NULL);
10786       if (*slot != NULL)
10787         {
10788           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10789           sect_offset dup_sect_off = dup_cu->sect_off;
10790
10791           complaint (&symfile_complaints,
10792                      _("debug cu entry at offset 0x%x is duplicate to"
10793                        " the entry at offset 0x%x, signature %s"),
10794                      to_underlying (sect_off), to_underlying (dup_sect_off),
10795                      hex_string (dwo_unit->signature));
10796         }
10797       *slot = (void *)dwo_unit;
10798     }
10799 }
10800
10801 /* DWP file .debug_{cu,tu}_index section format:
10802    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10803
10804    DWP Version 1:
10805
10806    Both index sections have the same format, and serve to map a 64-bit
10807    signature to a set of section numbers.  Each section begins with a header,
10808    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10809    indexes, and a pool of 32-bit section numbers.  The index sections will be
10810    aligned at 8-byte boundaries in the file.
10811
10812    The index section header consists of:
10813
10814     V, 32 bit version number
10815     -, 32 bits unused
10816     N, 32 bit number of compilation units or type units in the index
10817     M, 32 bit number of slots in the hash table
10818
10819    Numbers are recorded using the byte order of the application binary.
10820
10821    The hash table begins at offset 16 in the section, and consists of an array
10822    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
10823    order of the application binary).  Unused slots in the hash table are 0.
10824    (We rely on the extreme unlikeliness of a signature being exactly 0.)
10825
10826    The parallel table begins immediately after the hash table
10827    (at offset 16 + 8 * M from the beginning of the section), and consists of an
10828    array of 32-bit indexes (using the byte order of the application binary),
10829    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
10830    table contains a 32-bit index into the pool of section numbers.  For unused
10831    hash table slots, the corresponding entry in the parallel table will be 0.
10832
10833    The pool of section numbers begins immediately following the hash table
10834    (at offset 16 + 12 * M from the beginning of the section).  The pool of
10835    section numbers consists of an array of 32-bit words (using the byte order
10836    of the application binary).  Each item in the array is indexed starting
10837    from 0.  The hash table entry provides the index of the first section
10838    number in the set.  Additional section numbers in the set follow, and the
10839    set is terminated by a 0 entry (section number 0 is not used in ELF).
10840
10841    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
10842    section must be the first entry in the set, and the .debug_abbrev.dwo must
10843    be the second entry. Other members of the set may follow in any order.
10844
10845    ---
10846
10847    DWP Version 2:
10848
10849    DWP Version 2 combines all the .debug_info, etc. sections into one,
10850    and the entries in the index tables are now offsets into these sections.
10851    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10852    section.
10853
10854    Index Section Contents:
10855     Header
10856     Hash Table of Signatures   dwp_hash_table.hash_table
10857     Parallel Table of Indices  dwp_hash_table.unit_table
10858     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10859     Table of Section Sizes     dwp_hash_table.v2.sizes
10860
10861    The index section header consists of:
10862
10863     V, 32 bit version number
10864     L, 32 bit number of columns in the table of section offsets
10865     N, 32 bit number of compilation units or type units in the index
10866     M, 32 bit number of slots in the hash table
10867
10868    Numbers are recorded using the byte order of the application binary.
10869
10870    The hash table has the same format as version 1.
10871    The parallel table of indices has the same format as version 1,
10872    except that the entries are origin-1 indices into the table of sections
10873    offsets and the table of section sizes.
10874
10875    The table of offsets begins immediately following the parallel table
10876    (at offset 16 + 12 * M from the beginning of the section).  The table is
10877    a two-dimensional array of 32-bit words (using the byte order of the
10878    application binary), with L columns and N+1 rows, in row-major order.
10879    Each row in the array is indexed starting from 0.  The first row provides
10880    a key to the remaining rows: each column in this row provides an identifier
10881    for a debug section, and the offsets in the same column of subsequent rows
10882    refer to that section.  The section identifiers are:
10883
10884     DW_SECT_INFO         1  .debug_info.dwo
10885     DW_SECT_TYPES        2  .debug_types.dwo
10886     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10887     DW_SECT_LINE         4  .debug_line.dwo
10888     DW_SECT_LOC          5  .debug_loc.dwo
10889     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10890     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10891     DW_SECT_MACRO        8  .debug_macro.dwo
10892
10893    The offsets provided by the CU and TU index sections are the base offsets
10894    for the contributions made by each CU or TU to the corresponding section
10895    in the package file.  Each CU and TU header contains an abbrev_offset
10896    field, used to find the abbreviations table for that CU or TU within the
10897    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10898    be interpreted as relative to the base offset given in the index section.
10899    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10900    should be interpreted as relative to the base offset for .debug_line.dwo,
10901    and offsets into other debug sections obtained from DWARF attributes should
10902    also be interpreted as relative to the corresponding base offset.
10903
10904    The table of sizes begins immediately following the table of offsets.
10905    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10906    with L columns and N rows, in row-major order.  Each row in the array is
10907    indexed starting from 1 (row 0 is shared by the two tables).
10908
10909    ---
10910
10911    Hash table lookup is handled the same in version 1 and 2:
10912
10913    We assume that N and M will not exceed 2^32 - 1.
10914    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10915
10916    Given a 64-bit compilation unit signature or a type signature S, an entry
10917    in the hash table is located as follows:
10918
10919    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10920       the low-order k bits all set to 1.
10921
10922    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10923
10924    3) If the hash table entry at index H matches the signature, use that
10925       entry.  If the hash table entry at index H is unused (all zeroes),
10926       terminate the search: the signature is not present in the table.
10927
10928    4) Let H = (H + H') modulo M. Repeat at Step 3.
10929
10930    Because M > N and H' and M are relatively prime, the search is guaranteed
10931    to stop at an unused slot or find the match.  */
10932
10933 /* Create a hash table to map DWO IDs to their CU/TU entry in
10934    .debug_{info,types}.dwo in DWP_FILE.
10935    Returns NULL if there isn't one.
10936    Note: This function processes DWP files only, not DWO files.  */
10937
10938 static struct dwp_hash_table *
10939 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10940 {
10941   struct objfile *objfile = dwarf2_per_objfile->objfile;
10942   bfd *dbfd = dwp_file->dbfd;
10943   const gdb_byte *index_ptr, *index_end;
10944   struct dwarf2_section_info *index;
10945   uint32_t version, nr_columns, nr_units, nr_slots;
10946   struct dwp_hash_table *htab;
10947
10948   if (is_debug_types)
10949     index = &dwp_file->sections.tu_index;
10950   else
10951     index = &dwp_file->sections.cu_index;
10952
10953   if (dwarf2_section_empty_p (index))
10954     return NULL;
10955   dwarf2_read_section (objfile, index);
10956
10957   index_ptr = index->buffer;
10958   index_end = index_ptr + index->size;
10959
10960   version = read_4_bytes (dbfd, index_ptr);
10961   index_ptr += 4;
10962   if (version == 2)
10963     nr_columns = read_4_bytes (dbfd, index_ptr);
10964   else
10965     nr_columns = 0;
10966   index_ptr += 4;
10967   nr_units = read_4_bytes (dbfd, index_ptr);
10968   index_ptr += 4;
10969   nr_slots = read_4_bytes (dbfd, index_ptr);
10970   index_ptr += 4;
10971
10972   if (version != 1 && version != 2)
10973     {
10974       error (_("Dwarf Error: unsupported DWP file version (%s)"
10975                " [in module %s]"),
10976              pulongest (version), dwp_file->name);
10977     }
10978   if (nr_slots != (nr_slots & -nr_slots))
10979     {
10980       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10981                " is not power of 2 [in module %s]"),
10982              pulongest (nr_slots), dwp_file->name);
10983     }
10984
10985   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10986   htab->version = version;
10987   htab->nr_columns = nr_columns;
10988   htab->nr_units = nr_units;
10989   htab->nr_slots = nr_slots;
10990   htab->hash_table = index_ptr;
10991   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10992
10993   /* Exit early if the table is empty.  */
10994   if (nr_slots == 0 || nr_units == 0
10995       || (version == 2 && nr_columns == 0))
10996     {
10997       /* All must be zero.  */
10998       if (nr_slots != 0 || nr_units != 0
10999           || (version == 2 && nr_columns != 0))
11000         {
11001           complaint (&symfile_complaints,
11002                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
11003                        " all zero [in modules %s]"),
11004                      dwp_file->name);
11005         }
11006       return htab;
11007     }
11008
11009   if (version == 1)
11010     {
11011       htab->section_pool.v1.indices =
11012         htab->unit_table + sizeof (uint32_t) * nr_slots;
11013       /* It's harder to decide whether the section is too small in v1.
11014          V1 is deprecated anyway so we punt.  */
11015     }
11016   else
11017     {
11018       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11019       int *ids = htab->section_pool.v2.section_ids;
11020       /* Reverse map for error checking.  */
11021       int ids_seen[DW_SECT_MAX + 1];
11022       int i;
11023
11024       if (nr_columns < 2)
11025         {
11026           error (_("Dwarf Error: bad DWP hash table, too few columns"
11027                    " in section table [in module %s]"),
11028                  dwp_file->name);
11029         }
11030       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11031         {
11032           error (_("Dwarf Error: bad DWP hash table, too many columns"
11033                    " in section table [in module %s]"),
11034                  dwp_file->name);
11035         }
11036       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
11037       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
11038       for (i = 0; i < nr_columns; ++i)
11039         {
11040           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11041
11042           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11043             {
11044               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11045                        " in section table [in module %s]"),
11046                      id, dwp_file->name);
11047             }
11048           if (ids_seen[id] != -1)
11049             {
11050               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11051                        " id %d in section table [in module %s]"),
11052                      id, dwp_file->name);
11053             }
11054           ids_seen[id] = i;
11055           ids[i] = id;
11056         }
11057       /* Must have exactly one info or types section.  */
11058       if (((ids_seen[DW_SECT_INFO] != -1)
11059            + (ids_seen[DW_SECT_TYPES] != -1))
11060           != 1)
11061         {
11062           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11063                    " DWO info/types section [in module %s]"),
11064                  dwp_file->name);
11065         }
11066       /* Must have an abbrev section.  */
11067       if (ids_seen[DW_SECT_ABBREV] == -1)
11068         {
11069           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11070                    " section [in module %s]"),
11071                  dwp_file->name);
11072         }
11073       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11074       htab->section_pool.v2.sizes =
11075         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11076                                          * nr_units * nr_columns);
11077       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11078                                           * nr_units * nr_columns))
11079           > index_end)
11080         {
11081           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11082                    " [in module %s]"),
11083                  dwp_file->name);
11084         }
11085     }
11086
11087   return htab;
11088 }
11089
11090 /* Update SECTIONS with the data from SECTP.
11091
11092    This function is like the other "locate" section routines that are
11093    passed to bfd_map_over_sections, but in this context the sections to
11094    read comes from the DWP V1 hash table, not the full ELF section table.
11095
11096    The result is non-zero for success, or zero if an error was found.  */
11097
11098 static int
11099 locate_v1_virtual_dwo_sections (asection *sectp,
11100                                 struct virtual_v1_dwo_sections *sections)
11101 {
11102   const struct dwop_section_names *names = &dwop_section_names;
11103
11104   if (section_is_p (sectp->name, &names->abbrev_dwo))
11105     {
11106       /* There can be only one.  */
11107       if (sections->abbrev.s.section != NULL)
11108         return 0;
11109       sections->abbrev.s.section = sectp;
11110       sections->abbrev.size = bfd_get_section_size (sectp);
11111     }
11112   else if (section_is_p (sectp->name, &names->info_dwo)
11113            || section_is_p (sectp->name, &names->types_dwo))
11114     {
11115       /* There can be only one.  */
11116       if (sections->info_or_types.s.section != NULL)
11117         return 0;
11118       sections->info_or_types.s.section = sectp;
11119       sections->info_or_types.size = bfd_get_section_size (sectp);
11120     }
11121   else if (section_is_p (sectp->name, &names->line_dwo))
11122     {
11123       /* There can be only one.  */
11124       if (sections->line.s.section != NULL)
11125         return 0;
11126       sections->line.s.section = sectp;
11127       sections->line.size = bfd_get_section_size (sectp);
11128     }
11129   else if (section_is_p (sectp->name, &names->loc_dwo))
11130     {
11131       /* There can be only one.  */
11132       if (sections->loc.s.section != NULL)
11133         return 0;
11134       sections->loc.s.section = sectp;
11135       sections->loc.size = bfd_get_section_size (sectp);
11136     }
11137   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11138     {
11139       /* There can be only one.  */
11140       if (sections->macinfo.s.section != NULL)
11141         return 0;
11142       sections->macinfo.s.section = sectp;
11143       sections->macinfo.size = bfd_get_section_size (sectp);
11144     }
11145   else if (section_is_p (sectp->name, &names->macro_dwo))
11146     {
11147       /* There can be only one.  */
11148       if (sections->macro.s.section != NULL)
11149         return 0;
11150       sections->macro.s.section = sectp;
11151       sections->macro.size = bfd_get_section_size (sectp);
11152     }
11153   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11154     {
11155       /* There can be only one.  */
11156       if (sections->str_offsets.s.section != NULL)
11157         return 0;
11158       sections->str_offsets.s.section = sectp;
11159       sections->str_offsets.size = bfd_get_section_size (sectp);
11160     }
11161   else
11162     {
11163       /* No other kind of section is valid.  */
11164       return 0;
11165     }
11166
11167   return 1;
11168 }
11169
11170 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11171    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11172    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11173    This is for DWP version 1 files.  */
11174
11175 static struct dwo_unit *
11176 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
11177                            uint32_t unit_index,
11178                            const char *comp_dir,
11179                            ULONGEST signature, int is_debug_types)
11180 {
11181   struct objfile *objfile = dwarf2_per_objfile->objfile;
11182   const struct dwp_hash_table *dwp_htab =
11183     is_debug_types ? dwp_file->tus : dwp_file->cus;
11184   bfd *dbfd = dwp_file->dbfd;
11185   const char *kind = is_debug_types ? "TU" : "CU";
11186   struct dwo_file *dwo_file;
11187   struct dwo_unit *dwo_unit;
11188   struct virtual_v1_dwo_sections sections;
11189   void **dwo_file_slot;
11190   int i;
11191
11192   gdb_assert (dwp_file->version == 1);
11193
11194   if (dwarf_read_debug)
11195     {
11196       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
11197                           kind,
11198                           pulongest (unit_index), hex_string (signature),
11199                           dwp_file->name);
11200     }
11201
11202   /* Fetch the sections of this DWO unit.
11203      Put a limit on the number of sections we look for so that bad data
11204      doesn't cause us to loop forever.  */
11205
11206 #define MAX_NR_V1_DWO_SECTIONS \
11207   (1 /* .debug_info or .debug_types */ \
11208    + 1 /* .debug_abbrev */ \
11209    + 1 /* .debug_line */ \
11210    + 1 /* .debug_loc */ \
11211    + 1 /* .debug_str_offsets */ \
11212    + 1 /* .debug_macro or .debug_macinfo */ \
11213    + 1 /* trailing zero */)
11214
11215   memset (&sections, 0, sizeof (sections));
11216
11217   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
11218     {
11219       asection *sectp;
11220       uint32_t section_nr =
11221         read_4_bytes (dbfd,
11222                       dwp_htab->section_pool.v1.indices
11223                       + (unit_index + i) * sizeof (uint32_t));
11224
11225       if (section_nr == 0)
11226         break;
11227       if (section_nr >= dwp_file->num_sections)
11228         {
11229           error (_("Dwarf Error: bad DWP hash table, section number too large"
11230                    " [in module %s]"),
11231                  dwp_file->name);
11232         }
11233
11234       sectp = dwp_file->elf_sections[section_nr];
11235       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
11236         {
11237           error (_("Dwarf Error: bad DWP hash table, invalid section found"
11238                    " [in module %s]"),
11239                  dwp_file->name);
11240         }
11241     }
11242
11243   if (i < 2
11244       || dwarf2_section_empty_p (&sections.info_or_types)
11245       || dwarf2_section_empty_p (&sections.abbrev))
11246     {
11247       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
11248                " [in module %s]"),
11249              dwp_file->name);
11250     }
11251   if (i == MAX_NR_V1_DWO_SECTIONS)
11252     {
11253       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
11254                " [in module %s]"),
11255              dwp_file->name);
11256     }
11257
11258   /* It's easier for the rest of the code if we fake a struct dwo_file and
11259      have dwo_unit "live" in that.  At least for now.
11260
11261      The DWP file can be made up of a random collection of CUs and TUs.
11262      However, for each CU + set of TUs that came from the same original DWO
11263      file, we can combine them back into a virtual DWO file to save space
11264      (fewer struct dwo_file objects to allocate).  Remember that for really
11265      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11266
11267   std::string virtual_dwo_name =
11268     string_printf ("virtual-dwo/%d-%d-%d-%d",
11269                    get_section_id (&sections.abbrev),
11270                    get_section_id (&sections.line),
11271                    get_section_id (&sections.loc),
11272                    get_section_id (&sections.str_offsets));
11273   /* Can we use an existing virtual DWO file?  */
11274   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
11275   /* Create one if necessary.  */
11276   if (*dwo_file_slot == NULL)
11277     {
11278       if (dwarf_read_debug)
11279         {
11280           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11281                               virtual_dwo_name.c_str ());
11282         }
11283       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11284       dwo_file->dwo_name
11285         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11286                                         virtual_dwo_name.c_str (),
11287                                         virtual_dwo_name.size ());
11288       dwo_file->comp_dir = comp_dir;
11289       dwo_file->sections.abbrev = sections.abbrev;
11290       dwo_file->sections.line = sections.line;
11291       dwo_file->sections.loc = sections.loc;
11292       dwo_file->sections.macinfo = sections.macinfo;
11293       dwo_file->sections.macro = sections.macro;
11294       dwo_file->sections.str_offsets = sections.str_offsets;
11295       /* The "str" section is global to the entire DWP file.  */
11296       dwo_file->sections.str = dwp_file->sections.str;
11297       /* The info or types section is assigned below to dwo_unit,
11298          there's no need to record it in dwo_file.
11299          Also, we can't simply record type sections in dwo_file because
11300          we record a pointer into the vector in dwo_unit.  As we collect more
11301          types we'll grow the vector and eventually have to reallocate space
11302          for it, invalidating all copies of pointers into the previous
11303          contents.  */
11304       *dwo_file_slot = dwo_file;
11305     }
11306   else
11307     {
11308       if (dwarf_read_debug)
11309         {
11310           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11311                               virtual_dwo_name.c_str ());
11312         }
11313       dwo_file = (struct dwo_file *) *dwo_file_slot;
11314     }
11315
11316   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11317   dwo_unit->dwo_file = dwo_file;
11318   dwo_unit->signature = signature;
11319   dwo_unit->section =
11320     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11321   *dwo_unit->section = sections.info_or_types;
11322   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11323
11324   return dwo_unit;
11325 }
11326
11327 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
11328    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
11329    piece within that section used by a TU/CU, return a virtual section
11330    of just that piece.  */
11331
11332 static struct dwarf2_section_info
11333 create_dwp_v2_section (struct dwarf2_section_info *section,
11334                        bfd_size_type offset, bfd_size_type size)
11335 {
11336   struct dwarf2_section_info result;
11337   asection *sectp;
11338
11339   gdb_assert (section != NULL);
11340   gdb_assert (!section->is_virtual);
11341
11342   memset (&result, 0, sizeof (result));
11343   result.s.containing_section = section;
11344   result.is_virtual = 1;
11345
11346   if (size == 0)
11347     return result;
11348
11349   sectp = get_section_bfd_section (section);
11350
11351   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
11352      bounds of the real section.  This is a pretty-rare event, so just
11353      flag an error (easier) instead of a warning and trying to cope.  */
11354   if (sectp == NULL
11355       || offset + size > bfd_get_section_size (sectp))
11356     {
11357       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
11358                " in section %s [in module %s]"),
11359              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
11360              objfile_name (dwarf2_per_objfile->objfile));
11361     }
11362
11363   result.virtual_offset = offset;
11364   result.size = size;
11365   return result;
11366 }
11367
11368 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11369    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11370    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11371    This is for DWP version 2 files.  */
11372
11373 static struct dwo_unit *
11374 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
11375                            uint32_t unit_index,
11376                            const char *comp_dir,
11377                            ULONGEST signature, int is_debug_types)
11378 {
11379   struct objfile *objfile = dwarf2_per_objfile->objfile;
11380   const struct dwp_hash_table *dwp_htab =
11381     is_debug_types ? dwp_file->tus : dwp_file->cus;
11382   bfd *dbfd = dwp_file->dbfd;
11383   const char *kind = is_debug_types ? "TU" : "CU";
11384   struct dwo_file *dwo_file;
11385   struct dwo_unit *dwo_unit;
11386   struct virtual_v2_dwo_sections sections;
11387   void **dwo_file_slot;
11388   int i;
11389
11390   gdb_assert (dwp_file->version == 2);
11391
11392   if (dwarf_read_debug)
11393     {
11394       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
11395                           kind,
11396                           pulongest (unit_index), hex_string (signature),
11397                           dwp_file->name);
11398     }
11399
11400   /* Fetch the section offsets of this DWO unit.  */
11401
11402   memset (&sections, 0, sizeof (sections));
11403
11404   for (i = 0; i < dwp_htab->nr_columns; ++i)
11405     {
11406       uint32_t offset = read_4_bytes (dbfd,
11407                                       dwp_htab->section_pool.v2.offsets
11408                                       + (((unit_index - 1) * dwp_htab->nr_columns
11409                                           + i)
11410                                          * sizeof (uint32_t)));
11411       uint32_t size = read_4_bytes (dbfd,
11412                                     dwp_htab->section_pool.v2.sizes
11413                                     + (((unit_index - 1) * dwp_htab->nr_columns
11414                                         + i)
11415                                        * sizeof (uint32_t)));
11416
11417       switch (dwp_htab->section_pool.v2.section_ids[i])
11418         {
11419         case DW_SECT_INFO:
11420         case DW_SECT_TYPES:
11421           sections.info_or_types_offset = offset;
11422           sections.info_or_types_size = size;
11423           break;
11424         case DW_SECT_ABBREV:
11425           sections.abbrev_offset = offset;
11426           sections.abbrev_size = size;
11427           break;
11428         case DW_SECT_LINE:
11429           sections.line_offset = offset;
11430           sections.line_size = size;
11431           break;
11432         case DW_SECT_LOC:
11433           sections.loc_offset = offset;
11434           sections.loc_size = size;
11435           break;
11436         case DW_SECT_STR_OFFSETS:
11437           sections.str_offsets_offset = offset;
11438           sections.str_offsets_size = size;
11439           break;
11440         case DW_SECT_MACINFO:
11441           sections.macinfo_offset = offset;
11442           sections.macinfo_size = size;
11443           break;
11444         case DW_SECT_MACRO:
11445           sections.macro_offset = offset;
11446           sections.macro_size = size;
11447           break;
11448         }
11449     }
11450
11451   /* It's easier for the rest of the code if we fake a struct dwo_file and
11452      have dwo_unit "live" in that.  At least for now.
11453
11454      The DWP file can be made up of a random collection of CUs and TUs.
11455      However, for each CU + set of TUs that came from the same original DWO
11456      file, we can combine them back into a virtual DWO file to save space
11457      (fewer struct dwo_file objects to allocate).  Remember that for really
11458      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11459
11460   std::string virtual_dwo_name =
11461     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
11462                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11463                    (long) (sections.line_size ? sections.line_offset : 0),
11464                    (long) (sections.loc_size ? sections.loc_offset : 0),
11465                    (long) (sections.str_offsets_size
11466                            ? sections.str_offsets_offset : 0));
11467   /* Can we use an existing virtual DWO file?  */
11468   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
11469   /* Create one if necessary.  */
11470   if (*dwo_file_slot == NULL)
11471     {
11472       if (dwarf_read_debug)
11473         {
11474           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11475                               virtual_dwo_name.c_str ());
11476         }
11477       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11478       dwo_file->dwo_name
11479         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11480                                         virtual_dwo_name.c_str (),
11481                                         virtual_dwo_name.size ());
11482       dwo_file->comp_dir = comp_dir;
11483       dwo_file->sections.abbrev =
11484         create_dwp_v2_section (&dwp_file->sections.abbrev,
11485                                sections.abbrev_offset, sections.abbrev_size);
11486       dwo_file->sections.line =
11487         create_dwp_v2_section (&dwp_file->sections.line,
11488                                sections.line_offset, sections.line_size);
11489       dwo_file->sections.loc =
11490         create_dwp_v2_section (&dwp_file->sections.loc,
11491                                sections.loc_offset, sections.loc_size);
11492       dwo_file->sections.macinfo =
11493         create_dwp_v2_section (&dwp_file->sections.macinfo,
11494                                sections.macinfo_offset, sections.macinfo_size);
11495       dwo_file->sections.macro =
11496         create_dwp_v2_section (&dwp_file->sections.macro,
11497                                sections.macro_offset, sections.macro_size);
11498       dwo_file->sections.str_offsets =
11499         create_dwp_v2_section (&dwp_file->sections.str_offsets,
11500                                sections.str_offsets_offset,
11501                                sections.str_offsets_size);
11502       /* The "str" section is global to the entire DWP file.  */
11503       dwo_file->sections.str = dwp_file->sections.str;
11504       /* The info or types section is assigned below to dwo_unit,
11505          there's no need to record it in dwo_file.
11506          Also, we can't simply record type sections in dwo_file because
11507          we record a pointer into the vector in dwo_unit.  As we collect more
11508          types we'll grow the vector and eventually have to reallocate space
11509          for it, invalidating all copies of pointers into the previous
11510          contents.  */
11511       *dwo_file_slot = dwo_file;
11512     }
11513   else
11514     {
11515       if (dwarf_read_debug)
11516         {
11517           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11518                               virtual_dwo_name.c_str ());
11519         }
11520       dwo_file = (struct dwo_file *) *dwo_file_slot;
11521     }
11522
11523   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11524   dwo_unit->dwo_file = dwo_file;
11525   dwo_unit->signature = signature;
11526   dwo_unit->section =
11527     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11528   *dwo_unit->section = create_dwp_v2_section (is_debug_types
11529                                               ? &dwp_file->sections.types
11530                                               : &dwp_file->sections.info,
11531                                               sections.info_or_types_offset,
11532                                               sections.info_or_types_size);
11533   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11534
11535   return dwo_unit;
11536 }
11537
11538 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
11539    Returns NULL if the signature isn't found.  */
11540
11541 static struct dwo_unit *
11542 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
11543                         ULONGEST signature, int is_debug_types)
11544 {
11545   const struct dwp_hash_table *dwp_htab =
11546     is_debug_types ? dwp_file->tus : dwp_file->cus;
11547   bfd *dbfd = dwp_file->dbfd;
11548   uint32_t mask = dwp_htab->nr_slots - 1;
11549   uint32_t hash = signature & mask;
11550   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11551   unsigned int i;
11552   void **slot;
11553   struct dwo_unit find_dwo_cu;
11554
11555   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11556   find_dwo_cu.signature = signature;
11557   slot = htab_find_slot (is_debug_types
11558                          ? dwp_file->loaded_tus
11559                          : dwp_file->loaded_cus,
11560                          &find_dwo_cu, INSERT);
11561
11562   if (*slot != NULL)
11563     return (struct dwo_unit *) *slot;
11564
11565   /* Use a for loop so that we don't loop forever on bad debug info.  */
11566   for (i = 0; i < dwp_htab->nr_slots; ++i)
11567     {
11568       ULONGEST signature_in_table;
11569
11570       signature_in_table =
11571         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11572       if (signature_in_table == signature)
11573         {
11574           uint32_t unit_index =
11575             read_4_bytes (dbfd,
11576                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11577
11578           if (dwp_file->version == 1)
11579             {
11580               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
11581                                                  comp_dir, signature,
11582                                                  is_debug_types);
11583             }
11584           else
11585             {
11586               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
11587                                                  comp_dir, signature,
11588                                                  is_debug_types);
11589             }
11590           return (struct dwo_unit *) *slot;
11591         }
11592       if (signature_in_table == 0)
11593         return NULL;
11594       hash = (hash + hash2) & mask;
11595     }
11596
11597   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11598            " [in module %s]"),
11599          dwp_file->name);
11600 }
11601
11602 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11603    Open the file specified by FILE_NAME and hand it off to BFD for
11604    preliminary analysis.  Return a newly initialized bfd *, which
11605    includes a canonicalized copy of FILE_NAME.
11606    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11607    SEARCH_CWD is true if the current directory is to be searched.
11608    It will be searched before debug-file-directory.
11609    If successful, the file is added to the bfd include table of the
11610    objfile's bfd (see gdb_bfd_record_inclusion).
11611    If unable to find/open the file, return NULL.
11612    NOTE: This function is derived from symfile_bfd_open.  */
11613
11614 static gdb_bfd_ref_ptr
11615 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
11616 {
11617   int desc, flags;
11618   char *absolute_name;
11619   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
11620      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
11621      to debug_file_directory.  */
11622   char *search_path;
11623   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
11624
11625   if (search_cwd)
11626     {
11627       if (*debug_file_directory != '\0')
11628         search_path = concat (".", dirname_separator_string,
11629                               debug_file_directory, (char *) NULL);
11630       else
11631         search_path = xstrdup (".");
11632     }
11633   else
11634     search_path = xstrdup (debug_file_directory);
11635
11636   flags = OPF_RETURN_REALPATH;
11637   if (is_dwp)
11638     flags |= OPF_SEARCH_IN_PATH;
11639   desc = openp (search_path, flags, file_name,
11640                 O_RDONLY | O_BINARY, &absolute_name);
11641   xfree (search_path);
11642   if (desc < 0)
11643     return NULL;
11644
11645   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
11646   xfree (absolute_name);
11647   if (sym_bfd == NULL)
11648     return NULL;
11649   bfd_set_cacheable (sym_bfd.get (), 1);
11650
11651   if (!bfd_check_format (sym_bfd.get (), bfd_object))
11652     return NULL;
11653
11654   /* Success.  Record the bfd as having been included by the objfile's bfd.
11655      This is important because things like demangled_names_hash lives in the
11656      objfile's per_bfd space and may have references to things like symbol
11657      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
11658   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
11659
11660   return sym_bfd;
11661 }
11662
11663 /* Try to open DWO file FILE_NAME.
11664    COMP_DIR is the DW_AT_comp_dir attribute.
11665    The result is the bfd handle of the file.
11666    If there is a problem finding or opening the file, return NULL.
11667    Upon success, the canonicalized path of the file is stored in the bfd,
11668    same as symfile_bfd_open.  */
11669
11670 static gdb_bfd_ref_ptr
11671 open_dwo_file (const char *file_name, const char *comp_dir)
11672 {
11673   if (IS_ABSOLUTE_PATH (file_name))
11674     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
11675
11676   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
11677
11678   if (comp_dir != NULL)
11679     {
11680       char *path_to_try = concat (comp_dir, SLASH_STRING,
11681                                   file_name, (char *) NULL);
11682
11683       /* NOTE: If comp_dir is a relative path, this will also try the
11684          search path, which seems useful.  */
11685       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
11686                                                 1 /*search_cwd*/));
11687       xfree (path_to_try);
11688       if (abfd != NULL)
11689         return abfd;
11690     }
11691
11692   /* That didn't work, try debug-file-directory, which, despite its name,
11693      is a list of paths.  */
11694
11695   if (*debug_file_directory == '\0')
11696     return NULL;
11697
11698   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
11699 }
11700
11701 /* This function is mapped across the sections and remembers the offset and
11702    size of each of the DWO debugging sections we are interested in.  */
11703
11704 static void
11705 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
11706 {
11707   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
11708   const struct dwop_section_names *names = &dwop_section_names;
11709
11710   if (section_is_p (sectp->name, &names->abbrev_dwo))
11711     {
11712       dwo_sections->abbrev.s.section = sectp;
11713       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
11714     }
11715   else if (section_is_p (sectp->name, &names->info_dwo))
11716     {
11717       dwo_sections->info.s.section = sectp;
11718       dwo_sections->info.size = bfd_get_section_size (sectp);
11719     }
11720   else if (section_is_p (sectp->name, &names->line_dwo))
11721     {
11722       dwo_sections->line.s.section = sectp;
11723       dwo_sections->line.size = bfd_get_section_size (sectp);
11724     }
11725   else if (section_is_p (sectp->name, &names->loc_dwo))
11726     {
11727       dwo_sections->loc.s.section = sectp;
11728       dwo_sections->loc.size = bfd_get_section_size (sectp);
11729     }
11730   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11731     {
11732       dwo_sections->macinfo.s.section = sectp;
11733       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
11734     }
11735   else if (section_is_p (sectp->name, &names->macro_dwo))
11736     {
11737       dwo_sections->macro.s.section = sectp;
11738       dwo_sections->macro.size = bfd_get_section_size (sectp);
11739     }
11740   else if (section_is_p (sectp->name, &names->str_dwo))
11741     {
11742       dwo_sections->str.s.section = sectp;
11743       dwo_sections->str.size = bfd_get_section_size (sectp);
11744     }
11745   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11746     {
11747       dwo_sections->str_offsets.s.section = sectp;
11748       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
11749     }
11750   else if (section_is_p (sectp->name, &names->types_dwo))
11751     {
11752       struct dwarf2_section_info type_section;
11753
11754       memset (&type_section, 0, sizeof (type_section));
11755       type_section.s.section = sectp;
11756       type_section.size = bfd_get_section_size (sectp);
11757       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
11758                      &type_section);
11759     }
11760 }
11761
11762 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
11763    by PER_CU.  This is for the non-DWP case.
11764    The result is NULL if DWO_NAME can't be found.  */
11765
11766 static struct dwo_file *
11767 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
11768                         const char *dwo_name, const char *comp_dir)
11769 {
11770   struct objfile *objfile = dwarf2_per_objfile->objfile;
11771   struct dwo_file *dwo_file;
11772   struct cleanup *cleanups;
11773
11774   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
11775   if (dbfd == NULL)
11776     {
11777       if (dwarf_read_debug)
11778         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
11779       return NULL;
11780     }
11781   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11782   dwo_file->dwo_name = dwo_name;
11783   dwo_file->comp_dir = comp_dir;
11784   dwo_file->dbfd = dbfd.release ();
11785
11786   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
11787
11788   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
11789                          &dwo_file->sections);
11790
11791   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
11792
11793   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
11794                                  dwo_file->tus);
11795
11796   discard_cleanups (cleanups);
11797
11798   if (dwarf_read_debug)
11799     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
11800
11801   return dwo_file;
11802 }
11803
11804 /* This function is mapped across the sections and remembers the offset and
11805    size of each of the DWP debugging sections common to version 1 and 2 that
11806    we are interested in.  */
11807
11808 static void
11809 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
11810                                    void *dwp_file_ptr)
11811 {
11812   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11813   const struct dwop_section_names *names = &dwop_section_names;
11814   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11815
11816   /* Record the ELF section number for later lookup: this is what the
11817      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11818   gdb_assert (elf_section_nr < dwp_file->num_sections);
11819   dwp_file->elf_sections[elf_section_nr] = sectp;
11820
11821   /* Look for specific sections that we need.  */
11822   if (section_is_p (sectp->name, &names->str_dwo))
11823     {
11824       dwp_file->sections.str.s.section = sectp;
11825       dwp_file->sections.str.size = bfd_get_section_size (sectp);
11826     }
11827   else if (section_is_p (sectp->name, &names->cu_index))
11828     {
11829       dwp_file->sections.cu_index.s.section = sectp;
11830       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
11831     }
11832   else if (section_is_p (sectp->name, &names->tu_index))
11833     {
11834       dwp_file->sections.tu_index.s.section = sectp;
11835       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
11836     }
11837 }
11838
11839 /* This function is mapped across the sections and remembers the offset and
11840    size of each of the DWP version 2 debugging sections that we are interested
11841    in.  This is split into a separate function because we don't know if we
11842    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11843
11844 static void
11845 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11846 {
11847   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11848   const struct dwop_section_names *names = &dwop_section_names;
11849   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11850
11851   /* Record the ELF section number for later lookup: this is what the
11852      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11853   gdb_assert (elf_section_nr < dwp_file->num_sections);
11854   dwp_file->elf_sections[elf_section_nr] = sectp;
11855
11856   /* Look for specific sections that we need.  */
11857   if (section_is_p (sectp->name, &names->abbrev_dwo))
11858     {
11859       dwp_file->sections.abbrev.s.section = sectp;
11860       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11861     }
11862   else if (section_is_p (sectp->name, &names->info_dwo))
11863     {
11864       dwp_file->sections.info.s.section = sectp;
11865       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11866     }
11867   else if (section_is_p (sectp->name, &names->line_dwo))
11868     {
11869       dwp_file->sections.line.s.section = sectp;
11870       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11871     }
11872   else if (section_is_p (sectp->name, &names->loc_dwo))
11873     {
11874       dwp_file->sections.loc.s.section = sectp;
11875       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11876     }
11877   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11878     {
11879       dwp_file->sections.macinfo.s.section = sectp;
11880       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11881     }
11882   else if (section_is_p (sectp->name, &names->macro_dwo))
11883     {
11884       dwp_file->sections.macro.s.section = sectp;
11885       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11886     }
11887   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11888     {
11889       dwp_file->sections.str_offsets.s.section = sectp;
11890       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11891     }
11892   else if (section_is_p (sectp->name, &names->types_dwo))
11893     {
11894       dwp_file->sections.types.s.section = sectp;
11895       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11896     }
11897 }
11898
11899 /* Hash function for dwp_file loaded CUs/TUs.  */
11900
11901 static hashval_t
11902 hash_dwp_loaded_cutus (const void *item)
11903 {
11904   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11905
11906   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11907   return dwo_unit->signature;
11908 }
11909
11910 /* Equality function for dwp_file loaded CUs/TUs.  */
11911
11912 static int
11913 eq_dwp_loaded_cutus (const void *a, const void *b)
11914 {
11915   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11916   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11917
11918   return dua->signature == dub->signature;
11919 }
11920
11921 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11922
11923 static htab_t
11924 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11925 {
11926   return htab_create_alloc_ex (3,
11927                                hash_dwp_loaded_cutus,
11928                                eq_dwp_loaded_cutus,
11929                                NULL,
11930                                &objfile->objfile_obstack,
11931                                hashtab_obstack_allocate,
11932                                dummy_obstack_deallocate);
11933 }
11934
11935 /* Try to open DWP file FILE_NAME.
11936    The result is the bfd handle of the file.
11937    If there is a problem finding or opening the file, return NULL.
11938    Upon success, the canonicalized path of the file is stored in the bfd,
11939    same as symfile_bfd_open.  */
11940
11941 static gdb_bfd_ref_ptr
11942 open_dwp_file (const char *file_name)
11943 {
11944   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11945                                             1 /*search_cwd*/));
11946   if (abfd != NULL)
11947     return abfd;
11948
11949   /* Work around upstream bug 15652.
11950      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11951      [Whether that's a "bug" is debatable, but it is getting in our way.]
11952      We have no real idea where the dwp file is, because gdb's realpath-ing
11953      of the executable's path may have discarded the needed info.
11954      [IWBN if the dwp file name was recorded in the executable, akin to
11955      .gnu_debuglink, but that doesn't exist yet.]
11956      Strip the directory from FILE_NAME and search again.  */
11957   if (*debug_file_directory != '\0')
11958     {
11959       /* Don't implicitly search the current directory here.
11960          If the user wants to search "." to handle this case,
11961          it must be added to debug-file-directory.  */
11962       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11963                                  0 /*search_cwd*/);
11964     }
11965
11966   return NULL;
11967 }
11968
11969 /* Initialize the use of the DWP file for the current objfile.
11970    By convention the name of the DWP file is ${objfile}.dwp.
11971    The result is NULL if it can't be found.  */
11972
11973 static struct dwp_file *
11974 open_and_init_dwp_file (void)
11975 {
11976   struct objfile *objfile = dwarf2_per_objfile->objfile;
11977   struct dwp_file *dwp_file;
11978
11979   /* Try to find first .dwp for the binary file before any symbolic links
11980      resolving.  */
11981
11982   /* If the objfile is a debug file, find the name of the real binary
11983      file and get the name of dwp file from there.  */
11984   std::string dwp_name;
11985   if (objfile->separate_debug_objfile_backlink != NULL)
11986     {
11987       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11988       const char *backlink_basename = lbasename (backlink->original_name);
11989
11990       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11991     }
11992   else
11993     dwp_name = objfile->original_name;
11994
11995   dwp_name += ".dwp";
11996
11997   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11998   if (dbfd == NULL
11999       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12000     {
12001       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12002       dwp_name = objfile_name (objfile);
12003       dwp_name += ".dwp";
12004       dbfd = open_dwp_file (dwp_name.c_str ());
12005     }
12006
12007   if (dbfd == NULL)
12008     {
12009       if (dwarf_read_debug)
12010         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
12011       return NULL;
12012     }
12013   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
12014   dwp_file->name = bfd_get_filename (dbfd.get ());
12015   dwp_file->dbfd = dbfd.release ();
12016
12017   /* +1: section 0 is unused */
12018   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
12019   dwp_file->elf_sections =
12020     OBSTACK_CALLOC (&objfile->objfile_obstack,
12021                     dwp_file->num_sections, asection *);
12022
12023   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
12024                          dwp_file);
12025
12026   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
12027
12028   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
12029
12030   /* The DWP file version is stored in the hash table.  Oh well.  */
12031   if (dwp_file->cus && dwp_file->tus
12032       && dwp_file->cus->version != dwp_file->tus->version)
12033     {
12034       /* Technically speaking, we should try to limp along, but this is
12035          pretty bizarre.  We use pulongest here because that's the established
12036          portability solution (e.g, we cannot use %u for uint32_t).  */
12037       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12038                " TU version %s [in DWP file %s]"),
12039              pulongest (dwp_file->cus->version),
12040              pulongest (dwp_file->tus->version), dwp_name.c_str ());
12041     }
12042
12043   if (dwp_file->cus)
12044     dwp_file->version = dwp_file->cus->version;
12045   else if (dwp_file->tus)
12046     dwp_file->version = dwp_file->tus->version;
12047   else
12048     dwp_file->version = 2;
12049
12050   if (dwp_file->version == 2)
12051     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
12052                            dwp_file);
12053
12054   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
12055   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
12056
12057   if (dwarf_read_debug)
12058     {
12059       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
12060       fprintf_unfiltered (gdb_stdlog,
12061                           "    %s CUs, %s TUs\n",
12062                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12063                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12064     }
12065
12066   return dwp_file;
12067 }
12068
12069 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12070
12071 static struct dwp_file *
12072 get_dwp_file (void)
12073 {
12074   if (! dwarf2_per_objfile->dwp_checked)
12075     {
12076       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
12077       dwarf2_per_objfile->dwp_checked = 1;
12078     }
12079   return dwarf2_per_objfile->dwp_file;
12080 }
12081
12082 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12083    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12084    or in the DWP file for the objfile, referenced by THIS_UNIT.
12085    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12086    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12087
12088    This is called, for example, when wanting to read a variable with a
12089    complex location.  Therefore we don't want to do file i/o for every call.
12090    Therefore we don't want to look for a DWO file on every call.
12091    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12092    then we check if we've already seen DWO_NAME, and only THEN do we check
12093    for a DWO file.
12094
12095    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12096    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12097
12098 static struct dwo_unit *
12099 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
12100                  const char *dwo_name, const char *comp_dir,
12101                  ULONGEST signature, int is_debug_types)
12102 {
12103   struct objfile *objfile = dwarf2_per_objfile->objfile;
12104   const char *kind = is_debug_types ? "TU" : "CU";
12105   void **dwo_file_slot;
12106   struct dwo_file *dwo_file;
12107   struct dwp_file *dwp_file;
12108
12109   /* First see if there's a DWP file.
12110      If we have a DWP file but didn't find the DWO inside it, don't
12111      look for the original DWO file.  It makes gdb behave differently
12112      depending on whether one is debugging in the build tree.  */
12113
12114   dwp_file = get_dwp_file ();
12115   if (dwp_file != NULL)
12116     {
12117       const struct dwp_hash_table *dwp_htab =
12118         is_debug_types ? dwp_file->tus : dwp_file->cus;
12119
12120       if (dwp_htab != NULL)
12121         {
12122           struct dwo_unit *dwo_cutu =
12123             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
12124                                     signature, is_debug_types);
12125
12126           if (dwo_cutu != NULL)
12127             {
12128               if (dwarf_read_debug)
12129                 {
12130                   fprintf_unfiltered (gdb_stdlog,
12131                                       "Virtual DWO %s %s found: @%s\n",
12132                                       kind, hex_string (signature),
12133                                       host_address_to_string (dwo_cutu));
12134                 }
12135               return dwo_cutu;
12136             }
12137         }
12138     }
12139   else
12140     {
12141       /* No DWP file, look for the DWO file.  */
12142
12143       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
12144       if (*dwo_file_slot == NULL)
12145         {
12146           /* Read in the file and build a table of the CUs/TUs it contains.  */
12147           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
12148         }
12149       /* NOTE: This will be NULL if unable to open the file.  */
12150       dwo_file = (struct dwo_file *) *dwo_file_slot;
12151
12152       if (dwo_file != NULL)
12153         {
12154           struct dwo_unit *dwo_cutu = NULL;
12155
12156           if (is_debug_types && dwo_file->tus)
12157             {
12158               struct dwo_unit find_dwo_cutu;
12159
12160               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12161               find_dwo_cutu.signature = signature;
12162               dwo_cutu
12163                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
12164             }
12165           else if (!is_debug_types && dwo_file->cus)
12166             {
12167               struct dwo_unit find_dwo_cutu;
12168
12169               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12170               find_dwo_cutu.signature = signature;
12171               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
12172                                                        &find_dwo_cutu);
12173             }
12174
12175           if (dwo_cutu != NULL)
12176             {
12177               if (dwarf_read_debug)
12178                 {
12179                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
12180                                       kind, dwo_name, hex_string (signature),
12181                                       host_address_to_string (dwo_cutu));
12182                 }
12183               return dwo_cutu;
12184             }
12185         }
12186     }
12187
12188   /* We didn't find it.  This could mean a dwo_id mismatch, or
12189      someone deleted the DWO/DWP file, or the search path isn't set up
12190      correctly to find the file.  */
12191
12192   if (dwarf_read_debug)
12193     {
12194       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
12195                           kind, dwo_name, hex_string (signature));
12196     }
12197
12198   /* This is a warning and not a complaint because it can be caused by
12199      pilot error (e.g., user accidentally deleting the DWO).  */
12200   {
12201     /* Print the name of the DWP file if we looked there, helps the user
12202        better diagnose the problem.  */
12203     std::string dwp_text;
12204
12205     if (dwp_file != NULL)
12206       dwp_text = string_printf (" [in DWP file %s]",
12207                                 lbasename (dwp_file->name));
12208
12209     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
12210                " [in module %s]"),
12211              kind, dwo_name, hex_string (signature),
12212              dwp_text.c_str (),
12213              this_unit->is_debug_types ? "TU" : "CU",
12214              to_underlying (this_unit->sect_off), objfile_name (objfile));
12215   }
12216   return NULL;
12217 }
12218
12219 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
12220    See lookup_dwo_cutu_unit for details.  */
12221
12222 static struct dwo_unit *
12223 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
12224                       const char *dwo_name, const char *comp_dir,
12225                       ULONGEST signature)
12226 {
12227   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
12228 }
12229
12230 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
12231    See lookup_dwo_cutu_unit for details.  */
12232
12233 static struct dwo_unit *
12234 lookup_dwo_type_unit (struct signatured_type *this_tu,
12235                       const char *dwo_name, const char *comp_dir)
12236 {
12237   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
12238 }
12239
12240 /* Traversal function for queue_and_load_all_dwo_tus.  */
12241
12242 static int
12243 queue_and_load_dwo_tu (void **slot, void *info)
12244 {
12245   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
12246   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
12247   ULONGEST signature = dwo_unit->signature;
12248   struct signatured_type *sig_type =
12249     lookup_dwo_signatured_type (per_cu->cu, signature);
12250
12251   if (sig_type != NULL)
12252     {
12253       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
12254
12255       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
12256          a real dependency of PER_CU on SIG_TYPE.  That is detected later
12257          while processing PER_CU.  */
12258       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
12259         load_full_type_unit (sig_cu);
12260       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
12261     }
12262
12263   return 1;
12264 }
12265
12266 /* Queue all TUs contained in the DWO of PER_CU to be read in.
12267    The DWO may have the only definition of the type, though it may not be
12268    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
12269    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
12270
12271 static void
12272 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
12273 {
12274   struct dwo_unit *dwo_unit;
12275   struct dwo_file *dwo_file;
12276
12277   gdb_assert (!per_cu->is_debug_types);
12278   gdb_assert (get_dwp_file () == NULL);
12279   gdb_assert (per_cu->cu != NULL);
12280
12281   dwo_unit = per_cu->cu->dwo_unit;
12282   gdb_assert (dwo_unit != NULL);
12283
12284   dwo_file = dwo_unit->dwo_file;
12285   if (dwo_file->tus != NULL)
12286     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
12287 }
12288
12289 /* Free all resources associated with DWO_FILE.
12290    Close the DWO file and munmap the sections.
12291    All memory should be on the objfile obstack.  */
12292
12293 static void
12294 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
12295 {
12296
12297   /* Note: dbfd is NULL for virtual DWO files.  */
12298   gdb_bfd_unref (dwo_file->dbfd);
12299
12300   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
12301 }
12302
12303 /* Wrapper for free_dwo_file for use in cleanups.  */
12304
12305 static void
12306 free_dwo_file_cleanup (void *arg)
12307 {
12308   struct dwo_file *dwo_file = (struct dwo_file *) arg;
12309   struct objfile *objfile = dwarf2_per_objfile->objfile;
12310
12311   free_dwo_file (dwo_file, objfile);
12312 }
12313
12314 /* Traversal function for free_dwo_files.  */
12315
12316 static int
12317 free_dwo_file_from_slot (void **slot, void *info)
12318 {
12319   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
12320   struct objfile *objfile = (struct objfile *) info;
12321
12322   free_dwo_file (dwo_file, objfile);
12323
12324   return 1;
12325 }
12326
12327 /* Free all resources associated with DWO_FILES.  */
12328
12329 static void
12330 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
12331 {
12332   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
12333 }
12334 \f
12335 /* Read in various DIEs.  */
12336
12337 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
12338    Inherit only the children of the DW_AT_abstract_origin DIE not being
12339    already referenced by DW_AT_abstract_origin from the children of the
12340    current DIE.  */
12341
12342 static void
12343 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
12344 {
12345   struct die_info *child_die;
12346   sect_offset *offsetp;
12347   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
12348   struct die_info *origin_die;
12349   /* Iterator of the ORIGIN_DIE children.  */
12350   struct die_info *origin_child_die;
12351   struct attribute *attr;
12352   struct dwarf2_cu *origin_cu;
12353   struct pending **origin_previous_list_in_scope;
12354
12355   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12356   if (!attr)
12357     return;
12358
12359   /* Note that following die references may follow to a die in a
12360      different cu.  */
12361
12362   origin_cu = cu;
12363   origin_die = follow_die_ref (die, attr, &origin_cu);
12364
12365   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
12366      symbols in.  */
12367   origin_previous_list_in_scope = origin_cu->list_in_scope;
12368   origin_cu->list_in_scope = cu->list_in_scope;
12369
12370   if (die->tag != origin_die->tag
12371       && !(die->tag == DW_TAG_inlined_subroutine
12372            && origin_die->tag == DW_TAG_subprogram))
12373     complaint (&symfile_complaints,
12374                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
12375                to_underlying (die->sect_off),
12376                to_underlying (origin_die->sect_off));
12377
12378   std::vector<sect_offset> offsets;
12379
12380   for (child_die = die->child;
12381        child_die && child_die->tag;
12382        child_die = sibling_die (child_die))
12383     {
12384       struct die_info *child_origin_die;
12385       struct dwarf2_cu *child_origin_cu;
12386
12387       /* We are trying to process concrete instance entries:
12388          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
12389          it's not relevant to our analysis here. i.e. detecting DIEs that are
12390          present in the abstract instance but not referenced in the concrete
12391          one.  */
12392       if (child_die->tag == DW_TAG_call_site
12393           || child_die->tag == DW_TAG_GNU_call_site)
12394         continue;
12395
12396       /* For each CHILD_DIE, find the corresponding child of
12397          ORIGIN_DIE.  If there is more than one layer of
12398          DW_AT_abstract_origin, follow them all; there shouldn't be,
12399          but GCC versions at least through 4.4 generate this (GCC PR
12400          40573).  */
12401       child_origin_die = child_die;
12402       child_origin_cu = cu;
12403       while (1)
12404         {
12405           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
12406                               child_origin_cu);
12407           if (attr == NULL)
12408             break;
12409           child_origin_die = follow_die_ref (child_origin_die, attr,
12410                                              &child_origin_cu);
12411         }
12412
12413       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
12414          counterpart may exist.  */
12415       if (child_origin_die != child_die)
12416         {
12417           if (child_die->tag != child_origin_die->tag
12418               && !(child_die->tag == DW_TAG_inlined_subroutine
12419                    && child_origin_die->tag == DW_TAG_subprogram))
12420             complaint (&symfile_complaints,
12421                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12422                          "different tags"),
12423                        to_underlying (child_die->sect_off),
12424                        to_underlying (child_origin_die->sect_off));
12425           if (child_origin_die->parent != origin_die)
12426             complaint (&symfile_complaints,
12427                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12428                          "different parents"),
12429                        to_underlying (child_die->sect_off),
12430                        to_underlying (child_origin_die->sect_off));
12431           else
12432             offsets.push_back (child_origin_die->sect_off);
12433         }
12434     }
12435   std::sort (offsets.begin (), offsets.end ());
12436   sect_offset *offsets_end = offsets.data () + offsets.size ();
12437   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
12438     if (offsetp[-1] == *offsetp)
12439       complaint (&symfile_complaints,
12440                  _("Multiple children of DIE 0x%x refer "
12441                    "to DIE 0x%x as their abstract origin"),
12442                  to_underlying (die->sect_off), to_underlying (*offsetp));
12443
12444   offsetp = offsets.data ();
12445   origin_child_die = origin_die->child;
12446   while (origin_child_die && origin_child_die->tag)
12447     {
12448       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
12449       while (offsetp < offsets_end
12450              && *offsetp < origin_child_die->sect_off)
12451         offsetp++;
12452       if (offsetp >= offsets_end
12453           || *offsetp > origin_child_die->sect_off)
12454         {
12455           /* Found that ORIGIN_CHILD_DIE is really not referenced.
12456              Check whether we're already processing ORIGIN_CHILD_DIE.
12457              This can happen with mutually referenced abstract_origins.
12458              PR 16581.  */
12459           if (!origin_child_die->in_process)
12460             process_die (origin_child_die, origin_cu);
12461         }
12462       origin_child_die = sibling_die (origin_child_die);
12463     }
12464   origin_cu->list_in_scope = origin_previous_list_in_scope;
12465 }
12466
12467 static void
12468 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
12469 {
12470   struct objfile *objfile = cu->objfile;
12471   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12472   struct context_stack *newobj;
12473   CORE_ADDR lowpc;
12474   CORE_ADDR highpc;
12475   struct die_info *child_die;
12476   struct attribute *attr, *call_line, *call_file;
12477   const char *name;
12478   CORE_ADDR baseaddr;
12479   struct block *block;
12480   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
12481   std::vector<struct symbol *> template_args;
12482   struct template_symbol *templ_func = NULL;
12483
12484   if (inlined_func)
12485     {
12486       /* If we do not have call site information, we can't show the
12487          caller of this inlined function.  That's too confusing, so
12488          only use the scope for local variables.  */
12489       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
12490       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
12491       if (call_line == NULL || call_file == NULL)
12492         {
12493           read_lexical_block_scope (die, cu);
12494           return;
12495         }
12496     }
12497
12498   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12499
12500   name = dwarf2_name (die, cu);
12501
12502   /* Ignore functions with missing or empty names.  These are actually
12503      illegal according to the DWARF standard.  */
12504   if (name == NULL)
12505     {
12506       complaint (&symfile_complaints,
12507                  _("missing name for subprogram DIE at %d"),
12508                  to_underlying (die->sect_off));
12509       return;
12510     }
12511
12512   /* Ignore functions with missing or invalid low and high pc attributes.  */
12513   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
12514       <= PC_BOUNDS_INVALID)
12515     {
12516       attr = dwarf2_attr (die, DW_AT_external, cu);
12517       if (!attr || !DW_UNSND (attr))
12518         complaint (&symfile_complaints,
12519                    _("cannot get low and high bounds "
12520                      "for subprogram DIE at %d"),
12521                    to_underlying (die->sect_off));
12522       return;
12523     }
12524
12525   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12526   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12527
12528   /* If we have any template arguments, then we must allocate a
12529      different sort of symbol.  */
12530   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
12531     {
12532       if (child_die->tag == DW_TAG_template_type_param
12533           || child_die->tag == DW_TAG_template_value_param)
12534         {
12535           templ_func = allocate_template_symbol (objfile);
12536           templ_func->subclass = SYMBOL_TEMPLATE;
12537           break;
12538         }
12539     }
12540
12541   newobj = push_context (0, lowpc);
12542   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
12543                                (struct symbol *) templ_func);
12544
12545   /* If there is a location expression for DW_AT_frame_base, record
12546      it.  */
12547   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
12548   if (attr)
12549     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
12550
12551   /* If there is a location for the static link, record it.  */
12552   newobj->static_link = NULL;
12553   attr = dwarf2_attr (die, DW_AT_static_link, cu);
12554   if (attr)
12555     {
12556       newobj->static_link
12557         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
12558       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
12559     }
12560
12561   cu->list_in_scope = &local_symbols;
12562
12563   if (die->child != NULL)
12564     {
12565       child_die = die->child;
12566       while (child_die && child_die->tag)
12567         {
12568           if (child_die->tag == DW_TAG_template_type_param
12569               || child_die->tag == DW_TAG_template_value_param)
12570             {
12571               struct symbol *arg = new_symbol (child_die, NULL, cu);
12572
12573               if (arg != NULL)
12574                 template_args.push_back (arg);
12575             }
12576           else
12577             process_die (child_die, cu);
12578           child_die = sibling_die (child_die);
12579         }
12580     }
12581
12582   inherit_abstract_dies (die, cu);
12583
12584   /* If we have a DW_AT_specification, we might need to import using
12585      directives from the context of the specification DIE.  See the
12586      comment in determine_prefix.  */
12587   if (cu->language == language_cplus
12588       && dwarf2_attr (die, DW_AT_specification, cu))
12589     {
12590       struct dwarf2_cu *spec_cu = cu;
12591       struct die_info *spec_die = die_specification (die, &spec_cu);
12592
12593       while (spec_die)
12594         {
12595           child_die = spec_die->child;
12596           while (child_die && child_die->tag)
12597             {
12598               if (child_die->tag == DW_TAG_imported_module)
12599                 process_die (child_die, spec_cu);
12600               child_die = sibling_die (child_die);
12601             }
12602
12603           /* In some cases, GCC generates specification DIEs that
12604              themselves contain DW_AT_specification attributes.  */
12605           spec_die = die_specification (spec_die, &spec_cu);
12606         }
12607     }
12608
12609   newobj = pop_context ();
12610   /* Make a block for the local symbols within.  */
12611   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
12612                         newobj->static_link, lowpc, highpc);
12613
12614   /* For C++, set the block's scope.  */
12615   if ((cu->language == language_cplus
12616        || cu->language == language_fortran
12617        || cu->language == language_d
12618        || cu->language == language_rust)
12619       && cu->processing_has_namespace_info)
12620     block_set_scope (block, determine_prefix (die, cu),
12621                      &objfile->objfile_obstack);
12622
12623   /* If we have address ranges, record them.  */
12624   dwarf2_record_block_ranges (die, block, baseaddr, cu);
12625
12626   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
12627
12628   /* Attach template arguments to function.  */
12629   if (!template_args.empty ())
12630     {
12631       gdb_assert (templ_func != NULL);
12632
12633       templ_func->n_template_arguments = template_args.size ();
12634       templ_func->template_arguments
12635         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
12636                      templ_func->n_template_arguments);
12637       memcpy (templ_func->template_arguments,
12638               template_args.data (),
12639               (templ_func->n_template_arguments * sizeof (struct symbol *)));
12640     }
12641
12642   /* In C++, we can have functions nested inside functions (e.g., when
12643      a function declares a class that has methods).  This means that
12644      when we finish processing a function scope, we may need to go
12645      back to building a containing block's symbol lists.  */
12646   local_symbols = newobj->locals;
12647   local_using_directives = newobj->local_using_directives;
12648
12649   /* If we've finished processing a top-level function, subsequent
12650      symbols go in the file symbol list.  */
12651   if (outermost_context_p ())
12652     cu->list_in_scope = &file_symbols;
12653 }
12654
12655 /* Process all the DIES contained within a lexical block scope.  Start
12656    a new scope, process the dies, and then close the scope.  */
12657
12658 static void
12659 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
12660 {
12661   struct objfile *objfile = cu->objfile;
12662   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12663   struct context_stack *newobj;
12664   CORE_ADDR lowpc, highpc;
12665   struct die_info *child_die;
12666   CORE_ADDR baseaddr;
12667
12668   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12669
12670   /* Ignore blocks with missing or invalid low and high pc attributes.  */
12671   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
12672      as multiple lexical blocks?  Handling children in a sane way would
12673      be nasty.  Might be easier to properly extend generic blocks to
12674      describe ranges.  */
12675   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
12676     {
12677     case PC_BOUNDS_NOT_PRESENT:
12678       /* DW_TAG_lexical_block has no attributes, process its children as if
12679          there was no wrapping by that DW_TAG_lexical_block.
12680          GCC does no longer produces such DWARF since GCC r224161.  */
12681       for (child_die = die->child;
12682            child_die != NULL && child_die->tag;
12683            child_die = sibling_die (child_die))
12684         process_die (child_die, cu);
12685       return;
12686     case PC_BOUNDS_INVALID:
12687       return;
12688     }
12689   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12690   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12691
12692   push_context (0, lowpc);
12693   if (die->child != NULL)
12694     {
12695       child_die = die->child;
12696       while (child_die && child_die->tag)
12697         {
12698           process_die (child_die, cu);
12699           child_die = sibling_die (child_die);
12700         }
12701     }
12702   inherit_abstract_dies (die, cu);
12703   newobj = pop_context ();
12704
12705   if (local_symbols != NULL || local_using_directives != NULL)
12706     {
12707       struct block *block
12708         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
12709                         newobj->start_addr, highpc);
12710
12711       /* Note that recording ranges after traversing children, as we
12712          do here, means that recording a parent's ranges entails
12713          walking across all its children's ranges as they appear in
12714          the address map, which is quadratic behavior.
12715
12716          It would be nicer to record the parent's ranges before
12717          traversing its children, simply overriding whatever you find
12718          there.  But since we don't even decide whether to create a
12719          block until after we've traversed its children, that's hard
12720          to do.  */
12721       dwarf2_record_block_ranges (die, block, baseaddr, cu);
12722     }
12723   local_symbols = newobj->locals;
12724   local_using_directives = newobj->local_using_directives;
12725 }
12726
12727 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
12728
12729 static void
12730 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
12731 {
12732   struct objfile *objfile = cu->objfile;
12733   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12734   CORE_ADDR pc, baseaddr;
12735   struct attribute *attr;
12736   struct call_site *call_site, call_site_local;
12737   void **slot;
12738   int nparams;
12739   struct die_info *child_die;
12740
12741   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12742
12743   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
12744   if (attr == NULL)
12745     {
12746       /* This was a pre-DWARF-5 GNU extension alias
12747          for DW_AT_call_return_pc.  */
12748       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12749     }
12750   if (!attr)
12751     {
12752       complaint (&symfile_complaints,
12753                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
12754                    "DIE 0x%x [in module %s]"),
12755                  to_underlying (die->sect_off), objfile_name (objfile));
12756       return;
12757     }
12758   pc = attr_value_as_address (attr) + baseaddr;
12759   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
12760
12761   if (cu->call_site_htab == NULL)
12762     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
12763                                                NULL, &objfile->objfile_obstack,
12764                                                hashtab_obstack_allocate, NULL);
12765   call_site_local.pc = pc;
12766   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
12767   if (*slot != NULL)
12768     {
12769       complaint (&symfile_complaints,
12770                  _("Duplicate PC %s for DW_TAG_call_site "
12771                    "DIE 0x%x [in module %s]"),
12772                  paddress (gdbarch, pc), to_underlying (die->sect_off),
12773                  objfile_name (objfile));
12774       return;
12775     }
12776
12777   /* Count parameters at the caller.  */
12778
12779   nparams = 0;
12780   for (child_die = die->child; child_die && child_die->tag;
12781        child_die = sibling_die (child_die))
12782     {
12783       if (child_die->tag != DW_TAG_call_site_parameter
12784           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12785         {
12786           complaint (&symfile_complaints,
12787                      _("Tag %d is not DW_TAG_call_site_parameter in "
12788                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12789                      child_die->tag, to_underlying (child_die->sect_off),
12790                      objfile_name (objfile));
12791           continue;
12792         }
12793
12794       nparams++;
12795     }
12796
12797   call_site
12798     = ((struct call_site *)
12799        obstack_alloc (&objfile->objfile_obstack,
12800                       sizeof (*call_site)
12801                       + (sizeof (*call_site->parameter) * (nparams - 1))));
12802   *slot = call_site;
12803   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
12804   call_site->pc = pc;
12805
12806   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
12807       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
12808     {
12809       struct die_info *func_die;
12810
12811       /* Skip also over DW_TAG_inlined_subroutine.  */
12812       for (func_die = die->parent;
12813            func_die && func_die->tag != DW_TAG_subprogram
12814            && func_die->tag != DW_TAG_subroutine_type;
12815            func_die = func_die->parent);
12816
12817       /* DW_AT_call_all_calls is a superset
12818          of DW_AT_call_all_tail_calls.  */
12819       if (func_die
12820           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12821           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12822           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12823           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12824         {
12825           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12826              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12827              both the initial caller containing the real return address PC and
12828              the final callee containing the current PC of a chain of tail
12829              calls do not need to have the tail call list complete.  But any
12830              function candidate for a virtual tail call frame searched via
12831              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12832              determined unambiguously.  */
12833         }
12834       else
12835         {
12836           struct type *func_type = NULL;
12837
12838           if (func_die)
12839             func_type = get_die_type (func_die, cu);
12840           if (func_type != NULL)
12841             {
12842               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12843
12844               /* Enlist this call site to the function.  */
12845               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12846               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12847             }
12848           else
12849             complaint (&symfile_complaints,
12850                        _("Cannot find function owning DW_TAG_call_site "
12851                          "DIE 0x%x [in module %s]"),
12852                        to_underlying (die->sect_off), objfile_name (objfile));
12853         }
12854     }
12855
12856   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12857   if (attr == NULL)
12858     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12859   if (attr == NULL)
12860     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12861   if (attr == NULL)
12862     {
12863       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12864       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12865     }
12866   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12867   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12868     /* Keep NULL DWARF_BLOCK.  */;
12869   else if (attr_form_is_block (attr))
12870     {
12871       struct dwarf2_locexpr_baton *dlbaton;
12872
12873       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12874       dlbaton->data = DW_BLOCK (attr)->data;
12875       dlbaton->size = DW_BLOCK (attr)->size;
12876       dlbaton->per_cu = cu->per_cu;
12877
12878       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12879     }
12880   else if (attr_form_is_ref (attr))
12881     {
12882       struct dwarf2_cu *target_cu = cu;
12883       struct die_info *target_die;
12884
12885       target_die = follow_die_ref (die, attr, &target_cu);
12886       gdb_assert (target_cu->objfile == objfile);
12887       if (die_is_declaration (target_die, target_cu))
12888         {
12889           const char *target_physname;
12890
12891           /* Prefer the mangled name; otherwise compute the demangled one.  */
12892           target_physname = dw2_linkage_name (target_die, target_cu);
12893           if (target_physname == NULL)
12894             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12895           if (target_physname == NULL)
12896             complaint (&symfile_complaints,
12897                        _("DW_AT_call_target target DIE has invalid "
12898                          "physname, for referencing DIE 0x%x [in module %s]"),
12899                        to_underlying (die->sect_off), objfile_name (objfile));
12900           else
12901             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12902         }
12903       else
12904         {
12905           CORE_ADDR lowpc;
12906
12907           /* DW_AT_entry_pc should be preferred.  */
12908           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12909               <= PC_BOUNDS_INVALID)
12910             complaint (&symfile_complaints,
12911                        _("DW_AT_call_target target DIE has invalid "
12912                          "low pc, for referencing DIE 0x%x [in module %s]"),
12913                        to_underlying (die->sect_off), objfile_name (objfile));
12914           else
12915             {
12916               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12917               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12918             }
12919         }
12920     }
12921   else
12922     complaint (&symfile_complaints,
12923                _("DW_TAG_call_site DW_AT_call_target is neither "
12924                  "block nor reference, for DIE 0x%x [in module %s]"),
12925                to_underlying (die->sect_off), objfile_name (objfile));
12926
12927   call_site->per_cu = cu->per_cu;
12928
12929   for (child_die = die->child;
12930        child_die && child_die->tag;
12931        child_die = sibling_die (child_die))
12932     {
12933       struct call_site_parameter *parameter;
12934       struct attribute *loc, *origin;
12935
12936       if (child_die->tag != DW_TAG_call_site_parameter
12937           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12938         {
12939           /* Already printed the complaint above.  */
12940           continue;
12941         }
12942
12943       gdb_assert (call_site->parameter_count < nparams);
12944       parameter = &call_site->parameter[call_site->parameter_count];
12945
12946       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12947          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12948          register is contained in DW_AT_call_value.  */
12949
12950       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12951       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12952       if (origin == NULL)
12953         {
12954           /* This was a pre-DWARF-5 GNU extension alias
12955              for DW_AT_call_parameter.  */
12956           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12957         }
12958       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12959         {
12960           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12961
12962           sect_offset sect_off
12963             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12964           if (!offset_in_cu_p (&cu->header, sect_off))
12965             {
12966               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12967                  binding can be done only inside one CU.  Such referenced DIE
12968                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12969               complaint (&symfile_complaints,
12970                          _("DW_AT_call_parameter offset is not in CU for "
12971                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12972                          to_underlying (child_die->sect_off),
12973                          objfile_name (objfile));
12974               continue;
12975             }
12976           parameter->u.param_cu_off
12977             = (cu_offset) (sect_off - cu->header.sect_off);
12978         }
12979       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12980         {
12981           complaint (&symfile_complaints,
12982                      _("No DW_FORM_block* DW_AT_location for "
12983                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12984                      to_underlying (child_die->sect_off), objfile_name (objfile));
12985           continue;
12986         }
12987       else
12988         {
12989           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12990             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12991           if (parameter->u.dwarf_reg != -1)
12992             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12993           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12994                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12995                                              &parameter->u.fb_offset))
12996             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12997           else
12998             {
12999               complaint (&symfile_complaints,
13000                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
13001                            "for DW_FORM_block* DW_AT_location is supported for "
13002                            "DW_TAG_call_site child DIE 0x%x "
13003                            "[in module %s]"),
13004                          to_underlying (child_die->sect_off),
13005                          objfile_name (objfile));
13006               continue;
13007             }
13008         }
13009
13010       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13011       if (attr == NULL)
13012         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13013       if (!attr_form_is_block (attr))
13014         {
13015           complaint (&symfile_complaints,
13016                      _("No DW_FORM_block* DW_AT_call_value for "
13017                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13018                      to_underlying (child_die->sect_off),
13019                      objfile_name (objfile));
13020           continue;
13021         }
13022       parameter->value = DW_BLOCK (attr)->data;
13023       parameter->value_size = DW_BLOCK (attr)->size;
13024
13025       /* Parameters are not pre-cleared by memset above.  */
13026       parameter->data_value = NULL;
13027       parameter->data_value_size = 0;
13028       call_site->parameter_count++;
13029
13030       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13031       if (attr == NULL)
13032         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13033       if (attr)
13034         {
13035           if (!attr_form_is_block (attr))
13036             complaint (&symfile_complaints,
13037                        _("No DW_FORM_block* DW_AT_call_data_value for "
13038                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13039                        to_underlying (child_die->sect_off),
13040                        objfile_name (objfile));
13041           else
13042             {
13043               parameter->data_value = DW_BLOCK (attr)->data;
13044               parameter->data_value_size = DW_BLOCK (attr)->size;
13045             }
13046         }
13047     }
13048 }
13049
13050 /* Helper function for read_variable.  If DIE represents a virtual
13051    table, then return the type of the concrete object that is
13052    associated with the virtual table.  Otherwise, return NULL.  */
13053
13054 static struct type *
13055 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13056 {
13057   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13058   if (attr == NULL)
13059     return NULL;
13060
13061   /* Find the type DIE.  */
13062   struct die_info *type_die = NULL;
13063   struct dwarf2_cu *type_cu = cu;
13064
13065   if (attr_form_is_ref (attr))
13066     type_die = follow_die_ref (die, attr, &type_cu);
13067   if (type_die == NULL)
13068     return NULL;
13069
13070   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13071     return NULL;
13072   return die_containing_type (type_die, type_cu);
13073 }
13074
13075 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13076
13077 static void
13078 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13079 {
13080   struct rust_vtable_symbol *storage = NULL;
13081
13082   if (cu->language == language_rust)
13083     {
13084       struct type *containing_type = rust_containing_type (die, cu);
13085
13086       if (containing_type != NULL)
13087         {
13088           struct objfile *objfile = cu->objfile;
13089
13090           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
13091                                     struct rust_vtable_symbol);
13092           initialize_objfile_symbol (storage);
13093           storage->concrete_type = containing_type;
13094           storage->subclass = SYMBOL_RUST_VTABLE;
13095         }
13096     }
13097
13098   new_symbol_full (die, NULL, cu, storage);
13099 }
13100
13101 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13102    reading .debug_rnglists.
13103    Callback's type should be:
13104     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13105    Return true if the attributes are present and valid, otherwise,
13106    return false.  */
13107
13108 template <typename Callback>
13109 static bool
13110 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13111                          Callback &&callback)
13112 {
13113   struct objfile *objfile = cu->objfile;
13114   bfd *obfd = objfile->obfd;
13115   /* Base address selection entry.  */
13116   CORE_ADDR base;
13117   int found_base;
13118   const gdb_byte *buffer;
13119   CORE_ADDR baseaddr;
13120   bool overflow = false;
13121
13122   found_base = cu->base_known;
13123   base = cu->base_address;
13124
13125   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
13126   if (offset >= dwarf2_per_objfile->rnglists.size)
13127     {
13128       complaint (&symfile_complaints,
13129                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
13130                  offset);
13131       return false;
13132     }
13133   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
13134
13135   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13136
13137   while (1)
13138     {
13139       /* Initialize it due to a false compiler warning.  */
13140       CORE_ADDR range_beginning = 0, range_end = 0;
13141       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
13142                                  + dwarf2_per_objfile->rnglists.size);
13143       unsigned int bytes_read;
13144
13145       if (buffer == buf_end)
13146         {
13147           overflow = true;
13148           break;
13149         }
13150       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13151       switch (rlet)
13152         {
13153         case DW_RLE_end_of_list:
13154           break;
13155         case DW_RLE_base_address:
13156           if (buffer + cu->header.addr_size > buf_end)
13157             {
13158               overflow = true;
13159               break;
13160             }
13161           base = read_address (obfd, buffer, cu, &bytes_read);
13162           found_base = 1;
13163           buffer += bytes_read;
13164           break;
13165         case DW_RLE_start_length:
13166           if (buffer + cu->header.addr_size > buf_end)
13167             {
13168               overflow = true;
13169               break;
13170             }
13171           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13172           buffer += bytes_read;
13173           range_end = (range_beginning
13174                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13175           buffer += bytes_read;
13176           if (buffer > buf_end)
13177             {
13178               overflow = true;
13179               break;
13180             }
13181           break;
13182         case DW_RLE_offset_pair:
13183           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13184           buffer += bytes_read;
13185           if (buffer > buf_end)
13186             {
13187               overflow = true;
13188               break;
13189             }
13190           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13191           buffer += bytes_read;
13192           if (buffer > buf_end)
13193             {
13194               overflow = true;
13195               break;
13196             }
13197           break;
13198         case DW_RLE_start_end:
13199           if (buffer + 2 * cu->header.addr_size > buf_end)
13200             {
13201               overflow = true;
13202               break;
13203             }
13204           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13205           buffer += bytes_read;
13206           range_end = read_address (obfd, buffer, cu, &bytes_read);
13207           buffer += bytes_read;
13208           break;
13209         default:
13210           complaint (&symfile_complaints,
13211                      _("Invalid .debug_rnglists data (no base address)"));
13212           return false;
13213         }
13214       if (rlet == DW_RLE_end_of_list || overflow)
13215         break;
13216       if (rlet == DW_RLE_base_address)
13217         continue;
13218
13219       if (!found_base)
13220         {
13221           /* We have no valid base address for the ranges
13222              data.  */
13223           complaint (&symfile_complaints,
13224                      _("Invalid .debug_rnglists data (no base address)"));
13225           return false;
13226         }
13227
13228       if (range_beginning > range_end)
13229         {
13230           /* Inverted range entries are invalid.  */
13231           complaint (&symfile_complaints,
13232                      _("Invalid .debug_rnglists data (inverted range)"));
13233           return false;
13234         }
13235
13236       /* Empty range entries have no effect.  */
13237       if (range_beginning == range_end)
13238         continue;
13239
13240       range_beginning += base;
13241       range_end += base;
13242
13243       /* A not-uncommon case of bad debug info.
13244          Don't pollute the addrmap with bad data.  */
13245       if (range_beginning + baseaddr == 0
13246           && !dwarf2_per_objfile->has_section_at_zero)
13247         {
13248           complaint (&symfile_complaints,
13249                      _(".debug_rnglists entry has start address of zero"
13250                        " [in module %s]"), objfile_name (objfile));
13251           continue;
13252         }
13253
13254       callback (range_beginning, range_end);
13255     }
13256
13257   if (overflow)
13258     {
13259       complaint (&symfile_complaints,
13260                  _("Offset %d is not terminated "
13261                    "for DW_AT_ranges attribute"),
13262                  offset);
13263       return false;
13264     }
13265
13266   return true;
13267 }
13268
13269 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
13270    Callback's type should be:
13271     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13272    Return 1 if the attributes are present and valid, otherwise, return 0.  */
13273
13274 template <typename Callback>
13275 static int
13276 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
13277                        Callback &&callback)
13278 {
13279   struct objfile *objfile = cu->objfile;
13280   struct comp_unit_head *cu_header = &cu->header;
13281   bfd *obfd = objfile->obfd;
13282   unsigned int addr_size = cu_header->addr_size;
13283   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13284   /* Base address selection entry.  */
13285   CORE_ADDR base;
13286   int found_base;
13287   unsigned int dummy;
13288   const gdb_byte *buffer;
13289   CORE_ADDR baseaddr;
13290
13291   if (cu_header->version >= 5)
13292     return dwarf2_rnglists_process (offset, cu, callback);
13293
13294   found_base = cu->base_known;
13295   base = cu->base_address;
13296
13297   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
13298   if (offset >= dwarf2_per_objfile->ranges.size)
13299     {
13300       complaint (&symfile_complaints,
13301                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
13302                  offset);
13303       return 0;
13304     }
13305   buffer = dwarf2_per_objfile->ranges.buffer + offset;
13306
13307   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13308
13309   while (1)
13310     {
13311       CORE_ADDR range_beginning, range_end;
13312
13313       range_beginning = read_address (obfd, buffer, cu, &dummy);
13314       buffer += addr_size;
13315       range_end = read_address (obfd, buffer, cu, &dummy);
13316       buffer += addr_size;
13317       offset += 2 * addr_size;
13318
13319       /* An end of list marker is a pair of zero addresses.  */
13320       if (range_beginning == 0 && range_end == 0)
13321         /* Found the end of list entry.  */
13322         break;
13323
13324       /* Each base address selection entry is a pair of 2 values.
13325          The first is the largest possible address, the second is
13326          the base address.  Check for a base address here.  */
13327       if ((range_beginning & mask) == mask)
13328         {
13329           /* If we found the largest possible address, then we already
13330              have the base address in range_end.  */
13331           base = range_end;
13332           found_base = 1;
13333           continue;
13334         }
13335
13336       if (!found_base)
13337         {
13338           /* We have no valid base address for the ranges
13339              data.  */
13340           complaint (&symfile_complaints,
13341                      _("Invalid .debug_ranges data (no base address)"));
13342           return 0;
13343         }
13344
13345       if (range_beginning > range_end)
13346         {
13347           /* Inverted range entries are invalid.  */
13348           complaint (&symfile_complaints,
13349                      _("Invalid .debug_ranges data (inverted range)"));
13350           return 0;
13351         }
13352
13353       /* Empty range entries have no effect.  */
13354       if (range_beginning == range_end)
13355         continue;
13356
13357       range_beginning += base;
13358       range_end += base;
13359
13360       /* A not-uncommon case of bad debug info.
13361          Don't pollute the addrmap with bad data.  */
13362       if (range_beginning + baseaddr == 0
13363           && !dwarf2_per_objfile->has_section_at_zero)
13364         {
13365           complaint (&symfile_complaints,
13366                      _(".debug_ranges entry has start address of zero"
13367                        " [in module %s]"), objfile_name (objfile));
13368           continue;
13369         }
13370
13371       callback (range_beginning, range_end);
13372     }
13373
13374   return 1;
13375 }
13376
13377 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
13378    Return 1 if the attributes are present and valid, otherwise, return 0.
13379    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
13380
13381 static int
13382 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
13383                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
13384                     struct partial_symtab *ranges_pst)
13385 {
13386   struct objfile *objfile = cu->objfile;
13387   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13388   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
13389                                        SECT_OFF_TEXT (objfile));
13390   int low_set = 0;
13391   CORE_ADDR low = 0;
13392   CORE_ADDR high = 0;
13393   int retval;
13394
13395   retval = dwarf2_ranges_process (offset, cu,
13396     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
13397     {
13398       if (ranges_pst != NULL)
13399         {
13400           CORE_ADDR lowpc;
13401           CORE_ADDR highpc;
13402
13403           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13404                                               range_beginning + baseaddr);
13405           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13406                                                range_end + baseaddr);
13407           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
13408                              ranges_pst);
13409         }
13410
13411       /* FIXME: This is recording everything as a low-high
13412          segment of consecutive addresses.  We should have a
13413          data structure for discontiguous block ranges
13414          instead.  */
13415       if (! low_set)
13416         {
13417           low = range_beginning;
13418           high = range_end;
13419           low_set = 1;
13420         }
13421       else
13422         {
13423           if (range_beginning < low)
13424             low = range_beginning;
13425           if (range_end > high)
13426             high = range_end;
13427         }
13428     });
13429   if (!retval)
13430     return 0;
13431
13432   if (! low_set)
13433     /* If the first entry is an end-of-list marker, the range
13434        describes an empty scope, i.e. no instructions.  */
13435     return 0;
13436
13437   if (low_return)
13438     *low_return = low;
13439   if (high_return)
13440     *high_return = high;
13441   return 1;
13442 }
13443
13444 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
13445    definition for the return value.  *LOWPC and *HIGHPC are set iff
13446    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
13447
13448 static enum pc_bounds_kind
13449 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
13450                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
13451                       struct partial_symtab *pst)
13452 {
13453   struct attribute *attr;
13454   struct attribute *attr_high;
13455   CORE_ADDR low = 0;
13456   CORE_ADDR high = 0;
13457   enum pc_bounds_kind ret;
13458
13459   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13460   if (attr_high)
13461     {
13462       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13463       if (attr)
13464         {
13465           low = attr_value_as_address (attr);
13466           high = attr_value_as_address (attr_high);
13467           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13468             high += low;
13469         }
13470       else
13471         /* Found high w/o low attribute.  */
13472         return PC_BOUNDS_INVALID;
13473
13474       /* Found consecutive range of addresses.  */
13475       ret = PC_BOUNDS_HIGH_LOW;
13476     }
13477   else
13478     {
13479       attr = dwarf2_attr (die, DW_AT_ranges, cu);
13480       if (attr != NULL)
13481         {
13482           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13483              We take advantage of the fact that DW_AT_ranges does not appear
13484              in DW_TAG_compile_unit of DWO files.  */
13485           int need_ranges_base = die->tag != DW_TAG_compile_unit;
13486           unsigned int ranges_offset = (DW_UNSND (attr)
13487                                         + (need_ranges_base
13488                                            ? cu->ranges_base
13489                                            : 0));
13490
13491           /* Value of the DW_AT_ranges attribute is the offset in the
13492              .debug_ranges section.  */
13493           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
13494             return PC_BOUNDS_INVALID;
13495           /* Found discontinuous range of addresses.  */
13496           ret = PC_BOUNDS_RANGES;
13497         }
13498       else
13499         return PC_BOUNDS_NOT_PRESENT;
13500     }
13501
13502   /* read_partial_die has also the strict LOW < HIGH requirement.  */
13503   if (high <= low)
13504     return PC_BOUNDS_INVALID;
13505
13506   /* When using the GNU linker, .gnu.linkonce. sections are used to
13507      eliminate duplicate copies of functions and vtables and such.
13508      The linker will arbitrarily choose one and discard the others.
13509      The AT_*_pc values for such functions refer to local labels in
13510      these sections.  If the section from that file was discarded, the
13511      labels are not in the output, so the relocs get a value of 0.
13512      If this is a discarded function, mark the pc bounds as invalid,
13513      so that GDB will ignore it.  */
13514   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
13515     return PC_BOUNDS_INVALID;
13516
13517   *lowpc = low;
13518   if (highpc)
13519     *highpc = high;
13520   return ret;
13521 }
13522
13523 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
13524    its low and high PC addresses.  Do nothing if these addresses could not
13525    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
13526    and HIGHPC to the high address if greater than HIGHPC.  */
13527
13528 static void
13529 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
13530                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
13531                                  struct dwarf2_cu *cu)
13532 {
13533   CORE_ADDR low, high;
13534   struct die_info *child = die->child;
13535
13536   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
13537     {
13538       *lowpc = std::min (*lowpc, low);
13539       *highpc = std::max (*highpc, high);
13540     }
13541
13542   /* If the language does not allow nested subprograms (either inside
13543      subprograms or lexical blocks), we're done.  */
13544   if (cu->language != language_ada)
13545     return;
13546
13547   /* Check all the children of the given DIE.  If it contains nested
13548      subprograms, then check their pc bounds.  Likewise, we need to
13549      check lexical blocks as well, as they may also contain subprogram
13550      definitions.  */
13551   while (child && child->tag)
13552     {
13553       if (child->tag == DW_TAG_subprogram
13554           || child->tag == DW_TAG_lexical_block)
13555         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
13556       child = sibling_die (child);
13557     }
13558 }
13559
13560 /* Get the low and high pc's represented by the scope DIE, and store
13561    them in *LOWPC and *HIGHPC.  If the correct values can't be
13562    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
13563
13564 static void
13565 get_scope_pc_bounds (struct die_info *die,
13566                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
13567                      struct dwarf2_cu *cu)
13568 {
13569   CORE_ADDR best_low = (CORE_ADDR) -1;
13570   CORE_ADDR best_high = (CORE_ADDR) 0;
13571   CORE_ADDR current_low, current_high;
13572
13573   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
13574       >= PC_BOUNDS_RANGES)
13575     {
13576       best_low = current_low;
13577       best_high = current_high;
13578     }
13579   else
13580     {
13581       struct die_info *child = die->child;
13582
13583       while (child && child->tag)
13584         {
13585           switch (child->tag) {
13586           case DW_TAG_subprogram:
13587             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
13588             break;
13589           case DW_TAG_namespace:
13590           case DW_TAG_module:
13591             /* FIXME: carlton/2004-01-16: Should we do this for
13592                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
13593                that current GCC's always emit the DIEs corresponding
13594                to definitions of methods of classes as children of a
13595                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
13596                the DIEs giving the declarations, which could be
13597                anywhere).  But I don't see any reason why the
13598                standards says that they have to be there.  */
13599             get_scope_pc_bounds (child, &current_low, &current_high, cu);
13600
13601             if (current_low != ((CORE_ADDR) -1))
13602               {
13603                 best_low = std::min (best_low, current_low);
13604                 best_high = std::max (best_high, current_high);
13605               }
13606             break;
13607           default:
13608             /* Ignore.  */
13609             break;
13610           }
13611
13612           child = sibling_die (child);
13613         }
13614     }
13615
13616   *lowpc = best_low;
13617   *highpc = best_high;
13618 }
13619
13620 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
13621    in DIE.  */
13622
13623 static void
13624 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
13625                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
13626 {
13627   struct objfile *objfile = cu->objfile;
13628   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13629   struct attribute *attr;
13630   struct attribute *attr_high;
13631
13632   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13633   if (attr_high)
13634     {
13635       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13636       if (attr)
13637         {
13638           CORE_ADDR low = attr_value_as_address (attr);
13639           CORE_ADDR high = attr_value_as_address (attr_high);
13640
13641           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13642             high += low;
13643
13644           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
13645           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
13646           record_block_range (block, low, high - 1);
13647         }
13648     }
13649
13650   attr = dwarf2_attr (die, DW_AT_ranges, cu);
13651   if (attr)
13652     {
13653       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13654          We take advantage of the fact that DW_AT_ranges does not appear
13655          in DW_TAG_compile_unit of DWO files.  */
13656       int need_ranges_base = die->tag != DW_TAG_compile_unit;
13657
13658       /* The value of the DW_AT_ranges attribute is the offset of the
13659          address range list in the .debug_ranges section.  */
13660       unsigned long offset = (DW_UNSND (attr)
13661                               + (need_ranges_base ? cu->ranges_base : 0));
13662       const gdb_byte *buffer;
13663
13664       /* For some target architectures, but not others, the
13665          read_address function sign-extends the addresses it returns.
13666          To recognize base address selection entries, we need a
13667          mask.  */
13668       unsigned int addr_size = cu->header.addr_size;
13669       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13670
13671       /* The base address, to which the next pair is relative.  Note
13672          that this 'base' is a DWARF concept: most entries in a range
13673          list are relative, to reduce the number of relocs against the
13674          debugging information.  This is separate from this function's
13675          'baseaddr' argument, which GDB uses to relocate debugging
13676          information from a shared library based on the address at
13677          which the library was loaded.  */
13678       CORE_ADDR base = cu->base_address;
13679       int base_known = cu->base_known;
13680
13681       dwarf2_ranges_process (offset, cu,
13682         [&] (CORE_ADDR start, CORE_ADDR end)
13683         {
13684           start += baseaddr;
13685           end += baseaddr;
13686           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
13687           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
13688           record_block_range (block, start, end - 1);
13689         });
13690     }
13691 }
13692
13693 /* Check whether the producer field indicates either of GCC < 4.6, or the
13694    Intel C/C++ compiler, and cache the result in CU.  */
13695
13696 static void
13697 check_producer (struct dwarf2_cu *cu)
13698 {
13699   int major, minor;
13700
13701   if (cu->producer == NULL)
13702     {
13703       /* For unknown compilers expect their behavior is DWARF version
13704          compliant.
13705
13706          GCC started to support .debug_types sections by -gdwarf-4 since
13707          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
13708          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
13709          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
13710          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
13711     }
13712   else if (producer_is_gcc (cu->producer, &major, &minor))
13713     {
13714       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
13715       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
13716     }
13717   else if (producer_is_icc (cu->producer, &major, &minor))
13718     cu->producer_is_icc_lt_14 = major < 14;
13719   else
13720     {
13721       /* For other non-GCC compilers, expect their behavior is DWARF version
13722          compliant.  */
13723     }
13724
13725   cu->checked_producer = 1;
13726 }
13727
13728 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
13729    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
13730    during 4.6.0 experimental.  */
13731
13732 static int
13733 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
13734 {
13735   if (!cu->checked_producer)
13736     check_producer (cu);
13737
13738   return cu->producer_is_gxx_lt_4_6;
13739 }
13740
13741 /* Return the default accessibility type if it is not overriden by
13742    DW_AT_accessibility.  */
13743
13744 static enum dwarf_access_attribute
13745 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
13746 {
13747   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
13748     {
13749       /* The default DWARF 2 accessibility for members is public, the default
13750          accessibility for inheritance is private.  */
13751
13752       if (die->tag != DW_TAG_inheritance)
13753         return DW_ACCESS_public;
13754       else
13755         return DW_ACCESS_private;
13756     }
13757   else
13758     {
13759       /* DWARF 3+ defines the default accessibility a different way.  The same
13760          rules apply now for DW_TAG_inheritance as for the members and it only
13761          depends on the container kind.  */
13762
13763       if (die->parent->tag == DW_TAG_class_type)
13764         return DW_ACCESS_private;
13765       else
13766         return DW_ACCESS_public;
13767     }
13768 }
13769
13770 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
13771    offset.  If the attribute was not found return 0, otherwise return
13772    1.  If it was found but could not properly be handled, set *OFFSET
13773    to 0.  */
13774
13775 static int
13776 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
13777                              LONGEST *offset)
13778 {
13779   struct attribute *attr;
13780
13781   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
13782   if (attr != NULL)
13783     {
13784       *offset = 0;
13785
13786       /* Note that we do not check for a section offset first here.
13787          This is because DW_AT_data_member_location is new in DWARF 4,
13788          so if we see it, we can assume that a constant form is really
13789          a constant and not a section offset.  */
13790       if (attr_form_is_constant (attr))
13791         *offset = dwarf2_get_attr_constant_value (attr, 0);
13792       else if (attr_form_is_section_offset (attr))
13793         dwarf2_complex_location_expr_complaint ();
13794       else if (attr_form_is_block (attr))
13795         *offset = decode_locdesc (DW_BLOCK (attr), cu);
13796       else
13797         dwarf2_complex_location_expr_complaint ();
13798
13799       return 1;
13800     }
13801
13802   return 0;
13803 }
13804
13805 /* Add an aggregate field to the field list.  */
13806
13807 static void
13808 dwarf2_add_field (struct field_info *fip, struct die_info *die,
13809                   struct dwarf2_cu *cu)
13810 {
13811   struct objfile *objfile = cu->objfile;
13812   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13813   struct nextfield *new_field;
13814   struct attribute *attr;
13815   struct field *fp;
13816   const char *fieldname = "";
13817
13818   /* Allocate a new field list entry and link it in.  */
13819   new_field = XNEW (struct nextfield);
13820   make_cleanup (xfree, new_field);
13821   memset (new_field, 0, sizeof (struct nextfield));
13822
13823   if (die->tag == DW_TAG_inheritance)
13824     {
13825       new_field->next = fip->baseclasses;
13826       fip->baseclasses = new_field;
13827     }
13828   else
13829     {
13830       new_field->next = fip->fields;
13831       fip->fields = new_field;
13832     }
13833   fip->nfields++;
13834
13835   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13836   if (attr)
13837     new_field->accessibility = DW_UNSND (attr);
13838   else
13839     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
13840   if (new_field->accessibility != DW_ACCESS_public)
13841     fip->non_public_fields = 1;
13842
13843   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13844   if (attr)
13845     new_field->virtuality = DW_UNSND (attr);
13846   else
13847     new_field->virtuality = DW_VIRTUALITY_none;
13848
13849   fp = &new_field->field;
13850
13851   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
13852     {
13853       LONGEST offset;
13854
13855       /* Data member other than a C++ static data member.  */
13856
13857       /* Get type of field.  */
13858       fp->type = die_type (die, cu);
13859
13860       SET_FIELD_BITPOS (*fp, 0);
13861
13862       /* Get bit size of field (zero if none).  */
13863       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13864       if (attr)
13865         {
13866           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13867         }
13868       else
13869         {
13870           FIELD_BITSIZE (*fp) = 0;
13871         }
13872
13873       /* Get bit offset of field.  */
13874       if (handle_data_member_location (die, cu, &offset))
13875         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13876       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13877       if (attr)
13878         {
13879           if (gdbarch_bits_big_endian (gdbarch))
13880             {
13881               /* For big endian bits, the DW_AT_bit_offset gives the
13882                  additional bit offset from the MSB of the containing
13883                  anonymous object to the MSB of the field.  We don't
13884                  have to do anything special since we don't need to
13885                  know the size of the anonymous object.  */
13886               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13887             }
13888           else
13889             {
13890               /* For little endian bits, compute the bit offset to the
13891                  MSB of the anonymous object, subtract off the number of
13892                  bits from the MSB of the field to the MSB of the
13893                  object, and then subtract off the number of bits of
13894                  the field itself.  The result is the bit offset of
13895                  the LSB of the field.  */
13896               int anonymous_size;
13897               int bit_offset = DW_UNSND (attr);
13898
13899               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13900               if (attr)
13901                 {
13902                   /* The size of the anonymous object containing
13903                      the bit field is explicit, so use the
13904                      indicated size (in bytes).  */
13905                   anonymous_size = DW_UNSND (attr);
13906                 }
13907               else
13908                 {
13909                   /* The size of the anonymous object containing
13910                      the bit field must be inferred from the type
13911                      attribute of the data member containing the
13912                      bit field.  */
13913                   anonymous_size = TYPE_LENGTH (fp->type);
13914                 }
13915               SET_FIELD_BITPOS (*fp,
13916                                 (FIELD_BITPOS (*fp)
13917                                  + anonymous_size * bits_per_byte
13918                                  - bit_offset - FIELD_BITSIZE (*fp)));
13919             }
13920         }
13921       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13922       if (attr != NULL)
13923         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13924                                 + dwarf2_get_attr_constant_value (attr, 0)));
13925
13926       /* Get name of field.  */
13927       fieldname = dwarf2_name (die, cu);
13928       if (fieldname == NULL)
13929         fieldname = "";
13930
13931       /* The name is already allocated along with this objfile, so we don't
13932          need to duplicate it for the type.  */
13933       fp->name = fieldname;
13934
13935       /* Change accessibility for artificial fields (e.g. virtual table
13936          pointer or virtual base class pointer) to private.  */
13937       if (dwarf2_attr (die, DW_AT_artificial, cu))
13938         {
13939           FIELD_ARTIFICIAL (*fp) = 1;
13940           new_field->accessibility = DW_ACCESS_private;
13941           fip->non_public_fields = 1;
13942         }
13943     }
13944   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13945     {
13946       /* C++ static member.  */
13947
13948       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13949          is a declaration, but all versions of G++ as of this writing
13950          (so through at least 3.2.1) incorrectly generate
13951          DW_TAG_variable tags.  */
13952
13953       const char *physname;
13954
13955       /* Get name of field.  */
13956       fieldname = dwarf2_name (die, cu);
13957       if (fieldname == NULL)
13958         return;
13959
13960       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13961       if (attr
13962           /* Only create a symbol if this is an external value.
13963              new_symbol checks this and puts the value in the global symbol
13964              table, which we want.  If it is not external, new_symbol
13965              will try to put the value in cu->list_in_scope which is wrong.  */
13966           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13967         {
13968           /* A static const member, not much different than an enum as far as
13969              we're concerned, except that we can support more types.  */
13970           new_symbol (die, NULL, cu);
13971         }
13972
13973       /* Get physical name.  */
13974       physname = dwarf2_physname (fieldname, die, cu);
13975
13976       /* The name is already allocated along with this objfile, so we don't
13977          need to duplicate it for the type.  */
13978       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13979       FIELD_TYPE (*fp) = die_type (die, cu);
13980       FIELD_NAME (*fp) = fieldname;
13981     }
13982   else if (die->tag == DW_TAG_inheritance)
13983     {
13984       LONGEST offset;
13985
13986       /* C++ base class field.  */
13987       if (handle_data_member_location (die, cu, &offset))
13988         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13989       FIELD_BITSIZE (*fp) = 0;
13990       FIELD_TYPE (*fp) = die_type (die, cu);
13991       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13992       fip->nbaseclasses++;
13993     }
13994 }
13995
13996 /* Can the type given by DIE define another type?  */
13997
13998 static bool
13999 type_can_define_types (const struct die_info *die)
14000 {
14001   switch (die->tag)
14002     {
14003     case DW_TAG_typedef:
14004     case DW_TAG_class_type:
14005     case DW_TAG_structure_type:
14006     case DW_TAG_union_type:
14007     case DW_TAG_enumeration_type:
14008       return true;
14009
14010     default:
14011       return false;
14012     }
14013 }
14014
14015 /* Add a type definition defined in the scope of the FIP's class.  */
14016
14017 static void
14018 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14019                       struct dwarf2_cu *cu)
14020 {
14021   struct decl_field_list *new_field;
14022   struct decl_field *fp;
14023
14024   /* Allocate a new field list entry and link it in.  */
14025   new_field = XCNEW (struct decl_field_list);
14026   make_cleanup (xfree, new_field);
14027
14028   gdb_assert (type_can_define_types (die));
14029
14030   fp = &new_field->field;
14031
14032   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14033   fp->name = dwarf2_name (die, cu);
14034   fp->type = read_type_die (die, cu);
14035
14036   /* Save accessibility.  */
14037   enum dwarf_access_attribute accessibility;
14038   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14039   if (attr != NULL)
14040     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14041   else
14042     accessibility = dwarf2_default_access_attribute (die, cu);
14043   switch (accessibility)
14044     {
14045     case DW_ACCESS_public:
14046       /* The assumed value if neither private nor protected.  */
14047       break;
14048     case DW_ACCESS_private:
14049       fp->is_private = 1;
14050       break;
14051     case DW_ACCESS_protected:
14052       fp->is_protected = 1;
14053       break;
14054     default:
14055       complaint (&symfile_complaints,
14056                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
14057     }
14058
14059   if (die->tag == DW_TAG_typedef)
14060     {
14061       new_field->next = fip->typedef_field_list;
14062       fip->typedef_field_list = new_field;
14063       fip->typedef_field_list_count++;
14064     }
14065   else
14066     {
14067       new_field->next = fip->nested_types_list;
14068       fip->nested_types_list = new_field;
14069       fip->nested_types_list_count++;
14070     }
14071 }
14072
14073 /* Create the vector of fields, and attach it to the type.  */
14074
14075 static void
14076 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14077                               struct dwarf2_cu *cu)
14078 {
14079   int nfields = fip->nfields;
14080
14081   /* Record the field count, allocate space for the array of fields,
14082      and create blank accessibility bitfields if necessary.  */
14083   TYPE_NFIELDS (type) = nfields;
14084   TYPE_FIELDS (type) = (struct field *)
14085     TYPE_ALLOC (type, sizeof (struct field) * nfields);
14086   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
14087
14088   if (fip->non_public_fields && cu->language != language_ada)
14089     {
14090       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14091
14092       TYPE_FIELD_PRIVATE_BITS (type) =
14093         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14094       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14095
14096       TYPE_FIELD_PROTECTED_BITS (type) =
14097         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14098       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14099
14100       TYPE_FIELD_IGNORE_BITS (type) =
14101         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14102       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14103     }
14104
14105   /* If the type has baseclasses, allocate and clear a bit vector for
14106      TYPE_FIELD_VIRTUAL_BITS.  */
14107   if (fip->nbaseclasses && cu->language != language_ada)
14108     {
14109       int num_bytes = B_BYTES (fip->nbaseclasses);
14110       unsigned char *pointer;
14111
14112       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14113       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14114       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14115       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
14116       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
14117     }
14118
14119   /* Copy the saved-up fields into the field vector.  Start from the head of
14120      the list, adding to the tail of the field array, so that they end up in
14121      the same order in the array in which they were added to the list.  */
14122   while (nfields-- > 0)
14123     {
14124       struct nextfield *fieldp;
14125
14126       if (fip->fields)
14127         {
14128           fieldp = fip->fields;
14129           fip->fields = fieldp->next;
14130         }
14131       else
14132         {
14133           fieldp = fip->baseclasses;
14134           fip->baseclasses = fieldp->next;
14135         }
14136
14137       TYPE_FIELD (type, nfields) = fieldp->field;
14138       switch (fieldp->accessibility)
14139         {
14140         case DW_ACCESS_private:
14141           if (cu->language != language_ada)
14142             SET_TYPE_FIELD_PRIVATE (type, nfields);
14143           break;
14144
14145         case DW_ACCESS_protected:
14146           if (cu->language != language_ada)
14147             SET_TYPE_FIELD_PROTECTED (type, nfields);
14148           break;
14149
14150         case DW_ACCESS_public:
14151           break;
14152
14153         default:
14154           /* Unknown accessibility.  Complain and treat it as public.  */
14155           {
14156             complaint (&symfile_complaints, _("unsupported accessibility %d"),
14157                        fieldp->accessibility);
14158           }
14159           break;
14160         }
14161       if (nfields < fip->nbaseclasses)
14162         {
14163           switch (fieldp->virtuality)
14164             {
14165             case DW_VIRTUALITY_virtual:
14166             case DW_VIRTUALITY_pure_virtual:
14167               if (cu->language == language_ada)
14168                 error (_("unexpected virtuality in component of Ada type"));
14169               SET_TYPE_FIELD_VIRTUAL (type, nfields);
14170               break;
14171             }
14172         }
14173     }
14174 }
14175
14176 /* Return true if this member function is a constructor, false
14177    otherwise.  */
14178
14179 static int
14180 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14181 {
14182   const char *fieldname;
14183   const char *type_name;
14184   int len;
14185
14186   if (die->parent == NULL)
14187     return 0;
14188
14189   if (die->parent->tag != DW_TAG_structure_type
14190       && die->parent->tag != DW_TAG_union_type
14191       && die->parent->tag != DW_TAG_class_type)
14192     return 0;
14193
14194   fieldname = dwarf2_name (die, cu);
14195   type_name = dwarf2_name (die->parent, cu);
14196   if (fieldname == NULL || type_name == NULL)
14197     return 0;
14198
14199   len = strlen (fieldname);
14200   return (strncmp (fieldname, type_name, len) == 0
14201           && (type_name[len] == '\0' || type_name[len] == '<'));
14202 }
14203
14204 /* Add a member function to the proper fieldlist.  */
14205
14206 static void
14207 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
14208                       struct type *type, struct dwarf2_cu *cu)
14209 {
14210   struct objfile *objfile = cu->objfile;
14211   struct attribute *attr;
14212   struct fnfieldlist *flp;
14213   int i;
14214   struct fn_field *fnp;
14215   const char *fieldname;
14216   struct nextfnfield *new_fnfield;
14217   struct type *this_type;
14218   enum dwarf_access_attribute accessibility;
14219
14220   if (cu->language == language_ada)
14221     error (_("unexpected member function in Ada type"));
14222
14223   /* Get name of member function.  */
14224   fieldname = dwarf2_name (die, cu);
14225   if (fieldname == NULL)
14226     return;
14227
14228   /* Look up member function name in fieldlist.  */
14229   for (i = 0; i < fip->nfnfields; i++)
14230     {
14231       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
14232         break;
14233     }
14234
14235   /* Create new list element if necessary.  */
14236   if (i < fip->nfnfields)
14237     flp = &fip->fnfieldlists[i];
14238   else
14239     {
14240       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
14241         {
14242           fip->fnfieldlists = (struct fnfieldlist *)
14243             xrealloc (fip->fnfieldlists,
14244                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
14245                       * sizeof (struct fnfieldlist));
14246           if (fip->nfnfields == 0)
14247             make_cleanup (free_current_contents, &fip->fnfieldlists);
14248         }
14249       flp = &fip->fnfieldlists[fip->nfnfields];
14250       flp->name = fieldname;
14251       flp->length = 0;
14252       flp->head = NULL;
14253       i = fip->nfnfields++;
14254     }
14255
14256   /* Create a new member function field and chain it to the field list
14257      entry.  */
14258   new_fnfield = XNEW (struct nextfnfield);
14259   make_cleanup (xfree, new_fnfield);
14260   memset (new_fnfield, 0, sizeof (struct nextfnfield));
14261   new_fnfield->next = flp->head;
14262   flp->head = new_fnfield;
14263   flp->length++;
14264
14265   /* Fill in the member function field info.  */
14266   fnp = &new_fnfield->fnfield;
14267
14268   /* Delay processing of the physname until later.  */
14269   if (cu->language == language_cplus)
14270     {
14271       add_to_method_list (type, i, flp->length - 1, fieldname,
14272                           die, cu);
14273     }
14274   else
14275     {
14276       const char *physname = dwarf2_physname (fieldname, die, cu);
14277       fnp->physname = physname ? physname : "";
14278     }
14279
14280   fnp->type = alloc_type (objfile);
14281   this_type = read_type_die (die, cu);
14282   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
14283     {
14284       int nparams = TYPE_NFIELDS (this_type);
14285
14286       /* TYPE is the domain of this method, and THIS_TYPE is the type
14287            of the method itself (TYPE_CODE_METHOD).  */
14288       smash_to_method_type (fnp->type, type,
14289                             TYPE_TARGET_TYPE (this_type),
14290                             TYPE_FIELDS (this_type),
14291                             TYPE_NFIELDS (this_type),
14292                             TYPE_VARARGS (this_type));
14293
14294       /* Handle static member functions.
14295          Dwarf2 has no clean way to discern C++ static and non-static
14296          member functions.  G++ helps GDB by marking the first
14297          parameter for non-static member functions (which is the this
14298          pointer) as artificial.  We obtain this information from
14299          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
14300       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
14301         fnp->voffset = VOFFSET_STATIC;
14302     }
14303   else
14304     complaint (&symfile_complaints, _("member function type missing for '%s'"),
14305                dwarf2_full_name (fieldname, die, cu));
14306
14307   /* Get fcontext from DW_AT_containing_type if present.  */
14308   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14309     fnp->fcontext = die_containing_type (die, cu);
14310
14311   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
14312      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
14313
14314   /* Get accessibility.  */
14315   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14316   if (attr)
14317     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14318   else
14319     accessibility = dwarf2_default_access_attribute (die, cu);
14320   switch (accessibility)
14321     {
14322     case DW_ACCESS_private:
14323       fnp->is_private = 1;
14324       break;
14325     case DW_ACCESS_protected:
14326       fnp->is_protected = 1;
14327       break;
14328     }
14329
14330   /* Check for artificial methods.  */
14331   attr = dwarf2_attr (die, DW_AT_artificial, cu);
14332   if (attr && DW_UNSND (attr) != 0)
14333     fnp->is_artificial = 1;
14334
14335   fnp->is_constructor = dwarf2_is_constructor (die, cu);
14336
14337   /* Get index in virtual function table if it is a virtual member
14338      function.  For older versions of GCC, this is an offset in the
14339      appropriate virtual table, as specified by DW_AT_containing_type.
14340      For everyone else, it is an expression to be evaluated relative
14341      to the object address.  */
14342
14343   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
14344   if (attr)
14345     {
14346       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
14347         {
14348           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
14349             {
14350               /* Old-style GCC.  */
14351               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
14352             }
14353           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
14354                    || (DW_BLOCK (attr)->size > 1
14355                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
14356                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
14357             {
14358               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
14359               if ((fnp->voffset % cu->header.addr_size) != 0)
14360                 dwarf2_complex_location_expr_complaint ();
14361               else
14362                 fnp->voffset /= cu->header.addr_size;
14363               fnp->voffset += 2;
14364             }
14365           else
14366             dwarf2_complex_location_expr_complaint ();
14367
14368           if (!fnp->fcontext)
14369             {
14370               /* If there is no `this' field and no DW_AT_containing_type,
14371                  we cannot actually find a base class context for the
14372                  vtable!  */
14373               if (TYPE_NFIELDS (this_type) == 0
14374                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
14375                 {
14376                   complaint (&symfile_complaints,
14377                              _("cannot determine context for virtual member "
14378                                "function \"%s\" (offset %d)"),
14379                              fieldname, to_underlying (die->sect_off));
14380                 }
14381               else
14382                 {
14383                   fnp->fcontext
14384                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
14385                 }
14386             }
14387         }
14388       else if (attr_form_is_section_offset (attr))
14389         {
14390           dwarf2_complex_location_expr_complaint ();
14391         }
14392       else
14393         {
14394           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
14395                                                  fieldname);
14396         }
14397     }
14398   else
14399     {
14400       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14401       if (attr && DW_UNSND (attr))
14402         {
14403           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
14404           complaint (&symfile_complaints,
14405                      _("Member function \"%s\" (offset %d) is virtual "
14406                        "but the vtable offset is not specified"),
14407                      fieldname, to_underlying (die->sect_off));
14408           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14409           TYPE_CPLUS_DYNAMIC (type) = 1;
14410         }
14411     }
14412 }
14413
14414 /* Create the vector of member function fields, and attach it to the type.  */
14415
14416 static void
14417 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
14418                                  struct dwarf2_cu *cu)
14419 {
14420   struct fnfieldlist *flp;
14421   int i;
14422
14423   if (cu->language == language_ada)
14424     error (_("unexpected member functions in Ada type"));
14425
14426   ALLOCATE_CPLUS_STRUCT_TYPE (type);
14427   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
14428     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
14429
14430   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
14431     {
14432       struct nextfnfield *nfp = flp->head;
14433       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
14434       int k;
14435
14436       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
14437       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
14438       fn_flp->fn_fields = (struct fn_field *)
14439         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
14440       for (k = flp->length; (k--, nfp); nfp = nfp->next)
14441         fn_flp->fn_fields[k] = nfp->fnfield;
14442     }
14443
14444   TYPE_NFN_FIELDS (type) = fip->nfnfields;
14445 }
14446
14447 /* Returns non-zero if NAME is the name of a vtable member in CU's
14448    language, zero otherwise.  */
14449 static int
14450 is_vtable_name (const char *name, struct dwarf2_cu *cu)
14451 {
14452   static const char vptr[] = "_vptr";
14453
14454   /* Look for the C++ form of the vtable.  */
14455   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
14456     return 1;
14457
14458   return 0;
14459 }
14460
14461 /* GCC outputs unnamed structures that are really pointers to member
14462    functions, with the ABI-specified layout.  If TYPE describes
14463    such a structure, smash it into a member function type.
14464
14465    GCC shouldn't do this; it should just output pointer to member DIEs.
14466    This is GCC PR debug/28767.  */
14467
14468 static void
14469 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
14470 {
14471   struct type *pfn_type, *self_type, *new_type;
14472
14473   /* Check for a structure with no name and two children.  */
14474   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
14475     return;
14476
14477   /* Check for __pfn and __delta members.  */
14478   if (TYPE_FIELD_NAME (type, 0) == NULL
14479       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
14480       || TYPE_FIELD_NAME (type, 1) == NULL
14481       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
14482     return;
14483
14484   /* Find the type of the method.  */
14485   pfn_type = TYPE_FIELD_TYPE (type, 0);
14486   if (pfn_type == NULL
14487       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
14488       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
14489     return;
14490
14491   /* Look for the "this" argument.  */
14492   pfn_type = TYPE_TARGET_TYPE (pfn_type);
14493   if (TYPE_NFIELDS (pfn_type) == 0
14494       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
14495       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
14496     return;
14497
14498   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
14499   new_type = alloc_type (objfile);
14500   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
14501                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
14502                         TYPE_VARARGS (pfn_type));
14503   smash_to_methodptr_type (type, new_type);
14504 }
14505
14506
14507 /* Called when we find the DIE that starts a structure or union scope
14508    (definition) to create a type for the structure or union.  Fill in
14509    the type's name and general properties; the members will not be
14510    processed until process_structure_scope.  A symbol table entry for
14511    the type will also not be done until process_structure_scope (assuming
14512    the type has a name).
14513
14514    NOTE: we need to call these functions regardless of whether or not the
14515    DIE has a DW_AT_name attribute, since it might be an anonymous
14516    structure or union.  This gets the type entered into our set of
14517    user defined types.  */
14518
14519 static struct type *
14520 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
14521 {
14522   struct objfile *objfile = cu->objfile;
14523   struct type *type;
14524   struct attribute *attr;
14525   const char *name;
14526
14527   /* If the definition of this type lives in .debug_types, read that type.
14528      Don't follow DW_AT_specification though, that will take us back up
14529      the chain and we want to go down.  */
14530   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14531   if (attr)
14532     {
14533       type = get_DW_AT_signature_type (die, attr, cu);
14534
14535       /* The type's CU may not be the same as CU.
14536          Ensure TYPE is recorded with CU in die_type_hash.  */
14537       return set_die_type (die, type, cu);
14538     }
14539
14540   type = alloc_type (objfile);
14541   INIT_CPLUS_SPECIFIC (type);
14542
14543   name = dwarf2_name (die, cu);
14544   if (name != NULL)
14545     {
14546       if (cu->language == language_cplus
14547           || cu->language == language_d
14548           || cu->language == language_rust)
14549         {
14550           const char *full_name = dwarf2_full_name (name, die, cu);
14551
14552           /* dwarf2_full_name might have already finished building the DIE's
14553              type.  If so, there is no need to continue.  */
14554           if (get_die_type (die, cu) != NULL)
14555             return get_die_type (die, cu);
14556
14557           TYPE_TAG_NAME (type) = full_name;
14558           if (die->tag == DW_TAG_structure_type
14559               || die->tag == DW_TAG_class_type)
14560             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14561         }
14562       else
14563         {
14564           /* The name is already allocated along with this objfile, so
14565              we don't need to duplicate it for the type.  */
14566           TYPE_TAG_NAME (type) = name;
14567           if (die->tag == DW_TAG_class_type)
14568             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14569         }
14570     }
14571
14572   if (die->tag == DW_TAG_structure_type)
14573     {
14574       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14575     }
14576   else if (die->tag == DW_TAG_union_type)
14577     {
14578       TYPE_CODE (type) = TYPE_CODE_UNION;
14579     }
14580   else
14581     {
14582       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14583     }
14584
14585   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
14586     TYPE_DECLARED_CLASS (type) = 1;
14587
14588   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14589   if (attr)
14590     {
14591       if (attr_form_is_constant (attr))
14592         TYPE_LENGTH (type) = DW_UNSND (attr);
14593       else
14594         {
14595           /* For the moment, dynamic type sizes are not supported
14596              by GDB's struct type.  The actual size is determined
14597              on-demand when resolving the type of a given object,
14598              so set the type's length to zero for now.  Otherwise,
14599              we record an expression as the length, and that expression
14600              could lead to a very large value, which could eventually
14601              lead to us trying to allocate that much memory when creating
14602              a value of that type.  */
14603           TYPE_LENGTH (type) = 0;
14604         }
14605     }
14606   else
14607     {
14608       TYPE_LENGTH (type) = 0;
14609     }
14610
14611   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
14612     {
14613       /* ICC<14 does not output the required DW_AT_declaration on
14614          incomplete types, but gives them a size of zero.  */
14615       TYPE_STUB (type) = 1;
14616     }
14617   else
14618     TYPE_STUB_SUPPORTED (type) = 1;
14619
14620   if (die_is_declaration (die, cu))
14621     TYPE_STUB (type) = 1;
14622   else if (attr == NULL && die->child == NULL
14623            && producer_is_realview (cu->producer))
14624     /* RealView does not output the required DW_AT_declaration
14625        on incomplete types.  */
14626     TYPE_STUB (type) = 1;
14627
14628   /* We need to add the type field to the die immediately so we don't
14629      infinitely recurse when dealing with pointers to the structure
14630      type within the structure itself.  */
14631   set_die_type (die, type, cu);
14632
14633   /* set_die_type should be already done.  */
14634   set_descriptive_type (type, die, cu);
14635
14636   return type;
14637 }
14638
14639 /* Finish creating a structure or union type, including filling in
14640    its members and creating a symbol for it.  */
14641
14642 static void
14643 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
14644 {
14645   struct objfile *objfile = cu->objfile;
14646   struct die_info *child_die;
14647   struct type *type;
14648
14649   type = get_die_type (die, cu);
14650   if (type == NULL)
14651     type = read_structure_type (die, cu);
14652
14653   if (die->child != NULL && ! die_is_declaration (die, cu))
14654     {
14655       struct field_info fi;
14656       std::vector<struct symbol *> template_args;
14657       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
14658
14659       memset (&fi, 0, sizeof (struct field_info));
14660
14661       child_die = die->child;
14662
14663       while (child_die && child_die->tag)
14664         {
14665           if (child_die->tag == DW_TAG_member
14666               || child_die->tag == DW_TAG_variable)
14667             {
14668               /* NOTE: carlton/2002-11-05: A C++ static data member
14669                  should be a DW_TAG_member that is a declaration, but
14670                  all versions of G++ as of this writing (so through at
14671                  least 3.2.1) incorrectly generate DW_TAG_variable
14672                  tags for them instead.  */
14673               dwarf2_add_field (&fi, child_die, cu);
14674             }
14675           else if (child_die->tag == DW_TAG_subprogram)
14676             {
14677               /* Rust doesn't have member functions in the C++ sense.
14678                  However, it does emit ordinary functions as children
14679                  of a struct DIE.  */
14680               if (cu->language == language_rust)
14681                 read_func_scope (child_die, cu);
14682               else
14683                 {
14684                   /* C++ member function.  */
14685                   dwarf2_add_member_fn (&fi, child_die, type, cu);
14686                 }
14687             }
14688           else if (child_die->tag == DW_TAG_inheritance)
14689             {
14690               /* C++ base class field.  */
14691               dwarf2_add_field (&fi, child_die, cu);
14692             }
14693           else if (type_can_define_types (child_die))
14694             dwarf2_add_type_defn (&fi, child_die, cu);
14695           else if (child_die->tag == DW_TAG_template_type_param
14696                    || child_die->tag == DW_TAG_template_value_param)
14697             {
14698               struct symbol *arg = new_symbol (child_die, NULL, cu);
14699
14700               if (arg != NULL)
14701                 template_args.push_back (arg);
14702             }
14703
14704           child_die = sibling_die (child_die);
14705         }
14706
14707       /* Attach template arguments to type.  */
14708       if (!template_args.empty ())
14709         {
14710           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14711           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
14712           TYPE_TEMPLATE_ARGUMENTS (type)
14713             = XOBNEWVEC (&objfile->objfile_obstack,
14714                          struct symbol *,
14715                          TYPE_N_TEMPLATE_ARGUMENTS (type));
14716           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
14717                   template_args.data (),
14718                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
14719                    * sizeof (struct symbol *)));
14720         }
14721
14722       /* Attach fields and member functions to the type.  */
14723       if (fi.nfields)
14724         dwarf2_attach_fields_to_type (&fi, type, cu);
14725       if (fi.nfnfields)
14726         {
14727           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
14728
14729           /* Get the type which refers to the base class (possibly this
14730              class itself) which contains the vtable pointer for the current
14731              class from the DW_AT_containing_type attribute.  This use of
14732              DW_AT_containing_type is a GNU extension.  */
14733
14734           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14735             {
14736               struct type *t = die_containing_type (die, cu);
14737
14738               set_type_vptr_basetype (type, t);
14739               if (type == t)
14740                 {
14741                   int i;
14742
14743                   /* Our own class provides vtbl ptr.  */
14744                   for (i = TYPE_NFIELDS (t) - 1;
14745                        i >= TYPE_N_BASECLASSES (t);
14746                        --i)
14747                     {
14748                       const char *fieldname = TYPE_FIELD_NAME (t, i);
14749
14750                       if (is_vtable_name (fieldname, cu))
14751                         {
14752                           set_type_vptr_fieldno (type, i);
14753                           break;
14754                         }
14755                     }
14756
14757                   /* Complain if virtual function table field not found.  */
14758                   if (i < TYPE_N_BASECLASSES (t))
14759                     complaint (&symfile_complaints,
14760                                _("virtual function table pointer "
14761                                  "not found when defining class '%s'"),
14762                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
14763                                "");
14764                 }
14765               else
14766                 {
14767                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
14768                 }
14769             }
14770           else if (cu->producer
14771                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
14772             {
14773               /* The IBM XLC compiler does not provide direct indication
14774                  of the containing type, but the vtable pointer is
14775                  always named __vfp.  */
14776
14777               int i;
14778
14779               for (i = TYPE_NFIELDS (type) - 1;
14780                    i >= TYPE_N_BASECLASSES (type);
14781                    --i)
14782                 {
14783                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
14784                     {
14785                       set_type_vptr_fieldno (type, i);
14786                       set_type_vptr_basetype (type, type);
14787                       break;
14788                     }
14789                 }
14790             }
14791         }
14792
14793       /* Copy fi.typedef_field_list linked list elements content into the
14794          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
14795       if (fi.typedef_field_list)
14796         {
14797           int i = fi.typedef_field_list_count;
14798
14799           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14800           TYPE_TYPEDEF_FIELD_ARRAY (type)
14801             = ((struct decl_field *)
14802                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
14803           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
14804
14805           /* Reverse the list order to keep the debug info elements order.  */
14806           while (--i >= 0)
14807             {
14808               struct decl_field *dest, *src;
14809
14810               dest = &TYPE_TYPEDEF_FIELD (type, i);
14811               src = &fi.typedef_field_list->field;
14812               fi.typedef_field_list = fi.typedef_field_list->next;
14813               *dest = *src;
14814             }
14815         }
14816
14817       /* Copy fi.nested_types_list linked list elements content into the
14818          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
14819       if (fi.nested_types_list != NULL && cu->language != language_ada)
14820         {
14821           int i = fi.nested_types_list_count;
14822
14823           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14824           TYPE_NESTED_TYPES_ARRAY (type)
14825             = ((struct decl_field *)
14826                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
14827           TYPE_NESTED_TYPES_COUNT (type) = i;
14828
14829           /* Reverse the list order to keep the debug info elements order.  */
14830           while (--i >= 0)
14831             {
14832               struct decl_field *dest, *src;
14833
14834               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
14835               src = &fi.nested_types_list->field;
14836               fi.nested_types_list = fi.nested_types_list->next;
14837               *dest = *src;
14838             }
14839         }
14840
14841       do_cleanups (back_to);
14842     }
14843
14844   quirk_gcc_member_function_pointer (type, objfile);
14845
14846   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
14847      snapshots) has been known to create a die giving a declaration
14848      for a class that has, as a child, a die giving a definition for a
14849      nested class.  So we have to process our children even if the
14850      current die is a declaration.  Normally, of course, a declaration
14851      won't have any children at all.  */
14852
14853   child_die = die->child;
14854
14855   while (child_die != NULL && child_die->tag)
14856     {
14857       if (child_die->tag == DW_TAG_member
14858           || child_die->tag == DW_TAG_variable
14859           || child_die->tag == DW_TAG_inheritance
14860           || child_die->tag == DW_TAG_template_value_param
14861           || child_die->tag == DW_TAG_template_type_param)
14862         {
14863           /* Do nothing.  */
14864         }
14865       else
14866         process_die (child_die, cu);
14867
14868       child_die = sibling_die (child_die);
14869     }
14870
14871   /* Do not consider external references.  According to the DWARF standard,
14872      these DIEs are identified by the fact that they have no byte_size
14873      attribute, and a declaration attribute.  */
14874   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
14875       || !die_is_declaration (die, cu))
14876     new_symbol (die, type, cu);
14877 }
14878
14879 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
14880    update TYPE using some information only available in DIE's children.  */
14881
14882 static void
14883 update_enumeration_type_from_children (struct die_info *die,
14884                                        struct type *type,
14885                                        struct dwarf2_cu *cu)
14886 {
14887   struct die_info *child_die;
14888   int unsigned_enum = 1;
14889   int flag_enum = 1;
14890   ULONGEST mask = 0;
14891
14892   auto_obstack obstack;
14893
14894   for (child_die = die->child;
14895        child_die != NULL && child_die->tag;
14896        child_die = sibling_die (child_die))
14897     {
14898       struct attribute *attr;
14899       LONGEST value;
14900       const gdb_byte *bytes;
14901       struct dwarf2_locexpr_baton *baton;
14902       const char *name;
14903
14904       if (child_die->tag != DW_TAG_enumerator)
14905         continue;
14906
14907       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
14908       if (attr == NULL)
14909         continue;
14910
14911       name = dwarf2_name (child_die, cu);
14912       if (name == NULL)
14913         name = "<anonymous enumerator>";
14914
14915       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
14916                                &value, &bytes, &baton);
14917       if (value < 0)
14918         {
14919           unsigned_enum = 0;
14920           flag_enum = 0;
14921         }
14922       else if ((mask & value) != 0)
14923         flag_enum = 0;
14924       else
14925         mask |= value;
14926
14927       /* If we already know that the enum type is neither unsigned, nor
14928          a flag type, no need to look at the rest of the enumerates.  */
14929       if (!unsigned_enum && !flag_enum)
14930         break;
14931     }
14932
14933   if (unsigned_enum)
14934     TYPE_UNSIGNED (type) = 1;
14935   if (flag_enum)
14936     TYPE_FLAG_ENUM (type) = 1;
14937 }
14938
14939 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14940    complete the type's fields yet, or create any symbols.  */
14941
14942 static struct type *
14943 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14944 {
14945   struct objfile *objfile = cu->objfile;
14946   struct type *type;
14947   struct attribute *attr;
14948   const char *name;
14949
14950   /* If the definition of this type lives in .debug_types, read that type.
14951      Don't follow DW_AT_specification though, that will take us back up
14952      the chain and we want to go down.  */
14953   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14954   if (attr)
14955     {
14956       type = get_DW_AT_signature_type (die, attr, cu);
14957
14958       /* The type's CU may not be the same as CU.
14959          Ensure TYPE is recorded with CU in die_type_hash.  */
14960       return set_die_type (die, type, cu);
14961     }
14962
14963   type = alloc_type (objfile);
14964
14965   TYPE_CODE (type) = TYPE_CODE_ENUM;
14966   name = dwarf2_full_name (NULL, die, cu);
14967   if (name != NULL)
14968     TYPE_TAG_NAME (type) = name;
14969
14970   attr = dwarf2_attr (die, DW_AT_type, cu);
14971   if (attr != NULL)
14972     {
14973       struct type *underlying_type = die_type (die, cu);
14974
14975       TYPE_TARGET_TYPE (type) = underlying_type;
14976     }
14977
14978   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14979   if (attr)
14980     {
14981       TYPE_LENGTH (type) = DW_UNSND (attr);
14982     }
14983   else
14984     {
14985       TYPE_LENGTH (type) = 0;
14986     }
14987
14988   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14989      declared as private in the package spec, and then defined only
14990      inside the package body.  Such types are known as Taft Amendment
14991      Types.  When another package uses such a type, an incomplete DIE
14992      may be generated by the compiler.  */
14993   if (die_is_declaration (die, cu))
14994     TYPE_STUB (type) = 1;
14995
14996   /* Finish the creation of this type by using the enum's children.
14997      We must call this even when the underlying type has been provided
14998      so that we can determine if we're looking at a "flag" enum.  */
14999   update_enumeration_type_from_children (die, type, cu);
15000
15001   /* If this type has an underlying type that is not a stub, then we
15002      may use its attributes.  We always use the "unsigned" attribute
15003      in this situation, because ordinarily we guess whether the type
15004      is unsigned -- but the guess can be wrong and the underlying type
15005      can tell us the reality.  However, we defer to a local size
15006      attribute if one exists, because this lets the compiler override
15007      the underlying type if needed.  */
15008   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
15009     {
15010       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
15011       if (TYPE_LENGTH (type) == 0)
15012         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
15013     }
15014
15015   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
15016
15017   return set_die_type (die, type, cu);
15018 }
15019
15020 /* Given a pointer to a die which begins an enumeration, process all
15021    the dies that define the members of the enumeration, and create the
15022    symbol for the enumeration type.
15023
15024    NOTE: We reverse the order of the element list.  */
15025
15026 static void
15027 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
15028 {
15029   struct type *this_type;
15030
15031   this_type = get_die_type (die, cu);
15032   if (this_type == NULL)
15033     this_type = read_enumeration_type (die, cu);
15034
15035   if (die->child != NULL)
15036     {
15037       struct die_info *child_die;
15038       struct symbol *sym;
15039       struct field *fields = NULL;
15040       int num_fields = 0;
15041       const char *name;
15042
15043       child_die = die->child;
15044       while (child_die && child_die->tag)
15045         {
15046           if (child_die->tag != DW_TAG_enumerator)
15047             {
15048               process_die (child_die, cu);
15049             }
15050           else
15051             {
15052               name = dwarf2_name (child_die, cu);
15053               if (name)
15054                 {
15055                   sym = new_symbol (child_die, this_type, cu);
15056
15057                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
15058                     {
15059                       fields = (struct field *)
15060                         xrealloc (fields,
15061                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
15062                                   * sizeof (struct field));
15063                     }
15064
15065                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
15066                   FIELD_TYPE (fields[num_fields]) = NULL;
15067                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
15068                   FIELD_BITSIZE (fields[num_fields]) = 0;
15069
15070                   num_fields++;
15071                 }
15072             }
15073
15074           child_die = sibling_die (child_die);
15075         }
15076
15077       if (num_fields)
15078         {
15079           TYPE_NFIELDS (this_type) = num_fields;
15080           TYPE_FIELDS (this_type) = (struct field *)
15081             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
15082           memcpy (TYPE_FIELDS (this_type), fields,
15083                   sizeof (struct field) * num_fields);
15084           xfree (fields);
15085         }
15086     }
15087
15088   /* If we are reading an enum from a .debug_types unit, and the enum
15089      is a declaration, and the enum is not the signatured type in the
15090      unit, then we do not want to add a symbol for it.  Adding a
15091      symbol would in some cases obscure the true definition of the
15092      enum, giving users an incomplete type when the definition is
15093      actually available.  Note that we do not want to do this for all
15094      enums which are just declarations, because C++0x allows forward
15095      enum declarations.  */
15096   if (cu->per_cu->is_debug_types
15097       && die_is_declaration (die, cu))
15098     {
15099       struct signatured_type *sig_type;
15100
15101       sig_type = (struct signatured_type *) cu->per_cu;
15102       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
15103       if (sig_type->type_offset_in_section != die->sect_off)
15104         return;
15105     }
15106
15107   new_symbol (die, this_type, cu);
15108 }
15109
15110 /* Extract all information from a DW_TAG_array_type DIE and put it in
15111    the DIE's type field.  For now, this only handles one dimensional
15112    arrays.  */
15113
15114 static struct type *
15115 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
15116 {
15117   struct objfile *objfile = cu->objfile;
15118   struct die_info *child_die;
15119   struct type *type;
15120   struct type *element_type, *range_type, *index_type;
15121   struct attribute *attr;
15122   const char *name;
15123   unsigned int bit_stride = 0;
15124
15125   element_type = die_type (die, cu);
15126
15127   /* The die_type call above may have already set the type for this DIE.  */
15128   type = get_die_type (die, cu);
15129   if (type)
15130     return type;
15131
15132   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
15133   if (attr != NULL)
15134     bit_stride = DW_UNSND (attr) * 8;
15135
15136   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
15137   if (attr != NULL)
15138     bit_stride = DW_UNSND (attr);
15139
15140   /* Irix 6.2 native cc creates array types without children for
15141      arrays with unspecified length.  */
15142   if (die->child == NULL)
15143     {
15144       index_type = objfile_type (objfile)->builtin_int;
15145       range_type = create_static_range_type (NULL, index_type, 0, -1);
15146       type = create_array_type_with_stride (NULL, element_type, range_type,
15147                                             bit_stride);
15148       return set_die_type (die, type, cu);
15149     }
15150
15151   std::vector<struct type *> range_types;
15152   child_die = die->child;
15153   while (child_die && child_die->tag)
15154     {
15155       if (child_die->tag == DW_TAG_subrange_type)
15156         {
15157           struct type *child_type = read_type_die (child_die, cu);
15158
15159           if (child_type != NULL)
15160             {
15161               /* The range type was succesfully read.  Save it for the
15162                  array type creation.  */
15163               range_types.push_back (child_type);
15164             }
15165         }
15166       child_die = sibling_die (child_die);
15167     }
15168
15169   /* Dwarf2 dimensions are output from left to right, create the
15170      necessary array types in backwards order.  */
15171
15172   type = element_type;
15173
15174   if (read_array_order (die, cu) == DW_ORD_col_major)
15175     {
15176       int i = 0;
15177
15178       while (i < range_types.size ())
15179         type = create_array_type_with_stride (NULL, type, range_types[i++],
15180                                               bit_stride);
15181     }
15182   else
15183     {
15184       size_t ndim = range_types.size ();
15185       while (ndim-- > 0)
15186         type = create_array_type_with_stride (NULL, type, range_types[ndim],
15187                                               bit_stride);
15188     }
15189
15190   /* Understand Dwarf2 support for vector types (like they occur on
15191      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
15192      array type.  This is not part of the Dwarf2/3 standard yet, but a
15193      custom vendor extension.  The main difference between a regular
15194      array and the vector variant is that vectors are passed by value
15195      to functions.  */
15196   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
15197   if (attr)
15198     make_vector_type (type);
15199
15200   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
15201      implementation may choose to implement triple vectors using this
15202      attribute.  */
15203   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15204   if (attr)
15205     {
15206       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
15207         TYPE_LENGTH (type) = DW_UNSND (attr);
15208       else
15209         complaint (&symfile_complaints,
15210                    _("DW_AT_byte_size for array type smaller "
15211                      "than the total size of elements"));
15212     }
15213
15214   name = dwarf2_name (die, cu);
15215   if (name)
15216     TYPE_NAME (type) = name;
15217
15218   /* Install the type in the die.  */
15219   set_die_type (die, type, cu);
15220
15221   /* set_die_type should be already done.  */
15222   set_descriptive_type (type, die, cu);
15223
15224   return type;
15225 }
15226
15227 static enum dwarf_array_dim_ordering
15228 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
15229 {
15230   struct attribute *attr;
15231
15232   attr = dwarf2_attr (die, DW_AT_ordering, cu);
15233
15234   if (attr)
15235     return (enum dwarf_array_dim_ordering) DW_SND (attr);
15236
15237   /* GNU F77 is a special case, as at 08/2004 array type info is the
15238      opposite order to the dwarf2 specification, but data is still
15239      laid out as per normal fortran.
15240
15241      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
15242      version checking.  */
15243
15244   if (cu->language == language_fortran
15245       && cu->producer && strstr (cu->producer, "GNU F77"))
15246     {
15247       return DW_ORD_row_major;
15248     }
15249
15250   switch (cu->language_defn->la_array_ordering)
15251     {
15252     case array_column_major:
15253       return DW_ORD_col_major;
15254     case array_row_major:
15255     default:
15256       return DW_ORD_row_major;
15257     };
15258 }
15259
15260 /* Extract all information from a DW_TAG_set_type DIE and put it in
15261    the DIE's type field.  */
15262
15263 static struct type *
15264 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
15265 {
15266   struct type *domain_type, *set_type;
15267   struct attribute *attr;
15268
15269   domain_type = die_type (die, cu);
15270
15271   /* The die_type call above may have already set the type for this DIE.  */
15272   set_type = get_die_type (die, cu);
15273   if (set_type)
15274     return set_type;
15275
15276   set_type = create_set_type (NULL, domain_type);
15277
15278   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15279   if (attr)
15280     TYPE_LENGTH (set_type) = DW_UNSND (attr);
15281
15282   return set_die_type (die, set_type, cu);
15283 }
15284
15285 /* A helper for read_common_block that creates a locexpr baton.
15286    SYM is the symbol which we are marking as computed.
15287    COMMON_DIE is the DIE for the common block.
15288    COMMON_LOC is the location expression attribute for the common
15289    block itself.
15290    MEMBER_LOC is the location expression attribute for the particular
15291    member of the common block that we are processing.
15292    CU is the CU from which the above come.  */
15293
15294 static void
15295 mark_common_block_symbol_computed (struct symbol *sym,
15296                                    struct die_info *common_die,
15297                                    struct attribute *common_loc,
15298                                    struct attribute *member_loc,
15299                                    struct dwarf2_cu *cu)
15300 {
15301   struct objfile *objfile = dwarf2_per_objfile->objfile;
15302   struct dwarf2_locexpr_baton *baton;
15303   gdb_byte *ptr;
15304   unsigned int cu_off;
15305   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
15306   LONGEST offset = 0;
15307
15308   gdb_assert (common_loc && member_loc);
15309   gdb_assert (attr_form_is_block (common_loc));
15310   gdb_assert (attr_form_is_block (member_loc)
15311               || attr_form_is_constant (member_loc));
15312
15313   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
15314   baton->per_cu = cu->per_cu;
15315   gdb_assert (baton->per_cu);
15316
15317   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
15318
15319   if (attr_form_is_constant (member_loc))
15320     {
15321       offset = dwarf2_get_attr_constant_value (member_loc, 0);
15322       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
15323     }
15324   else
15325     baton->size += DW_BLOCK (member_loc)->size;
15326
15327   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
15328   baton->data = ptr;
15329
15330   *ptr++ = DW_OP_call4;
15331   cu_off = common_die->sect_off - cu->per_cu->sect_off;
15332   store_unsigned_integer (ptr, 4, byte_order, cu_off);
15333   ptr += 4;
15334
15335   if (attr_form_is_constant (member_loc))
15336     {
15337       *ptr++ = DW_OP_addr;
15338       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
15339       ptr += cu->header.addr_size;
15340     }
15341   else
15342     {
15343       /* We have to copy the data here, because DW_OP_call4 will only
15344          use a DW_AT_location attribute.  */
15345       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
15346       ptr += DW_BLOCK (member_loc)->size;
15347     }
15348
15349   *ptr++ = DW_OP_plus;
15350   gdb_assert (ptr - baton->data == baton->size);
15351
15352   SYMBOL_LOCATION_BATON (sym) = baton;
15353   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
15354 }
15355
15356 /* Create appropriate locally-scoped variables for all the
15357    DW_TAG_common_block entries.  Also create a struct common_block
15358    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
15359    is used to sepate the common blocks name namespace from regular
15360    variable names.  */
15361
15362 static void
15363 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
15364 {
15365   struct attribute *attr;
15366
15367   attr = dwarf2_attr (die, DW_AT_location, cu);
15368   if (attr)
15369     {
15370       /* Support the .debug_loc offsets.  */
15371       if (attr_form_is_block (attr))
15372         {
15373           /* Ok.  */
15374         }
15375       else if (attr_form_is_section_offset (attr))
15376         {
15377           dwarf2_complex_location_expr_complaint ();
15378           attr = NULL;
15379         }
15380       else
15381         {
15382           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15383                                                  "common block member");
15384           attr = NULL;
15385         }
15386     }
15387
15388   if (die->child != NULL)
15389     {
15390       struct objfile *objfile = cu->objfile;
15391       struct die_info *child_die;
15392       size_t n_entries = 0, size;
15393       struct common_block *common_block;
15394       struct symbol *sym;
15395
15396       for (child_die = die->child;
15397            child_die && child_die->tag;
15398            child_die = sibling_die (child_die))
15399         ++n_entries;
15400
15401       size = (sizeof (struct common_block)
15402               + (n_entries - 1) * sizeof (struct symbol *));
15403       common_block
15404         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
15405                                                  size);
15406       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
15407       common_block->n_entries = 0;
15408
15409       for (child_die = die->child;
15410            child_die && child_die->tag;
15411            child_die = sibling_die (child_die))
15412         {
15413           /* Create the symbol in the DW_TAG_common_block block in the current
15414              symbol scope.  */
15415           sym = new_symbol (child_die, NULL, cu);
15416           if (sym != NULL)
15417             {
15418               struct attribute *member_loc;
15419
15420               common_block->contents[common_block->n_entries++] = sym;
15421
15422               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
15423                                         cu);
15424               if (member_loc)
15425                 {
15426                   /* GDB has handled this for a long time, but it is
15427                      not specified by DWARF.  It seems to have been
15428                      emitted by gfortran at least as recently as:
15429                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
15430                   complaint (&symfile_complaints,
15431                              _("Variable in common block has "
15432                                "DW_AT_data_member_location "
15433                                "- DIE at 0x%x [in module %s]"),
15434                              to_underlying (child_die->sect_off),
15435                              objfile_name (cu->objfile));
15436
15437                   if (attr_form_is_section_offset (member_loc))
15438                     dwarf2_complex_location_expr_complaint ();
15439                   else if (attr_form_is_constant (member_loc)
15440                            || attr_form_is_block (member_loc))
15441                     {
15442                       if (attr)
15443                         mark_common_block_symbol_computed (sym, die, attr,
15444                                                            member_loc, cu);
15445                     }
15446                   else
15447                     dwarf2_complex_location_expr_complaint ();
15448                 }
15449             }
15450         }
15451
15452       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
15453       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
15454     }
15455 }
15456
15457 /* Create a type for a C++ namespace.  */
15458
15459 static struct type *
15460 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
15461 {
15462   struct objfile *objfile = cu->objfile;
15463   const char *previous_prefix, *name;
15464   int is_anonymous;
15465   struct type *type;
15466
15467   /* For extensions, reuse the type of the original namespace.  */
15468   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
15469     {
15470       struct die_info *ext_die;
15471       struct dwarf2_cu *ext_cu = cu;
15472
15473       ext_die = dwarf2_extension (die, &ext_cu);
15474       type = read_type_die (ext_die, ext_cu);
15475
15476       /* EXT_CU may not be the same as CU.
15477          Ensure TYPE is recorded with CU in die_type_hash.  */
15478       return set_die_type (die, type, cu);
15479     }
15480
15481   name = namespace_name (die, &is_anonymous, cu);
15482
15483   /* Now build the name of the current namespace.  */
15484
15485   previous_prefix = determine_prefix (die, cu);
15486   if (previous_prefix[0] != '\0')
15487     name = typename_concat (&objfile->objfile_obstack,
15488                             previous_prefix, name, 0, cu);
15489
15490   /* Create the type.  */
15491   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
15492   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15493
15494   return set_die_type (die, type, cu);
15495 }
15496
15497 /* Read a namespace scope.  */
15498
15499 static void
15500 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
15501 {
15502   struct objfile *objfile = cu->objfile;
15503   int is_anonymous;
15504
15505   /* Add a symbol associated to this if we haven't seen the namespace
15506      before.  Also, add a using directive if it's an anonymous
15507      namespace.  */
15508
15509   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
15510     {
15511       struct type *type;
15512
15513       type = read_type_die (die, cu);
15514       new_symbol (die, type, cu);
15515
15516       namespace_name (die, &is_anonymous, cu);
15517       if (is_anonymous)
15518         {
15519           const char *previous_prefix = determine_prefix (die, cu);
15520
15521           std::vector<const char *> excludes;
15522           add_using_directive (using_directives (cu->language),
15523                                previous_prefix, TYPE_NAME (type), NULL,
15524                                NULL, excludes, 0, &objfile->objfile_obstack);
15525         }
15526     }
15527
15528   if (die->child != NULL)
15529     {
15530       struct die_info *child_die = die->child;
15531
15532       while (child_die && child_die->tag)
15533         {
15534           process_die (child_die, cu);
15535           child_die = sibling_die (child_die);
15536         }
15537     }
15538 }
15539
15540 /* Read a Fortran module as type.  This DIE can be only a declaration used for
15541    imported module.  Still we need that type as local Fortran "use ... only"
15542    declaration imports depend on the created type in determine_prefix.  */
15543
15544 static struct type *
15545 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
15546 {
15547   struct objfile *objfile = cu->objfile;
15548   const char *module_name;
15549   struct type *type;
15550
15551   module_name = dwarf2_name (die, cu);
15552   if (!module_name)
15553     complaint (&symfile_complaints,
15554                _("DW_TAG_module has no name, offset 0x%x"),
15555                to_underlying (die->sect_off));
15556   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
15557
15558   /* determine_prefix uses TYPE_TAG_NAME.  */
15559   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15560
15561   return set_die_type (die, type, cu);
15562 }
15563
15564 /* Read a Fortran module.  */
15565
15566 static void
15567 read_module (struct die_info *die, struct dwarf2_cu *cu)
15568 {
15569   struct die_info *child_die = die->child;
15570   struct type *type;
15571
15572   type = read_type_die (die, cu);
15573   new_symbol (die, type, cu);
15574
15575   while (child_die && child_die->tag)
15576     {
15577       process_die (child_die, cu);
15578       child_die = sibling_die (child_die);
15579     }
15580 }
15581
15582 /* Return the name of the namespace represented by DIE.  Set
15583    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
15584    namespace.  */
15585
15586 static const char *
15587 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
15588 {
15589   struct die_info *current_die;
15590   const char *name = NULL;
15591
15592   /* Loop through the extensions until we find a name.  */
15593
15594   for (current_die = die;
15595        current_die != NULL;
15596        current_die = dwarf2_extension (die, &cu))
15597     {
15598       /* We don't use dwarf2_name here so that we can detect the absence
15599          of a name -> anonymous namespace.  */
15600       name = dwarf2_string_attr (die, DW_AT_name, cu);
15601
15602       if (name != NULL)
15603         break;
15604     }
15605
15606   /* Is it an anonymous namespace?  */
15607
15608   *is_anonymous = (name == NULL);
15609   if (*is_anonymous)
15610     name = CP_ANONYMOUS_NAMESPACE_STR;
15611
15612   return name;
15613 }
15614
15615 /* Extract all information from a DW_TAG_pointer_type DIE and add to
15616    the user defined type vector.  */
15617
15618 static struct type *
15619 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
15620 {
15621   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
15622   struct comp_unit_head *cu_header = &cu->header;
15623   struct type *type;
15624   struct attribute *attr_byte_size;
15625   struct attribute *attr_address_class;
15626   int byte_size, addr_class;
15627   struct type *target_type;
15628
15629   target_type = die_type (die, cu);
15630
15631   /* The die_type call above may have already set the type for this DIE.  */
15632   type = get_die_type (die, cu);
15633   if (type)
15634     return type;
15635
15636   type = lookup_pointer_type (target_type);
15637
15638   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
15639   if (attr_byte_size)
15640     byte_size = DW_UNSND (attr_byte_size);
15641   else
15642     byte_size = cu_header->addr_size;
15643
15644   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
15645   if (attr_address_class)
15646     addr_class = DW_UNSND (attr_address_class);
15647   else
15648     addr_class = DW_ADDR_none;
15649
15650   /* If the pointer size or address class is different than the
15651      default, create a type variant marked as such and set the
15652      length accordingly.  */
15653   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
15654     {
15655       if (gdbarch_address_class_type_flags_p (gdbarch))
15656         {
15657           int type_flags;
15658
15659           type_flags = gdbarch_address_class_type_flags
15660                          (gdbarch, byte_size, addr_class);
15661           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
15662                       == 0);
15663           type = make_type_with_address_space (type, type_flags);
15664         }
15665       else if (TYPE_LENGTH (type) != byte_size)
15666         {
15667           complaint (&symfile_complaints,
15668                      _("invalid pointer size %d"), byte_size);
15669         }
15670       else
15671         {
15672           /* Should we also complain about unhandled address classes?  */
15673         }
15674     }
15675
15676   TYPE_LENGTH (type) = byte_size;
15677   return set_die_type (die, type, cu);
15678 }
15679
15680 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
15681    the user defined type vector.  */
15682
15683 static struct type *
15684 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
15685 {
15686   struct type *type;
15687   struct type *to_type;
15688   struct type *domain;
15689
15690   to_type = die_type (die, cu);
15691   domain = die_containing_type (die, cu);
15692
15693   /* The calls above may have already set the type for this DIE.  */
15694   type = get_die_type (die, cu);
15695   if (type)
15696     return type;
15697
15698   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
15699     type = lookup_methodptr_type (to_type);
15700   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
15701     {
15702       struct type *new_type = alloc_type (cu->objfile);
15703
15704       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
15705                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
15706                             TYPE_VARARGS (to_type));
15707       type = lookup_methodptr_type (new_type);
15708     }
15709   else
15710     type = lookup_memberptr_type (to_type, domain);
15711
15712   return set_die_type (die, type, cu);
15713 }
15714
15715 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
15716    the user defined type vector.  */
15717
15718 static struct type *
15719 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
15720                           enum type_code refcode)
15721 {
15722   struct comp_unit_head *cu_header = &cu->header;
15723   struct type *type, *target_type;
15724   struct attribute *attr;
15725
15726   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
15727
15728   target_type = die_type (die, cu);
15729
15730   /* The die_type call above may have already set the type for this DIE.  */
15731   type = get_die_type (die, cu);
15732   if (type)
15733     return type;
15734
15735   type = lookup_reference_type (target_type, refcode);
15736   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15737   if (attr)
15738     {
15739       TYPE_LENGTH (type) = DW_UNSND (attr);
15740     }
15741   else
15742     {
15743       TYPE_LENGTH (type) = cu_header->addr_size;
15744     }
15745   return set_die_type (die, type, cu);
15746 }
15747
15748 /* Add the given cv-qualifiers to the element type of the array.  GCC
15749    outputs DWARF type qualifiers that apply to an array, not the
15750    element type.  But GDB relies on the array element type to carry
15751    the cv-qualifiers.  This mimics section 6.7.3 of the C99
15752    specification.  */
15753
15754 static struct type *
15755 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
15756                    struct type *base_type, int cnst, int voltl)
15757 {
15758   struct type *el_type, *inner_array;
15759
15760   base_type = copy_type (base_type);
15761   inner_array = base_type;
15762
15763   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
15764     {
15765       TYPE_TARGET_TYPE (inner_array) =
15766         copy_type (TYPE_TARGET_TYPE (inner_array));
15767       inner_array = TYPE_TARGET_TYPE (inner_array);
15768     }
15769
15770   el_type = TYPE_TARGET_TYPE (inner_array);
15771   cnst |= TYPE_CONST (el_type);
15772   voltl |= TYPE_VOLATILE (el_type);
15773   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
15774
15775   return set_die_type (die, base_type, cu);
15776 }
15777
15778 static struct type *
15779 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
15780 {
15781   struct type *base_type, *cv_type;
15782
15783   base_type = die_type (die, cu);
15784
15785   /* The die_type call above may have already set the type for this DIE.  */
15786   cv_type = get_die_type (die, cu);
15787   if (cv_type)
15788     return cv_type;
15789
15790   /* In case the const qualifier is applied to an array type, the element type
15791      is so qualified, not the array type (section 6.7.3 of C99).  */
15792   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15793     return add_array_cv_type (die, cu, base_type, 1, 0);
15794
15795   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
15796   return set_die_type (die, cv_type, cu);
15797 }
15798
15799 static struct type *
15800 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
15801 {
15802   struct type *base_type, *cv_type;
15803
15804   base_type = die_type (die, cu);
15805
15806   /* The die_type call above may have already set the type for this DIE.  */
15807   cv_type = get_die_type (die, cu);
15808   if (cv_type)
15809     return cv_type;
15810
15811   /* In case the volatile qualifier is applied to an array type, the
15812      element type is so qualified, not the array type (section 6.7.3
15813      of C99).  */
15814   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15815     return add_array_cv_type (die, cu, base_type, 0, 1);
15816
15817   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
15818   return set_die_type (die, cv_type, cu);
15819 }
15820
15821 /* Handle DW_TAG_restrict_type.  */
15822
15823 static struct type *
15824 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
15825 {
15826   struct type *base_type, *cv_type;
15827
15828   base_type = die_type (die, cu);
15829
15830   /* The die_type call above may have already set the type for this DIE.  */
15831   cv_type = get_die_type (die, cu);
15832   if (cv_type)
15833     return cv_type;
15834
15835   cv_type = make_restrict_type (base_type);
15836   return set_die_type (die, cv_type, cu);
15837 }
15838
15839 /* Handle DW_TAG_atomic_type.  */
15840
15841 static struct type *
15842 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
15843 {
15844   struct type *base_type, *cv_type;
15845
15846   base_type = die_type (die, cu);
15847
15848   /* The die_type call above may have already set the type for this DIE.  */
15849   cv_type = get_die_type (die, cu);
15850   if (cv_type)
15851     return cv_type;
15852
15853   cv_type = make_atomic_type (base_type);
15854   return set_die_type (die, cv_type, cu);
15855 }
15856
15857 /* Extract all information from a DW_TAG_string_type DIE and add to
15858    the user defined type vector.  It isn't really a user defined type,
15859    but it behaves like one, with other DIE's using an AT_user_def_type
15860    attribute to reference it.  */
15861
15862 static struct type *
15863 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
15864 {
15865   struct objfile *objfile = cu->objfile;
15866   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15867   struct type *type, *range_type, *index_type, *char_type;
15868   struct attribute *attr;
15869   unsigned int length;
15870
15871   attr = dwarf2_attr (die, DW_AT_string_length, cu);
15872   if (attr)
15873     {
15874       length = DW_UNSND (attr);
15875     }
15876   else
15877     {
15878       /* Check for the DW_AT_byte_size attribute.  */
15879       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15880       if (attr)
15881         {
15882           length = DW_UNSND (attr);
15883         }
15884       else
15885         {
15886           length = 1;
15887         }
15888     }
15889
15890   index_type = objfile_type (objfile)->builtin_int;
15891   range_type = create_static_range_type (NULL, index_type, 1, length);
15892   char_type = language_string_char_type (cu->language_defn, gdbarch);
15893   type = create_string_type (NULL, char_type, range_type);
15894
15895   return set_die_type (die, type, cu);
15896 }
15897
15898 /* Assuming that DIE corresponds to a function, returns nonzero
15899    if the function is prototyped.  */
15900
15901 static int
15902 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
15903 {
15904   struct attribute *attr;
15905
15906   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15907   if (attr && (DW_UNSND (attr) != 0))
15908     return 1;
15909
15910   /* The DWARF standard implies that the DW_AT_prototyped attribute
15911      is only meaninful for C, but the concept also extends to other
15912      languages that allow unprototyped functions (Eg: Objective C).
15913      For all other languages, assume that functions are always
15914      prototyped.  */
15915   if (cu->language != language_c
15916       && cu->language != language_objc
15917       && cu->language != language_opencl)
15918     return 1;
15919
15920   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15921      prototyped and unprototyped functions; default to prototyped,
15922      since that is more common in modern code (and RealView warns
15923      about unprototyped functions).  */
15924   if (producer_is_realview (cu->producer))
15925     return 1;
15926
15927   return 0;
15928 }
15929
15930 /* Handle DIES due to C code like:
15931
15932    struct foo
15933    {
15934    int (*funcp)(int a, long l);
15935    int b;
15936    };
15937
15938    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15939
15940 static struct type *
15941 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15942 {
15943   struct objfile *objfile = cu->objfile;
15944   struct type *type;            /* Type that this function returns.  */
15945   struct type *ftype;           /* Function that returns above type.  */
15946   struct attribute *attr;
15947
15948   type = die_type (die, cu);
15949
15950   /* The die_type call above may have already set the type for this DIE.  */
15951   ftype = get_die_type (die, cu);
15952   if (ftype)
15953     return ftype;
15954
15955   ftype = lookup_function_type (type);
15956
15957   if (prototyped_function_p (die, cu))
15958     TYPE_PROTOTYPED (ftype) = 1;
15959
15960   /* Store the calling convention in the type if it's available in
15961      the subroutine die.  Otherwise set the calling convention to
15962      the default value DW_CC_normal.  */
15963   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15964   if (attr)
15965     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15966   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15967     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15968   else
15969     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15970
15971   /* Record whether the function returns normally to its caller or not
15972      if the DWARF producer set that information.  */
15973   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15974   if (attr && (DW_UNSND (attr) != 0))
15975     TYPE_NO_RETURN (ftype) = 1;
15976
15977   /* We need to add the subroutine type to the die immediately so
15978      we don't infinitely recurse when dealing with parameters
15979      declared as the same subroutine type.  */
15980   set_die_type (die, ftype, cu);
15981
15982   if (die->child != NULL)
15983     {
15984       struct type *void_type = objfile_type (objfile)->builtin_void;
15985       struct die_info *child_die;
15986       int nparams, iparams;
15987
15988       /* Count the number of parameters.
15989          FIXME: GDB currently ignores vararg functions, but knows about
15990          vararg member functions.  */
15991       nparams = 0;
15992       child_die = die->child;
15993       while (child_die && child_die->tag)
15994         {
15995           if (child_die->tag == DW_TAG_formal_parameter)
15996             nparams++;
15997           else if (child_die->tag == DW_TAG_unspecified_parameters)
15998             TYPE_VARARGS (ftype) = 1;
15999           child_die = sibling_die (child_die);
16000         }
16001
16002       /* Allocate storage for parameters and fill them in.  */
16003       TYPE_NFIELDS (ftype) = nparams;
16004       TYPE_FIELDS (ftype) = (struct field *)
16005         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
16006
16007       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
16008          even if we error out during the parameters reading below.  */
16009       for (iparams = 0; iparams < nparams; iparams++)
16010         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
16011
16012       iparams = 0;
16013       child_die = die->child;
16014       while (child_die && child_die->tag)
16015         {
16016           if (child_die->tag == DW_TAG_formal_parameter)
16017             {
16018               struct type *arg_type;
16019
16020               /* DWARF version 2 has no clean way to discern C++
16021                  static and non-static member functions.  G++ helps
16022                  GDB by marking the first parameter for non-static
16023                  member functions (which is the this pointer) as
16024                  artificial.  We pass this information to
16025                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
16026
16027                  DWARF version 3 added DW_AT_object_pointer, which GCC
16028                  4.5 does not yet generate.  */
16029               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
16030               if (attr)
16031                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
16032               else
16033                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
16034               arg_type = die_type (child_die, cu);
16035
16036               /* RealView does not mark THIS as const, which the testsuite
16037                  expects.  GCC marks THIS as const in method definitions,
16038                  but not in the class specifications (GCC PR 43053).  */
16039               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
16040                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
16041                 {
16042                   int is_this = 0;
16043                   struct dwarf2_cu *arg_cu = cu;
16044                   const char *name = dwarf2_name (child_die, cu);
16045
16046                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
16047                   if (attr)
16048                     {
16049                       /* If the compiler emits this, use it.  */
16050                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
16051                         is_this = 1;
16052                     }
16053                   else if (name && strcmp (name, "this") == 0)
16054                     /* Function definitions will have the argument names.  */
16055                     is_this = 1;
16056                   else if (name == NULL && iparams == 0)
16057                     /* Declarations may not have the names, so like
16058                        elsewhere in GDB, assume an artificial first
16059                        argument is "this".  */
16060                     is_this = 1;
16061
16062                   if (is_this)
16063                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
16064                                              arg_type, 0);
16065                 }
16066
16067               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
16068               iparams++;
16069             }
16070           child_die = sibling_die (child_die);
16071         }
16072     }
16073
16074   return ftype;
16075 }
16076
16077 static struct type *
16078 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
16079 {
16080   struct objfile *objfile = cu->objfile;
16081   const char *name = NULL;
16082   struct type *this_type, *target_type;
16083
16084   name = dwarf2_full_name (NULL, die, cu);
16085   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
16086   TYPE_TARGET_STUB (this_type) = 1;
16087   set_die_type (die, this_type, cu);
16088   target_type = die_type (die, cu);
16089   if (target_type != this_type)
16090     TYPE_TARGET_TYPE (this_type) = target_type;
16091   else
16092     {
16093       /* Self-referential typedefs are, it seems, not allowed by the DWARF
16094          spec and cause infinite loops in GDB.  */
16095       complaint (&symfile_complaints,
16096                  _("Self-referential DW_TAG_typedef "
16097                    "- DIE at 0x%x [in module %s]"),
16098                  to_underlying (die->sect_off), objfile_name (objfile));
16099       TYPE_TARGET_TYPE (this_type) = NULL;
16100     }
16101   return this_type;
16102 }
16103
16104 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
16105    (which may be different from NAME) to the architecture back-end to allow
16106    it to guess the correct format if necessary.  */
16107
16108 static struct type *
16109 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
16110                         const char *name_hint)
16111 {
16112   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16113   const struct floatformat **format;
16114   struct type *type;
16115
16116   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
16117   if (format)
16118     type = init_float_type (objfile, bits, name, format);
16119   else
16120     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
16121
16122   return type;
16123 }
16124
16125 /* Find a representation of a given base type and install
16126    it in the TYPE field of the die.  */
16127
16128 static struct type *
16129 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
16130 {
16131   struct objfile *objfile = cu->objfile;
16132   struct type *type;
16133   struct attribute *attr;
16134   int encoding = 0, bits = 0;
16135   const char *name;
16136
16137   attr = dwarf2_attr (die, DW_AT_encoding, cu);
16138   if (attr)
16139     {
16140       encoding = DW_UNSND (attr);
16141     }
16142   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16143   if (attr)
16144     {
16145       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
16146     }
16147   name = dwarf2_name (die, cu);
16148   if (!name)
16149     {
16150       complaint (&symfile_complaints,
16151                  _("DW_AT_name missing from DW_TAG_base_type"));
16152     }
16153
16154   switch (encoding)
16155     {
16156       case DW_ATE_address:
16157         /* Turn DW_ATE_address into a void * pointer.  */
16158         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
16159         type = init_pointer_type (objfile, bits, name, type);
16160         break;
16161       case DW_ATE_boolean:
16162         type = init_boolean_type (objfile, bits, 1, name);
16163         break;
16164       case DW_ATE_complex_float:
16165         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
16166         type = init_complex_type (objfile, name, type);
16167         break;
16168       case DW_ATE_decimal_float:
16169         type = init_decfloat_type (objfile, bits, name);
16170         break;
16171       case DW_ATE_float:
16172         type = dwarf2_init_float_type (objfile, bits, name, name);
16173         break;
16174       case DW_ATE_signed:
16175         type = init_integer_type (objfile, bits, 0, name);
16176         break;
16177       case DW_ATE_unsigned:
16178         if (cu->language == language_fortran
16179             && name
16180             && startswith (name, "character("))
16181           type = init_character_type (objfile, bits, 1, name);
16182         else
16183           type = init_integer_type (objfile, bits, 1, name);
16184         break;
16185       case DW_ATE_signed_char:
16186         if (cu->language == language_ada || cu->language == language_m2
16187             || cu->language == language_pascal
16188             || cu->language == language_fortran)
16189           type = init_character_type (objfile, bits, 0, name);
16190         else
16191           type = init_integer_type (objfile, bits, 0, name);
16192         break;
16193       case DW_ATE_unsigned_char:
16194         if (cu->language == language_ada || cu->language == language_m2
16195             || cu->language == language_pascal
16196             || cu->language == language_fortran
16197             || cu->language == language_rust)
16198           type = init_character_type (objfile, bits, 1, name);
16199         else
16200           type = init_integer_type (objfile, bits, 1, name);
16201         break;
16202       case DW_ATE_UTF:
16203         {
16204           gdbarch *arch = get_objfile_arch (objfile);
16205
16206           if (bits == 16)
16207             type = builtin_type (arch)->builtin_char16;
16208           else if (bits == 32)
16209             type = builtin_type (arch)->builtin_char32;
16210           else
16211             {
16212               complaint (&symfile_complaints,
16213                          _("unsupported DW_ATE_UTF bit size: '%d'"),
16214                          bits);
16215               type = init_integer_type (objfile, bits, 1, name);
16216             }
16217           return set_die_type (die, type, cu);
16218         }
16219         break;
16220
16221       default:
16222         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
16223                    dwarf_type_encoding_name (encoding));
16224         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
16225         break;
16226     }
16227
16228   if (name && strcmp (name, "char") == 0)
16229     TYPE_NOSIGN (type) = 1;
16230
16231   return set_die_type (die, type, cu);
16232 }
16233
16234 /* Parse dwarf attribute if it's a block, reference or constant and put the
16235    resulting value of the attribute into struct bound_prop.
16236    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
16237
16238 static int
16239 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
16240                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
16241 {
16242   struct dwarf2_property_baton *baton;
16243   struct obstack *obstack = &cu->objfile->objfile_obstack;
16244
16245   if (attr == NULL || prop == NULL)
16246     return 0;
16247
16248   if (attr_form_is_block (attr))
16249     {
16250       baton = XOBNEW (obstack, struct dwarf2_property_baton);
16251       baton->referenced_type = NULL;
16252       baton->locexpr.per_cu = cu->per_cu;
16253       baton->locexpr.size = DW_BLOCK (attr)->size;
16254       baton->locexpr.data = DW_BLOCK (attr)->data;
16255       prop->data.baton = baton;
16256       prop->kind = PROP_LOCEXPR;
16257       gdb_assert (prop->data.baton != NULL);
16258     }
16259   else if (attr_form_is_ref (attr))
16260     {
16261       struct dwarf2_cu *target_cu = cu;
16262       struct die_info *target_die;
16263       struct attribute *target_attr;
16264
16265       target_die = follow_die_ref (die, attr, &target_cu);
16266       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
16267       if (target_attr == NULL)
16268         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
16269                                    target_cu);
16270       if (target_attr == NULL)
16271         return 0;
16272
16273       switch (target_attr->name)
16274         {
16275           case DW_AT_location:
16276             if (attr_form_is_section_offset (target_attr))
16277               {
16278                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
16279                 baton->referenced_type = die_type (target_die, target_cu);
16280                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
16281                 prop->data.baton = baton;
16282                 prop->kind = PROP_LOCLIST;
16283                 gdb_assert (prop->data.baton != NULL);
16284               }
16285             else if (attr_form_is_block (target_attr))
16286               {
16287                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
16288                 baton->referenced_type = die_type (target_die, target_cu);
16289                 baton->locexpr.per_cu = cu->per_cu;
16290                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
16291                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
16292                 prop->data.baton = baton;
16293                 prop->kind = PROP_LOCEXPR;
16294                 gdb_assert (prop->data.baton != NULL);
16295               }
16296             else
16297               {
16298                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16299                                                        "dynamic property");
16300                 return 0;
16301               }
16302             break;
16303           case DW_AT_data_member_location:
16304             {
16305               LONGEST offset;
16306
16307               if (!handle_data_member_location (target_die, target_cu,
16308                                                 &offset))
16309                 return 0;
16310
16311               baton = XOBNEW (obstack, struct dwarf2_property_baton);
16312               baton->referenced_type = read_type_die (target_die->parent,
16313                                                       target_cu);
16314               baton->offset_info.offset = offset;
16315               baton->offset_info.type = die_type (target_die, target_cu);
16316               prop->data.baton = baton;
16317               prop->kind = PROP_ADDR_OFFSET;
16318               break;
16319             }
16320         }
16321     }
16322   else if (attr_form_is_constant (attr))
16323     {
16324       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
16325       prop->kind = PROP_CONST;
16326     }
16327   else
16328     {
16329       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
16330                                              dwarf2_name (die, cu));
16331       return 0;
16332     }
16333
16334   return 1;
16335 }
16336
16337 /* Read the given DW_AT_subrange DIE.  */
16338
16339 static struct type *
16340 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
16341 {
16342   struct type *base_type, *orig_base_type;
16343   struct type *range_type;
16344   struct attribute *attr;
16345   struct dynamic_prop low, high;
16346   int low_default_is_valid;
16347   int high_bound_is_count = 0;
16348   const char *name;
16349   LONGEST negative_mask;
16350
16351   orig_base_type = die_type (die, cu);
16352   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
16353      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
16354      creating the range type, but we use the result of check_typedef
16355      when examining properties of the type.  */
16356   base_type = check_typedef (orig_base_type);
16357
16358   /* The die_type call above may have already set the type for this DIE.  */
16359   range_type = get_die_type (die, cu);
16360   if (range_type)
16361     return range_type;
16362
16363   low.kind = PROP_CONST;
16364   high.kind = PROP_CONST;
16365   high.data.const_val = 0;
16366
16367   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
16368      omitting DW_AT_lower_bound.  */
16369   switch (cu->language)
16370     {
16371     case language_c:
16372     case language_cplus:
16373       low.data.const_val = 0;
16374       low_default_is_valid = 1;
16375       break;
16376     case language_fortran:
16377       low.data.const_val = 1;
16378       low_default_is_valid = 1;
16379       break;
16380     case language_d:
16381     case language_objc:
16382     case language_rust:
16383       low.data.const_val = 0;
16384       low_default_is_valid = (cu->header.version >= 4);
16385       break;
16386     case language_ada:
16387     case language_m2:
16388     case language_pascal:
16389       low.data.const_val = 1;
16390       low_default_is_valid = (cu->header.version >= 4);
16391       break;
16392     default:
16393       low.data.const_val = 0;
16394       low_default_is_valid = 0;
16395       break;
16396     }
16397
16398   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
16399   if (attr)
16400     attr_to_dynamic_prop (attr, die, cu, &low);
16401   else if (!low_default_is_valid)
16402     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
16403                                       "- DIE at 0x%x [in module %s]"),
16404                to_underlying (die->sect_off), objfile_name (cu->objfile));
16405
16406   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
16407   if (!attr_to_dynamic_prop (attr, die, cu, &high))
16408     {
16409       attr = dwarf2_attr (die, DW_AT_count, cu);
16410       if (attr_to_dynamic_prop (attr, die, cu, &high))
16411         {
16412           /* If bounds are constant do the final calculation here.  */
16413           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
16414             high.data.const_val = low.data.const_val + high.data.const_val - 1;
16415           else
16416             high_bound_is_count = 1;
16417         }
16418     }
16419
16420   /* Dwarf-2 specifications explicitly allows to create subrange types
16421      without specifying a base type.
16422      In that case, the base type must be set to the type of
16423      the lower bound, upper bound or count, in that order, if any of these
16424      three attributes references an object that has a type.
16425      If no base type is found, the Dwarf-2 specifications say that
16426      a signed integer type of size equal to the size of an address should
16427      be used.
16428      For the following C code: `extern char gdb_int [];'
16429      GCC produces an empty range DIE.
16430      FIXME: muller/2010-05-28: Possible references to object for low bound,
16431      high bound or count are not yet handled by this code.  */
16432   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
16433     {
16434       struct objfile *objfile = cu->objfile;
16435       struct gdbarch *gdbarch = get_objfile_arch (objfile);
16436       int addr_size = gdbarch_addr_bit (gdbarch) /8;
16437       struct type *int_type = objfile_type (objfile)->builtin_int;
16438
16439       /* Test "int", "long int", and "long long int" objfile types,
16440          and select the first one having a size above or equal to the
16441          architecture address size.  */
16442       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16443         base_type = int_type;
16444       else
16445         {
16446           int_type = objfile_type (objfile)->builtin_long;
16447           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16448             base_type = int_type;
16449           else
16450             {
16451               int_type = objfile_type (objfile)->builtin_long_long;
16452               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16453                 base_type = int_type;
16454             }
16455         }
16456     }
16457
16458   /* Normally, the DWARF producers are expected to use a signed
16459      constant form (Eg. DW_FORM_sdata) to express negative bounds.
16460      But this is unfortunately not always the case, as witnessed
16461      with GCC, for instance, where the ambiguous DW_FORM_dataN form
16462      is used instead.  To work around that ambiguity, we treat
16463      the bounds as signed, and thus sign-extend their values, when
16464      the base type is signed.  */
16465   negative_mask =
16466     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
16467   if (low.kind == PROP_CONST
16468       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
16469     low.data.const_val |= negative_mask;
16470   if (high.kind == PROP_CONST
16471       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
16472     high.data.const_val |= negative_mask;
16473
16474   range_type = create_range_type (NULL, orig_base_type, &low, &high);
16475
16476   if (high_bound_is_count)
16477     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
16478
16479   /* Ada expects an empty array on no boundary attributes.  */
16480   if (attr == NULL && cu->language != language_ada)
16481     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
16482
16483   name = dwarf2_name (die, cu);
16484   if (name)
16485     TYPE_NAME (range_type) = name;
16486
16487   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16488   if (attr)
16489     TYPE_LENGTH (range_type) = DW_UNSND (attr);
16490
16491   set_die_type (die, range_type, cu);
16492
16493   /* set_die_type should be already done.  */
16494   set_descriptive_type (range_type, die, cu);
16495
16496   return range_type;
16497 }
16498
16499 static struct type *
16500 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
16501 {
16502   struct type *type;
16503
16504   /* For now, we only support the C meaning of an unspecified type: void.  */
16505
16506   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
16507   TYPE_NAME (type) = dwarf2_name (die, cu);
16508
16509   return set_die_type (die, type, cu);
16510 }
16511
16512 /* Read a single die and all its descendents.  Set the die's sibling
16513    field to NULL; set other fields in the die correctly, and set all
16514    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
16515    location of the info_ptr after reading all of those dies.  PARENT
16516    is the parent of the die in question.  */
16517
16518 static struct die_info *
16519 read_die_and_children (const struct die_reader_specs *reader,
16520                        const gdb_byte *info_ptr,
16521                        const gdb_byte **new_info_ptr,
16522                        struct die_info *parent)
16523 {
16524   struct die_info *die;
16525   const gdb_byte *cur_ptr;
16526   int has_children;
16527
16528   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
16529   if (die == NULL)
16530     {
16531       *new_info_ptr = cur_ptr;
16532       return NULL;
16533     }
16534   store_in_ref_table (die, reader->cu);
16535
16536   if (has_children)
16537     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
16538   else
16539     {
16540       die->child = NULL;
16541       *new_info_ptr = cur_ptr;
16542     }
16543
16544   die->sibling = NULL;
16545   die->parent = parent;
16546   return die;
16547 }
16548
16549 /* Read a die, all of its descendents, and all of its siblings; set
16550    all of the fields of all of the dies correctly.  Arguments are as
16551    in read_die_and_children.  */
16552
16553 static struct die_info *
16554 read_die_and_siblings_1 (const struct die_reader_specs *reader,
16555                          const gdb_byte *info_ptr,
16556                          const gdb_byte **new_info_ptr,
16557                          struct die_info *parent)
16558 {
16559   struct die_info *first_die, *last_sibling;
16560   const gdb_byte *cur_ptr;
16561
16562   cur_ptr = info_ptr;
16563   first_die = last_sibling = NULL;
16564
16565   while (1)
16566     {
16567       struct die_info *die
16568         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
16569
16570       if (die == NULL)
16571         {
16572           *new_info_ptr = cur_ptr;
16573           return first_die;
16574         }
16575
16576       if (!first_die)
16577         first_die = die;
16578       else
16579         last_sibling->sibling = die;
16580
16581       last_sibling = die;
16582     }
16583 }
16584
16585 /* Read a die, all of its descendents, and all of its siblings; set
16586    all of the fields of all of the dies correctly.  Arguments are as
16587    in read_die_and_children.
16588    This the main entry point for reading a DIE and all its children.  */
16589
16590 static struct die_info *
16591 read_die_and_siblings (const struct die_reader_specs *reader,
16592                        const gdb_byte *info_ptr,
16593                        const gdb_byte **new_info_ptr,
16594                        struct die_info *parent)
16595 {
16596   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
16597                                                   new_info_ptr, parent);
16598
16599   if (dwarf_die_debug)
16600     {
16601       fprintf_unfiltered (gdb_stdlog,
16602                           "Read die from %s@0x%x of %s:\n",
16603                           get_section_name (reader->die_section),
16604                           (unsigned) (info_ptr - reader->die_section->buffer),
16605                           bfd_get_filename (reader->abfd));
16606       dump_die (die, dwarf_die_debug);
16607     }
16608
16609   return die;
16610 }
16611
16612 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
16613    attributes.
16614    The caller is responsible for filling in the extra attributes
16615    and updating (*DIEP)->num_attrs.
16616    Set DIEP to point to a newly allocated die with its information,
16617    except for its child, sibling, and parent fields.
16618    Set HAS_CHILDREN to tell whether the die has children or not.  */
16619
16620 static const gdb_byte *
16621 read_full_die_1 (const struct die_reader_specs *reader,
16622                  struct die_info **diep, const gdb_byte *info_ptr,
16623                  int *has_children, int num_extra_attrs)
16624 {
16625   unsigned int abbrev_number, bytes_read, i;
16626   struct abbrev_info *abbrev;
16627   struct die_info *die;
16628   struct dwarf2_cu *cu = reader->cu;
16629   bfd *abfd = reader->abfd;
16630
16631   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
16632   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16633   info_ptr += bytes_read;
16634   if (!abbrev_number)
16635     {
16636       *diep = NULL;
16637       *has_children = 0;
16638       return info_ptr;
16639     }
16640
16641   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
16642   if (!abbrev)
16643     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
16644            abbrev_number,
16645            bfd_get_filename (abfd));
16646
16647   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
16648   die->sect_off = sect_off;
16649   die->tag = abbrev->tag;
16650   die->abbrev = abbrev_number;
16651
16652   /* Make the result usable.
16653      The caller needs to update num_attrs after adding the extra
16654      attributes.  */
16655   die->num_attrs = abbrev->num_attrs;
16656
16657   for (i = 0; i < abbrev->num_attrs; ++i)
16658     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
16659                                info_ptr);
16660
16661   *diep = die;
16662   *has_children = abbrev->has_children;
16663   return info_ptr;
16664 }
16665
16666 /* Read a die and all its attributes.
16667    Set DIEP to point to a newly allocated die with its information,
16668    except for its child, sibling, and parent fields.
16669    Set HAS_CHILDREN to tell whether the die has children or not.  */
16670
16671 static const gdb_byte *
16672 read_full_die (const struct die_reader_specs *reader,
16673                struct die_info **diep, const gdb_byte *info_ptr,
16674                int *has_children)
16675 {
16676   const gdb_byte *result;
16677
16678   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
16679
16680   if (dwarf_die_debug)
16681     {
16682       fprintf_unfiltered (gdb_stdlog,
16683                           "Read die from %s@0x%x of %s:\n",
16684                           get_section_name (reader->die_section),
16685                           (unsigned) (info_ptr - reader->die_section->buffer),
16686                           bfd_get_filename (reader->abfd));
16687       dump_die (*diep, dwarf_die_debug);
16688     }
16689
16690   return result;
16691 }
16692 \f
16693 /* Abbreviation tables.
16694
16695    In DWARF version 2, the description of the debugging information is
16696    stored in a separate .debug_abbrev section.  Before we read any
16697    dies from a section we read in all abbreviations and install them
16698    in a hash table.  */
16699
16700 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
16701
16702 static struct abbrev_info *
16703 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
16704 {
16705   struct abbrev_info *abbrev;
16706
16707   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
16708   memset (abbrev, 0, sizeof (struct abbrev_info));
16709
16710   return abbrev;
16711 }
16712
16713 /* Add an abbreviation to the table.  */
16714
16715 static void
16716 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
16717                          unsigned int abbrev_number,
16718                          struct abbrev_info *abbrev)
16719 {
16720   unsigned int hash_number;
16721
16722   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16723   abbrev->next = abbrev_table->abbrevs[hash_number];
16724   abbrev_table->abbrevs[hash_number] = abbrev;
16725 }
16726
16727 /* Look up an abbrev in the table.
16728    Returns NULL if the abbrev is not found.  */
16729
16730 static struct abbrev_info *
16731 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
16732                             unsigned int abbrev_number)
16733 {
16734   unsigned int hash_number;
16735   struct abbrev_info *abbrev;
16736
16737   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16738   abbrev = abbrev_table->abbrevs[hash_number];
16739
16740   while (abbrev)
16741     {
16742       if (abbrev->number == abbrev_number)
16743         return abbrev;
16744       abbrev = abbrev->next;
16745     }
16746   return NULL;
16747 }
16748
16749 /* Read in an abbrev table.  */
16750
16751 static struct abbrev_table *
16752 abbrev_table_read_table (struct dwarf2_section_info *section,
16753                          sect_offset sect_off)
16754 {
16755   struct objfile *objfile = dwarf2_per_objfile->objfile;
16756   bfd *abfd = get_section_bfd_owner (section);
16757   struct abbrev_table *abbrev_table;
16758   const gdb_byte *abbrev_ptr;
16759   struct abbrev_info *cur_abbrev;
16760   unsigned int abbrev_number, bytes_read, abbrev_name;
16761   unsigned int abbrev_form;
16762   struct attr_abbrev *cur_attrs;
16763   unsigned int allocated_attrs;
16764
16765   abbrev_table = XNEW (struct abbrev_table);
16766   abbrev_table->sect_off = sect_off;
16767   obstack_init (&abbrev_table->abbrev_obstack);
16768   abbrev_table->abbrevs =
16769     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
16770                ABBREV_HASH_SIZE);
16771   memset (abbrev_table->abbrevs, 0,
16772           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
16773
16774   dwarf2_read_section (objfile, section);
16775   abbrev_ptr = section->buffer + to_underlying (sect_off);
16776   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16777   abbrev_ptr += bytes_read;
16778
16779   allocated_attrs = ATTR_ALLOC_CHUNK;
16780   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
16781
16782   /* Loop until we reach an abbrev number of 0.  */
16783   while (abbrev_number)
16784     {
16785       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
16786
16787       /* read in abbrev header */
16788       cur_abbrev->number = abbrev_number;
16789       cur_abbrev->tag
16790         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16791       abbrev_ptr += bytes_read;
16792       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
16793       abbrev_ptr += 1;
16794
16795       /* now read in declarations */
16796       for (;;)
16797         {
16798           LONGEST implicit_const;
16799
16800           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16801           abbrev_ptr += bytes_read;
16802           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16803           abbrev_ptr += bytes_read;
16804           if (abbrev_form == DW_FORM_implicit_const)
16805             {
16806               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
16807                                                    &bytes_read);
16808               abbrev_ptr += bytes_read;
16809             }
16810           else
16811             {
16812               /* Initialize it due to a false compiler warning.  */
16813               implicit_const = -1;
16814             }
16815
16816           if (abbrev_name == 0)
16817             break;
16818
16819           if (cur_abbrev->num_attrs == allocated_attrs)
16820             {
16821               allocated_attrs += ATTR_ALLOC_CHUNK;
16822               cur_attrs
16823                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
16824             }
16825
16826           cur_attrs[cur_abbrev->num_attrs].name
16827             = (enum dwarf_attribute) abbrev_name;
16828           cur_attrs[cur_abbrev->num_attrs].form
16829             = (enum dwarf_form) abbrev_form;
16830           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
16831           ++cur_abbrev->num_attrs;
16832         }
16833
16834       cur_abbrev->attrs =
16835         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
16836                    cur_abbrev->num_attrs);
16837       memcpy (cur_abbrev->attrs, cur_attrs,
16838               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
16839
16840       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
16841
16842       /* Get next abbreviation.
16843          Under Irix6 the abbreviations for a compilation unit are not
16844          always properly terminated with an abbrev number of 0.
16845          Exit loop if we encounter an abbreviation which we have
16846          already read (which means we are about to read the abbreviations
16847          for the next compile unit) or if the end of the abbreviation
16848          table is reached.  */
16849       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
16850         break;
16851       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16852       abbrev_ptr += bytes_read;
16853       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
16854         break;
16855     }
16856
16857   xfree (cur_attrs);
16858   return abbrev_table;
16859 }
16860
16861 /* Free the resources held by ABBREV_TABLE.  */
16862
16863 static void
16864 abbrev_table_free (struct abbrev_table *abbrev_table)
16865 {
16866   obstack_free (&abbrev_table->abbrev_obstack, NULL);
16867   xfree (abbrev_table);
16868 }
16869
16870 /* Same as abbrev_table_free but as a cleanup.
16871    We pass in a pointer to the pointer to the table so that we can
16872    set the pointer to NULL when we're done.  It also simplifies
16873    build_type_psymtabs_1.  */
16874
16875 static void
16876 abbrev_table_free_cleanup (void *table_ptr)
16877 {
16878   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
16879
16880   if (*abbrev_table_ptr != NULL)
16881     abbrev_table_free (*abbrev_table_ptr);
16882   *abbrev_table_ptr = NULL;
16883 }
16884
16885 /* Read the abbrev table for CU from ABBREV_SECTION.  */
16886
16887 static void
16888 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
16889                      struct dwarf2_section_info *abbrev_section)
16890 {
16891   cu->abbrev_table =
16892     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
16893 }
16894
16895 /* Release the memory used by the abbrev table for a compilation unit.  */
16896
16897 static void
16898 dwarf2_free_abbrev_table (void *ptr_to_cu)
16899 {
16900   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
16901
16902   if (cu->abbrev_table != NULL)
16903     abbrev_table_free (cu->abbrev_table);
16904   /* Set this to NULL so that we SEGV if we try to read it later,
16905      and also because free_comp_unit verifies this is NULL.  */
16906   cu->abbrev_table = NULL;
16907 }
16908 \f
16909 /* Returns nonzero if TAG represents a type that we might generate a partial
16910    symbol for.  */
16911
16912 static int
16913 is_type_tag_for_partial (int tag)
16914 {
16915   switch (tag)
16916     {
16917 #if 0
16918     /* Some types that would be reasonable to generate partial symbols for,
16919        that we don't at present.  */
16920     case DW_TAG_array_type:
16921     case DW_TAG_file_type:
16922     case DW_TAG_ptr_to_member_type:
16923     case DW_TAG_set_type:
16924     case DW_TAG_string_type:
16925     case DW_TAG_subroutine_type:
16926 #endif
16927     case DW_TAG_base_type:
16928     case DW_TAG_class_type:
16929     case DW_TAG_interface_type:
16930     case DW_TAG_enumeration_type:
16931     case DW_TAG_structure_type:
16932     case DW_TAG_subrange_type:
16933     case DW_TAG_typedef:
16934     case DW_TAG_union_type:
16935       return 1;
16936     default:
16937       return 0;
16938     }
16939 }
16940
16941 /* Load all DIEs that are interesting for partial symbols into memory.  */
16942
16943 static struct partial_die_info *
16944 load_partial_dies (const struct die_reader_specs *reader,
16945                    const gdb_byte *info_ptr, int building_psymtab)
16946 {
16947   struct dwarf2_cu *cu = reader->cu;
16948   struct objfile *objfile = cu->objfile;
16949   struct partial_die_info *part_die;
16950   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16951   struct abbrev_info *abbrev;
16952   unsigned int bytes_read;
16953   unsigned int load_all = 0;
16954   int nesting_level = 1;
16955
16956   parent_die = NULL;
16957   last_die = NULL;
16958
16959   gdb_assert (cu->per_cu != NULL);
16960   if (cu->per_cu->load_all_dies)
16961     load_all = 1;
16962
16963   cu->partial_dies
16964     = htab_create_alloc_ex (cu->header.length / 12,
16965                             partial_die_hash,
16966                             partial_die_eq,
16967                             NULL,
16968                             &cu->comp_unit_obstack,
16969                             hashtab_obstack_allocate,
16970                             dummy_obstack_deallocate);
16971
16972   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16973
16974   while (1)
16975     {
16976       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16977
16978       /* A NULL abbrev means the end of a series of children.  */
16979       if (abbrev == NULL)
16980         {
16981           if (--nesting_level == 0)
16982             {
16983               /* PART_DIE was probably the last thing allocated on the
16984                  comp_unit_obstack, so we could call obstack_free
16985                  here.  We don't do that because the waste is small,
16986                  and will be cleaned up when we're done with this
16987                  compilation unit.  This way, we're also more robust
16988                  against other users of the comp_unit_obstack.  */
16989               return first_die;
16990             }
16991           info_ptr += bytes_read;
16992           last_die = parent_die;
16993           parent_die = parent_die->die_parent;
16994           continue;
16995         }
16996
16997       /* Check for template arguments.  We never save these; if
16998          they're seen, we just mark the parent, and go on our way.  */
16999       if (parent_die != NULL
17000           && cu->language == language_cplus
17001           && (abbrev->tag == DW_TAG_template_type_param
17002               || abbrev->tag == DW_TAG_template_value_param))
17003         {
17004           parent_die->has_template_arguments = 1;
17005
17006           if (!load_all)
17007             {
17008               /* We don't need a partial DIE for the template argument.  */
17009               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17010               continue;
17011             }
17012         }
17013
17014       /* We only recurse into c++ subprograms looking for template arguments.
17015          Skip their other children.  */
17016       if (!load_all
17017           && cu->language == language_cplus
17018           && parent_die != NULL
17019           && parent_die->tag == DW_TAG_subprogram)
17020         {
17021           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17022           continue;
17023         }
17024
17025       /* Check whether this DIE is interesting enough to save.  Normally
17026          we would not be interested in members here, but there may be
17027          later variables referencing them via DW_AT_specification (for
17028          static members).  */
17029       if (!load_all
17030           && !is_type_tag_for_partial (abbrev->tag)
17031           && abbrev->tag != DW_TAG_constant
17032           && abbrev->tag != DW_TAG_enumerator
17033           && abbrev->tag != DW_TAG_subprogram
17034           && abbrev->tag != DW_TAG_lexical_block
17035           && abbrev->tag != DW_TAG_variable
17036           && abbrev->tag != DW_TAG_namespace
17037           && abbrev->tag != DW_TAG_module
17038           && abbrev->tag != DW_TAG_member
17039           && abbrev->tag != DW_TAG_imported_unit
17040           && abbrev->tag != DW_TAG_imported_declaration)
17041         {
17042           /* Otherwise we skip to the next sibling, if any.  */
17043           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17044           continue;
17045         }
17046
17047       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
17048                                    info_ptr);
17049
17050       /* This two-pass algorithm for processing partial symbols has a
17051          high cost in cache pressure.  Thus, handle some simple cases
17052          here which cover the majority of C partial symbols.  DIEs
17053          which neither have specification tags in them, nor could have
17054          specification tags elsewhere pointing at them, can simply be
17055          processed and discarded.
17056
17057          This segment is also optional; scan_partial_symbols and
17058          add_partial_symbol will handle these DIEs if we chain
17059          them in normally.  When compilers which do not emit large
17060          quantities of duplicate debug information are more common,
17061          this code can probably be removed.  */
17062
17063       /* Any complete simple types at the top level (pretty much all
17064          of them, for a language without namespaces), can be processed
17065          directly.  */
17066       if (parent_die == NULL
17067           && part_die->has_specification == 0
17068           && part_die->is_declaration == 0
17069           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
17070               || part_die->tag == DW_TAG_base_type
17071               || part_die->tag == DW_TAG_subrange_type))
17072         {
17073           if (building_psymtab && part_die->name != NULL)
17074             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
17075                                  VAR_DOMAIN, LOC_TYPEDEF,
17076                                  &objfile->static_psymbols,
17077                                  0, cu->language, objfile);
17078           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
17079           continue;
17080         }
17081
17082       /* The exception for DW_TAG_typedef with has_children above is
17083          a workaround of GCC PR debug/47510.  In the case of this complaint
17084          type_name_no_tag_or_error will error on such types later.
17085
17086          GDB skipped children of DW_TAG_typedef by the shortcut above and then
17087          it could not find the child DIEs referenced later, this is checked
17088          above.  In correct DWARF DW_TAG_typedef should have no children.  */
17089
17090       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
17091         complaint (&symfile_complaints,
17092                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
17093                      "- DIE at 0x%x [in module %s]"),
17094                    to_underlying (part_die->sect_off), objfile_name (objfile));
17095
17096       /* If we're at the second level, and we're an enumerator, and
17097          our parent has no specification (meaning possibly lives in a
17098          namespace elsewhere), then we can add the partial symbol now
17099          instead of queueing it.  */
17100       if (part_die->tag == DW_TAG_enumerator
17101           && parent_die != NULL
17102           && parent_die->die_parent == NULL
17103           && parent_die->tag == DW_TAG_enumeration_type
17104           && parent_die->has_specification == 0)
17105         {
17106           if (part_die->name == NULL)
17107             complaint (&symfile_complaints,
17108                        _("malformed enumerator DIE ignored"));
17109           else if (building_psymtab)
17110             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
17111                                  VAR_DOMAIN, LOC_CONST,
17112                                  cu->language == language_cplus
17113                                  ? &objfile->global_psymbols
17114                                  : &objfile->static_psymbols,
17115                                  0, cu->language, objfile);
17116
17117           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
17118           continue;
17119         }
17120
17121       /* We'll save this DIE so link it in.  */
17122       part_die->die_parent = parent_die;
17123       part_die->die_sibling = NULL;
17124       part_die->die_child = NULL;
17125
17126       if (last_die && last_die == parent_die)
17127         last_die->die_child = part_die;
17128       else if (last_die)
17129         last_die->die_sibling = part_die;
17130
17131       last_die = part_die;
17132
17133       if (first_die == NULL)
17134         first_die = part_die;
17135
17136       /* Maybe add the DIE to the hash table.  Not all DIEs that we
17137          find interesting need to be in the hash table, because we
17138          also have the parent/sibling/child chains; only those that we
17139          might refer to by offset later during partial symbol reading.
17140
17141          For now this means things that might have be the target of a
17142          DW_AT_specification, DW_AT_abstract_origin, or
17143          DW_AT_extension.  DW_AT_extension will refer only to
17144          namespaces; DW_AT_abstract_origin refers to functions (and
17145          many things under the function DIE, but we do not recurse
17146          into function DIEs during partial symbol reading) and
17147          possibly variables as well; DW_AT_specification refers to
17148          declarations.  Declarations ought to have the DW_AT_declaration
17149          flag.  It happens that GCC forgets to put it in sometimes, but
17150          only for functions, not for types.
17151
17152          Adding more things than necessary to the hash table is harmless
17153          except for the performance cost.  Adding too few will result in
17154          wasted time in find_partial_die, when we reread the compilation
17155          unit with load_all_dies set.  */
17156
17157       if (load_all
17158           || abbrev->tag == DW_TAG_constant
17159           || abbrev->tag == DW_TAG_subprogram
17160           || abbrev->tag == DW_TAG_variable
17161           || abbrev->tag == DW_TAG_namespace
17162           || part_die->is_declaration)
17163         {
17164           void **slot;
17165
17166           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
17167                                            to_underlying (part_die->sect_off),
17168                                            INSERT);
17169           *slot = part_die;
17170         }
17171
17172       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
17173
17174       /* For some DIEs we want to follow their children (if any).  For C
17175          we have no reason to follow the children of structures; for other
17176          languages we have to, so that we can get at method physnames
17177          to infer fully qualified class names, for DW_AT_specification,
17178          and for C++ template arguments.  For C++, we also look one level
17179          inside functions to find template arguments (if the name of the
17180          function does not already contain the template arguments).
17181
17182          For Ada, we need to scan the children of subprograms and lexical
17183          blocks as well because Ada allows the definition of nested
17184          entities that could be interesting for the debugger, such as
17185          nested subprograms for instance.  */
17186       if (last_die->has_children
17187           && (load_all
17188               || last_die->tag == DW_TAG_namespace
17189               || last_die->tag == DW_TAG_module
17190               || last_die->tag == DW_TAG_enumeration_type
17191               || (cu->language == language_cplus
17192                   && last_die->tag == DW_TAG_subprogram
17193                   && (last_die->name == NULL
17194                       || strchr (last_die->name, '<') == NULL))
17195               || (cu->language != language_c
17196                   && (last_die->tag == DW_TAG_class_type
17197                       || last_die->tag == DW_TAG_interface_type
17198                       || last_die->tag == DW_TAG_structure_type
17199                       || last_die->tag == DW_TAG_union_type))
17200               || (cu->language == language_ada
17201                   && (last_die->tag == DW_TAG_subprogram
17202                       || last_die->tag == DW_TAG_lexical_block))))
17203         {
17204           nesting_level++;
17205           parent_die = last_die;
17206           continue;
17207         }
17208
17209       /* Otherwise we skip to the next sibling, if any.  */
17210       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
17211
17212       /* Back to the top, do it again.  */
17213     }
17214 }
17215
17216 /* Read a minimal amount of information into the minimal die structure.  */
17217
17218 static const gdb_byte *
17219 read_partial_die (const struct die_reader_specs *reader,
17220                   struct partial_die_info *part_die,
17221                   struct abbrev_info *abbrev, unsigned int abbrev_len,
17222                   const gdb_byte *info_ptr)
17223 {
17224   struct dwarf2_cu *cu = reader->cu;
17225   struct objfile *objfile = cu->objfile;
17226   const gdb_byte *buffer = reader->buffer;
17227   unsigned int i;
17228   struct attribute attr;
17229   int has_low_pc_attr = 0;
17230   int has_high_pc_attr = 0;
17231   int high_pc_relative = 0;
17232
17233   memset (part_die, 0, sizeof (struct partial_die_info));
17234
17235   part_die->sect_off = (sect_offset) (info_ptr - buffer);
17236
17237   info_ptr += abbrev_len;
17238
17239   if (abbrev == NULL)
17240     return info_ptr;
17241
17242   part_die->tag = abbrev->tag;
17243   part_die->has_children = abbrev->has_children;
17244
17245   for (i = 0; i < abbrev->num_attrs; ++i)
17246     {
17247       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
17248
17249       /* Store the data if it is of an attribute we want to keep in a
17250          partial symbol table.  */
17251       switch (attr.name)
17252         {
17253         case DW_AT_name:
17254           switch (part_die->tag)
17255             {
17256             case DW_TAG_compile_unit:
17257             case DW_TAG_partial_unit:
17258             case DW_TAG_type_unit:
17259               /* Compilation units have a DW_AT_name that is a filename, not
17260                  a source language identifier.  */
17261             case DW_TAG_enumeration_type:
17262             case DW_TAG_enumerator:
17263               /* These tags always have simple identifiers already; no need
17264                  to canonicalize them.  */
17265               part_die->name = DW_STRING (&attr);
17266               break;
17267             default:
17268               part_die->name
17269                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
17270                                             &objfile->per_bfd->storage_obstack);
17271               break;
17272             }
17273           break;
17274         case DW_AT_linkage_name:
17275         case DW_AT_MIPS_linkage_name:
17276           /* Note that both forms of linkage name might appear.  We
17277              assume they will be the same, and we only store the last
17278              one we see.  */
17279           if (cu->language == language_ada)
17280             part_die->name = DW_STRING (&attr);
17281           part_die->linkage_name = DW_STRING (&attr);
17282           break;
17283         case DW_AT_low_pc:
17284           has_low_pc_attr = 1;
17285           part_die->lowpc = attr_value_as_address (&attr);
17286           break;
17287         case DW_AT_high_pc:
17288           has_high_pc_attr = 1;
17289           part_die->highpc = attr_value_as_address (&attr);
17290           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
17291                 high_pc_relative = 1;
17292           break;
17293         case DW_AT_location:
17294           /* Support the .debug_loc offsets.  */
17295           if (attr_form_is_block (&attr))
17296             {
17297                part_die->d.locdesc = DW_BLOCK (&attr);
17298             }
17299           else if (attr_form_is_section_offset (&attr))
17300             {
17301               dwarf2_complex_location_expr_complaint ();
17302             }
17303           else
17304             {
17305               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17306                                                      "partial symbol information");
17307             }
17308           break;
17309         case DW_AT_external:
17310           part_die->is_external = DW_UNSND (&attr);
17311           break;
17312         case DW_AT_declaration:
17313           part_die->is_declaration = DW_UNSND (&attr);
17314           break;
17315         case DW_AT_type:
17316           part_die->has_type = 1;
17317           break;
17318         case DW_AT_abstract_origin:
17319         case DW_AT_specification:
17320         case DW_AT_extension:
17321           part_die->has_specification = 1;
17322           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
17323           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
17324                                    || cu->per_cu->is_dwz);
17325           break;
17326         case DW_AT_sibling:
17327           /* Ignore absolute siblings, they might point outside of
17328              the current compile unit.  */
17329           if (attr.form == DW_FORM_ref_addr)
17330             complaint (&symfile_complaints,
17331                        _("ignoring absolute DW_AT_sibling"));
17332           else
17333             {
17334               sect_offset off = dwarf2_get_ref_die_offset (&attr);
17335               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
17336
17337               if (sibling_ptr < info_ptr)
17338                 complaint (&symfile_complaints,
17339                            _("DW_AT_sibling points backwards"));
17340               else if (sibling_ptr > reader->buffer_end)
17341                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
17342               else
17343                 part_die->sibling = sibling_ptr;
17344             }
17345           break;
17346         case DW_AT_byte_size:
17347           part_die->has_byte_size = 1;
17348           break;
17349         case DW_AT_const_value:
17350           part_die->has_const_value = 1;
17351           break;
17352         case DW_AT_calling_convention:
17353           /* DWARF doesn't provide a way to identify a program's source-level
17354              entry point.  DW_AT_calling_convention attributes are only meant
17355              to describe functions' calling conventions.
17356
17357              However, because it's a necessary piece of information in
17358              Fortran, and before DWARF 4 DW_CC_program was the only
17359              piece of debugging information whose definition refers to
17360              a 'main program' at all, several compilers marked Fortran
17361              main programs with DW_CC_program --- even when those
17362              functions use the standard calling conventions.
17363
17364              Although DWARF now specifies a way to provide this
17365              information, we support this practice for backward
17366              compatibility.  */
17367           if (DW_UNSND (&attr) == DW_CC_program
17368               && cu->language == language_fortran)
17369             part_die->main_subprogram = 1;
17370           break;
17371         case DW_AT_inline:
17372           if (DW_UNSND (&attr) == DW_INL_inlined
17373               || DW_UNSND (&attr) == DW_INL_declared_inlined)
17374             part_die->may_be_inlined = 1;
17375           break;
17376
17377         case DW_AT_import:
17378           if (part_die->tag == DW_TAG_imported_unit)
17379             {
17380               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
17381               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
17382                                   || cu->per_cu->is_dwz);
17383             }
17384           break;
17385
17386         case DW_AT_main_subprogram:
17387           part_die->main_subprogram = DW_UNSND (&attr);
17388           break;
17389
17390         default:
17391           break;
17392         }
17393     }
17394
17395   if (high_pc_relative)
17396     part_die->highpc += part_die->lowpc;
17397
17398   if (has_low_pc_attr && has_high_pc_attr)
17399     {
17400       /* When using the GNU linker, .gnu.linkonce. sections are used to
17401          eliminate duplicate copies of functions and vtables and such.
17402          The linker will arbitrarily choose one and discard the others.
17403          The AT_*_pc values for such functions refer to local labels in
17404          these sections.  If the section from that file was discarded, the
17405          labels are not in the output, so the relocs get a value of 0.
17406          If this is a discarded function, mark the pc bounds as invalid,
17407          so that GDB will ignore it.  */
17408       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
17409         {
17410           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17411
17412           complaint (&symfile_complaints,
17413                      _("DW_AT_low_pc %s is zero "
17414                        "for DIE at 0x%x [in module %s]"),
17415                      paddress (gdbarch, part_die->lowpc),
17416                      to_underlying (part_die->sect_off), objfile_name (objfile));
17417         }
17418       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
17419       else if (part_die->lowpc >= part_die->highpc)
17420         {
17421           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17422
17423           complaint (&symfile_complaints,
17424                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
17425                        "for DIE at 0x%x [in module %s]"),
17426                      paddress (gdbarch, part_die->lowpc),
17427                      paddress (gdbarch, part_die->highpc),
17428                      to_underlying (part_die->sect_off),
17429                      objfile_name (objfile));
17430         }
17431       else
17432         part_die->has_pc_info = 1;
17433     }
17434
17435   return info_ptr;
17436 }
17437
17438 /* Find a cached partial DIE at OFFSET in CU.  */
17439
17440 static struct partial_die_info *
17441 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
17442 {
17443   struct partial_die_info *lookup_die = NULL;
17444   struct partial_die_info part_die;
17445
17446   part_die.sect_off = sect_off;
17447   lookup_die = ((struct partial_die_info *)
17448                 htab_find_with_hash (cu->partial_dies, &part_die,
17449                                      to_underlying (sect_off)));
17450
17451   return lookup_die;
17452 }
17453
17454 /* Find a partial DIE at OFFSET, which may or may not be in CU,
17455    except in the case of .debug_types DIEs which do not reference
17456    outside their CU (they do however referencing other types via
17457    DW_FORM_ref_sig8).  */
17458
17459 static struct partial_die_info *
17460 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
17461 {
17462   struct objfile *objfile = cu->objfile;
17463   struct dwarf2_per_cu_data *per_cu = NULL;
17464   struct partial_die_info *pd = NULL;
17465
17466   if (offset_in_dwz == cu->per_cu->is_dwz
17467       && offset_in_cu_p (&cu->header, sect_off))
17468     {
17469       pd = find_partial_die_in_comp_unit (sect_off, cu);
17470       if (pd != NULL)
17471         return pd;
17472       /* We missed recording what we needed.
17473          Load all dies and try again.  */
17474       per_cu = cu->per_cu;
17475     }
17476   else
17477     {
17478       /* TUs don't reference other CUs/TUs (except via type signatures).  */
17479       if (cu->per_cu->is_debug_types)
17480         {
17481           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
17482                    " external reference to offset 0x%x [in module %s].\n"),
17483                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
17484                  bfd_get_filename (objfile->obfd));
17485         }
17486       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
17487                                                  objfile);
17488
17489       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
17490         load_partial_comp_unit (per_cu);
17491
17492       per_cu->cu->last_used = 0;
17493       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17494     }
17495
17496   /* If we didn't find it, and not all dies have been loaded,
17497      load them all and try again.  */
17498
17499   if (pd == NULL && per_cu->load_all_dies == 0)
17500     {
17501       per_cu->load_all_dies = 1;
17502
17503       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
17504          THIS_CU->cu may already be in use.  So we can't just free it and
17505          replace its DIEs with the ones we read in.  Instead, we leave those
17506          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
17507          and clobber THIS_CU->cu->partial_dies with the hash table for the new
17508          set.  */
17509       load_partial_comp_unit (per_cu);
17510
17511       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17512     }
17513
17514   if (pd == NULL)
17515     internal_error (__FILE__, __LINE__,
17516                     _("could not find partial DIE 0x%x "
17517                       "in cache [from module %s]\n"),
17518                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
17519   return pd;
17520 }
17521
17522 /* See if we can figure out if the class lives in a namespace.  We do
17523    this by looking for a member function; its demangled name will
17524    contain namespace info, if there is any.  */
17525
17526 static void
17527 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
17528                                   struct dwarf2_cu *cu)
17529 {
17530   /* NOTE: carlton/2003-10-07: Getting the info this way changes
17531      what template types look like, because the demangler
17532      frequently doesn't give the same name as the debug info.  We
17533      could fix this by only using the demangled name to get the
17534      prefix (but see comment in read_structure_type).  */
17535
17536   struct partial_die_info *real_pdi;
17537   struct partial_die_info *child_pdi;
17538
17539   /* If this DIE (this DIE's specification, if any) has a parent, then
17540      we should not do this.  We'll prepend the parent's fully qualified
17541      name when we create the partial symbol.  */
17542
17543   real_pdi = struct_pdi;
17544   while (real_pdi->has_specification)
17545     real_pdi = find_partial_die (real_pdi->spec_offset,
17546                                  real_pdi->spec_is_dwz, cu);
17547
17548   if (real_pdi->die_parent != NULL)
17549     return;
17550
17551   for (child_pdi = struct_pdi->die_child;
17552        child_pdi != NULL;
17553        child_pdi = child_pdi->die_sibling)
17554     {
17555       if (child_pdi->tag == DW_TAG_subprogram
17556           && child_pdi->linkage_name != NULL)
17557         {
17558           char *actual_class_name
17559             = language_class_name_from_physname (cu->language_defn,
17560                                                  child_pdi->linkage_name);
17561           if (actual_class_name != NULL)
17562             {
17563               struct_pdi->name
17564                 = ((const char *)
17565                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17566                                   actual_class_name,
17567                                   strlen (actual_class_name)));
17568               xfree (actual_class_name);
17569             }
17570           break;
17571         }
17572     }
17573 }
17574
17575 /* Adjust PART_DIE before generating a symbol for it.  This function
17576    may set the is_external flag or change the DIE's name.  */
17577
17578 static void
17579 fixup_partial_die (struct partial_die_info *part_die,
17580                    struct dwarf2_cu *cu)
17581 {
17582   /* Once we've fixed up a die, there's no point in doing so again.
17583      This also avoids a memory leak if we were to call
17584      guess_partial_die_structure_name multiple times.  */
17585   if (part_die->fixup_called)
17586     return;
17587
17588   /* If we found a reference attribute and the DIE has no name, try
17589      to find a name in the referred to DIE.  */
17590
17591   if (part_die->name == NULL && part_die->has_specification)
17592     {
17593       struct partial_die_info *spec_die;
17594
17595       spec_die = find_partial_die (part_die->spec_offset,
17596                                    part_die->spec_is_dwz, cu);
17597
17598       fixup_partial_die (spec_die, cu);
17599
17600       if (spec_die->name)
17601         {
17602           part_die->name = spec_die->name;
17603
17604           /* Copy DW_AT_external attribute if it is set.  */
17605           if (spec_die->is_external)
17606             part_die->is_external = spec_die->is_external;
17607         }
17608     }
17609
17610   /* Set default names for some unnamed DIEs.  */
17611
17612   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
17613     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
17614
17615   /* If there is no parent die to provide a namespace, and there are
17616      children, see if we can determine the namespace from their linkage
17617      name.  */
17618   if (cu->language == language_cplus
17619       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17620       && part_die->die_parent == NULL
17621       && part_die->has_children
17622       && (part_die->tag == DW_TAG_class_type
17623           || part_die->tag == DW_TAG_structure_type
17624           || part_die->tag == DW_TAG_union_type))
17625     guess_partial_die_structure_name (part_die, cu);
17626
17627   /* GCC might emit a nameless struct or union that has a linkage
17628      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17629   if (part_die->name == NULL
17630       && (part_die->tag == DW_TAG_class_type
17631           || part_die->tag == DW_TAG_interface_type
17632           || part_die->tag == DW_TAG_structure_type
17633           || part_die->tag == DW_TAG_union_type)
17634       && part_die->linkage_name != NULL)
17635     {
17636       char *demangled;
17637
17638       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
17639       if (demangled)
17640         {
17641           const char *base;
17642
17643           /* Strip any leading namespaces/classes, keep only the base name.
17644              DW_AT_name for named DIEs does not contain the prefixes.  */
17645           base = strrchr (demangled, ':');
17646           if (base && base > demangled && base[-1] == ':')
17647             base++;
17648           else
17649             base = demangled;
17650
17651           part_die->name
17652             = ((const char *)
17653                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17654                               base, strlen (base)));
17655           xfree (demangled);
17656         }
17657     }
17658
17659   part_die->fixup_called = 1;
17660 }
17661
17662 /* Read an attribute value described by an attribute form.  */
17663
17664 static const gdb_byte *
17665 read_attribute_value (const struct die_reader_specs *reader,
17666                       struct attribute *attr, unsigned form,
17667                       LONGEST implicit_const, const gdb_byte *info_ptr)
17668 {
17669   struct dwarf2_cu *cu = reader->cu;
17670   struct objfile *objfile = cu->objfile;
17671   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17672   bfd *abfd = reader->abfd;
17673   struct comp_unit_head *cu_header = &cu->header;
17674   unsigned int bytes_read;
17675   struct dwarf_block *blk;
17676
17677   attr->form = (enum dwarf_form) form;
17678   switch (form)
17679     {
17680     case DW_FORM_ref_addr:
17681       if (cu->header.version == 2)
17682         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17683       else
17684         DW_UNSND (attr) = read_offset (abfd, info_ptr,
17685                                        &cu->header, &bytes_read);
17686       info_ptr += bytes_read;
17687       break;
17688     case DW_FORM_GNU_ref_alt:
17689       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17690       info_ptr += bytes_read;
17691       break;
17692     case DW_FORM_addr:
17693       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17694       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
17695       info_ptr += bytes_read;
17696       break;
17697     case DW_FORM_block2:
17698       blk = dwarf_alloc_block (cu);
17699       blk->size = read_2_bytes (abfd, info_ptr);
17700       info_ptr += 2;
17701       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17702       info_ptr += blk->size;
17703       DW_BLOCK (attr) = blk;
17704       break;
17705     case DW_FORM_block4:
17706       blk = dwarf_alloc_block (cu);
17707       blk->size = read_4_bytes (abfd, info_ptr);
17708       info_ptr += 4;
17709       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17710       info_ptr += blk->size;
17711       DW_BLOCK (attr) = blk;
17712       break;
17713     case DW_FORM_data2:
17714       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
17715       info_ptr += 2;
17716       break;
17717     case DW_FORM_data4:
17718       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
17719       info_ptr += 4;
17720       break;
17721     case DW_FORM_data8:
17722       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
17723       info_ptr += 8;
17724       break;
17725     case DW_FORM_data16:
17726       blk = dwarf_alloc_block (cu);
17727       blk->size = 16;
17728       blk->data = read_n_bytes (abfd, info_ptr, 16);
17729       info_ptr += 16;
17730       DW_BLOCK (attr) = blk;
17731       break;
17732     case DW_FORM_sec_offset:
17733       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17734       info_ptr += bytes_read;
17735       break;
17736     case DW_FORM_string:
17737       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
17738       DW_STRING_IS_CANONICAL (attr) = 0;
17739       info_ptr += bytes_read;
17740       break;
17741     case DW_FORM_strp:
17742       if (!cu->per_cu->is_dwz)
17743         {
17744           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
17745                                                    &bytes_read);
17746           DW_STRING_IS_CANONICAL (attr) = 0;
17747           info_ptr += bytes_read;
17748           break;
17749         }
17750       /* FALLTHROUGH */
17751     case DW_FORM_line_strp:
17752       if (!cu->per_cu->is_dwz)
17753         {
17754           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
17755                                                         cu_header, &bytes_read);
17756           DW_STRING_IS_CANONICAL (attr) = 0;
17757           info_ptr += bytes_read;
17758           break;
17759         }
17760       /* FALLTHROUGH */
17761     case DW_FORM_GNU_strp_alt:
17762       {
17763         struct dwz_file *dwz = dwarf2_get_dwz_file ();
17764         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
17765                                           &bytes_read);
17766
17767         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
17768         DW_STRING_IS_CANONICAL (attr) = 0;
17769         info_ptr += bytes_read;
17770       }
17771       break;
17772     case DW_FORM_exprloc:
17773     case DW_FORM_block:
17774       blk = dwarf_alloc_block (cu);
17775       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17776       info_ptr += bytes_read;
17777       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17778       info_ptr += blk->size;
17779       DW_BLOCK (attr) = blk;
17780       break;
17781     case DW_FORM_block1:
17782       blk = dwarf_alloc_block (cu);
17783       blk->size = read_1_byte (abfd, info_ptr);
17784       info_ptr += 1;
17785       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17786       info_ptr += blk->size;
17787       DW_BLOCK (attr) = blk;
17788       break;
17789     case DW_FORM_data1:
17790       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17791       info_ptr += 1;
17792       break;
17793     case DW_FORM_flag:
17794       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17795       info_ptr += 1;
17796       break;
17797     case DW_FORM_flag_present:
17798       DW_UNSND (attr) = 1;
17799       break;
17800     case DW_FORM_sdata:
17801       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17802       info_ptr += bytes_read;
17803       break;
17804     case DW_FORM_udata:
17805       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17806       info_ptr += bytes_read;
17807       break;
17808     case DW_FORM_ref1:
17809       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17810                          + read_1_byte (abfd, info_ptr));
17811       info_ptr += 1;
17812       break;
17813     case DW_FORM_ref2:
17814       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17815                          + read_2_bytes (abfd, info_ptr));
17816       info_ptr += 2;
17817       break;
17818     case DW_FORM_ref4:
17819       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17820                          + read_4_bytes (abfd, info_ptr));
17821       info_ptr += 4;
17822       break;
17823     case DW_FORM_ref8:
17824       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17825                          + read_8_bytes (abfd, info_ptr));
17826       info_ptr += 8;
17827       break;
17828     case DW_FORM_ref_sig8:
17829       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
17830       info_ptr += 8;
17831       break;
17832     case DW_FORM_ref_udata:
17833       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17834                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
17835       info_ptr += bytes_read;
17836       break;
17837     case DW_FORM_indirect:
17838       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17839       info_ptr += bytes_read;
17840       if (form == DW_FORM_implicit_const)
17841         {
17842           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17843           info_ptr += bytes_read;
17844         }
17845       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
17846                                        info_ptr);
17847       break;
17848     case DW_FORM_implicit_const:
17849       DW_SND (attr) = implicit_const;
17850       break;
17851     case DW_FORM_GNU_addr_index:
17852       if (reader->dwo_file == NULL)
17853         {
17854           /* For now flag a hard error.
17855              Later we can turn this into a complaint.  */
17856           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17857                  dwarf_form_name (form),
17858                  bfd_get_filename (abfd));
17859         }
17860       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
17861       info_ptr += bytes_read;
17862       break;
17863     case DW_FORM_GNU_str_index:
17864       if (reader->dwo_file == NULL)
17865         {
17866           /* For now flag a hard error.
17867              Later we can turn this into a complaint if warranted.  */
17868           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17869                  dwarf_form_name (form),
17870                  bfd_get_filename (abfd));
17871         }
17872       {
17873         ULONGEST str_index =
17874           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17875
17876         DW_STRING (attr) = read_str_index (reader, str_index);
17877         DW_STRING_IS_CANONICAL (attr) = 0;
17878         info_ptr += bytes_read;
17879       }
17880       break;
17881     default:
17882       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
17883              dwarf_form_name (form),
17884              bfd_get_filename (abfd));
17885     }
17886
17887   /* Super hack.  */
17888   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
17889     attr->form = DW_FORM_GNU_ref_alt;
17890
17891   /* We have seen instances where the compiler tried to emit a byte
17892      size attribute of -1 which ended up being encoded as an unsigned
17893      0xffffffff.  Although 0xffffffff is technically a valid size value,
17894      an object of this size seems pretty unlikely so we can relatively
17895      safely treat these cases as if the size attribute was invalid and
17896      treat them as zero by default.  */
17897   if (attr->name == DW_AT_byte_size
17898       && form == DW_FORM_data4
17899       && DW_UNSND (attr) >= 0xffffffff)
17900     {
17901       complaint
17902         (&symfile_complaints,
17903          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
17904          hex_string (DW_UNSND (attr)));
17905       DW_UNSND (attr) = 0;
17906     }
17907
17908   return info_ptr;
17909 }
17910
17911 /* Read an attribute described by an abbreviated attribute.  */
17912
17913 static const gdb_byte *
17914 read_attribute (const struct die_reader_specs *reader,
17915                 struct attribute *attr, struct attr_abbrev *abbrev,
17916                 const gdb_byte *info_ptr)
17917 {
17918   attr->name = abbrev->name;
17919   return read_attribute_value (reader, attr, abbrev->form,
17920                                abbrev->implicit_const, info_ptr);
17921 }
17922
17923 /* Read dwarf information from a buffer.  */
17924
17925 static unsigned int
17926 read_1_byte (bfd *abfd, const gdb_byte *buf)
17927 {
17928   return bfd_get_8 (abfd, buf);
17929 }
17930
17931 static int
17932 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17933 {
17934   return bfd_get_signed_8 (abfd, buf);
17935 }
17936
17937 static unsigned int
17938 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17939 {
17940   return bfd_get_16 (abfd, buf);
17941 }
17942
17943 static int
17944 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17945 {
17946   return bfd_get_signed_16 (abfd, buf);
17947 }
17948
17949 static unsigned int
17950 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17951 {
17952   return bfd_get_32 (abfd, buf);
17953 }
17954
17955 static int
17956 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17957 {
17958   return bfd_get_signed_32 (abfd, buf);
17959 }
17960
17961 static ULONGEST
17962 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17963 {
17964   return bfd_get_64 (abfd, buf);
17965 }
17966
17967 static CORE_ADDR
17968 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17969               unsigned int *bytes_read)
17970 {
17971   struct comp_unit_head *cu_header = &cu->header;
17972   CORE_ADDR retval = 0;
17973
17974   if (cu_header->signed_addr_p)
17975     {
17976       switch (cu_header->addr_size)
17977         {
17978         case 2:
17979           retval = bfd_get_signed_16 (abfd, buf);
17980           break;
17981         case 4:
17982           retval = bfd_get_signed_32 (abfd, buf);
17983           break;
17984         case 8:
17985           retval = bfd_get_signed_64 (abfd, buf);
17986           break;
17987         default:
17988           internal_error (__FILE__, __LINE__,
17989                           _("read_address: bad switch, signed [in module %s]"),
17990                           bfd_get_filename (abfd));
17991         }
17992     }
17993   else
17994     {
17995       switch (cu_header->addr_size)
17996         {
17997         case 2:
17998           retval = bfd_get_16 (abfd, buf);
17999           break;
18000         case 4:
18001           retval = bfd_get_32 (abfd, buf);
18002           break;
18003         case 8:
18004           retval = bfd_get_64 (abfd, buf);
18005           break;
18006         default:
18007           internal_error (__FILE__, __LINE__,
18008                           _("read_address: bad switch, "
18009                             "unsigned [in module %s]"),
18010                           bfd_get_filename (abfd));
18011         }
18012     }
18013
18014   *bytes_read = cu_header->addr_size;
18015   return retval;
18016 }
18017
18018 /* Read the initial length from a section.  The (draft) DWARF 3
18019    specification allows the initial length to take up either 4 bytes
18020    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
18021    bytes describe the length and all offsets will be 8 bytes in length
18022    instead of 4.
18023
18024    An older, non-standard 64-bit format is also handled by this
18025    function.  The older format in question stores the initial length
18026    as an 8-byte quantity without an escape value.  Lengths greater
18027    than 2^32 aren't very common which means that the initial 4 bytes
18028    is almost always zero.  Since a length value of zero doesn't make
18029    sense for the 32-bit format, this initial zero can be considered to
18030    be an escape value which indicates the presence of the older 64-bit
18031    format.  As written, the code can't detect (old format) lengths
18032    greater than 4GB.  If it becomes necessary to handle lengths
18033    somewhat larger than 4GB, we could allow other small values (such
18034    as the non-sensical values of 1, 2, and 3) to also be used as
18035    escape values indicating the presence of the old format.
18036
18037    The value returned via bytes_read should be used to increment the
18038    relevant pointer after calling read_initial_length().
18039
18040    [ Note:  read_initial_length() and read_offset() are based on the
18041      document entitled "DWARF Debugging Information Format", revision
18042      3, draft 8, dated November 19, 2001.  This document was obtained
18043      from:
18044
18045         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
18046
18047      This document is only a draft and is subject to change.  (So beware.)
18048
18049      Details regarding the older, non-standard 64-bit format were
18050      determined empirically by examining 64-bit ELF files produced by
18051      the SGI toolchain on an IRIX 6.5 machine.
18052
18053      - Kevin, July 16, 2002
18054    ] */
18055
18056 static LONGEST
18057 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
18058 {
18059   LONGEST length = bfd_get_32 (abfd, buf);
18060
18061   if (length == 0xffffffff)
18062     {
18063       length = bfd_get_64 (abfd, buf + 4);
18064       *bytes_read = 12;
18065     }
18066   else if (length == 0)
18067     {
18068       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
18069       length = bfd_get_64 (abfd, buf);
18070       *bytes_read = 8;
18071     }
18072   else
18073     {
18074       *bytes_read = 4;
18075     }
18076
18077   return length;
18078 }
18079
18080 /* Cover function for read_initial_length.
18081    Returns the length of the object at BUF, and stores the size of the
18082    initial length in *BYTES_READ and stores the size that offsets will be in
18083    *OFFSET_SIZE.
18084    If the initial length size is not equivalent to that specified in
18085    CU_HEADER then issue a complaint.
18086    This is useful when reading non-comp-unit headers.  */
18087
18088 static LONGEST
18089 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
18090                                         const struct comp_unit_head *cu_header,
18091                                         unsigned int *bytes_read,
18092                                         unsigned int *offset_size)
18093 {
18094   LONGEST length = read_initial_length (abfd, buf, bytes_read);
18095
18096   gdb_assert (cu_header->initial_length_size == 4
18097               || cu_header->initial_length_size == 8
18098               || cu_header->initial_length_size == 12);
18099
18100   if (cu_header->initial_length_size != *bytes_read)
18101     complaint (&symfile_complaints,
18102                _("intermixed 32-bit and 64-bit DWARF sections"));
18103
18104   *offset_size = (*bytes_read == 4) ? 4 : 8;
18105   return length;
18106 }
18107
18108 /* Read an offset from the data stream.  The size of the offset is
18109    given by cu_header->offset_size.  */
18110
18111 static LONGEST
18112 read_offset (bfd *abfd, const gdb_byte *buf,
18113              const struct comp_unit_head *cu_header,
18114              unsigned int *bytes_read)
18115 {
18116   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
18117
18118   *bytes_read = cu_header->offset_size;
18119   return offset;
18120 }
18121
18122 /* Read an offset from the data stream.  */
18123
18124 static LONGEST
18125 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
18126 {
18127   LONGEST retval = 0;
18128
18129   switch (offset_size)
18130     {
18131     case 4:
18132       retval = bfd_get_32 (abfd, buf);
18133       break;
18134     case 8:
18135       retval = bfd_get_64 (abfd, buf);
18136       break;
18137     default:
18138       internal_error (__FILE__, __LINE__,
18139                       _("read_offset_1: bad switch [in module %s]"),
18140                       bfd_get_filename (abfd));
18141     }
18142
18143   return retval;
18144 }
18145
18146 static const gdb_byte *
18147 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
18148 {
18149   /* If the size of a host char is 8 bits, we can return a pointer
18150      to the buffer, otherwise we have to copy the data to a buffer
18151      allocated on the temporary obstack.  */
18152   gdb_assert (HOST_CHAR_BIT == 8);
18153   return buf;
18154 }
18155
18156 static const char *
18157 read_direct_string (bfd *abfd, const gdb_byte *buf,
18158                     unsigned int *bytes_read_ptr)
18159 {
18160   /* If the size of a host char is 8 bits, we can return a pointer
18161      to the string, otherwise we have to copy the string to a buffer
18162      allocated on the temporary obstack.  */
18163   gdb_assert (HOST_CHAR_BIT == 8);
18164   if (*buf == '\0')
18165     {
18166       *bytes_read_ptr = 1;
18167       return NULL;
18168     }
18169   *bytes_read_ptr = strlen ((const char *) buf) + 1;
18170   return (const char *) buf;
18171 }
18172
18173 /* Return pointer to string at section SECT offset STR_OFFSET with error
18174    reporting strings FORM_NAME and SECT_NAME.  */
18175
18176 static const char *
18177 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
18178                                      struct dwarf2_section_info *sect,
18179                                      const char *form_name,
18180                                      const char *sect_name)
18181 {
18182   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
18183   if (sect->buffer == NULL)
18184     error (_("%s used without %s section [in module %s]"),
18185            form_name, sect_name, bfd_get_filename (abfd));
18186   if (str_offset >= sect->size)
18187     error (_("%s pointing outside of %s section [in module %s]"),
18188            form_name, sect_name, bfd_get_filename (abfd));
18189   gdb_assert (HOST_CHAR_BIT == 8);
18190   if (sect->buffer[str_offset] == '\0')
18191     return NULL;
18192   return (const char *) (sect->buffer + str_offset);
18193 }
18194
18195 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
18196
18197 static const char *
18198 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
18199 {
18200   return read_indirect_string_at_offset_from (abfd, str_offset,
18201                                               &dwarf2_per_objfile->str,
18202                                               "DW_FORM_strp", ".debug_str");
18203 }
18204
18205 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
18206
18207 static const char *
18208 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
18209 {
18210   return read_indirect_string_at_offset_from (abfd, str_offset,
18211                                               &dwarf2_per_objfile->line_str,
18212                                               "DW_FORM_line_strp",
18213                                               ".debug_line_str");
18214 }
18215
18216 /* Read a string at offset STR_OFFSET in the .debug_str section from
18217    the .dwz file DWZ.  Throw an error if the offset is too large.  If
18218    the string consists of a single NUL byte, return NULL; otherwise
18219    return a pointer to the string.  */
18220
18221 static const char *
18222 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
18223 {
18224   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
18225
18226   if (dwz->str.buffer == NULL)
18227     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
18228              "section [in module %s]"),
18229            bfd_get_filename (dwz->dwz_bfd));
18230   if (str_offset >= dwz->str.size)
18231     error (_("DW_FORM_GNU_strp_alt pointing outside of "
18232              ".debug_str section [in module %s]"),
18233            bfd_get_filename (dwz->dwz_bfd));
18234   gdb_assert (HOST_CHAR_BIT == 8);
18235   if (dwz->str.buffer[str_offset] == '\0')
18236     return NULL;
18237   return (const char *) (dwz->str.buffer + str_offset);
18238 }
18239
18240 /* Return pointer to string at .debug_str offset as read from BUF.
18241    BUF is assumed to be in a compilation unit described by CU_HEADER.
18242    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18243
18244 static const char *
18245 read_indirect_string (bfd *abfd, const gdb_byte *buf,
18246                       const struct comp_unit_head *cu_header,
18247                       unsigned int *bytes_read_ptr)
18248 {
18249   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
18250
18251   return read_indirect_string_at_offset (abfd, str_offset);
18252 }
18253
18254 /* Return pointer to string at .debug_line_str offset as read from BUF.
18255    BUF is assumed to be in a compilation unit described by CU_HEADER.
18256    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18257
18258 static const char *
18259 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
18260                            const struct comp_unit_head *cu_header,
18261                            unsigned int *bytes_read_ptr)
18262 {
18263   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
18264
18265   return read_indirect_line_string_at_offset (abfd, str_offset);
18266 }
18267
18268 ULONGEST
18269 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
18270                           unsigned int *bytes_read_ptr)
18271 {
18272   ULONGEST result;
18273   unsigned int num_read;
18274   int shift;
18275   unsigned char byte;
18276
18277   result = 0;
18278   shift = 0;
18279   num_read = 0;
18280   while (1)
18281     {
18282       byte = bfd_get_8 (abfd, buf);
18283       buf++;
18284       num_read++;
18285       result |= ((ULONGEST) (byte & 127) << shift);
18286       if ((byte & 128) == 0)
18287         {
18288           break;
18289         }
18290       shift += 7;
18291     }
18292   *bytes_read_ptr = num_read;
18293   return result;
18294 }
18295
18296 static LONGEST
18297 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
18298                     unsigned int *bytes_read_ptr)
18299 {
18300   LONGEST result;
18301   int shift, num_read;
18302   unsigned char byte;
18303
18304   result = 0;
18305   shift = 0;
18306   num_read = 0;
18307   while (1)
18308     {
18309       byte = bfd_get_8 (abfd, buf);
18310       buf++;
18311       num_read++;
18312       result |= ((LONGEST) (byte & 127) << shift);
18313       shift += 7;
18314       if ((byte & 128) == 0)
18315         {
18316           break;
18317         }
18318     }
18319   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
18320     result |= -(((LONGEST) 1) << shift);
18321   *bytes_read_ptr = num_read;
18322   return result;
18323 }
18324
18325 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
18326    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
18327    ADDR_SIZE is the size of addresses from the CU header.  */
18328
18329 static CORE_ADDR
18330 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
18331 {
18332   struct objfile *objfile = dwarf2_per_objfile->objfile;
18333   bfd *abfd = objfile->obfd;
18334   const gdb_byte *info_ptr;
18335
18336   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
18337   if (dwarf2_per_objfile->addr.buffer == NULL)
18338     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
18339            objfile_name (objfile));
18340   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
18341     error (_("DW_FORM_addr_index pointing outside of "
18342              ".debug_addr section [in module %s]"),
18343            objfile_name (objfile));
18344   info_ptr = (dwarf2_per_objfile->addr.buffer
18345               + addr_base + addr_index * addr_size);
18346   if (addr_size == 4)
18347     return bfd_get_32 (abfd, info_ptr);
18348   else
18349     return bfd_get_64 (abfd, info_ptr);
18350 }
18351
18352 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
18353
18354 static CORE_ADDR
18355 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
18356 {
18357   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
18358 }
18359
18360 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
18361
18362 static CORE_ADDR
18363 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
18364                              unsigned int *bytes_read)
18365 {
18366   bfd *abfd = cu->objfile->obfd;
18367   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
18368
18369   return read_addr_index (cu, addr_index);
18370 }
18371
18372 /* Data structure to pass results from dwarf2_read_addr_index_reader
18373    back to dwarf2_read_addr_index.  */
18374
18375 struct dwarf2_read_addr_index_data
18376 {
18377   ULONGEST addr_base;
18378   int addr_size;
18379 };
18380
18381 /* die_reader_func for dwarf2_read_addr_index.  */
18382
18383 static void
18384 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
18385                                const gdb_byte *info_ptr,
18386                                struct die_info *comp_unit_die,
18387                                int has_children,
18388                                void *data)
18389 {
18390   struct dwarf2_cu *cu = reader->cu;
18391   struct dwarf2_read_addr_index_data *aidata =
18392     (struct dwarf2_read_addr_index_data *) data;
18393
18394   aidata->addr_base = cu->addr_base;
18395   aidata->addr_size = cu->header.addr_size;
18396 }
18397
18398 /* Given an index in .debug_addr, fetch the value.
18399    NOTE: This can be called during dwarf expression evaluation,
18400    long after the debug information has been read, and thus per_cu->cu
18401    may no longer exist.  */
18402
18403 CORE_ADDR
18404 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
18405                         unsigned int addr_index)
18406 {
18407   struct objfile *objfile = per_cu->objfile;
18408   struct dwarf2_cu *cu = per_cu->cu;
18409   ULONGEST addr_base;
18410   int addr_size;
18411
18412   /* This is intended to be called from outside this file.  */
18413   dw2_setup (objfile);
18414
18415   /* We need addr_base and addr_size.
18416      If we don't have PER_CU->cu, we have to get it.
18417      Nasty, but the alternative is storing the needed info in PER_CU,
18418      which at this point doesn't seem justified: it's not clear how frequently
18419      it would get used and it would increase the size of every PER_CU.
18420      Entry points like dwarf2_per_cu_addr_size do a similar thing
18421      so we're not in uncharted territory here.
18422      Alas we need to be a bit more complicated as addr_base is contained
18423      in the DIE.
18424
18425      We don't need to read the entire CU(/TU).
18426      We just need the header and top level die.
18427
18428      IWBN to use the aging mechanism to let us lazily later discard the CU.
18429      For now we skip this optimization.  */
18430
18431   if (cu != NULL)
18432     {
18433       addr_base = cu->addr_base;
18434       addr_size = cu->header.addr_size;
18435     }
18436   else
18437     {
18438       struct dwarf2_read_addr_index_data aidata;
18439
18440       /* Note: We can't use init_cutu_and_read_dies_simple here,
18441          we need addr_base.  */
18442       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
18443                                dwarf2_read_addr_index_reader, &aidata);
18444       addr_base = aidata.addr_base;
18445       addr_size = aidata.addr_size;
18446     }
18447
18448   return read_addr_index_1 (addr_index, addr_base, addr_size);
18449 }
18450
18451 /* Given a DW_FORM_GNU_str_index, fetch the string.
18452    This is only used by the Fission support.  */
18453
18454 static const char *
18455 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
18456 {
18457   struct objfile *objfile = dwarf2_per_objfile->objfile;
18458   const char *objf_name = objfile_name (objfile);
18459   bfd *abfd = objfile->obfd;
18460   struct dwarf2_cu *cu = reader->cu;
18461   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
18462   struct dwarf2_section_info *str_offsets_section =
18463     &reader->dwo_file->sections.str_offsets;
18464   const gdb_byte *info_ptr;
18465   ULONGEST str_offset;
18466   static const char form_name[] = "DW_FORM_GNU_str_index";
18467
18468   dwarf2_read_section (objfile, str_section);
18469   dwarf2_read_section (objfile, str_offsets_section);
18470   if (str_section->buffer == NULL)
18471     error (_("%s used without .debug_str.dwo section"
18472              " in CU at offset 0x%x [in module %s]"),
18473            form_name, to_underlying (cu->header.sect_off), objf_name);
18474   if (str_offsets_section->buffer == NULL)
18475     error (_("%s used without .debug_str_offsets.dwo section"
18476              " in CU at offset 0x%x [in module %s]"),
18477            form_name, to_underlying (cu->header.sect_off), objf_name);
18478   if (str_index * cu->header.offset_size >= str_offsets_section->size)
18479     error (_("%s pointing outside of .debug_str_offsets.dwo"
18480              " section in CU at offset 0x%x [in module %s]"),
18481            form_name, to_underlying (cu->header.sect_off), objf_name);
18482   info_ptr = (str_offsets_section->buffer
18483               + str_index * cu->header.offset_size);
18484   if (cu->header.offset_size == 4)
18485     str_offset = bfd_get_32 (abfd, info_ptr);
18486   else
18487     str_offset = bfd_get_64 (abfd, info_ptr);
18488   if (str_offset >= str_section->size)
18489     error (_("Offset from %s pointing outside of"
18490              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
18491            form_name, to_underlying (cu->header.sect_off), objf_name);
18492   return (const char *) (str_section->buffer + str_offset);
18493 }
18494
18495 /* Return the length of an LEB128 number in BUF.  */
18496
18497 static int
18498 leb128_size (const gdb_byte *buf)
18499 {
18500   const gdb_byte *begin = buf;
18501   gdb_byte byte;
18502
18503   while (1)
18504     {
18505       byte = *buf++;
18506       if ((byte & 128) == 0)
18507         return buf - begin;
18508     }
18509 }
18510
18511 static void
18512 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
18513 {
18514   switch (lang)
18515     {
18516     case DW_LANG_C89:
18517     case DW_LANG_C99:
18518     case DW_LANG_C11:
18519     case DW_LANG_C:
18520     case DW_LANG_UPC:
18521       cu->language = language_c;
18522       break;
18523     case DW_LANG_Java:
18524     case DW_LANG_C_plus_plus:
18525     case DW_LANG_C_plus_plus_11:
18526     case DW_LANG_C_plus_plus_14:
18527       cu->language = language_cplus;
18528       break;
18529     case DW_LANG_D:
18530       cu->language = language_d;
18531       break;
18532     case DW_LANG_Fortran77:
18533     case DW_LANG_Fortran90:
18534     case DW_LANG_Fortran95:
18535     case DW_LANG_Fortran03:
18536     case DW_LANG_Fortran08:
18537       cu->language = language_fortran;
18538       break;
18539     case DW_LANG_Go:
18540       cu->language = language_go;
18541       break;
18542     case DW_LANG_Mips_Assembler:
18543       cu->language = language_asm;
18544       break;
18545     case DW_LANG_Ada83:
18546     case DW_LANG_Ada95:
18547       cu->language = language_ada;
18548       break;
18549     case DW_LANG_Modula2:
18550       cu->language = language_m2;
18551       break;
18552     case DW_LANG_Pascal83:
18553       cu->language = language_pascal;
18554       break;
18555     case DW_LANG_ObjC:
18556       cu->language = language_objc;
18557       break;
18558     case DW_LANG_Rust:
18559     case DW_LANG_Rust_old:
18560       cu->language = language_rust;
18561       break;
18562     case DW_LANG_Cobol74:
18563     case DW_LANG_Cobol85:
18564     default:
18565       cu->language = language_minimal;
18566       break;
18567     }
18568   cu->language_defn = language_def (cu->language);
18569 }
18570
18571 /* Return the named attribute or NULL if not there.  */
18572
18573 static struct attribute *
18574 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18575 {
18576   for (;;)
18577     {
18578       unsigned int i;
18579       struct attribute *spec = NULL;
18580
18581       for (i = 0; i < die->num_attrs; ++i)
18582         {
18583           if (die->attrs[i].name == name)
18584             return &die->attrs[i];
18585           if (die->attrs[i].name == DW_AT_specification
18586               || die->attrs[i].name == DW_AT_abstract_origin)
18587             spec = &die->attrs[i];
18588         }
18589
18590       if (!spec)
18591         break;
18592
18593       die = follow_die_ref (die, spec, &cu);
18594     }
18595
18596   return NULL;
18597 }
18598
18599 /* Return the named attribute or NULL if not there,
18600    but do not follow DW_AT_specification, etc.
18601    This is for use in contexts where we're reading .debug_types dies.
18602    Following DW_AT_specification, DW_AT_abstract_origin will take us
18603    back up the chain, and we want to go down.  */
18604
18605 static struct attribute *
18606 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
18607 {
18608   unsigned int i;
18609
18610   for (i = 0; i < die->num_attrs; ++i)
18611     if (die->attrs[i].name == name)
18612       return &die->attrs[i];
18613
18614   return NULL;
18615 }
18616
18617 /* Return the string associated with a string-typed attribute, or NULL if it
18618    is either not found or is of an incorrect type.  */
18619
18620 static const char *
18621 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18622 {
18623   struct attribute *attr;
18624   const char *str = NULL;
18625
18626   attr = dwarf2_attr (die, name, cu);
18627
18628   if (attr != NULL)
18629     {
18630       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
18631           || attr->form == DW_FORM_string
18632           || attr->form == DW_FORM_GNU_str_index
18633           || attr->form == DW_FORM_GNU_strp_alt)
18634         str = DW_STRING (attr);
18635       else
18636         complaint (&symfile_complaints,
18637                    _("string type expected for attribute %s for "
18638                      "DIE at 0x%x in module %s"),
18639                    dwarf_attr_name (name), to_underlying (die->sect_off),
18640                    objfile_name (cu->objfile));
18641     }
18642
18643   return str;
18644 }
18645
18646 /* Return non-zero iff the attribute NAME is defined for the given DIE,
18647    and holds a non-zero value.  This function should only be used for
18648    DW_FORM_flag or DW_FORM_flag_present attributes.  */
18649
18650 static int
18651 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
18652 {
18653   struct attribute *attr = dwarf2_attr (die, name, cu);
18654
18655   return (attr && DW_UNSND (attr));
18656 }
18657
18658 static int
18659 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
18660 {
18661   /* A DIE is a declaration if it has a DW_AT_declaration attribute
18662      which value is non-zero.  However, we have to be careful with
18663      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
18664      (via dwarf2_flag_true_p) follows this attribute.  So we may
18665      end up accidently finding a declaration attribute that belongs
18666      to a different DIE referenced by the specification attribute,
18667      even though the given DIE does not have a declaration attribute.  */
18668   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
18669           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
18670 }
18671
18672 /* Return the die giving the specification for DIE, if there is
18673    one.  *SPEC_CU is the CU containing DIE on input, and the CU
18674    containing the return value on output.  If there is no
18675    specification, but there is an abstract origin, that is
18676    returned.  */
18677
18678 static struct die_info *
18679 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
18680 {
18681   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
18682                                              *spec_cu);
18683
18684   if (spec_attr == NULL)
18685     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
18686
18687   if (spec_attr == NULL)
18688     return NULL;
18689   else
18690     return follow_die_ref (die, spec_attr, spec_cu);
18691 }
18692
18693 /* Stub for free_line_header to match void * callback types.  */
18694
18695 static void
18696 free_line_header_voidp (void *arg)
18697 {
18698   struct line_header *lh = (struct line_header *) arg;
18699
18700   delete lh;
18701 }
18702
18703 void
18704 line_header::add_include_dir (const char *include_dir)
18705 {
18706   if (dwarf_line_debug >= 2)
18707     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
18708                         include_dirs.size () + 1, include_dir);
18709
18710   include_dirs.push_back (include_dir);
18711 }
18712
18713 void
18714 line_header::add_file_name (const char *name,
18715                             dir_index d_index,
18716                             unsigned int mod_time,
18717                             unsigned int length)
18718 {
18719   if (dwarf_line_debug >= 2)
18720     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
18721                         (unsigned) file_names.size () + 1, name);
18722
18723   file_names.emplace_back (name, d_index, mod_time, length);
18724 }
18725
18726 /* A convenience function to find the proper .debug_line section for a CU.  */
18727
18728 static struct dwarf2_section_info *
18729 get_debug_line_section (struct dwarf2_cu *cu)
18730 {
18731   struct dwarf2_section_info *section;
18732
18733   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
18734      DWO file.  */
18735   if (cu->dwo_unit && cu->per_cu->is_debug_types)
18736     section = &cu->dwo_unit->dwo_file->sections.line;
18737   else if (cu->per_cu->is_dwz)
18738     {
18739       struct dwz_file *dwz = dwarf2_get_dwz_file ();
18740
18741       section = &dwz->line;
18742     }
18743   else
18744     section = &dwarf2_per_objfile->line;
18745
18746   return section;
18747 }
18748
18749 /* Read directory or file name entry format, starting with byte of
18750    format count entries, ULEB128 pairs of entry formats, ULEB128 of
18751    entries count and the entries themselves in the described entry
18752    format.  */
18753
18754 static void
18755 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
18756                         struct line_header *lh,
18757                         const struct comp_unit_head *cu_header,
18758                         void (*callback) (struct line_header *lh,
18759                                           const char *name,
18760                                           dir_index d_index,
18761                                           unsigned int mod_time,
18762                                           unsigned int length))
18763 {
18764   gdb_byte format_count, formati;
18765   ULONGEST data_count, datai;
18766   const gdb_byte *buf = *bufp;
18767   const gdb_byte *format_header_data;
18768   unsigned int bytes_read;
18769
18770   format_count = read_1_byte (abfd, buf);
18771   buf += 1;
18772   format_header_data = buf;
18773   for (formati = 0; formati < format_count; formati++)
18774     {
18775       read_unsigned_leb128 (abfd, buf, &bytes_read);
18776       buf += bytes_read;
18777       read_unsigned_leb128 (abfd, buf, &bytes_read);
18778       buf += bytes_read;
18779     }
18780
18781   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
18782   buf += bytes_read;
18783   for (datai = 0; datai < data_count; datai++)
18784     {
18785       const gdb_byte *format = format_header_data;
18786       struct file_entry fe;
18787
18788       for (formati = 0; formati < format_count; formati++)
18789         {
18790           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
18791           format += bytes_read;
18792
18793           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
18794           format += bytes_read;
18795
18796           gdb::optional<const char *> string;
18797           gdb::optional<unsigned int> uint;
18798
18799           switch (form)
18800             {
18801             case DW_FORM_string:
18802               string.emplace (read_direct_string (abfd, buf, &bytes_read));
18803               buf += bytes_read;
18804               break;
18805
18806             case DW_FORM_line_strp:
18807               string.emplace (read_indirect_line_string (abfd, buf,
18808                                                          cu_header,
18809                                                          &bytes_read));
18810               buf += bytes_read;
18811               break;
18812
18813             case DW_FORM_data1:
18814               uint.emplace (read_1_byte (abfd, buf));
18815               buf += 1;
18816               break;
18817
18818             case DW_FORM_data2:
18819               uint.emplace (read_2_bytes (abfd, buf));
18820               buf += 2;
18821               break;
18822
18823             case DW_FORM_data4:
18824               uint.emplace (read_4_bytes (abfd, buf));
18825               buf += 4;
18826               break;
18827
18828             case DW_FORM_data8:
18829               uint.emplace (read_8_bytes (abfd, buf));
18830               buf += 8;
18831               break;
18832
18833             case DW_FORM_udata:
18834               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
18835               buf += bytes_read;
18836               break;
18837
18838             case DW_FORM_block:
18839               /* It is valid only for DW_LNCT_timestamp which is ignored by
18840                  current GDB.  */
18841               break;
18842             }
18843
18844           switch (content_type)
18845             {
18846             case DW_LNCT_path:
18847               if (string.has_value ())
18848                 fe.name = *string;
18849               break;
18850             case DW_LNCT_directory_index:
18851               if (uint.has_value ())
18852                 fe.d_index = (dir_index) *uint;
18853               break;
18854             case DW_LNCT_timestamp:
18855               if (uint.has_value ())
18856                 fe.mod_time = *uint;
18857               break;
18858             case DW_LNCT_size:
18859               if (uint.has_value ())
18860                 fe.length = *uint;
18861               break;
18862             case DW_LNCT_MD5:
18863               break;
18864             default:
18865               complaint (&symfile_complaints,
18866                          _("Unknown format content type %s"),
18867                          pulongest (content_type));
18868             }
18869         }
18870
18871       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
18872     }
18873
18874   *bufp = buf;
18875 }
18876
18877 /* Read the statement program header starting at OFFSET in
18878    .debug_line, or .debug_line.dwo.  Return a pointer
18879    to a struct line_header, allocated using xmalloc.
18880    Returns NULL if there is a problem reading the header, e.g., if it
18881    has a version we don't understand.
18882
18883    NOTE: the strings in the include directory and file name tables of
18884    the returned object point into the dwarf line section buffer,
18885    and must not be freed.  */
18886
18887 static line_header_up
18888 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
18889 {
18890   const gdb_byte *line_ptr;
18891   unsigned int bytes_read, offset_size;
18892   int i;
18893   const char *cur_dir, *cur_file;
18894   struct dwarf2_section_info *section;
18895   bfd *abfd;
18896
18897   section = get_debug_line_section (cu);
18898   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18899   if (section->buffer == NULL)
18900     {
18901       if (cu->dwo_unit && cu->per_cu->is_debug_types)
18902         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
18903       else
18904         complaint (&symfile_complaints, _("missing .debug_line section"));
18905       return 0;
18906     }
18907
18908   /* We can't do this until we know the section is non-empty.
18909      Only then do we know we have such a section.  */
18910   abfd = get_section_bfd_owner (section);
18911
18912   /* Make sure that at least there's room for the total_length field.
18913      That could be 12 bytes long, but we're just going to fudge that.  */
18914   if (to_underlying (sect_off) + 4 >= section->size)
18915     {
18916       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18917       return 0;
18918     }
18919
18920   line_header_up lh (new line_header ());
18921
18922   lh->sect_off = sect_off;
18923   lh->offset_in_dwz = cu->per_cu->is_dwz;
18924
18925   line_ptr = section->buffer + to_underlying (sect_off);
18926
18927   /* Read in the header.  */
18928   lh->total_length =
18929     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18930                                             &bytes_read, &offset_size);
18931   line_ptr += bytes_read;
18932   if (line_ptr + lh->total_length > (section->buffer + section->size))
18933     {
18934       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18935       return 0;
18936     }
18937   lh->statement_program_end = line_ptr + lh->total_length;
18938   lh->version = read_2_bytes (abfd, line_ptr);
18939   line_ptr += 2;
18940   if (lh->version > 5)
18941     {
18942       /* This is a version we don't understand.  The format could have
18943          changed in ways we don't handle properly so just punt.  */
18944       complaint (&symfile_complaints,
18945                  _("unsupported version in .debug_line section"));
18946       return NULL;
18947     }
18948   if (lh->version >= 5)
18949     {
18950       gdb_byte segment_selector_size;
18951
18952       /* Skip address size.  */
18953       read_1_byte (abfd, line_ptr);
18954       line_ptr += 1;
18955
18956       segment_selector_size = read_1_byte (abfd, line_ptr);
18957       line_ptr += 1;
18958       if (segment_selector_size != 0)
18959         {
18960           complaint (&symfile_complaints,
18961                      _("unsupported segment selector size %u "
18962                        "in .debug_line section"),
18963                      segment_selector_size);
18964           return NULL;
18965         }
18966     }
18967   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18968   line_ptr += offset_size;
18969   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18970   line_ptr += 1;
18971   if (lh->version >= 4)
18972     {
18973       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18974       line_ptr += 1;
18975     }
18976   else
18977     lh->maximum_ops_per_instruction = 1;
18978
18979   if (lh->maximum_ops_per_instruction == 0)
18980     {
18981       lh->maximum_ops_per_instruction = 1;
18982       complaint (&symfile_complaints,
18983                  _("invalid maximum_ops_per_instruction "
18984                    "in `.debug_line' section"));
18985     }
18986
18987   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18988   line_ptr += 1;
18989   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18990   line_ptr += 1;
18991   lh->line_range = read_1_byte (abfd, line_ptr);
18992   line_ptr += 1;
18993   lh->opcode_base = read_1_byte (abfd, line_ptr);
18994   line_ptr += 1;
18995   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18996
18997   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18998   for (i = 1; i < lh->opcode_base; ++i)
18999     {
19000       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
19001       line_ptr += 1;
19002     }
19003
19004   if (lh->version >= 5)
19005     {
19006       /* Read directory table.  */
19007       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
19008                               [] (struct line_header *lh, const char *name,
19009                                   dir_index d_index, unsigned int mod_time,
19010                                   unsigned int length)
19011         {
19012           lh->add_include_dir (name);
19013         });
19014
19015       /* Read file name table.  */
19016       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
19017                               [] (struct line_header *lh, const char *name,
19018                                   dir_index d_index, unsigned int mod_time,
19019                                   unsigned int length)
19020         {
19021           lh->add_file_name (name, d_index, mod_time, length);
19022         });
19023     }
19024   else
19025     {
19026       /* Read directory table.  */
19027       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19028         {
19029           line_ptr += bytes_read;
19030           lh->add_include_dir (cur_dir);
19031         }
19032       line_ptr += bytes_read;
19033
19034       /* Read file name table.  */
19035       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19036         {
19037           unsigned int mod_time, length;
19038           dir_index d_index;
19039
19040           line_ptr += bytes_read;
19041           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19042           line_ptr += bytes_read;
19043           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19044           line_ptr += bytes_read;
19045           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19046           line_ptr += bytes_read;
19047
19048           lh->add_file_name (cur_file, d_index, mod_time, length);
19049         }
19050       line_ptr += bytes_read;
19051     }
19052   lh->statement_program_start = line_ptr;
19053
19054   if (line_ptr > (section->buffer + section->size))
19055     complaint (&symfile_complaints,
19056                _("line number info header doesn't "
19057                  "fit in `.debug_line' section"));
19058
19059   return lh;
19060 }
19061
19062 /* Subroutine of dwarf_decode_lines to simplify it.
19063    Return the file name of the psymtab for included file FILE_INDEX
19064    in line header LH of PST.
19065    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19066    If space for the result is malloc'd, it will be freed by a cleanup.
19067    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
19068
19069    The function creates dangling cleanup registration.  */
19070
19071 static const char *
19072 psymtab_include_file_name (const struct line_header *lh, int file_index,
19073                            const struct partial_symtab *pst,
19074                            const char *comp_dir)
19075 {
19076   const file_entry &fe = lh->file_names[file_index];
19077   const char *include_name = fe.name;
19078   const char *include_name_to_compare = include_name;
19079   const char *pst_filename;
19080   char *copied_name = NULL;
19081   int file_is_pst;
19082
19083   const char *dir_name = fe.include_dir (lh);
19084
19085   if (!IS_ABSOLUTE_PATH (include_name)
19086       && (dir_name != NULL || comp_dir != NULL))
19087     {
19088       /* Avoid creating a duplicate psymtab for PST.
19089          We do this by comparing INCLUDE_NAME and PST_FILENAME.
19090          Before we do the comparison, however, we need to account
19091          for DIR_NAME and COMP_DIR.
19092          First prepend dir_name (if non-NULL).  If we still don't
19093          have an absolute path prepend comp_dir (if non-NULL).
19094          However, the directory we record in the include-file's
19095          psymtab does not contain COMP_DIR (to match the
19096          corresponding symtab(s)).
19097
19098          Example:
19099
19100          bash$ cd /tmp
19101          bash$ gcc -g ./hello.c
19102          include_name = "hello.c"
19103          dir_name = "."
19104          DW_AT_comp_dir = comp_dir = "/tmp"
19105          DW_AT_name = "./hello.c"
19106
19107       */
19108
19109       if (dir_name != NULL)
19110         {
19111           char *tem = concat (dir_name, SLASH_STRING,
19112                               include_name, (char *)NULL);
19113
19114           make_cleanup (xfree, tem);
19115           include_name = tem;
19116           include_name_to_compare = include_name;
19117         }
19118       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
19119         {
19120           char *tem = concat (comp_dir, SLASH_STRING,
19121                               include_name, (char *)NULL);
19122
19123           make_cleanup (xfree, tem);
19124           include_name_to_compare = tem;
19125         }
19126     }
19127
19128   pst_filename = pst->filename;
19129   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
19130     {
19131       copied_name = concat (pst->dirname, SLASH_STRING,
19132                             pst_filename, (char *)NULL);
19133       pst_filename = copied_name;
19134     }
19135
19136   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
19137
19138   if (copied_name != NULL)
19139     xfree (copied_name);
19140
19141   if (file_is_pst)
19142     return NULL;
19143   return include_name;
19144 }
19145
19146 /* State machine to track the state of the line number program.  */
19147
19148 class lnp_state_machine
19149 {
19150 public:
19151   /* Initialize a machine state for the start of a line number
19152      program.  */
19153   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
19154
19155   file_entry *current_file ()
19156   {
19157     /* lh->file_names is 0-based, but the file name numbers in the
19158        statement program are 1-based.  */
19159     return m_line_header->file_name_at (m_file);
19160   }
19161
19162   /* Record the line in the state machine.  END_SEQUENCE is true if
19163      we're processing the end of a sequence.  */
19164   void record_line (bool end_sequence);
19165
19166   /* Check address and if invalid nop-out the rest of the lines in this
19167      sequence.  */
19168   void check_line_address (struct dwarf2_cu *cu,
19169                            const gdb_byte *line_ptr,
19170                            CORE_ADDR lowpc, CORE_ADDR address);
19171
19172   void handle_set_discriminator (unsigned int discriminator)
19173   {
19174     m_discriminator = discriminator;
19175     m_line_has_non_zero_discriminator |= discriminator != 0;
19176   }
19177
19178   /* Handle DW_LNE_set_address.  */
19179   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
19180   {
19181     m_op_index = 0;
19182     address += baseaddr;
19183     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
19184   }
19185
19186   /* Handle DW_LNS_advance_pc.  */
19187   void handle_advance_pc (CORE_ADDR adjust);
19188
19189   /* Handle a special opcode.  */
19190   void handle_special_opcode (unsigned char op_code);
19191
19192   /* Handle DW_LNS_advance_line.  */
19193   void handle_advance_line (int line_delta)
19194   {
19195     advance_line (line_delta);
19196   }
19197
19198   /* Handle DW_LNS_set_file.  */
19199   void handle_set_file (file_name_index file);
19200
19201   /* Handle DW_LNS_negate_stmt.  */
19202   void handle_negate_stmt ()
19203   {
19204     m_is_stmt = !m_is_stmt;
19205   }
19206
19207   /* Handle DW_LNS_const_add_pc.  */
19208   void handle_const_add_pc ();
19209
19210   /* Handle DW_LNS_fixed_advance_pc.  */
19211   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
19212   {
19213     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19214     m_op_index = 0;
19215   }
19216
19217   /* Handle DW_LNS_copy.  */
19218   void handle_copy ()
19219   {
19220     record_line (false);
19221     m_discriminator = 0;
19222   }
19223
19224   /* Handle DW_LNE_end_sequence.  */
19225   void handle_end_sequence ()
19226   {
19227     m_record_line_callback = ::record_line;
19228   }
19229
19230 private:
19231   /* Advance the line by LINE_DELTA.  */
19232   void advance_line (int line_delta)
19233   {
19234     m_line += line_delta;
19235
19236     if (line_delta != 0)
19237       m_line_has_non_zero_discriminator = m_discriminator != 0;
19238   }
19239
19240   gdbarch *m_gdbarch;
19241
19242   /* True if we're recording lines.
19243      Otherwise we're building partial symtabs and are just interested in
19244      finding include files mentioned by the line number program.  */
19245   bool m_record_lines_p;
19246
19247   /* The line number header.  */
19248   line_header *m_line_header;
19249
19250   /* These are part of the standard DWARF line number state machine,
19251      and initialized according to the DWARF spec.  */
19252
19253   unsigned char m_op_index = 0;
19254   /* The line table index (1-based) of the current file.  */
19255   file_name_index m_file = (file_name_index) 1;
19256   unsigned int m_line = 1;
19257
19258   /* These are initialized in the constructor.  */
19259
19260   CORE_ADDR m_address;
19261   bool m_is_stmt;
19262   unsigned int m_discriminator;
19263
19264   /* Additional bits of state we need to track.  */
19265
19266   /* The last file that we called dwarf2_start_subfile for.
19267      This is only used for TLLs.  */
19268   unsigned int m_last_file = 0;
19269   /* The last file a line number was recorded for.  */
19270   struct subfile *m_last_subfile = NULL;
19271
19272   /* The function to call to record a line.  */
19273   record_line_ftype *m_record_line_callback = NULL;
19274
19275   /* The last line number that was recorded, used to coalesce
19276      consecutive entries for the same line.  This can happen, for
19277      example, when discriminators are present.  PR 17276.  */
19278   unsigned int m_last_line = 0;
19279   bool m_line_has_non_zero_discriminator = false;
19280 };
19281
19282 void
19283 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
19284 {
19285   CORE_ADDR addr_adj = (((m_op_index + adjust)
19286                          / m_line_header->maximum_ops_per_instruction)
19287                         * m_line_header->minimum_instruction_length);
19288   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19289   m_op_index = ((m_op_index + adjust)
19290                 % m_line_header->maximum_ops_per_instruction);
19291 }
19292
19293 void
19294 lnp_state_machine::handle_special_opcode (unsigned char op_code)
19295 {
19296   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
19297   CORE_ADDR addr_adj = (((m_op_index
19298                           + (adj_opcode / m_line_header->line_range))
19299                          / m_line_header->maximum_ops_per_instruction)
19300                         * m_line_header->minimum_instruction_length);
19301   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19302   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
19303                 % m_line_header->maximum_ops_per_instruction);
19304
19305   int line_delta = (m_line_header->line_base
19306                     + (adj_opcode % m_line_header->line_range));
19307   advance_line (line_delta);
19308   record_line (false);
19309   m_discriminator = 0;
19310 }
19311
19312 void
19313 lnp_state_machine::handle_set_file (file_name_index file)
19314 {
19315   m_file = file;
19316
19317   const file_entry *fe = current_file ();
19318   if (fe == NULL)
19319     dwarf2_debug_line_missing_file_complaint ();
19320   else if (m_record_lines_p)
19321     {
19322       const char *dir = fe->include_dir (m_line_header);
19323
19324       m_last_subfile = current_subfile;
19325       m_line_has_non_zero_discriminator = m_discriminator != 0;
19326       dwarf2_start_subfile (fe->name, dir);
19327     }
19328 }
19329
19330 void
19331 lnp_state_machine::handle_const_add_pc ()
19332 {
19333   CORE_ADDR adjust
19334     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
19335
19336   CORE_ADDR addr_adj
19337     = (((m_op_index + adjust)
19338         / m_line_header->maximum_ops_per_instruction)
19339        * m_line_header->minimum_instruction_length);
19340
19341   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19342   m_op_index = ((m_op_index + adjust)
19343                 % m_line_header->maximum_ops_per_instruction);
19344 }
19345
19346 /* Ignore this record_line request.  */
19347
19348 static void
19349 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
19350 {
19351   return;
19352 }
19353
19354 /* Return non-zero if we should add LINE to the line number table.
19355    LINE is the line to add, LAST_LINE is the last line that was added,
19356    LAST_SUBFILE is the subfile for LAST_LINE.
19357    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
19358    had a non-zero discriminator.
19359
19360    We have to be careful in the presence of discriminators.
19361    E.g., for this line:
19362
19363      for (i = 0; i < 100000; i++);
19364
19365    clang can emit four line number entries for that one line,
19366    each with a different discriminator.
19367    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
19368
19369    However, we want gdb to coalesce all four entries into one.
19370    Otherwise the user could stepi into the middle of the line and
19371    gdb would get confused about whether the pc really was in the
19372    middle of the line.
19373
19374    Things are further complicated by the fact that two consecutive
19375    line number entries for the same line is a heuristic used by gcc
19376    to denote the end of the prologue.  So we can't just discard duplicate
19377    entries, we have to be selective about it.  The heuristic we use is
19378    that we only collapse consecutive entries for the same line if at least
19379    one of those entries has a non-zero discriminator.  PR 17276.
19380
19381    Note: Addresses in the line number state machine can never go backwards
19382    within one sequence, thus this coalescing is ok.  */
19383
19384 static int
19385 dwarf_record_line_p (unsigned int line, unsigned int last_line,
19386                      int line_has_non_zero_discriminator,
19387                      struct subfile *last_subfile)
19388 {
19389   if (current_subfile != last_subfile)
19390     return 1;
19391   if (line != last_line)
19392     return 1;
19393   /* Same line for the same file that we've seen already.
19394      As a last check, for pr 17276, only record the line if the line
19395      has never had a non-zero discriminator.  */
19396   if (!line_has_non_zero_discriminator)
19397     return 1;
19398   return 0;
19399 }
19400
19401 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
19402    in the line table of subfile SUBFILE.  */
19403
19404 static void
19405 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
19406                      unsigned int line, CORE_ADDR address,
19407                      record_line_ftype p_record_line)
19408 {
19409   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
19410
19411   if (dwarf_line_debug)
19412     {
19413       fprintf_unfiltered (gdb_stdlog,
19414                           "Recording line %u, file %s, address %s\n",
19415                           line, lbasename (subfile->name),
19416                           paddress (gdbarch, address));
19417     }
19418
19419   (*p_record_line) (subfile, line, addr);
19420 }
19421
19422 /* Subroutine of dwarf_decode_lines_1 to simplify it.
19423    Mark the end of a set of line number records.
19424    The arguments are the same as for dwarf_record_line_1.
19425    If SUBFILE is NULL the request is ignored.  */
19426
19427 static void
19428 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
19429                    CORE_ADDR address, record_line_ftype p_record_line)
19430 {
19431   if (subfile == NULL)
19432     return;
19433
19434   if (dwarf_line_debug)
19435     {
19436       fprintf_unfiltered (gdb_stdlog,
19437                           "Finishing current line, file %s, address %s\n",
19438                           lbasename (subfile->name),
19439                           paddress (gdbarch, address));
19440     }
19441
19442   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
19443 }
19444
19445 void
19446 lnp_state_machine::record_line (bool end_sequence)
19447 {
19448   if (dwarf_line_debug)
19449     {
19450       fprintf_unfiltered (gdb_stdlog,
19451                           "Processing actual line %u: file %u,"
19452                           " address %s, is_stmt %u, discrim %u\n",
19453                           m_line, to_underlying (m_file),
19454                           paddress (m_gdbarch, m_address),
19455                           m_is_stmt, m_discriminator);
19456     }
19457
19458   file_entry *fe = current_file ();
19459
19460   if (fe == NULL)
19461     dwarf2_debug_line_missing_file_complaint ();
19462   /* For now we ignore lines not starting on an instruction boundary.
19463      But not when processing end_sequence for compatibility with the
19464      previous version of the code.  */
19465   else if (m_op_index == 0 || end_sequence)
19466     {
19467       fe->included_p = 1;
19468       if (m_record_lines_p && m_is_stmt)
19469         {
19470           if (m_last_subfile != current_subfile || end_sequence)
19471             {
19472               dwarf_finish_line (m_gdbarch, m_last_subfile,
19473                                  m_address, m_record_line_callback);
19474             }
19475
19476           if (!end_sequence)
19477             {
19478               if (dwarf_record_line_p (m_line, m_last_line,
19479                                        m_line_has_non_zero_discriminator,
19480                                        m_last_subfile))
19481                 {
19482                   dwarf_record_line_1 (m_gdbarch, current_subfile,
19483                                        m_line, m_address,
19484                                        m_record_line_callback);
19485                 }
19486               m_last_subfile = current_subfile;
19487               m_last_line = m_line;
19488             }
19489         }
19490     }
19491 }
19492
19493 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
19494                                       bool record_lines_p)
19495 {
19496   m_gdbarch = arch;
19497   m_record_lines_p = record_lines_p;
19498   m_line_header = lh;
19499
19500   m_record_line_callback = ::record_line;
19501
19502   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
19503      was a line entry for it so that the backend has a chance to adjust it
19504      and also record it in case it needs it.  This is currently used by MIPS
19505      code, cf. `mips_adjust_dwarf2_line'.  */
19506   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
19507   m_is_stmt = lh->default_is_stmt;
19508   m_discriminator = 0;
19509 }
19510
19511 void
19512 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
19513                                        const gdb_byte *line_ptr,
19514                                        CORE_ADDR lowpc, CORE_ADDR address)
19515 {
19516   /* If address < lowpc then it's not a usable value, it's outside the
19517      pc range of the CU.  However, we restrict the test to only address
19518      values of zero to preserve GDB's previous behaviour which is to
19519      handle the specific case of a function being GC'd by the linker.  */
19520
19521   if (address == 0 && address < lowpc)
19522     {
19523       /* This line table is for a function which has been
19524          GCd by the linker.  Ignore it.  PR gdb/12528 */
19525
19526       struct objfile *objfile = cu->objfile;
19527       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
19528
19529       complaint (&symfile_complaints,
19530                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
19531                  line_offset, objfile_name (objfile));
19532       m_record_line_callback = noop_record_line;
19533       /* Note: record_line_callback is left as noop_record_line until
19534          we see DW_LNE_end_sequence.  */
19535     }
19536 }
19537
19538 /* Subroutine of dwarf_decode_lines to simplify it.
19539    Process the line number information in LH.
19540    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
19541    program in order to set included_p for every referenced header.  */
19542
19543 static void
19544 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
19545                       const int decode_for_pst_p, CORE_ADDR lowpc)
19546 {
19547   const gdb_byte *line_ptr, *extended_end;
19548   const gdb_byte *line_end;
19549   unsigned int bytes_read, extended_len;
19550   unsigned char op_code, extended_op;
19551   CORE_ADDR baseaddr;
19552   struct objfile *objfile = cu->objfile;
19553   bfd *abfd = objfile->obfd;
19554   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19555   /* True if we're recording line info (as opposed to building partial
19556      symtabs and just interested in finding include files mentioned by
19557      the line number program).  */
19558   bool record_lines_p = !decode_for_pst_p;
19559
19560   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19561
19562   line_ptr = lh->statement_program_start;
19563   line_end = lh->statement_program_end;
19564
19565   /* Read the statement sequences until there's nothing left.  */
19566   while (line_ptr < line_end)
19567     {
19568       /* The DWARF line number program state machine.  Reset the state
19569          machine at the start of each sequence.  */
19570       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
19571       bool end_sequence = false;
19572
19573       if (record_lines_p)
19574         {
19575           /* Start a subfile for the current file of the state
19576              machine.  */
19577           const file_entry *fe = state_machine.current_file ();
19578
19579           if (fe != NULL)
19580             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
19581         }
19582
19583       /* Decode the table.  */
19584       while (line_ptr < line_end && !end_sequence)
19585         {
19586           op_code = read_1_byte (abfd, line_ptr);
19587           line_ptr += 1;
19588
19589           if (op_code >= lh->opcode_base)
19590             {
19591               /* Special opcode.  */
19592               state_machine.handle_special_opcode (op_code);
19593             }
19594           else switch (op_code)
19595             {
19596             case DW_LNS_extended_op:
19597               extended_len = read_unsigned_leb128 (abfd, line_ptr,
19598                                                    &bytes_read);
19599               line_ptr += bytes_read;
19600               extended_end = line_ptr + extended_len;
19601               extended_op = read_1_byte (abfd, line_ptr);
19602               line_ptr += 1;
19603               switch (extended_op)
19604                 {
19605                 case DW_LNE_end_sequence:
19606                   state_machine.handle_end_sequence ();
19607                   end_sequence = true;
19608                   break;
19609                 case DW_LNE_set_address:
19610                   {
19611                     CORE_ADDR address
19612                       = read_address (abfd, line_ptr, cu, &bytes_read);
19613                     line_ptr += bytes_read;
19614
19615                     state_machine.check_line_address (cu, line_ptr,
19616                                                       lowpc, address);
19617                     state_machine.handle_set_address (baseaddr, address);
19618                   }
19619                   break;
19620                 case DW_LNE_define_file:
19621                   {
19622                     const char *cur_file;
19623                     unsigned int mod_time, length;
19624                     dir_index dindex;
19625
19626                     cur_file = read_direct_string (abfd, line_ptr,
19627                                                    &bytes_read);
19628                     line_ptr += bytes_read;
19629                     dindex = (dir_index)
19630                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19631                     line_ptr += bytes_read;
19632                     mod_time =
19633                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19634                     line_ptr += bytes_read;
19635                     length =
19636                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19637                     line_ptr += bytes_read;
19638                     lh->add_file_name (cur_file, dindex, mod_time, length);
19639                   }
19640                   break;
19641                 case DW_LNE_set_discriminator:
19642                   {
19643                     /* The discriminator is not interesting to the
19644                        debugger; just ignore it.  We still need to
19645                        check its value though:
19646                        if there are consecutive entries for the same
19647                        (non-prologue) line we want to coalesce them.
19648                        PR 17276.  */
19649                     unsigned int discr
19650                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19651                     line_ptr += bytes_read;
19652
19653                     state_machine.handle_set_discriminator (discr);
19654                   }
19655                   break;
19656                 default:
19657                   complaint (&symfile_complaints,
19658                              _("mangled .debug_line section"));
19659                   return;
19660                 }
19661               /* Make sure that we parsed the extended op correctly.  If e.g.
19662                  we expected a different address size than the producer used,
19663                  we may have read the wrong number of bytes.  */
19664               if (line_ptr != extended_end)
19665                 {
19666                   complaint (&symfile_complaints,
19667                              _("mangled .debug_line section"));
19668                   return;
19669                 }
19670               break;
19671             case DW_LNS_copy:
19672               state_machine.handle_copy ();
19673               break;
19674             case DW_LNS_advance_pc:
19675               {
19676                 CORE_ADDR adjust
19677                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19678                 line_ptr += bytes_read;
19679
19680                 state_machine.handle_advance_pc (adjust);
19681               }
19682               break;
19683             case DW_LNS_advance_line:
19684               {
19685                 int line_delta
19686                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
19687                 line_ptr += bytes_read;
19688
19689                 state_machine.handle_advance_line (line_delta);
19690               }
19691               break;
19692             case DW_LNS_set_file:
19693               {
19694                 file_name_index file
19695                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
19696                                                             &bytes_read);
19697                 line_ptr += bytes_read;
19698
19699                 state_machine.handle_set_file (file);
19700               }
19701               break;
19702             case DW_LNS_set_column:
19703               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19704               line_ptr += bytes_read;
19705               break;
19706             case DW_LNS_negate_stmt:
19707               state_machine.handle_negate_stmt ();
19708               break;
19709             case DW_LNS_set_basic_block:
19710               break;
19711             /* Add to the address register of the state machine the
19712                address increment value corresponding to special opcode
19713                255.  I.e., this value is scaled by the minimum
19714                instruction length since special opcode 255 would have
19715                scaled the increment.  */
19716             case DW_LNS_const_add_pc:
19717               state_machine.handle_const_add_pc ();
19718               break;
19719             case DW_LNS_fixed_advance_pc:
19720               {
19721                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
19722                 line_ptr += 2;
19723
19724                 state_machine.handle_fixed_advance_pc (addr_adj);
19725               }
19726               break;
19727             default:
19728               {
19729                 /* Unknown standard opcode, ignore it.  */
19730                 int i;
19731
19732                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
19733                   {
19734                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19735                     line_ptr += bytes_read;
19736                   }
19737               }
19738             }
19739         }
19740
19741       if (!end_sequence)
19742         dwarf2_debug_line_missing_end_sequence_complaint ();
19743
19744       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
19745          in which case we still finish recording the last line).  */
19746       state_machine.record_line (true);
19747     }
19748 }
19749
19750 /* Decode the Line Number Program (LNP) for the given line_header
19751    structure and CU.  The actual information extracted and the type
19752    of structures created from the LNP depends on the value of PST.
19753
19754    1. If PST is NULL, then this procedure uses the data from the program
19755       to create all necessary symbol tables, and their linetables.
19756
19757    2. If PST is not NULL, this procedure reads the program to determine
19758       the list of files included by the unit represented by PST, and
19759       builds all the associated partial symbol tables.
19760
19761    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19762    It is used for relative paths in the line table.
19763    NOTE: When processing partial symtabs (pst != NULL),
19764    comp_dir == pst->dirname.
19765
19766    NOTE: It is important that psymtabs have the same file name (via strcmp)
19767    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
19768    symtab we don't use it in the name of the psymtabs we create.
19769    E.g. expand_line_sal requires this when finding psymtabs to expand.
19770    A good testcase for this is mb-inline.exp.
19771
19772    LOWPC is the lowest address in CU (or 0 if not known).
19773
19774    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
19775    for its PC<->lines mapping information.  Otherwise only the filename
19776    table is read in.  */
19777
19778 static void
19779 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
19780                     struct dwarf2_cu *cu, struct partial_symtab *pst,
19781                     CORE_ADDR lowpc, int decode_mapping)
19782 {
19783   struct objfile *objfile = cu->objfile;
19784   const int decode_for_pst_p = (pst != NULL);
19785
19786   if (decode_mapping)
19787     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
19788
19789   if (decode_for_pst_p)
19790     {
19791       int file_index;
19792
19793       /* Now that we're done scanning the Line Header Program, we can
19794          create the psymtab of each included file.  */
19795       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
19796         if (lh->file_names[file_index].included_p == 1)
19797           {
19798             const char *include_name =
19799               psymtab_include_file_name (lh, file_index, pst, comp_dir);
19800             if (include_name != NULL)
19801               dwarf2_create_include_psymtab (include_name, pst, objfile);
19802           }
19803     }
19804   else
19805     {
19806       /* Make sure a symtab is created for every file, even files
19807          which contain only variables (i.e. no code with associated
19808          line numbers).  */
19809       struct compunit_symtab *cust = buildsym_compunit_symtab ();
19810       int i;
19811
19812       for (i = 0; i < lh->file_names.size (); i++)
19813         {
19814           file_entry &fe = lh->file_names[i];
19815
19816           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
19817
19818           if (current_subfile->symtab == NULL)
19819             {
19820               current_subfile->symtab
19821                 = allocate_symtab (cust, current_subfile->name);
19822             }
19823           fe.symtab = current_subfile->symtab;
19824         }
19825     }
19826 }
19827
19828 /* Start a subfile for DWARF.  FILENAME is the name of the file and
19829    DIRNAME the name of the source directory which contains FILENAME
19830    or NULL if not known.
19831    This routine tries to keep line numbers from identical absolute and
19832    relative file names in a common subfile.
19833
19834    Using the `list' example from the GDB testsuite, which resides in
19835    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
19836    of /srcdir/list0.c yields the following debugging information for list0.c:
19837
19838    DW_AT_name:          /srcdir/list0.c
19839    DW_AT_comp_dir:      /compdir
19840    files.files[0].name: list0.h
19841    files.files[0].dir:  /srcdir
19842    files.files[1].name: list0.c
19843    files.files[1].dir:  /srcdir
19844
19845    The line number information for list0.c has to end up in a single
19846    subfile, so that `break /srcdir/list0.c:1' works as expected.
19847    start_subfile will ensure that this happens provided that we pass the
19848    concatenation of files.files[1].dir and files.files[1].name as the
19849    subfile's name.  */
19850
19851 static void
19852 dwarf2_start_subfile (const char *filename, const char *dirname)
19853 {
19854   char *copy = NULL;
19855
19856   /* In order not to lose the line information directory,
19857      we concatenate it to the filename when it makes sense.
19858      Note that the Dwarf3 standard says (speaking of filenames in line
19859      information): ``The directory index is ignored for file names
19860      that represent full path names''.  Thus ignoring dirname in the
19861      `else' branch below isn't an issue.  */
19862
19863   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
19864     {
19865       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
19866       filename = copy;
19867     }
19868
19869   start_subfile (filename);
19870
19871   if (copy != NULL)
19872     xfree (copy);
19873 }
19874
19875 /* Start a symtab for DWARF.
19876    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
19877
19878 static struct compunit_symtab *
19879 dwarf2_start_symtab (struct dwarf2_cu *cu,
19880                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
19881 {
19882   struct compunit_symtab *cust
19883     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
19884
19885   record_debugformat ("DWARF 2");
19886   record_producer (cu->producer);
19887
19888   /* We assume that we're processing GCC output.  */
19889   processing_gcc_compilation = 2;
19890
19891   cu->processing_has_namespace_info = 0;
19892
19893   return cust;
19894 }
19895
19896 static void
19897 var_decode_location (struct attribute *attr, struct symbol *sym,
19898                      struct dwarf2_cu *cu)
19899 {
19900   struct objfile *objfile = cu->objfile;
19901   struct comp_unit_head *cu_header = &cu->header;
19902
19903   /* NOTE drow/2003-01-30: There used to be a comment and some special
19904      code here to turn a symbol with DW_AT_external and a
19905      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19906      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19907      with some versions of binutils) where shared libraries could have
19908      relocations against symbols in their debug information - the
19909      minimal symbol would have the right address, but the debug info
19910      would not.  It's no longer necessary, because we will explicitly
19911      apply relocations when we read in the debug information now.  */
19912
19913   /* A DW_AT_location attribute with no contents indicates that a
19914      variable has been optimized away.  */
19915   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19916     {
19917       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19918       return;
19919     }
19920
19921   /* Handle one degenerate form of location expression specially, to
19922      preserve GDB's previous behavior when section offsets are
19923      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19924      then mark this symbol as LOC_STATIC.  */
19925
19926   if (attr_form_is_block (attr)
19927       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19928            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19929           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19930               && (DW_BLOCK (attr)->size
19931                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19932     {
19933       unsigned int dummy;
19934
19935       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19936         SYMBOL_VALUE_ADDRESS (sym) =
19937           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19938       else
19939         SYMBOL_VALUE_ADDRESS (sym) =
19940           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19941       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19942       fixup_symbol_section (sym, objfile);
19943       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19944                                               SYMBOL_SECTION (sym));
19945       return;
19946     }
19947
19948   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19949      expression evaluator, and use LOC_COMPUTED only when necessary
19950      (i.e. when the value of a register or memory location is
19951      referenced, or a thread-local block, etc.).  Then again, it might
19952      not be worthwhile.  I'm assuming that it isn't unless performance
19953      or memory numbers show me otherwise.  */
19954
19955   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19956
19957   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19958     cu->has_loclist = 1;
19959 }
19960
19961 /* Given a pointer to a DWARF information entry, figure out if we need
19962    to make a symbol table entry for it, and if so, create a new entry
19963    and return a pointer to it.
19964    If TYPE is NULL, determine symbol type from the die, otherwise
19965    used the passed type.
19966    If SPACE is not NULL, use it to hold the new symbol.  If it is
19967    NULL, allocate a new symbol on the objfile's obstack.  */
19968
19969 static struct symbol *
19970 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19971                  struct symbol *space)
19972 {
19973   struct objfile *objfile = cu->objfile;
19974   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19975   struct symbol *sym = NULL;
19976   const char *name;
19977   struct attribute *attr = NULL;
19978   struct attribute *attr2 = NULL;
19979   CORE_ADDR baseaddr;
19980   struct pending **list_to_add = NULL;
19981
19982   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19983
19984   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19985
19986   name = dwarf2_name (die, cu);
19987   if (name)
19988     {
19989       const char *linkagename;
19990       int suppress_add = 0;
19991
19992       if (space)
19993         sym = space;
19994       else
19995         sym = allocate_symbol (objfile);
19996       OBJSTAT (objfile, n_syms++);
19997
19998       /* Cache this symbol's name and the name's demangled form (if any).  */
19999       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
20000       linkagename = dwarf2_physname (name, die, cu);
20001       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
20002
20003       /* Fortran does not have mangling standard and the mangling does differ
20004          between gfortran, iFort etc.  */
20005       if (cu->language == language_fortran
20006           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
20007         symbol_set_demangled_name (&(sym->ginfo),
20008                                    dwarf2_full_name (name, die, cu),
20009                                    NULL);
20010
20011       /* Default assumptions.
20012          Use the passed type or decode it from the die.  */
20013       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20014       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
20015       if (type != NULL)
20016         SYMBOL_TYPE (sym) = type;
20017       else
20018         SYMBOL_TYPE (sym) = die_type (die, cu);
20019       attr = dwarf2_attr (die,
20020                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
20021                           cu);
20022       if (attr)
20023         {
20024           SYMBOL_LINE (sym) = DW_UNSND (attr);
20025         }
20026
20027       attr = dwarf2_attr (die,
20028                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
20029                           cu);
20030       if (attr)
20031         {
20032           file_name_index file_index = (file_name_index) DW_UNSND (attr);
20033           struct file_entry *fe;
20034
20035           if (cu->line_header != NULL)
20036             fe = cu->line_header->file_name_at (file_index);
20037           else
20038             fe = NULL;
20039
20040           if (fe == NULL)
20041             complaint (&symfile_complaints,
20042                        _("file index out of range"));
20043           else
20044             symbol_set_symtab (sym, fe->symtab);
20045         }
20046
20047       switch (die->tag)
20048         {
20049         case DW_TAG_label:
20050           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
20051           if (attr)
20052             {
20053               CORE_ADDR addr;
20054
20055               addr = attr_value_as_address (attr);
20056               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
20057               SYMBOL_VALUE_ADDRESS (sym) = addr;
20058             }
20059           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
20060           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
20061           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
20062           add_symbol_to_list (sym, cu->list_in_scope);
20063           break;
20064         case DW_TAG_subprogram:
20065           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20066              finish_block.  */
20067           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20068           attr2 = dwarf2_attr (die, DW_AT_external, cu);
20069           if ((attr2 && (DW_UNSND (attr2) != 0))
20070               || cu->language == language_ada)
20071             {
20072               /* Subprograms marked external are stored as a global symbol.
20073                  Ada subprograms, whether marked external or not, are always
20074                  stored as a global symbol, because we want to be able to
20075                  access them globally.  For instance, we want to be able
20076                  to break on a nested subprogram without having to
20077                  specify the context.  */
20078               list_to_add = &global_symbols;
20079             }
20080           else
20081             {
20082               list_to_add = cu->list_in_scope;
20083             }
20084           break;
20085         case DW_TAG_inlined_subroutine:
20086           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20087              finish_block.  */
20088           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20089           SYMBOL_INLINED (sym) = 1;
20090           list_to_add = cu->list_in_scope;
20091           break;
20092         case DW_TAG_template_value_param:
20093           suppress_add = 1;
20094           /* Fall through.  */
20095         case DW_TAG_constant:
20096         case DW_TAG_variable:
20097         case DW_TAG_member:
20098           /* Compilation with minimal debug info may result in
20099              variables with missing type entries.  Change the
20100              misleading `void' type to something sensible.  */
20101           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
20102             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
20103
20104           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20105           /* In the case of DW_TAG_member, we should only be called for
20106              static const members.  */
20107           if (die->tag == DW_TAG_member)
20108             {
20109               /* dwarf2_add_field uses die_is_declaration,
20110                  so we do the same.  */
20111               gdb_assert (die_is_declaration (die, cu));
20112               gdb_assert (attr);
20113             }
20114           if (attr)
20115             {
20116               dwarf2_const_value (attr, sym, cu);
20117               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20118               if (!suppress_add)
20119                 {
20120                   if (attr2 && (DW_UNSND (attr2) != 0))
20121                     list_to_add = &global_symbols;
20122                   else
20123                     list_to_add = cu->list_in_scope;
20124                 }
20125               break;
20126             }
20127           attr = dwarf2_attr (die, DW_AT_location, cu);
20128           if (attr)
20129             {
20130               var_decode_location (attr, sym, cu);
20131               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20132
20133               /* Fortran explicitly imports any global symbols to the local
20134                  scope by DW_TAG_common_block.  */
20135               if (cu->language == language_fortran && die->parent
20136                   && die->parent->tag == DW_TAG_common_block)
20137                 attr2 = NULL;
20138
20139               if (SYMBOL_CLASS (sym) == LOC_STATIC
20140                   && SYMBOL_VALUE_ADDRESS (sym) == 0
20141                   && !dwarf2_per_objfile->has_section_at_zero)
20142                 {
20143                   /* When a static variable is eliminated by the linker,
20144                      the corresponding debug information is not stripped
20145                      out, but the variable address is set to null;
20146                      do not add such variables into symbol table.  */
20147                 }
20148               else if (attr2 && (DW_UNSND (attr2) != 0))
20149                 {
20150                   /* Workaround gfortran PR debug/40040 - it uses
20151                      DW_AT_location for variables in -fPIC libraries which may
20152                      get overriden by other libraries/executable and get
20153                      a different address.  Resolve it by the minimal symbol
20154                      which may come from inferior's executable using copy
20155                      relocation.  Make this workaround only for gfortran as for
20156                      other compilers GDB cannot guess the minimal symbol
20157                      Fortran mangling kind.  */
20158                   if (cu->language == language_fortran && die->parent
20159                       && die->parent->tag == DW_TAG_module
20160                       && cu->producer
20161                       && startswith (cu->producer, "GNU Fortran"))
20162                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
20163
20164                   /* A variable with DW_AT_external is never static,
20165                      but it may be block-scoped.  */
20166                   list_to_add = (cu->list_in_scope == &file_symbols
20167                                  ? &global_symbols : cu->list_in_scope);
20168                 }
20169               else
20170                 list_to_add = cu->list_in_scope;
20171             }
20172           else
20173             {
20174               /* We do not know the address of this symbol.
20175                  If it is an external symbol and we have type information
20176                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
20177                  The address of the variable will then be determined from
20178                  the minimal symbol table whenever the variable is
20179                  referenced.  */
20180               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20181
20182               /* Fortran explicitly imports any global symbols to the local
20183                  scope by DW_TAG_common_block.  */
20184               if (cu->language == language_fortran && die->parent
20185                   && die->parent->tag == DW_TAG_common_block)
20186                 {
20187                   /* SYMBOL_CLASS doesn't matter here because
20188                      read_common_block is going to reset it.  */
20189                   if (!suppress_add)
20190                     list_to_add = cu->list_in_scope;
20191                 }
20192               else if (attr2 && (DW_UNSND (attr2) != 0)
20193                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
20194                 {
20195                   /* A variable with DW_AT_external is never static, but it
20196                      may be block-scoped.  */
20197                   list_to_add = (cu->list_in_scope == &file_symbols
20198                                  ? &global_symbols : cu->list_in_scope);
20199
20200                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
20201                 }
20202               else if (!die_is_declaration (die, cu))
20203                 {
20204                   /* Use the default LOC_OPTIMIZED_OUT class.  */
20205                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
20206                   if (!suppress_add)
20207                     list_to_add = cu->list_in_scope;
20208                 }
20209             }
20210           break;
20211         case DW_TAG_formal_parameter:
20212           /* If we are inside a function, mark this as an argument.  If
20213              not, we might be looking at an argument to an inlined function
20214              when we do not have enough information to show inlined frames;
20215              pretend it's a local variable in that case so that the user can
20216              still see it.  */
20217           if (context_stack_depth > 0
20218               && context_stack[context_stack_depth - 1].name != NULL)
20219             SYMBOL_IS_ARGUMENT (sym) = 1;
20220           attr = dwarf2_attr (die, DW_AT_location, cu);
20221           if (attr)
20222             {
20223               var_decode_location (attr, sym, cu);
20224             }
20225           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20226           if (attr)
20227             {
20228               dwarf2_const_value (attr, sym, cu);
20229             }
20230
20231           list_to_add = cu->list_in_scope;
20232           break;
20233         case DW_TAG_unspecified_parameters:
20234           /* From varargs functions; gdb doesn't seem to have any
20235              interest in this information, so just ignore it for now.
20236              (FIXME?) */
20237           break;
20238         case DW_TAG_template_type_param:
20239           suppress_add = 1;
20240           /* Fall through.  */
20241         case DW_TAG_class_type:
20242         case DW_TAG_interface_type:
20243         case DW_TAG_structure_type:
20244         case DW_TAG_union_type:
20245         case DW_TAG_set_type:
20246         case DW_TAG_enumeration_type:
20247           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20248           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
20249
20250           {
20251             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
20252                really ever be static objects: otherwise, if you try
20253                to, say, break of a class's method and you're in a file
20254                which doesn't mention that class, it won't work unless
20255                the check for all static symbols in lookup_symbol_aux
20256                saves you.  See the OtherFileClass tests in
20257                gdb.c++/namespace.exp.  */
20258
20259             if (!suppress_add)
20260               {
20261                 list_to_add = (cu->list_in_scope == &file_symbols
20262                                && cu->language == language_cplus
20263                                ? &global_symbols : cu->list_in_scope);
20264
20265                 /* The semantics of C++ state that "struct foo {
20266                    ... }" also defines a typedef for "foo".  */
20267                 if (cu->language == language_cplus
20268                     || cu->language == language_ada
20269                     || cu->language == language_d
20270                     || cu->language == language_rust)
20271                   {
20272                     /* The symbol's name is already allocated along
20273                        with this objfile, so we don't need to
20274                        duplicate it for the type.  */
20275                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
20276                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
20277                   }
20278               }
20279           }
20280           break;
20281         case DW_TAG_typedef:
20282           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20283           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20284           list_to_add = cu->list_in_scope;
20285           break;
20286         case DW_TAG_base_type:
20287         case DW_TAG_subrange_type:
20288           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20289           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20290           list_to_add = cu->list_in_scope;
20291           break;
20292         case DW_TAG_enumerator:
20293           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20294           if (attr)
20295             {
20296               dwarf2_const_value (attr, sym, cu);
20297             }
20298           {
20299             /* NOTE: carlton/2003-11-10: See comment above in the
20300                DW_TAG_class_type, etc. block.  */
20301
20302             list_to_add = (cu->list_in_scope == &file_symbols
20303                            && cu->language == language_cplus
20304                            ? &global_symbols : cu->list_in_scope);
20305           }
20306           break;
20307         case DW_TAG_imported_declaration:
20308         case DW_TAG_namespace:
20309           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20310           list_to_add = &global_symbols;
20311           break;
20312         case DW_TAG_module:
20313           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20314           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
20315           list_to_add = &global_symbols;
20316           break;
20317         case DW_TAG_common_block:
20318           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
20319           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
20320           add_symbol_to_list (sym, cu->list_in_scope);
20321           break;
20322         default:
20323           /* Not a tag we recognize.  Hopefully we aren't processing
20324              trash data, but since we must specifically ignore things
20325              we don't recognize, there is nothing else we should do at
20326              this point.  */
20327           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
20328                      dwarf_tag_name (die->tag));
20329           break;
20330         }
20331
20332       if (suppress_add)
20333         {
20334           sym->hash_next = objfile->template_symbols;
20335           objfile->template_symbols = sym;
20336           list_to_add = NULL;
20337         }
20338
20339       if (list_to_add != NULL)
20340         add_symbol_to_list (sym, list_to_add);
20341
20342       /* For the benefit of old versions of GCC, check for anonymous
20343          namespaces based on the demangled name.  */
20344       if (!cu->processing_has_namespace_info
20345           && cu->language == language_cplus)
20346         cp_scan_for_anonymous_namespaces (sym, objfile);
20347     }
20348   return (sym);
20349 }
20350
20351 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
20352
20353 static struct symbol *
20354 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20355 {
20356   return new_symbol_full (die, type, cu, NULL);
20357 }
20358
20359 /* Given an attr with a DW_FORM_dataN value in host byte order,
20360    zero-extend it as appropriate for the symbol's type.  The DWARF
20361    standard (v4) is not entirely clear about the meaning of using
20362    DW_FORM_dataN for a constant with a signed type, where the type is
20363    wider than the data.  The conclusion of a discussion on the DWARF
20364    list was that this is unspecified.  We choose to always zero-extend
20365    because that is the interpretation long in use by GCC.  */
20366
20367 static gdb_byte *
20368 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
20369                          struct dwarf2_cu *cu, LONGEST *value, int bits)
20370 {
20371   struct objfile *objfile = cu->objfile;
20372   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
20373                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
20374   LONGEST l = DW_UNSND (attr);
20375
20376   if (bits < sizeof (*value) * 8)
20377     {
20378       l &= ((LONGEST) 1 << bits) - 1;
20379       *value = l;
20380     }
20381   else if (bits == sizeof (*value) * 8)
20382     *value = l;
20383   else
20384     {
20385       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
20386       store_unsigned_integer (bytes, bits / 8, byte_order, l);
20387       return bytes;
20388     }
20389
20390   return NULL;
20391 }
20392
20393 /* Read a constant value from an attribute.  Either set *VALUE, or if
20394    the value does not fit in *VALUE, set *BYTES - either already
20395    allocated on the objfile obstack, or newly allocated on OBSTACK,
20396    or, set *BATON, if we translated the constant to a location
20397    expression.  */
20398
20399 static void
20400 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
20401                          const char *name, struct obstack *obstack,
20402                          struct dwarf2_cu *cu,
20403                          LONGEST *value, const gdb_byte **bytes,
20404                          struct dwarf2_locexpr_baton **baton)
20405 {
20406   struct objfile *objfile = cu->objfile;
20407   struct comp_unit_head *cu_header = &cu->header;
20408   struct dwarf_block *blk;
20409   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
20410                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20411
20412   *value = 0;
20413   *bytes = NULL;
20414   *baton = NULL;
20415
20416   switch (attr->form)
20417     {
20418     case DW_FORM_addr:
20419     case DW_FORM_GNU_addr_index:
20420       {
20421         gdb_byte *data;
20422
20423         if (TYPE_LENGTH (type) != cu_header->addr_size)
20424           dwarf2_const_value_length_mismatch_complaint (name,
20425                                                         cu_header->addr_size,
20426                                                         TYPE_LENGTH (type));
20427         /* Symbols of this form are reasonably rare, so we just
20428            piggyback on the existing location code rather than writing
20429            a new implementation of symbol_computed_ops.  */
20430         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
20431         (*baton)->per_cu = cu->per_cu;
20432         gdb_assert ((*baton)->per_cu);
20433
20434         (*baton)->size = 2 + cu_header->addr_size;
20435         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
20436         (*baton)->data = data;
20437
20438         data[0] = DW_OP_addr;
20439         store_unsigned_integer (&data[1], cu_header->addr_size,
20440                                 byte_order, DW_ADDR (attr));
20441         data[cu_header->addr_size + 1] = DW_OP_stack_value;
20442       }
20443       break;
20444     case DW_FORM_string:
20445     case DW_FORM_strp:
20446     case DW_FORM_GNU_str_index:
20447     case DW_FORM_GNU_strp_alt:
20448       /* DW_STRING is already allocated on the objfile obstack, point
20449          directly to it.  */
20450       *bytes = (const gdb_byte *) DW_STRING (attr);
20451       break;
20452     case DW_FORM_block1:
20453     case DW_FORM_block2:
20454     case DW_FORM_block4:
20455     case DW_FORM_block:
20456     case DW_FORM_exprloc:
20457     case DW_FORM_data16:
20458       blk = DW_BLOCK (attr);
20459       if (TYPE_LENGTH (type) != blk->size)
20460         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
20461                                                       TYPE_LENGTH (type));
20462       *bytes = blk->data;
20463       break;
20464
20465       /* The DW_AT_const_value attributes are supposed to carry the
20466          symbol's value "represented as it would be on the target
20467          architecture."  By the time we get here, it's already been
20468          converted to host endianness, so we just need to sign- or
20469          zero-extend it as appropriate.  */
20470     case DW_FORM_data1:
20471       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
20472       break;
20473     case DW_FORM_data2:
20474       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
20475       break;
20476     case DW_FORM_data4:
20477       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
20478       break;
20479     case DW_FORM_data8:
20480       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
20481       break;
20482
20483     case DW_FORM_sdata:
20484     case DW_FORM_implicit_const:
20485       *value = DW_SND (attr);
20486       break;
20487
20488     case DW_FORM_udata:
20489       *value = DW_UNSND (attr);
20490       break;
20491
20492     default:
20493       complaint (&symfile_complaints,
20494                  _("unsupported const value attribute form: '%s'"),
20495                  dwarf_form_name (attr->form));
20496       *value = 0;
20497       break;
20498     }
20499 }
20500
20501
20502 /* Copy constant value from an attribute to a symbol.  */
20503
20504 static void
20505 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
20506                     struct dwarf2_cu *cu)
20507 {
20508   struct objfile *objfile = cu->objfile;
20509   LONGEST value;
20510   const gdb_byte *bytes;
20511   struct dwarf2_locexpr_baton *baton;
20512
20513   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
20514                            SYMBOL_PRINT_NAME (sym),
20515                            &objfile->objfile_obstack, cu,
20516                            &value, &bytes, &baton);
20517
20518   if (baton != NULL)
20519     {
20520       SYMBOL_LOCATION_BATON (sym) = baton;
20521       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
20522     }
20523   else if (bytes != NULL)
20524      {
20525       SYMBOL_VALUE_BYTES (sym) = bytes;
20526       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
20527     }
20528   else
20529     {
20530       SYMBOL_VALUE (sym) = value;
20531       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
20532     }
20533 }
20534
20535 /* Return the type of the die in question using its DW_AT_type attribute.  */
20536
20537 static struct type *
20538 die_type (struct die_info *die, struct dwarf2_cu *cu)
20539 {
20540   struct attribute *type_attr;
20541
20542   type_attr = dwarf2_attr (die, DW_AT_type, cu);
20543   if (!type_attr)
20544     {
20545       /* A missing DW_AT_type represents a void type.  */
20546       return objfile_type (cu->objfile)->builtin_void;
20547     }
20548
20549   return lookup_die_type (die, type_attr, cu);
20550 }
20551
20552 /* True iff CU's producer generates GNAT Ada auxiliary information
20553    that allows to find parallel types through that information instead
20554    of having to do expensive parallel lookups by type name.  */
20555
20556 static int
20557 need_gnat_info (struct dwarf2_cu *cu)
20558 {
20559   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
20560      of GNAT produces this auxiliary information, without any indication
20561      that it is produced.  Part of enhancing the FSF version of GNAT
20562      to produce that information will be to put in place an indicator
20563      that we can use in order to determine whether the descriptive type
20564      info is available or not.  One suggestion that has been made is
20565      to use a new attribute, attached to the CU die.  For now, assume
20566      that the descriptive type info is not available.  */
20567   return 0;
20568 }
20569
20570 /* Return the auxiliary type of the die in question using its
20571    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
20572    attribute is not present.  */
20573
20574 static struct type *
20575 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
20576 {
20577   struct attribute *type_attr;
20578
20579   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
20580   if (!type_attr)
20581     return NULL;
20582
20583   return lookup_die_type (die, type_attr, cu);
20584 }
20585
20586 /* If DIE has a descriptive_type attribute, then set the TYPE's
20587    descriptive type accordingly.  */
20588
20589 static void
20590 set_descriptive_type (struct type *type, struct die_info *die,
20591                       struct dwarf2_cu *cu)
20592 {
20593   struct type *descriptive_type = die_descriptive_type (die, cu);
20594
20595   if (descriptive_type)
20596     {
20597       ALLOCATE_GNAT_AUX_TYPE (type);
20598       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
20599     }
20600 }
20601
20602 /* Return the containing type of the die in question using its
20603    DW_AT_containing_type attribute.  */
20604
20605 static struct type *
20606 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
20607 {
20608   struct attribute *type_attr;
20609
20610   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
20611   if (!type_attr)
20612     error (_("Dwarf Error: Problem turning containing type into gdb type "
20613              "[in module %s]"), objfile_name (cu->objfile));
20614
20615   return lookup_die_type (die, type_attr, cu);
20616 }
20617
20618 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
20619
20620 static struct type *
20621 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
20622 {
20623   struct objfile *objfile = dwarf2_per_objfile->objfile;
20624   char *message, *saved;
20625
20626   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
20627                         objfile_name (objfile),
20628                         to_underlying (cu->header.sect_off),
20629                         to_underlying (die->sect_off));
20630   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
20631                                   message, strlen (message));
20632   xfree (message);
20633
20634   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
20635 }
20636
20637 /* Look up the type of DIE in CU using its type attribute ATTR.
20638    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
20639    DW_AT_containing_type.
20640    If there is no type substitute an error marker.  */
20641
20642 static struct type *
20643 lookup_die_type (struct die_info *die, const struct attribute *attr,
20644                  struct dwarf2_cu *cu)
20645 {
20646   struct objfile *objfile = cu->objfile;
20647   struct type *this_type;
20648
20649   gdb_assert (attr->name == DW_AT_type
20650               || attr->name == DW_AT_GNAT_descriptive_type
20651               || attr->name == DW_AT_containing_type);
20652
20653   /* First see if we have it cached.  */
20654
20655   if (attr->form == DW_FORM_GNU_ref_alt)
20656     {
20657       struct dwarf2_per_cu_data *per_cu;
20658       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20659
20660       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
20661       this_type = get_die_type_at_offset (sect_off, per_cu);
20662     }
20663   else if (attr_form_is_ref (attr))
20664     {
20665       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20666
20667       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
20668     }
20669   else if (attr->form == DW_FORM_ref_sig8)
20670     {
20671       ULONGEST signature = DW_SIGNATURE (attr);
20672
20673       return get_signatured_type (die, signature, cu);
20674     }
20675   else
20676     {
20677       complaint (&symfile_complaints,
20678                  _("Dwarf Error: Bad type attribute %s in DIE"
20679                    " at 0x%x [in module %s]"),
20680                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
20681                  objfile_name (objfile));
20682       return build_error_marker_type (cu, die);
20683     }
20684
20685   /* If not cached we need to read it in.  */
20686
20687   if (this_type == NULL)
20688     {
20689       struct die_info *type_die = NULL;
20690       struct dwarf2_cu *type_cu = cu;
20691
20692       if (attr_form_is_ref (attr))
20693         type_die = follow_die_ref (die, attr, &type_cu);
20694       if (type_die == NULL)
20695         return build_error_marker_type (cu, die);
20696       /* If we find the type now, it's probably because the type came
20697          from an inter-CU reference and the type's CU got expanded before
20698          ours.  */
20699       this_type = read_type_die (type_die, type_cu);
20700     }
20701
20702   /* If we still don't have a type use an error marker.  */
20703
20704   if (this_type == NULL)
20705     return build_error_marker_type (cu, die);
20706
20707   return this_type;
20708 }
20709
20710 /* Return the type in DIE, CU.
20711    Returns NULL for invalid types.
20712
20713    This first does a lookup in die_type_hash,
20714    and only reads the die in if necessary.
20715
20716    NOTE: This can be called when reading in partial or full symbols.  */
20717
20718 static struct type *
20719 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
20720 {
20721   struct type *this_type;
20722
20723   this_type = get_die_type (die, cu);
20724   if (this_type)
20725     return this_type;
20726
20727   return read_type_die_1 (die, cu);
20728 }
20729
20730 /* Read the type in DIE, CU.
20731    Returns NULL for invalid types.  */
20732
20733 static struct type *
20734 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
20735 {
20736   struct type *this_type = NULL;
20737
20738   switch (die->tag)
20739     {
20740     case DW_TAG_class_type:
20741     case DW_TAG_interface_type:
20742     case DW_TAG_structure_type:
20743     case DW_TAG_union_type:
20744       this_type = read_structure_type (die, cu);
20745       break;
20746     case DW_TAG_enumeration_type:
20747       this_type = read_enumeration_type (die, cu);
20748       break;
20749     case DW_TAG_subprogram:
20750     case DW_TAG_subroutine_type:
20751     case DW_TAG_inlined_subroutine:
20752       this_type = read_subroutine_type (die, cu);
20753       break;
20754     case DW_TAG_array_type:
20755       this_type = read_array_type (die, cu);
20756       break;
20757     case DW_TAG_set_type:
20758       this_type = read_set_type (die, cu);
20759       break;
20760     case DW_TAG_pointer_type:
20761       this_type = read_tag_pointer_type (die, cu);
20762       break;
20763     case DW_TAG_ptr_to_member_type:
20764       this_type = read_tag_ptr_to_member_type (die, cu);
20765       break;
20766     case DW_TAG_reference_type:
20767       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
20768       break;
20769     case DW_TAG_rvalue_reference_type:
20770       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
20771       break;
20772     case DW_TAG_const_type:
20773       this_type = read_tag_const_type (die, cu);
20774       break;
20775     case DW_TAG_volatile_type:
20776       this_type = read_tag_volatile_type (die, cu);
20777       break;
20778     case DW_TAG_restrict_type:
20779       this_type = read_tag_restrict_type (die, cu);
20780       break;
20781     case DW_TAG_string_type:
20782       this_type = read_tag_string_type (die, cu);
20783       break;
20784     case DW_TAG_typedef:
20785       this_type = read_typedef (die, cu);
20786       break;
20787     case DW_TAG_subrange_type:
20788       this_type = read_subrange_type (die, cu);
20789       break;
20790     case DW_TAG_base_type:
20791       this_type = read_base_type (die, cu);
20792       break;
20793     case DW_TAG_unspecified_type:
20794       this_type = read_unspecified_type (die, cu);
20795       break;
20796     case DW_TAG_namespace:
20797       this_type = read_namespace_type (die, cu);
20798       break;
20799     case DW_TAG_module:
20800       this_type = read_module_type (die, cu);
20801       break;
20802     case DW_TAG_atomic_type:
20803       this_type = read_tag_atomic_type (die, cu);
20804       break;
20805     default:
20806       complaint (&symfile_complaints,
20807                  _("unexpected tag in read_type_die: '%s'"),
20808                  dwarf_tag_name (die->tag));
20809       break;
20810     }
20811
20812   return this_type;
20813 }
20814
20815 /* See if we can figure out if the class lives in a namespace.  We do
20816    this by looking for a member function; its demangled name will
20817    contain namespace info, if there is any.
20818    Return the computed name or NULL.
20819    Space for the result is allocated on the objfile's obstack.
20820    This is the full-die version of guess_partial_die_structure_name.
20821    In this case we know DIE has no useful parent.  */
20822
20823 static char *
20824 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
20825 {
20826   struct die_info *spec_die;
20827   struct dwarf2_cu *spec_cu;
20828   struct die_info *child;
20829
20830   spec_cu = cu;
20831   spec_die = die_specification (die, &spec_cu);
20832   if (spec_die != NULL)
20833     {
20834       die = spec_die;
20835       cu = spec_cu;
20836     }
20837
20838   for (child = die->child;
20839        child != NULL;
20840        child = child->sibling)
20841     {
20842       if (child->tag == DW_TAG_subprogram)
20843         {
20844           const char *linkage_name = dw2_linkage_name (child, cu);
20845
20846           if (linkage_name != NULL)
20847             {
20848               char *actual_name
20849                 = language_class_name_from_physname (cu->language_defn,
20850                                                      linkage_name);
20851               char *name = NULL;
20852
20853               if (actual_name != NULL)
20854                 {
20855                   const char *die_name = dwarf2_name (die, cu);
20856
20857                   if (die_name != NULL
20858                       && strcmp (die_name, actual_name) != 0)
20859                     {
20860                       /* Strip off the class name from the full name.
20861                          We want the prefix.  */
20862                       int die_name_len = strlen (die_name);
20863                       int actual_name_len = strlen (actual_name);
20864
20865                       /* Test for '::' as a sanity check.  */
20866                       if (actual_name_len > die_name_len + 2
20867                           && actual_name[actual_name_len
20868                                          - die_name_len - 1] == ':')
20869                         name = (char *) obstack_copy0 (
20870                           &cu->objfile->per_bfd->storage_obstack,
20871                           actual_name, actual_name_len - die_name_len - 2);
20872                     }
20873                 }
20874               xfree (actual_name);
20875               return name;
20876             }
20877         }
20878     }
20879
20880   return NULL;
20881 }
20882
20883 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
20884    prefix part in such case.  See
20885    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20886
20887 static const char *
20888 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
20889 {
20890   struct attribute *attr;
20891   const char *base;
20892
20893   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
20894       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
20895     return NULL;
20896
20897   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
20898     return NULL;
20899
20900   attr = dw2_linkage_name_attr (die, cu);
20901   if (attr == NULL || DW_STRING (attr) == NULL)
20902     return NULL;
20903
20904   /* dwarf2_name had to be already called.  */
20905   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20906
20907   /* Strip the base name, keep any leading namespaces/classes.  */
20908   base = strrchr (DW_STRING (attr), ':');
20909   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20910     return "";
20911
20912   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20913                                  DW_STRING (attr),
20914                                  &base[-1] - DW_STRING (attr));
20915 }
20916
20917 /* Return the name of the namespace/class that DIE is defined within,
20918    or "" if we can't tell.  The caller should not xfree the result.
20919
20920    For example, if we're within the method foo() in the following
20921    code:
20922
20923    namespace N {
20924      class C {
20925        void foo () {
20926        }
20927      };
20928    }
20929
20930    then determine_prefix on foo's die will return "N::C".  */
20931
20932 static const char *
20933 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20934 {
20935   struct die_info *parent, *spec_die;
20936   struct dwarf2_cu *spec_cu;
20937   struct type *parent_type;
20938   const char *retval;
20939
20940   if (cu->language != language_cplus
20941       && cu->language != language_fortran && cu->language != language_d
20942       && cu->language != language_rust)
20943     return "";
20944
20945   retval = anonymous_struct_prefix (die, cu);
20946   if (retval)
20947     return retval;
20948
20949   /* We have to be careful in the presence of DW_AT_specification.
20950      For example, with GCC 3.4, given the code
20951
20952      namespace N {
20953        void foo() {
20954          // Definition of N::foo.
20955        }
20956      }
20957
20958      then we'll have a tree of DIEs like this:
20959
20960      1: DW_TAG_compile_unit
20961        2: DW_TAG_namespace        // N
20962          3: DW_TAG_subprogram     // declaration of N::foo
20963        4: DW_TAG_subprogram       // definition of N::foo
20964             DW_AT_specification   // refers to die #3
20965
20966      Thus, when processing die #4, we have to pretend that we're in
20967      the context of its DW_AT_specification, namely the contex of die
20968      #3.  */
20969   spec_cu = cu;
20970   spec_die = die_specification (die, &spec_cu);
20971   if (spec_die == NULL)
20972     parent = die->parent;
20973   else
20974     {
20975       parent = spec_die->parent;
20976       cu = spec_cu;
20977     }
20978
20979   if (parent == NULL)
20980     return "";
20981   else if (parent->building_fullname)
20982     {
20983       const char *name;
20984       const char *parent_name;
20985
20986       /* It has been seen on RealView 2.2 built binaries,
20987          DW_TAG_template_type_param types actually _defined_ as
20988          children of the parent class:
20989
20990          enum E {};
20991          template class <class Enum> Class{};
20992          Class<enum E> class_e;
20993
20994          1: DW_TAG_class_type (Class)
20995            2: DW_TAG_enumeration_type (E)
20996              3: DW_TAG_enumerator (enum1:0)
20997              3: DW_TAG_enumerator (enum2:1)
20998              ...
20999            2: DW_TAG_template_type_param
21000               DW_AT_type  DW_FORM_ref_udata (E)
21001
21002          Besides being broken debug info, it can put GDB into an
21003          infinite loop.  Consider:
21004
21005          When we're building the full name for Class<E>, we'll start
21006          at Class, and go look over its template type parameters,
21007          finding E.  We'll then try to build the full name of E, and
21008          reach here.  We're now trying to build the full name of E,
21009          and look over the parent DIE for containing scope.  In the
21010          broken case, if we followed the parent DIE of E, we'd again
21011          find Class, and once again go look at its template type
21012          arguments, etc., etc.  Simply don't consider such parent die
21013          as source-level parent of this die (it can't be, the language
21014          doesn't allow it), and break the loop here.  */
21015       name = dwarf2_name (die, cu);
21016       parent_name = dwarf2_name (parent, cu);
21017       complaint (&symfile_complaints,
21018                  _("template param type '%s' defined within parent '%s'"),
21019                  name ? name : "<unknown>",
21020                  parent_name ? parent_name : "<unknown>");
21021       return "";
21022     }
21023   else
21024     switch (parent->tag)
21025       {
21026       case DW_TAG_namespace:
21027         parent_type = read_type_die (parent, cu);
21028         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
21029            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
21030            Work around this problem here.  */
21031         if (cu->language == language_cplus
21032             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
21033           return "";
21034         /* We give a name to even anonymous namespaces.  */
21035         return TYPE_TAG_NAME (parent_type);
21036       case DW_TAG_class_type:
21037       case DW_TAG_interface_type:
21038       case DW_TAG_structure_type:
21039       case DW_TAG_union_type:
21040       case DW_TAG_module:
21041         parent_type = read_type_die (parent, cu);
21042         if (TYPE_TAG_NAME (parent_type) != NULL)
21043           return TYPE_TAG_NAME (parent_type);
21044         else
21045           /* An anonymous structure is only allowed non-static data
21046              members; no typedefs, no member functions, et cetera.
21047              So it does not need a prefix.  */
21048           return "";
21049       case DW_TAG_compile_unit:
21050       case DW_TAG_partial_unit:
21051         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
21052         if (cu->language == language_cplus
21053             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
21054             && die->child != NULL
21055             && (die->tag == DW_TAG_class_type
21056                 || die->tag == DW_TAG_structure_type
21057                 || die->tag == DW_TAG_union_type))
21058           {
21059             char *name = guess_full_die_structure_name (die, cu);
21060             if (name != NULL)
21061               return name;
21062           }
21063         return "";
21064       case DW_TAG_enumeration_type:
21065         parent_type = read_type_die (parent, cu);
21066         if (TYPE_DECLARED_CLASS (parent_type))
21067           {
21068             if (TYPE_TAG_NAME (parent_type) != NULL)
21069               return TYPE_TAG_NAME (parent_type);
21070             return "";
21071           }
21072         /* Fall through.  */
21073       default:
21074         return determine_prefix (parent, cu);
21075       }
21076 }
21077
21078 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
21079    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
21080    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
21081    an obconcat, otherwise allocate storage for the result.  The CU argument is
21082    used to determine the language and hence, the appropriate separator.  */
21083
21084 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
21085
21086 static char *
21087 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
21088                  int physname, struct dwarf2_cu *cu)
21089 {
21090   const char *lead = "";
21091   const char *sep;
21092
21093   if (suffix == NULL || suffix[0] == '\0'
21094       || prefix == NULL || prefix[0] == '\0')
21095     sep = "";
21096   else if (cu->language == language_d)
21097     {
21098       /* For D, the 'main' function could be defined in any module, but it
21099          should never be prefixed.  */
21100       if (strcmp (suffix, "D main") == 0)
21101         {
21102           prefix = "";
21103           sep = "";
21104         }
21105       else
21106         sep = ".";
21107     }
21108   else if (cu->language == language_fortran && physname)
21109     {
21110       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
21111          DW_AT_MIPS_linkage_name is preferred and used instead.  */
21112
21113       lead = "__";
21114       sep = "_MOD_";
21115     }
21116   else
21117     sep = "::";
21118
21119   if (prefix == NULL)
21120     prefix = "";
21121   if (suffix == NULL)
21122     suffix = "";
21123
21124   if (obs == NULL)
21125     {
21126       char *retval
21127         = ((char *)
21128            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
21129
21130       strcpy (retval, lead);
21131       strcat (retval, prefix);
21132       strcat (retval, sep);
21133       strcat (retval, suffix);
21134       return retval;
21135     }
21136   else
21137     {
21138       /* We have an obstack.  */
21139       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
21140     }
21141 }
21142
21143 /* Return sibling of die, NULL if no sibling.  */
21144
21145 static struct die_info *
21146 sibling_die (struct die_info *die)
21147 {
21148   return die->sibling;
21149 }
21150
21151 /* Get name of a die, return NULL if not found.  */
21152
21153 static const char *
21154 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
21155                           struct obstack *obstack)
21156 {
21157   if (name && cu->language == language_cplus)
21158     {
21159       std::string canon_name = cp_canonicalize_string (name);
21160
21161       if (!canon_name.empty ())
21162         {
21163           if (canon_name != name)
21164             name = (const char *) obstack_copy0 (obstack,
21165                                                  canon_name.c_str (),
21166                                                  canon_name.length ());
21167         }
21168     }
21169
21170   return name;
21171 }
21172
21173 /* Get name of a die, return NULL if not found.
21174    Anonymous namespaces are converted to their magic string.  */
21175
21176 static const char *
21177 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
21178 {
21179   struct attribute *attr;
21180
21181   attr = dwarf2_attr (die, DW_AT_name, cu);
21182   if ((!attr || !DW_STRING (attr))
21183       && die->tag != DW_TAG_namespace
21184       && die->tag != DW_TAG_class_type
21185       && die->tag != DW_TAG_interface_type
21186       && die->tag != DW_TAG_structure_type
21187       && die->tag != DW_TAG_union_type)
21188     return NULL;
21189
21190   switch (die->tag)
21191     {
21192     case DW_TAG_compile_unit:
21193     case DW_TAG_partial_unit:
21194       /* Compilation units have a DW_AT_name that is a filename, not
21195          a source language identifier.  */
21196     case DW_TAG_enumeration_type:
21197     case DW_TAG_enumerator:
21198       /* These tags always have simple identifiers already; no need
21199          to canonicalize them.  */
21200       return DW_STRING (attr);
21201
21202     case DW_TAG_namespace:
21203       if (attr != NULL && DW_STRING (attr) != NULL)
21204         return DW_STRING (attr);
21205       return CP_ANONYMOUS_NAMESPACE_STR;
21206
21207     case DW_TAG_class_type:
21208     case DW_TAG_interface_type:
21209     case DW_TAG_structure_type:
21210     case DW_TAG_union_type:
21211       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
21212          structures or unions.  These were of the form "._%d" in GCC 4.1,
21213          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
21214          and GCC 4.4.  We work around this problem by ignoring these.  */
21215       if (attr && DW_STRING (attr)
21216           && (startswith (DW_STRING (attr), "._")
21217               || startswith (DW_STRING (attr), "<anonymous")))
21218         return NULL;
21219
21220       /* GCC might emit a nameless typedef that has a linkage name.  See
21221          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
21222       if (!attr || DW_STRING (attr) == NULL)
21223         {
21224           char *demangled = NULL;
21225
21226           attr = dw2_linkage_name_attr (die, cu);
21227           if (attr == NULL || DW_STRING (attr) == NULL)
21228             return NULL;
21229
21230           /* Avoid demangling DW_STRING (attr) the second time on a second
21231              call for the same DIE.  */
21232           if (!DW_STRING_IS_CANONICAL (attr))
21233             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
21234
21235           if (demangled)
21236             {
21237               const char *base;
21238
21239               /* FIXME: we already did this for the partial symbol... */
21240               DW_STRING (attr)
21241                 = ((const char *)
21242                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
21243                                   demangled, strlen (demangled)));
21244               DW_STRING_IS_CANONICAL (attr) = 1;
21245               xfree (demangled);
21246
21247               /* Strip any leading namespaces/classes, keep only the base name.
21248                  DW_AT_name for named DIEs does not contain the prefixes.  */
21249               base = strrchr (DW_STRING (attr), ':');
21250               if (base && base > DW_STRING (attr) && base[-1] == ':')
21251                 return &base[1];
21252               else
21253                 return DW_STRING (attr);
21254             }
21255         }
21256       break;
21257
21258     default:
21259       break;
21260     }
21261
21262   if (!DW_STRING_IS_CANONICAL (attr))
21263     {
21264       DW_STRING (attr)
21265         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
21266                                     &cu->objfile->per_bfd->storage_obstack);
21267       DW_STRING_IS_CANONICAL (attr) = 1;
21268     }
21269   return DW_STRING (attr);
21270 }
21271
21272 /* Return the die that this die in an extension of, or NULL if there
21273    is none.  *EXT_CU is the CU containing DIE on input, and the CU
21274    containing the return value on output.  */
21275
21276 static struct die_info *
21277 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
21278 {
21279   struct attribute *attr;
21280
21281   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
21282   if (attr == NULL)
21283     return NULL;
21284
21285   return follow_die_ref (die, attr, ext_cu);
21286 }
21287
21288 /* Convert a DIE tag into its string name.  */
21289
21290 static const char *
21291 dwarf_tag_name (unsigned tag)
21292 {
21293   const char *name = get_DW_TAG_name (tag);
21294
21295   if (name == NULL)
21296     return "DW_TAG_<unknown>";
21297
21298   return name;
21299 }
21300
21301 /* Convert a DWARF attribute code into its string name.  */
21302
21303 static const char *
21304 dwarf_attr_name (unsigned attr)
21305 {
21306   const char *name;
21307
21308 #ifdef MIPS /* collides with DW_AT_HP_block_index */
21309   if (attr == DW_AT_MIPS_fde)
21310     return "DW_AT_MIPS_fde";
21311 #else
21312   if (attr == DW_AT_HP_block_index)
21313     return "DW_AT_HP_block_index";
21314 #endif
21315
21316   name = get_DW_AT_name (attr);
21317
21318   if (name == NULL)
21319     return "DW_AT_<unknown>";
21320
21321   return name;
21322 }
21323
21324 /* Convert a DWARF value form code into its string name.  */
21325
21326 static const char *
21327 dwarf_form_name (unsigned form)
21328 {
21329   const char *name = get_DW_FORM_name (form);
21330
21331   if (name == NULL)
21332     return "DW_FORM_<unknown>";
21333
21334   return name;
21335 }
21336
21337 static const char *
21338 dwarf_bool_name (unsigned mybool)
21339 {
21340   if (mybool)
21341     return "TRUE";
21342   else
21343     return "FALSE";
21344 }
21345
21346 /* Convert a DWARF type code into its string name.  */
21347
21348 static const char *
21349 dwarf_type_encoding_name (unsigned enc)
21350 {
21351   const char *name = get_DW_ATE_name (enc);
21352
21353   if (name == NULL)
21354     return "DW_ATE_<unknown>";
21355
21356   return name;
21357 }
21358
21359 static void
21360 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
21361 {
21362   unsigned int i;
21363
21364   print_spaces (indent, f);
21365   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
21366                       dwarf_tag_name (die->tag), die->abbrev,
21367                       to_underlying (die->sect_off));
21368
21369   if (die->parent != NULL)
21370     {
21371       print_spaces (indent, f);
21372       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
21373                           to_underlying (die->parent->sect_off));
21374     }
21375
21376   print_spaces (indent, f);
21377   fprintf_unfiltered (f, "  has children: %s\n",
21378            dwarf_bool_name (die->child != NULL));
21379
21380   print_spaces (indent, f);
21381   fprintf_unfiltered (f, "  attributes:\n");
21382
21383   for (i = 0; i < die->num_attrs; ++i)
21384     {
21385       print_spaces (indent, f);
21386       fprintf_unfiltered (f, "    %s (%s) ",
21387                dwarf_attr_name (die->attrs[i].name),
21388                dwarf_form_name (die->attrs[i].form));
21389
21390       switch (die->attrs[i].form)
21391         {
21392         case DW_FORM_addr:
21393         case DW_FORM_GNU_addr_index:
21394           fprintf_unfiltered (f, "address: ");
21395           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
21396           break;
21397         case DW_FORM_block2:
21398         case DW_FORM_block4:
21399         case DW_FORM_block:
21400         case DW_FORM_block1:
21401           fprintf_unfiltered (f, "block: size %s",
21402                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21403           break;
21404         case DW_FORM_exprloc:
21405           fprintf_unfiltered (f, "expression: size %s",
21406                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21407           break;
21408         case DW_FORM_data16:
21409           fprintf_unfiltered (f, "constant of 16 bytes");
21410           break;
21411         case DW_FORM_ref_addr:
21412           fprintf_unfiltered (f, "ref address: ");
21413           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21414           break;
21415         case DW_FORM_GNU_ref_alt:
21416           fprintf_unfiltered (f, "alt ref address: ");
21417           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21418           break;
21419         case DW_FORM_ref1:
21420         case DW_FORM_ref2:
21421         case DW_FORM_ref4:
21422         case DW_FORM_ref8:
21423         case DW_FORM_ref_udata:
21424           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
21425                               (long) (DW_UNSND (&die->attrs[i])));
21426           break;
21427         case DW_FORM_data1:
21428         case DW_FORM_data2:
21429         case DW_FORM_data4:
21430         case DW_FORM_data8:
21431         case DW_FORM_udata:
21432         case DW_FORM_sdata:
21433           fprintf_unfiltered (f, "constant: %s",
21434                               pulongest (DW_UNSND (&die->attrs[i])));
21435           break;
21436         case DW_FORM_sec_offset:
21437           fprintf_unfiltered (f, "section offset: %s",
21438                               pulongest (DW_UNSND (&die->attrs[i])));
21439           break;
21440         case DW_FORM_ref_sig8:
21441           fprintf_unfiltered (f, "signature: %s",
21442                               hex_string (DW_SIGNATURE (&die->attrs[i])));
21443           break;
21444         case DW_FORM_string:
21445         case DW_FORM_strp:
21446         case DW_FORM_line_strp:
21447         case DW_FORM_GNU_str_index:
21448         case DW_FORM_GNU_strp_alt:
21449           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
21450                    DW_STRING (&die->attrs[i])
21451                    ? DW_STRING (&die->attrs[i]) : "",
21452                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
21453           break;
21454         case DW_FORM_flag:
21455           if (DW_UNSND (&die->attrs[i]))
21456             fprintf_unfiltered (f, "flag: TRUE");
21457           else
21458             fprintf_unfiltered (f, "flag: FALSE");
21459           break;
21460         case DW_FORM_flag_present:
21461           fprintf_unfiltered (f, "flag: TRUE");
21462           break;
21463         case DW_FORM_indirect:
21464           /* The reader will have reduced the indirect form to
21465              the "base form" so this form should not occur.  */
21466           fprintf_unfiltered (f, 
21467                               "unexpected attribute form: DW_FORM_indirect");
21468           break;
21469         case DW_FORM_implicit_const:
21470           fprintf_unfiltered (f, "constant: %s",
21471                               plongest (DW_SND (&die->attrs[i])));
21472           break;
21473         default:
21474           fprintf_unfiltered (f, "unsupported attribute form: %d.",
21475                    die->attrs[i].form);
21476           break;
21477         }
21478       fprintf_unfiltered (f, "\n");
21479     }
21480 }
21481
21482 static void
21483 dump_die_for_error (struct die_info *die)
21484 {
21485   dump_die_shallow (gdb_stderr, 0, die);
21486 }
21487
21488 static void
21489 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
21490 {
21491   int indent = level * 4;
21492
21493   gdb_assert (die != NULL);
21494
21495   if (level >= max_level)
21496     return;
21497
21498   dump_die_shallow (f, indent, die);
21499
21500   if (die->child != NULL)
21501     {
21502       print_spaces (indent, f);
21503       fprintf_unfiltered (f, "  Children:");
21504       if (level + 1 < max_level)
21505         {
21506           fprintf_unfiltered (f, "\n");
21507           dump_die_1 (f, level + 1, max_level, die->child);
21508         }
21509       else
21510         {
21511           fprintf_unfiltered (f,
21512                               " [not printed, max nesting level reached]\n");
21513         }
21514     }
21515
21516   if (die->sibling != NULL && level > 0)
21517     {
21518       dump_die_1 (f, level, max_level, die->sibling);
21519     }
21520 }
21521
21522 /* This is called from the pdie macro in gdbinit.in.
21523    It's not static so gcc will keep a copy callable from gdb.  */
21524
21525 void
21526 dump_die (struct die_info *die, int max_level)
21527 {
21528   dump_die_1 (gdb_stdlog, 0, max_level, die);
21529 }
21530
21531 static void
21532 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
21533 {
21534   void **slot;
21535
21536   slot = htab_find_slot_with_hash (cu->die_hash, die,
21537                                    to_underlying (die->sect_off),
21538                                    INSERT);
21539
21540   *slot = die;
21541 }
21542
21543 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
21544    required kind.  */
21545
21546 static sect_offset
21547 dwarf2_get_ref_die_offset (const struct attribute *attr)
21548 {
21549   if (attr_form_is_ref (attr))
21550     return (sect_offset) DW_UNSND (attr);
21551
21552   complaint (&symfile_complaints,
21553              _("unsupported die ref attribute form: '%s'"),
21554              dwarf_form_name (attr->form));
21555   return {};
21556 }
21557
21558 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
21559  * the value held by the attribute is not constant.  */
21560
21561 static LONGEST
21562 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
21563 {
21564   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
21565     return DW_SND (attr);
21566   else if (attr->form == DW_FORM_udata
21567            || attr->form == DW_FORM_data1
21568            || attr->form == DW_FORM_data2
21569            || attr->form == DW_FORM_data4
21570            || attr->form == DW_FORM_data8)
21571     return DW_UNSND (attr);
21572   else
21573     {
21574       /* For DW_FORM_data16 see attr_form_is_constant.  */
21575       complaint (&symfile_complaints,
21576                  _("Attribute value is not a constant (%s)"),
21577                  dwarf_form_name (attr->form));
21578       return default_value;
21579     }
21580 }
21581
21582 /* Follow reference or signature attribute ATTR of SRC_DIE.
21583    On entry *REF_CU is the CU of SRC_DIE.
21584    On exit *REF_CU is the CU of the result.  */
21585
21586 static struct die_info *
21587 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
21588                        struct dwarf2_cu **ref_cu)
21589 {
21590   struct die_info *die;
21591
21592   if (attr_form_is_ref (attr))
21593     die = follow_die_ref (src_die, attr, ref_cu);
21594   else if (attr->form == DW_FORM_ref_sig8)
21595     die = follow_die_sig (src_die, attr, ref_cu);
21596   else
21597     {
21598       dump_die_for_error (src_die);
21599       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
21600              objfile_name ((*ref_cu)->objfile));
21601     }
21602
21603   return die;
21604 }
21605
21606 /* Follow reference OFFSET.
21607    On entry *REF_CU is the CU of the source die referencing OFFSET.
21608    On exit *REF_CU is the CU of the result.
21609    Returns NULL if OFFSET is invalid.  */
21610
21611 static struct die_info *
21612 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
21613                    struct dwarf2_cu **ref_cu)
21614 {
21615   struct die_info temp_die;
21616   struct dwarf2_cu *target_cu, *cu = *ref_cu;
21617
21618   gdb_assert (cu->per_cu != NULL);
21619
21620   target_cu = cu;
21621
21622   if (cu->per_cu->is_debug_types)
21623     {
21624       /* .debug_types CUs cannot reference anything outside their CU.
21625          If they need to, they have to reference a signatured type via
21626          DW_FORM_ref_sig8.  */
21627       if (!offset_in_cu_p (&cu->header, sect_off))
21628         return NULL;
21629     }
21630   else if (offset_in_dwz != cu->per_cu->is_dwz
21631            || !offset_in_cu_p (&cu->header, sect_off))
21632     {
21633       struct dwarf2_per_cu_data *per_cu;
21634
21635       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
21636                                                  cu->objfile);
21637
21638       /* If necessary, add it to the queue and load its DIEs.  */
21639       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
21640         load_full_comp_unit (per_cu, cu->language);
21641
21642       target_cu = per_cu->cu;
21643     }
21644   else if (cu->dies == NULL)
21645     {
21646       /* We're loading full DIEs during partial symbol reading.  */
21647       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
21648       load_full_comp_unit (cu->per_cu, language_minimal);
21649     }
21650
21651   *ref_cu = target_cu;
21652   temp_die.sect_off = sect_off;
21653   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
21654                                                   &temp_die,
21655                                                   to_underlying (sect_off));
21656 }
21657
21658 /* Follow reference attribute ATTR of SRC_DIE.
21659    On entry *REF_CU is the CU of SRC_DIE.
21660    On exit *REF_CU is the CU of the result.  */
21661
21662 static struct die_info *
21663 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
21664                 struct dwarf2_cu **ref_cu)
21665 {
21666   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21667   struct dwarf2_cu *cu = *ref_cu;
21668   struct die_info *die;
21669
21670   die = follow_die_offset (sect_off,
21671                            (attr->form == DW_FORM_GNU_ref_alt
21672                             || cu->per_cu->is_dwz),
21673                            ref_cu);
21674   if (!die)
21675     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
21676            "at 0x%x [in module %s]"),
21677            to_underlying (sect_off), to_underlying (src_die->sect_off),
21678            objfile_name (cu->objfile));
21679
21680   return die;
21681 }
21682
21683 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
21684    Returned value is intended for DW_OP_call*.  Returned
21685    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
21686
21687 struct dwarf2_locexpr_baton
21688 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
21689                                struct dwarf2_per_cu_data *per_cu,
21690                                CORE_ADDR (*get_frame_pc) (void *baton),
21691                                void *baton)
21692 {
21693   struct dwarf2_cu *cu;
21694   struct die_info *die;
21695   struct attribute *attr;
21696   struct dwarf2_locexpr_baton retval;
21697
21698   dw2_setup (per_cu->objfile);
21699
21700   if (per_cu->cu == NULL)
21701     load_cu (per_cu);
21702   cu = per_cu->cu;
21703   if (cu == NULL)
21704     {
21705       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21706          Instead just throw an error, not much else we can do.  */
21707       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21708              to_underlying (sect_off), objfile_name (per_cu->objfile));
21709     }
21710
21711   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21712   if (!die)
21713     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21714            to_underlying (sect_off), objfile_name (per_cu->objfile));
21715
21716   attr = dwarf2_attr (die, DW_AT_location, cu);
21717   if (!attr)
21718     {
21719       /* DWARF: "If there is no such attribute, then there is no effect.".
21720          DATA is ignored if SIZE is 0.  */
21721
21722       retval.data = NULL;
21723       retval.size = 0;
21724     }
21725   else if (attr_form_is_section_offset (attr))
21726     {
21727       struct dwarf2_loclist_baton loclist_baton;
21728       CORE_ADDR pc = (*get_frame_pc) (baton);
21729       size_t size;
21730
21731       fill_in_loclist_baton (cu, &loclist_baton, attr);
21732
21733       retval.data = dwarf2_find_location_expression (&loclist_baton,
21734                                                      &size, pc);
21735       retval.size = size;
21736     }
21737   else
21738     {
21739       if (!attr_form_is_block (attr))
21740         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
21741                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
21742                to_underlying (sect_off), objfile_name (per_cu->objfile));
21743
21744       retval.data = DW_BLOCK (attr)->data;
21745       retval.size = DW_BLOCK (attr)->size;
21746     }
21747   retval.per_cu = cu->per_cu;
21748
21749   age_cached_comp_units ();
21750
21751   return retval;
21752 }
21753
21754 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
21755    offset.  */
21756
21757 struct dwarf2_locexpr_baton
21758 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
21759                              struct dwarf2_per_cu_data *per_cu,
21760                              CORE_ADDR (*get_frame_pc) (void *baton),
21761                              void *baton)
21762 {
21763   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
21764
21765   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
21766 }
21767
21768 /* Write a constant of a given type as target-ordered bytes into
21769    OBSTACK.  */
21770
21771 static const gdb_byte *
21772 write_constant_as_bytes (struct obstack *obstack,
21773                          enum bfd_endian byte_order,
21774                          struct type *type,
21775                          ULONGEST value,
21776                          LONGEST *len)
21777 {
21778   gdb_byte *result;
21779
21780   *len = TYPE_LENGTH (type);
21781   result = (gdb_byte *) obstack_alloc (obstack, *len);
21782   store_unsigned_integer (result, *len, byte_order, value);
21783
21784   return result;
21785 }
21786
21787 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
21788    pointer to the constant bytes and set LEN to the length of the
21789    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
21790    does not have a DW_AT_const_value, return NULL.  */
21791
21792 const gdb_byte *
21793 dwarf2_fetch_constant_bytes (sect_offset sect_off,
21794                              struct dwarf2_per_cu_data *per_cu,
21795                              struct obstack *obstack,
21796                              LONGEST *len)
21797 {
21798   struct dwarf2_cu *cu;
21799   struct die_info *die;
21800   struct attribute *attr;
21801   const gdb_byte *result = NULL;
21802   struct type *type;
21803   LONGEST value;
21804   enum bfd_endian byte_order;
21805
21806   dw2_setup (per_cu->objfile);
21807
21808   if (per_cu->cu == NULL)
21809     load_cu (per_cu);
21810   cu = per_cu->cu;
21811   if (cu == NULL)
21812     {
21813       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21814          Instead just throw an error, not much else we can do.  */
21815       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21816              to_underlying (sect_off), objfile_name (per_cu->objfile));
21817     }
21818
21819   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21820   if (!die)
21821     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21822            to_underlying (sect_off), objfile_name (per_cu->objfile));
21823
21824
21825   attr = dwarf2_attr (die, DW_AT_const_value, cu);
21826   if (attr == NULL)
21827     return NULL;
21828
21829   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
21830                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21831
21832   switch (attr->form)
21833     {
21834     case DW_FORM_addr:
21835     case DW_FORM_GNU_addr_index:
21836       {
21837         gdb_byte *tem;
21838
21839         *len = cu->header.addr_size;
21840         tem = (gdb_byte *) obstack_alloc (obstack, *len);
21841         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
21842         result = tem;
21843       }
21844       break;
21845     case DW_FORM_string:
21846     case DW_FORM_strp:
21847     case DW_FORM_GNU_str_index:
21848     case DW_FORM_GNU_strp_alt:
21849       /* DW_STRING is already allocated on the objfile obstack, point
21850          directly to it.  */
21851       result = (const gdb_byte *) DW_STRING (attr);
21852       *len = strlen (DW_STRING (attr));
21853       break;
21854     case DW_FORM_block1:
21855     case DW_FORM_block2:
21856     case DW_FORM_block4:
21857     case DW_FORM_block:
21858     case DW_FORM_exprloc:
21859     case DW_FORM_data16:
21860       result = DW_BLOCK (attr)->data;
21861       *len = DW_BLOCK (attr)->size;
21862       break;
21863
21864       /* The DW_AT_const_value attributes are supposed to carry the
21865          symbol's value "represented as it would be on the target
21866          architecture."  By the time we get here, it's already been
21867          converted to host endianness, so we just need to sign- or
21868          zero-extend it as appropriate.  */
21869     case DW_FORM_data1:
21870       type = die_type (die, cu);
21871       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
21872       if (result == NULL)
21873         result = write_constant_as_bytes (obstack, byte_order,
21874                                           type, value, len);
21875       break;
21876     case DW_FORM_data2:
21877       type = die_type (die, cu);
21878       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
21879       if (result == NULL)
21880         result = write_constant_as_bytes (obstack, byte_order,
21881                                           type, value, len);
21882       break;
21883     case DW_FORM_data4:
21884       type = die_type (die, cu);
21885       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
21886       if (result == NULL)
21887         result = write_constant_as_bytes (obstack, byte_order,
21888                                           type, value, len);
21889       break;
21890     case DW_FORM_data8:
21891       type = die_type (die, cu);
21892       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
21893       if (result == NULL)
21894         result = write_constant_as_bytes (obstack, byte_order,
21895                                           type, value, len);
21896       break;
21897
21898     case DW_FORM_sdata:
21899     case DW_FORM_implicit_const:
21900       type = die_type (die, cu);
21901       result = write_constant_as_bytes (obstack, byte_order,
21902                                         type, DW_SND (attr), len);
21903       break;
21904
21905     case DW_FORM_udata:
21906       type = die_type (die, cu);
21907       result = write_constant_as_bytes (obstack, byte_order,
21908                                         type, DW_UNSND (attr), len);
21909       break;
21910
21911     default:
21912       complaint (&symfile_complaints,
21913                  _("unsupported const value attribute form: '%s'"),
21914                  dwarf_form_name (attr->form));
21915       break;
21916     }
21917
21918   return result;
21919 }
21920
21921 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21922    valid type for this die is found.  */
21923
21924 struct type *
21925 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21926                                 struct dwarf2_per_cu_data *per_cu)
21927 {
21928   struct dwarf2_cu *cu;
21929   struct die_info *die;
21930
21931   dw2_setup (per_cu->objfile);
21932
21933   if (per_cu->cu == NULL)
21934     load_cu (per_cu);
21935   cu = per_cu->cu;
21936   if (!cu)
21937     return NULL;
21938
21939   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21940   if (!die)
21941     return NULL;
21942
21943   return die_type (die, cu);
21944 }
21945
21946 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21947    PER_CU.  */
21948
21949 struct type *
21950 dwarf2_get_die_type (cu_offset die_offset,
21951                      struct dwarf2_per_cu_data *per_cu)
21952 {
21953   dw2_setup (per_cu->objfile);
21954
21955   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21956   return get_die_type_at_offset (die_offset_sect, per_cu);
21957 }
21958
21959 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21960    On entry *REF_CU is the CU of SRC_DIE.
21961    On exit *REF_CU is the CU of the result.
21962    Returns NULL if the referenced DIE isn't found.  */
21963
21964 static struct die_info *
21965 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21966                   struct dwarf2_cu **ref_cu)
21967 {
21968   struct die_info temp_die;
21969   struct dwarf2_cu *sig_cu;
21970   struct die_info *die;
21971
21972   /* While it might be nice to assert sig_type->type == NULL here,
21973      we can get here for DW_AT_imported_declaration where we need
21974      the DIE not the type.  */
21975
21976   /* If necessary, add it to the queue and load its DIEs.  */
21977
21978   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21979     read_signatured_type (sig_type);
21980
21981   sig_cu = sig_type->per_cu.cu;
21982   gdb_assert (sig_cu != NULL);
21983   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21984   temp_die.sect_off = sig_type->type_offset_in_section;
21985   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21986                                                  to_underlying (temp_die.sect_off));
21987   if (die)
21988     {
21989       /* For .gdb_index version 7 keep track of included TUs.
21990          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21991       if (dwarf2_per_objfile->index_table != NULL
21992           && dwarf2_per_objfile->index_table->version <= 7)
21993         {
21994           VEC_safe_push (dwarf2_per_cu_ptr,
21995                          (*ref_cu)->per_cu->imported_symtabs,
21996                          sig_cu->per_cu);
21997         }
21998
21999       *ref_cu = sig_cu;
22000       return die;
22001     }
22002
22003   return NULL;
22004 }
22005
22006 /* Follow signatured type referenced by ATTR in SRC_DIE.
22007    On entry *REF_CU is the CU of SRC_DIE.
22008    On exit *REF_CU is the CU of the result.
22009    The result is the DIE of the type.
22010    If the referenced type cannot be found an error is thrown.  */
22011
22012 static struct die_info *
22013 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
22014                 struct dwarf2_cu **ref_cu)
22015 {
22016   ULONGEST signature = DW_SIGNATURE (attr);
22017   struct signatured_type *sig_type;
22018   struct die_info *die;
22019
22020   gdb_assert (attr->form == DW_FORM_ref_sig8);
22021
22022   sig_type = lookup_signatured_type (*ref_cu, signature);
22023   /* sig_type will be NULL if the signatured type is missing from
22024      the debug info.  */
22025   if (sig_type == NULL)
22026     {
22027       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
22028                " from DIE at 0x%x [in module %s]"),
22029              hex_string (signature), to_underlying (src_die->sect_off),
22030              objfile_name ((*ref_cu)->objfile));
22031     }
22032
22033   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
22034   if (die == NULL)
22035     {
22036       dump_die_for_error (src_die);
22037       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
22038                " from DIE at 0x%x [in module %s]"),
22039              hex_string (signature), to_underlying (src_die->sect_off),
22040              objfile_name ((*ref_cu)->objfile));
22041     }
22042
22043   return die;
22044 }
22045
22046 /* Get the type specified by SIGNATURE referenced in DIE/CU,
22047    reading in and processing the type unit if necessary.  */
22048
22049 static struct type *
22050 get_signatured_type (struct die_info *die, ULONGEST signature,
22051                      struct dwarf2_cu *cu)
22052 {
22053   struct signatured_type *sig_type;
22054   struct dwarf2_cu *type_cu;
22055   struct die_info *type_die;
22056   struct type *type;
22057
22058   sig_type = lookup_signatured_type (cu, signature);
22059   /* sig_type will be NULL if the signatured type is missing from
22060      the debug info.  */
22061   if (sig_type == NULL)
22062     {
22063       complaint (&symfile_complaints,
22064                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
22065                    " from DIE at 0x%x [in module %s]"),
22066                  hex_string (signature), to_underlying (die->sect_off),
22067                  objfile_name (dwarf2_per_objfile->objfile));
22068       return build_error_marker_type (cu, die);
22069     }
22070
22071   /* If we already know the type we're done.  */
22072   if (sig_type->type != NULL)
22073     return sig_type->type;
22074
22075   type_cu = cu;
22076   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
22077   if (type_die != NULL)
22078     {
22079       /* N.B. We need to call get_die_type to ensure only one type for this DIE
22080          is created.  This is important, for example, because for c++ classes
22081          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
22082       type = read_type_die (type_die, type_cu);
22083       if (type == NULL)
22084         {
22085           complaint (&symfile_complaints,
22086                      _("Dwarf Error: Cannot build signatured type %s"
22087                        " referenced from DIE at 0x%x [in module %s]"),
22088                      hex_string (signature), to_underlying (die->sect_off),
22089                      objfile_name (dwarf2_per_objfile->objfile));
22090           type = build_error_marker_type (cu, die);
22091         }
22092     }
22093   else
22094     {
22095       complaint (&symfile_complaints,
22096                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
22097                    " from DIE at 0x%x [in module %s]"),
22098                  hex_string (signature), to_underlying (die->sect_off),
22099                  objfile_name (dwarf2_per_objfile->objfile));
22100       type = build_error_marker_type (cu, die);
22101     }
22102   sig_type->type = type;
22103
22104   return type;
22105 }
22106
22107 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
22108    reading in and processing the type unit if necessary.  */
22109
22110 static struct type *
22111 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
22112                           struct dwarf2_cu *cu) /* ARI: editCase function */
22113 {
22114   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
22115   if (attr_form_is_ref (attr))
22116     {
22117       struct dwarf2_cu *type_cu = cu;
22118       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
22119
22120       return read_type_die (type_die, type_cu);
22121     }
22122   else if (attr->form == DW_FORM_ref_sig8)
22123     {
22124       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
22125     }
22126   else
22127     {
22128       complaint (&symfile_complaints,
22129                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
22130                    " at 0x%x [in module %s]"),
22131                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
22132                  objfile_name (dwarf2_per_objfile->objfile));
22133       return build_error_marker_type (cu, die);
22134     }
22135 }
22136
22137 /* Load the DIEs associated with type unit PER_CU into memory.  */
22138
22139 static void
22140 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
22141 {
22142   struct signatured_type *sig_type;
22143
22144   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
22145   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
22146
22147   /* We have the per_cu, but we need the signatured_type.
22148      Fortunately this is an easy translation.  */
22149   gdb_assert (per_cu->is_debug_types);
22150   sig_type = (struct signatured_type *) per_cu;
22151
22152   gdb_assert (per_cu->cu == NULL);
22153
22154   read_signatured_type (sig_type);
22155
22156   gdb_assert (per_cu->cu != NULL);
22157 }
22158
22159 /* die_reader_func for read_signatured_type.
22160    This is identical to load_full_comp_unit_reader,
22161    but is kept separate for now.  */
22162
22163 static void
22164 read_signatured_type_reader (const struct die_reader_specs *reader,
22165                              const gdb_byte *info_ptr,
22166                              struct die_info *comp_unit_die,
22167                              int has_children,
22168                              void *data)
22169 {
22170   struct dwarf2_cu *cu = reader->cu;
22171
22172   gdb_assert (cu->die_hash == NULL);
22173   cu->die_hash =
22174     htab_create_alloc_ex (cu->header.length / 12,
22175                           die_hash,
22176                           die_eq,
22177                           NULL,
22178                           &cu->comp_unit_obstack,
22179                           hashtab_obstack_allocate,
22180                           dummy_obstack_deallocate);
22181
22182   if (has_children)
22183     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
22184                                                   &info_ptr, comp_unit_die);
22185   cu->dies = comp_unit_die;
22186   /* comp_unit_die is not stored in die_hash, no need.  */
22187
22188   /* We try not to read any attributes in this function, because not
22189      all CUs needed for references have been loaded yet, and symbol
22190      table processing isn't initialized.  But we have to set the CU language,
22191      or we won't be able to build types correctly.
22192      Similarly, if we do not read the producer, we can not apply
22193      producer-specific interpretation.  */
22194   prepare_one_comp_unit (cu, cu->dies, language_minimal);
22195 }
22196
22197 /* Read in a signatured type and build its CU and DIEs.
22198    If the type is a stub for the real type in a DWO file,
22199    read in the real type from the DWO file as well.  */
22200
22201 static void
22202 read_signatured_type (struct signatured_type *sig_type)
22203 {
22204   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
22205
22206   gdb_assert (per_cu->is_debug_types);
22207   gdb_assert (per_cu->cu == NULL);
22208
22209   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
22210                            read_signatured_type_reader, NULL);
22211   sig_type->per_cu.tu_read = 1;
22212 }
22213
22214 /* Decode simple location descriptions.
22215    Given a pointer to a dwarf block that defines a location, compute
22216    the location and return the value.
22217
22218    NOTE drow/2003-11-18: This function is called in two situations
22219    now: for the address of static or global variables (partial symbols
22220    only) and for offsets into structures which are expected to be
22221    (more or less) constant.  The partial symbol case should go away,
22222    and only the constant case should remain.  That will let this
22223    function complain more accurately.  A few special modes are allowed
22224    without complaint for global variables (for instance, global
22225    register values and thread-local values).
22226
22227    A location description containing no operations indicates that the
22228    object is optimized out.  The return value is 0 for that case.
22229    FIXME drow/2003-11-16: No callers check for this case any more; soon all
22230    callers will only want a very basic result and this can become a
22231    complaint.
22232
22233    Note that stack[0] is unused except as a default error return.  */
22234
22235 static CORE_ADDR
22236 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
22237 {
22238   struct objfile *objfile = cu->objfile;
22239   size_t i;
22240   size_t size = blk->size;
22241   const gdb_byte *data = blk->data;
22242   CORE_ADDR stack[64];
22243   int stacki;
22244   unsigned int bytes_read, unsnd;
22245   gdb_byte op;
22246
22247   i = 0;
22248   stacki = 0;
22249   stack[stacki] = 0;
22250   stack[++stacki] = 0;
22251
22252   while (i < size)
22253     {
22254       op = data[i++];
22255       switch (op)
22256         {
22257         case DW_OP_lit0:
22258         case DW_OP_lit1:
22259         case DW_OP_lit2:
22260         case DW_OP_lit3:
22261         case DW_OP_lit4:
22262         case DW_OP_lit5:
22263         case DW_OP_lit6:
22264         case DW_OP_lit7:
22265         case DW_OP_lit8:
22266         case DW_OP_lit9:
22267         case DW_OP_lit10:
22268         case DW_OP_lit11:
22269         case DW_OP_lit12:
22270         case DW_OP_lit13:
22271         case DW_OP_lit14:
22272         case DW_OP_lit15:
22273         case DW_OP_lit16:
22274         case DW_OP_lit17:
22275         case DW_OP_lit18:
22276         case DW_OP_lit19:
22277         case DW_OP_lit20:
22278         case DW_OP_lit21:
22279         case DW_OP_lit22:
22280         case DW_OP_lit23:
22281         case DW_OP_lit24:
22282         case DW_OP_lit25:
22283         case DW_OP_lit26:
22284         case DW_OP_lit27:
22285         case DW_OP_lit28:
22286         case DW_OP_lit29:
22287         case DW_OP_lit30:
22288         case DW_OP_lit31:
22289           stack[++stacki] = op - DW_OP_lit0;
22290           break;
22291
22292         case DW_OP_reg0:
22293         case DW_OP_reg1:
22294         case DW_OP_reg2:
22295         case DW_OP_reg3:
22296         case DW_OP_reg4:
22297         case DW_OP_reg5:
22298         case DW_OP_reg6:
22299         case DW_OP_reg7:
22300         case DW_OP_reg8:
22301         case DW_OP_reg9:
22302         case DW_OP_reg10:
22303         case DW_OP_reg11:
22304         case DW_OP_reg12:
22305         case DW_OP_reg13:
22306         case DW_OP_reg14:
22307         case DW_OP_reg15:
22308         case DW_OP_reg16:
22309         case DW_OP_reg17:
22310         case DW_OP_reg18:
22311         case DW_OP_reg19:
22312         case DW_OP_reg20:
22313         case DW_OP_reg21:
22314         case DW_OP_reg22:
22315         case DW_OP_reg23:
22316         case DW_OP_reg24:
22317         case DW_OP_reg25:
22318         case DW_OP_reg26:
22319         case DW_OP_reg27:
22320         case DW_OP_reg28:
22321         case DW_OP_reg29:
22322         case DW_OP_reg30:
22323         case DW_OP_reg31:
22324           stack[++stacki] = op - DW_OP_reg0;
22325           if (i < size)
22326             dwarf2_complex_location_expr_complaint ();
22327           break;
22328
22329         case DW_OP_regx:
22330           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
22331           i += bytes_read;
22332           stack[++stacki] = unsnd;
22333           if (i < size)
22334             dwarf2_complex_location_expr_complaint ();
22335           break;
22336
22337         case DW_OP_addr:
22338           stack[++stacki] = read_address (objfile->obfd, &data[i],
22339                                           cu, &bytes_read);
22340           i += bytes_read;
22341           break;
22342
22343         case DW_OP_const1u:
22344           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
22345           i += 1;
22346           break;
22347
22348         case DW_OP_const1s:
22349           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
22350           i += 1;
22351           break;
22352
22353         case DW_OP_const2u:
22354           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
22355           i += 2;
22356           break;
22357
22358         case DW_OP_const2s:
22359           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
22360           i += 2;
22361           break;
22362
22363         case DW_OP_const4u:
22364           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
22365           i += 4;
22366           break;
22367
22368         case DW_OP_const4s:
22369           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
22370           i += 4;
22371           break;
22372
22373         case DW_OP_const8u:
22374           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
22375           i += 8;
22376           break;
22377
22378         case DW_OP_constu:
22379           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
22380                                                   &bytes_read);
22381           i += bytes_read;
22382           break;
22383
22384         case DW_OP_consts:
22385           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
22386           i += bytes_read;
22387           break;
22388
22389         case DW_OP_dup:
22390           stack[stacki + 1] = stack[stacki];
22391           stacki++;
22392           break;
22393
22394         case DW_OP_plus:
22395           stack[stacki - 1] += stack[stacki];
22396           stacki--;
22397           break;
22398
22399         case DW_OP_plus_uconst:
22400           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
22401                                                  &bytes_read);
22402           i += bytes_read;
22403           break;
22404
22405         case DW_OP_minus:
22406           stack[stacki - 1] -= stack[stacki];
22407           stacki--;
22408           break;
22409
22410         case DW_OP_deref:
22411           /* If we're not the last op, then we definitely can't encode
22412              this using GDB's address_class enum.  This is valid for partial
22413              global symbols, although the variable's address will be bogus
22414              in the psymtab.  */
22415           if (i < size)
22416             dwarf2_complex_location_expr_complaint ();
22417           break;
22418
22419         case DW_OP_GNU_push_tls_address:
22420         case DW_OP_form_tls_address:
22421           /* The top of the stack has the offset from the beginning
22422              of the thread control block at which the variable is located.  */
22423           /* Nothing should follow this operator, so the top of stack would
22424              be returned.  */
22425           /* This is valid for partial global symbols, but the variable's
22426              address will be bogus in the psymtab.  Make it always at least
22427              non-zero to not look as a variable garbage collected by linker
22428              which have DW_OP_addr 0.  */
22429           if (i < size)
22430             dwarf2_complex_location_expr_complaint ();
22431           stack[stacki]++;
22432           break;
22433
22434         case DW_OP_GNU_uninit:
22435           break;
22436
22437         case DW_OP_GNU_addr_index:
22438         case DW_OP_GNU_const_index:
22439           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
22440                                                          &bytes_read);
22441           i += bytes_read;
22442           break;
22443
22444         default:
22445           {
22446             const char *name = get_DW_OP_name (op);
22447
22448             if (name)
22449               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
22450                          name);
22451             else
22452               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
22453                          op);
22454           }
22455
22456           return (stack[stacki]);
22457         }
22458
22459       /* Enforce maximum stack depth of SIZE-1 to avoid writing
22460          outside of the allocated space.  Also enforce minimum>0.  */
22461       if (stacki >= ARRAY_SIZE (stack) - 1)
22462         {
22463           complaint (&symfile_complaints,
22464                      _("location description stack overflow"));
22465           return 0;
22466         }
22467
22468       if (stacki <= 0)
22469         {
22470           complaint (&symfile_complaints,
22471                      _("location description stack underflow"));
22472           return 0;
22473         }
22474     }
22475   return (stack[stacki]);
22476 }
22477
22478 /* memory allocation interface */
22479
22480 static struct dwarf_block *
22481 dwarf_alloc_block (struct dwarf2_cu *cu)
22482 {
22483   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
22484 }
22485
22486 static struct die_info *
22487 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
22488 {
22489   struct die_info *die;
22490   size_t size = sizeof (struct die_info);
22491
22492   if (num_attrs > 1)
22493     size += (num_attrs - 1) * sizeof (struct attribute);
22494
22495   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
22496   memset (die, 0, sizeof (struct die_info));
22497   return (die);
22498 }
22499
22500 \f
22501 /* Macro support.  */
22502
22503 /* Return file name relative to the compilation directory of file number I in
22504    *LH's file name table.  The result is allocated using xmalloc; the caller is
22505    responsible for freeing it.  */
22506
22507 static char *
22508 file_file_name (int file, struct line_header *lh)
22509 {
22510   /* Is the file number a valid index into the line header's file name
22511      table?  Remember that file numbers start with one, not zero.  */
22512   if (1 <= file && file <= lh->file_names.size ())
22513     {
22514       const file_entry &fe = lh->file_names[file - 1];
22515
22516       if (!IS_ABSOLUTE_PATH (fe.name))
22517         {
22518           const char *dir = fe.include_dir (lh);
22519           if (dir != NULL)
22520             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
22521         }
22522       return xstrdup (fe.name);
22523     }
22524   else
22525     {
22526       /* The compiler produced a bogus file number.  We can at least
22527          record the macro definitions made in the file, even if we
22528          won't be able to find the file by name.  */
22529       char fake_name[80];
22530
22531       xsnprintf (fake_name, sizeof (fake_name),
22532                  "<bad macro file number %d>", file);
22533
22534       complaint (&symfile_complaints,
22535                  _("bad file number in macro information (%d)"),
22536                  file);
22537
22538       return xstrdup (fake_name);
22539     }
22540 }
22541
22542 /* Return the full name of file number I in *LH's file name table.
22543    Use COMP_DIR as the name of the current directory of the
22544    compilation.  The result is allocated using xmalloc; the caller is
22545    responsible for freeing it.  */
22546 static char *
22547 file_full_name (int file, struct line_header *lh, const char *comp_dir)
22548 {
22549   /* Is the file number a valid index into the line header's file name
22550      table?  Remember that file numbers start with one, not zero.  */
22551   if (1 <= file && file <= lh->file_names.size ())
22552     {
22553       char *relative = file_file_name (file, lh);
22554
22555       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
22556         return relative;
22557       return reconcat (relative, comp_dir, SLASH_STRING,
22558                        relative, (char *) NULL);
22559     }
22560   else
22561     return file_file_name (file, lh);
22562 }
22563
22564
22565 static struct macro_source_file *
22566 macro_start_file (int file, int line,
22567                   struct macro_source_file *current_file,
22568                   struct line_header *lh)
22569 {
22570   /* File name relative to the compilation directory of this source file.  */
22571   char *file_name = file_file_name (file, lh);
22572
22573   if (! current_file)
22574     {
22575       /* Note: We don't create a macro table for this compilation unit
22576          at all until we actually get a filename.  */
22577       struct macro_table *macro_table = get_macro_table ();
22578
22579       /* If we have no current file, then this must be the start_file
22580          directive for the compilation unit's main source file.  */
22581       current_file = macro_set_main (macro_table, file_name);
22582       macro_define_special (macro_table);
22583     }
22584   else
22585     current_file = macro_include (current_file, line, file_name);
22586
22587   xfree (file_name);
22588
22589   return current_file;
22590 }
22591
22592 static const char *
22593 consume_improper_spaces (const char *p, const char *body)
22594 {
22595   if (*p == ' ')
22596     {
22597       complaint (&symfile_complaints,
22598                  _("macro definition contains spaces "
22599                    "in formal argument list:\n`%s'"),
22600                  body);
22601
22602       while (*p == ' ')
22603         p++;
22604     }
22605
22606   return p;
22607 }
22608
22609
22610 static void
22611 parse_macro_definition (struct macro_source_file *file, int line,
22612                         const char *body)
22613 {
22614   const char *p;
22615
22616   /* The body string takes one of two forms.  For object-like macro
22617      definitions, it should be:
22618
22619         <macro name> " " <definition>
22620
22621      For function-like macro definitions, it should be:
22622
22623         <macro name> "() " <definition>
22624      or
22625         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
22626
22627      Spaces may appear only where explicitly indicated, and in the
22628      <definition>.
22629
22630      The Dwarf 2 spec says that an object-like macro's name is always
22631      followed by a space, but versions of GCC around March 2002 omit
22632      the space when the macro's definition is the empty string.
22633
22634      The Dwarf 2 spec says that there should be no spaces between the
22635      formal arguments in a function-like macro's formal argument list,
22636      but versions of GCC around March 2002 include spaces after the
22637      commas.  */
22638
22639
22640   /* Find the extent of the macro name.  The macro name is terminated
22641      by either a space or null character (for an object-like macro) or
22642      an opening paren (for a function-like macro).  */
22643   for (p = body; *p; p++)
22644     if (*p == ' ' || *p == '(')
22645       break;
22646
22647   if (*p == ' ' || *p == '\0')
22648     {
22649       /* It's an object-like macro.  */
22650       int name_len = p - body;
22651       char *name = savestring (body, name_len);
22652       const char *replacement;
22653
22654       if (*p == ' ')
22655         replacement = body + name_len + 1;
22656       else
22657         {
22658           dwarf2_macro_malformed_definition_complaint (body);
22659           replacement = body + name_len;
22660         }
22661
22662       macro_define_object (file, line, name, replacement);
22663
22664       xfree (name);
22665     }
22666   else if (*p == '(')
22667     {
22668       /* It's a function-like macro.  */
22669       char *name = savestring (body, p - body);
22670       int argc = 0;
22671       int argv_size = 1;
22672       char **argv = XNEWVEC (char *, argv_size);
22673
22674       p++;
22675
22676       p = consume_improper_spaces (p, body);
22677
22678       /* Parse the formal argument list.  */
22679       while (*p && *p != ')')
22680         {
22681           /* Find the extent of the current argument name.  */
22682           const char *arg_start = p;
22683
22684           while (*p && *p != ',' && *p != ')' && *p != ' ')
22685             p++;
22686
22687           if (! *p || p == arg_start)
22688             dwarf2_macro_malformed_definition_complaint (body);
22689           else
22690             {
22691               /* Make sure argv has room for the new argument.  */
22692               if (argc >= argv_size)
22693                 {
22694                   argv_size *= 2;
22695                   argv = XRESIZEVEC (char *, argv, argv_size);
22696                 }
22697
22698               argv[argc++] = savestring (arg_start, p - arg_start);
22699             }
22700
22701           p = consume_improper_spaces (p, body);
22702
22703           /* Consume the comma, if present.  */
22704           if (*p == ',')
22705             {
22706               p++;
22707
22708               p = consume_improper_spaces (p, body);
22709             }
22710         }
22711
22712       if (*p == ')')
22713         {
22714           p++;
22715
22716           if (*p == ' ')
22717             /* Perfectly formed definition, no complaints.  */
22718             macro_define_function (file, line, name,
22719                                    argc, (const char **) argv,
22720                                    p + 1);
22721           else if (*p == '\0')
22722             {
22723               /* Complain, but do define it.  */
22724               dwarf2_macro_malformed_definition_complaint (body);
22725               macro_define_function (file, line, name,
22726                                      argc, (const char **) argv,
22727                                      p);
22728             }
22729           else
22730             /* Just complain.  */
22731             dwarf2_macro_malformed_definition_complaint (body);
22732         }
22733       else
22734         /* Just complain.  */
22735         dwarf2_macro_malformed_definition_complaint (body);
22736
22737       xfree (name);
22738       {
22739         int i;
22740
22741         for (i = 0; i < argc; i++)
22742           xfree (argv[i]);
22743       }
22744       xfree (argv);
22745     }
22746   else
22747     dwarf2_macro_malformed_definition_complaint (body);
22748 }
22749
22750 /* Skip some bytes from BYTES according to the form given in FORM.
22751    Returns the new pointer.  */
22752
22753 static const gdb_byte *
22754 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
22755                  enum dwarf_form form,
22756                  unsigned int offset_size,
22757                  struct dwarf2_section_info *section)
22758 {
22759   unsigned int bytes_read;
22760
22761   switch (form)
22762     {
22763     case DW_FORM_data1:
22764     case DW_FORM_flag:
22765       ++bytes;
22766       break;
22767
22768     case DW_FORM_data2:
22769       bytes += 2;
22770       break;
22771
22772     case DW_FORM_data4:
22773       bytes += 4;
22774       break;
22775
22776     case DW_FORM_data8:
22777       bytes += 8;
22778       break;
22779
22780     case DW_FORM_data16:
22781       bytes += 16;
22782       break;
22783
22784     case DW_FORM_string:
22785       read_direct_string (abfd, bytes, &bytes_read);
22786       bytes += bytes_read;
22787       break;
22788
22789     case DW_FORM_sec_offset:
22790     case DW_FORM_strp:
22791     case DW_FORM_GNU_strp_alt:
22792       bytes += offset_size;
22793       break;
22794
22795     case DW_FORM_block:
22796       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
22797       bytes += bytes_read;
22798       break;
22799
22800     case DW_FORM_block1:
22801       bytes += 1 + read_1_byte (abfd, bytes);
22802       break;
22803     case DW_FORM_block2:
22804       bytes += 2 + read_2_bytes (abfd, bytes);
22805       break;
22806     case DW_FORM_block4:
22807       bytes += 4 + read_4_bytes (abfd, bytes);
22808       break;
22809
22810     case DW_FORM_sdata:
22811     case DW_FORM_udata:
22812     case DW_FORM_GNU_addr_index:
22813     case DW_FORM_GNU_str_index:
22814       bytes = gdb_skip_leb128 (bytes, buffer_end);
22815       if (bytes == NULL)
22816         {
22817           dwarf2_section_buffer_overflow_complaint (section);
22818           return NULL;
22819         }
22820       break;
22821
22822     case DW_FORM_implicit_const:
22823       break;
22824
22825     default:
22826       {
22827         complaint (&symfile_complaints,
22828                    _("invalid form 0x%x in `%s'"),
22829                    form, get_section_name (section));
22830         return NULL;
22831       }
22832     }
22833
22834   return bytes;
22835 }
22836
22837 /* A helper for dwarf_decode_macros that handles skipping an unknown
22838    opcode.  Returns an updated pointer to the macro data buffer; or,
22839    on error, issues a complaint and returns NULL.  */
22840
22841 static const gdb_byte *
22842 skip_unknown_opcode (unsigned int opcode,
22843                      const gdb_byte **opcode_definitions,
22844                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22845                      bfd *abfd,
22846                      unsigned int offset_size,
22847                      struct dwarf2_section_info *section)
22848 {
22849   unsigned int bytes_read, i;
22850   unsigned long arg;
22851   const gdb_byte *defn;
22852
22853   if (opcode_definitions[opcode] == NULL)
22854     {
22855       complaint (&symfile_complaints,
22856                  _("unrecognized DW_MACFINO opcode 0x%x"),
22857                  opcode);
22858       return NULL;
22859     }
22860
22861   defn = opcode_definitions[opcode];
22862   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
22863   defn += bytes_read;
22864
22865   for (i = 0; i < arg; ++i)
22866     {
22867       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
22868                                  (enum dwarf_form) defn[i], offset_size,
22869                                  section);
22870       if (mac_ptr == NULL)
22871         {
22872           /* skip_form_bytes already issued the complaint.  */
22873           return NULL;
22874         }
22875     }
22876
22877   return mac_ptr;
22878 }
22879
22880 /* A helper function which parses the header of a macro section.
22881    If the macro section is the extended (for now called "GNU") type,
22882    then this updates *OFFSET_SIZE.  Returns a pointer to just after
22883    the header, or issues a complaint and returns NULL on error.  */
22884
22885 static const gdb_byte *
22886 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
22887                           bfd *abfd,
22888                           const gdb_byte *mac_ptr,
22889                           unsigned int *offset_size,
22890                           int section_is_gnu)
22891 {
22892   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
22893
22894   if (section_is_gnu)
22895     {
22896       unsigned int version, flags;
22897
22898       version = read_2_bytes (abfd, mac_ptr);
22899       if (version != 4 && version != 5)
22900         {
22901           complaint (&symfile_complaints,
22902                      _("unrecognized version `%d' in .debug_macro section"),
22903                      version);
22904           return NULL;
22905         }
22906       mac_ptr += 2;
22907
22908       flags = read_1_byte (abfd, mac_ptr);
22909       ++mac_ptr;
22910       *offset_size = (flags & 1) ? 8 : 4;
22911
22912       if ((flags & 2) != 0)
22913         /* We don't need the line table offset.  */
22914         mac_ptr += *offset_size;
22915
22916       /* Vendor opcode descriptions.  */
22917       if ((flags & 4) != 0)
22918         {
22919           unsigned int i, count;
22920
22921           count = read_1_byte (abfd, mac_ptr);
22922           ++mac_ptr;
22923           for (i = 0; i < count; ++i)
22924             {
22925               unsigned int opcode, bytes_read;
22926               unsigned long arg;
22927
22928               opcode = read_1_byte (abfd, mac_ptr);
22929               ++mac_ptr;
22930               opcode_definitions[opcode] = mac_ptr;
22931               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22932               mac_ptr += bytes_read;
22933               mac_ptr += arg;
22934             }
22935         }
22936     }
22937
22938   return mac_ptr;
22939 }
22940
22941 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22942    including DW_MACRO_import.  */
22943
22944 static void
22945 dwarf_decode_macro_bytes (bfd *abfd,
22946                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22947                           struct macro_source_file *current_file,
22948                           struct line_header *lh,
22949                           struct dwarf2_section_info *section,
22950                           int section_is_gnu, int section_is_dwz,
22951                           unsigned int offset_size,
22952                           htab_t include_hash)
22953 {
22954   struct objfile *objfile = dwarf2_per_objfile->objfile;
22955   enum dwarf_macro_record_type macinfo_type;
22956   int at_commandline;
22957   const gdb_byte *opcode_definitions[256];
22958
22959   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22960                                       &offset_size, section_is_gnu);
22961   if (mac_ptr == NULL)
22962     {
22963       /* We already issued a complaint.  */
22964       return;
22965     }
22966
22967   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22968      GDB is still reading the definitions from command line.  First
22969      DW_MACINFO_start_file will need to be ignored as it was already executed
22970      to create CURRENT_FILE for the main source holding also the command line
22971      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22972      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22973
22974   at_commandline = 1;
22975
22976   do
22977     {
22978       /* Do we at least have room for a macinfo type byte?  */
22979       if (mac_ptr >= mac_end)
22980         {
22981           dwarf2_section_buffer_overflow_complaint (section);
22982           break;
22983         }
22984
22985       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22986       mac_ptr++;
22987
22988       /* Note that we rely on the fact that the corresponding GNU and
22989          DWARF constants are the same.  */
22990       switch (macinfo_type)
22991         {
22992           /* A zero macinfo type indicates the end of the macro
22993              information.  */
22994         case 0:
22995           break;
22996
22997         case DW_MACRO_define:
22998         case DW_MACRO_undef:
22999         case DW_MACRO_define_strp:
23000         case DW_MACRO_undef_strp:
23001         case DW_MACRO_define_sup:
23002         case DW_MACRO_undef_sup:
23003           {
23004             unsigned int bytes_read;
23005             int line;
23006             const char *body;
23007             int is_define;
23008
23009             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23010             mac_ptr += bytes_read;
23011
23012             if (macinfo_type == DW_MACRO_define
23013                 || macinfo_type == DW_MACRO_undef)
23014               {
23015                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
23016                 mac_ptr += bytes_read;
23017               }
23018             else
23019               {
23020                 LONGEST str_offset;
23021
23022                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
23023                 mac_ptr += offset_size;
23024
23025                 if (macinfo_type == DW_MACRO_define_sup
23026                     || macinfo_type == DW_MACRO_undef_sup
23027                     || section_is_dwz)
23028                   {
23029                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
23030
23031                     body = read_indirect_string_from_dwz (dwz, str_offset);
23032                   }
23033                 else
23034                   body = read_indirect_string_at_offset (abfd, str_offset);
23035               }
23036
23037             is_define = (macinfo_type == DW_MACRO_define
23038                          || macinfo_type == DW_MACRO_define_strp
23039                          || macinfo_type == DW_MACRO_define_sup);
23040             if (! current_file)
23041               {
23042                 /* DWARF violation as no main source is present.  */
23043                 complaint (&symfile_complaints,
23044                            _("debug info with no main source gives macro %s "
23045                              "on line %d: %s"),
23046                            is_define ? _("definition") : _("undefinition"),
23047                            line, body);
23048                 break;
23049               }
23050             if ((line == 0 && !at_commandline)
23051                 || (line != 0 && at_commandline))
23052               complaint (&symfile_complaints,
23053                          _("debug info gives %s macro %s with %s line %d: %s"),
23054                          at_commandline ? _("command-line") : _("in-file"),
23055                          is_define ? _("definition") : _("undefinition"),
23056                          line == 0 ? _("zero") : _("non-zero"), line, body);
23057
23058             if (is_define)
23059               parse_macro_definition (current_file, line, body);
23060             else
23061               {
23062                 gdb_assert (macinfo_type == DW_MACRO_undef
23063                             || macinfo_type == DW_MACRO_undef_strp
23064                             || macinfo_type == DW_MACRO_undef_sup);
23065                 macro_undef (current_file, line, body);
23066               }
23067           }
23068           break;
23069
23070         case DW_MACRO_start_file:
23071           {
23072             unsigned int bytes_read;
23073             int line, file;
23074
23075             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23076             mac_ptr += bytes_read;
23077             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23078             mac_ptr += bytes_read;
23079
23080             if ((line == 0 && !at_commandline)
23081                 || (line != 0 && at_commandline))
23082               complaint (&symfile_complaints,
23083                          _("debug info gives source %d included "
23084                            "from %s at %s line %d"),
23085                          file, at_commandline ? _("command-line") : _("file"),
23086                          line == 0 ? _("zero") : _("non-zero"), line);
23087
23088             if (at_commandline)
23089               {
23090                 /* This DW_MACRO_start_file was executed in the
23091                    pass one.  */
23092                 at_commandline = 0;
23093               }
23094             else
23095               current_file = macro_start_file (file, line, current_file, lh);
23096           }
23097           break;
23098
23099         case DW_MACRO_end_file:
23100           if (! current_file)
23101             complaint (&symfile_complaints,
23102                        _("macro debug info has an unmatched "
23103                          "`close_file' directive"));
23104           else
23105             {
23106               current_file = current_file->included_by;
23107               if (! current_file)
23108                 {
23109                   enum dwarf_macro_record_type next_type;
23110
23111                   /* GCC circa March 2002 doesn't produce the zero
23112                      type byte marking the end of the compilation
23113                      unit.  Complain if it's not there, but exit no
23114                      matter what.  */
23115
23116                   /* Do we at least have room for a macinfo type byte?  */
23117                   if (mac_ptr >= mac_end)
23118                     {
23119                       dwarf2_section_buffer_overflow_complaint (section);
23120                       return;
23121                     }
23122
23123                   /* We don't increment mac_ptr here, so this is just
23124                      a look-ahead.  */
23125                   next_type
23126                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
23127                                                                   mac_ptr);
23128                   if (next_type != 0)
23129                     complaint (&symfile_complaints,
23130                                _("no terminating 0-type entry for "
23131                                  "macros in `.debug_macinfo' section"));
23132
23133                   return;
23134                 }
23135             }
23136           break;
23137
23138         case DW_MACRO_import:
23139         case DW_MACRO_import_sup:
23140           {
23141             LONGEST offset;
23142             void **slot;
23143             bfd *include_bfd = abfd;
23144             struct dwarf2_section_info *include_section = section;
23145             const gdb_byte *include_mac_end = mac_end;
23146             int is_dwz = section_is_dwz;
23147             const gdb_byte *new_mac_ptr;
23148
23149             offset = read_offset_1 (abfd, mac_ptr, offset_size);
23150             mac_ptr += offset_size;
23151
23152             if (macinfo_type == DW_MACRO_import_sup)
23153               {
23154                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
23155
23156                 dwarf2_read_section (objfile, &dwz->macro);
23157
23158                 include_section = &dwz->macro;
23159                 include_bfd = get_section_bfd_owner (include_section);
23160                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
23161                 is_dwz = 1;
23162               }
23163
23164             new_mac_ptr = include_section->buffer + offset;
23165             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
23166
23167             if (*slot != NULL)
23168               {
23169                 /* This has actually happened; see
23170                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
23171                 complaint (&symfile_complaints,
23172                            _("recursive DW_MACRO_import in "
23173                              ".debug_macro section"));
23174               }
23175             else
23176               {
23177                 *slot = (void *) new_mac_ptr;
23178
23179                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
23180                                           include_mac_end, current_file, lh,
23181                                           section, section_is_gnu, is_dwz,
23182                                           offset_size, include_hash);
23183
23184                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
23185               }
23186           }
23187           break;
23188
23189         case DW_MACINFO_vendor_ext:
23190           if (!section_is_gnu)
23191             {
23192               unsigned int bytes_read;
23193
23194               /* This reads the constant, but since we don't recognize
23195                  any vendor extensions, we ignore it.  */
23196               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23197               mac_ptr += bytes_read;
23198               read_direct_string (abfd, mac_ptr, &bytes_read);
23199               mac_ptr += bytes_read;
23200
23201               /* We don't recognize any vendor extensions.  */
23202               break;
23203             }
23204           /* FALLTHROUGH */
23205
23206         default:
23207           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23208                                          mac_ptr, mac_end, abfd, offset_size,
23209                                          section);
23210           if (mac_ptr == NULL)
23211             return;
23212           break;
23213         }
23214     } while (macinfo_type != 0);
23215 }
23216
23217 static void
23218 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
23219                      int section_is_gnu)
23220 {
23221   struct objfile *objfile = dwarf2_per_objfile->objfile;
23222   struct line_header *lh = cu->line_header;
23223   bfd *abfd;
23224   const gdb_byte *mac_ptr, *mac_end;
23225   struct macro_source_file *current_file = 0;
23226   enum dwarf_macro_record_type macinfo_type;
23227   unsigned int offset_size = cu->header.offset_size;
23228   const gdb_byte *opcode_definitions[256];
23229   void **slot;
23230   struct dwarf2_section_info *section;
23231   const char *section_name;
23232
23233   if (cu->dwo_unit != NULL)
23234     {
23235       if (section_is_gnu)
23236         {
23237           section = &cu->dwo_unit->dwo_file->sections.macro;
23238           section_name = ".debug_macro.dwo";
23239         }
23240       else
23241         {
23242           section = &cu->dwo_unit->dwo_file->sections.macinfo;
23243           section_name = ".debug_macinfo.dwo";
23244         }
23245     }
23246   else
23247     {
23248       if (section_is_gnu)
23249         {
23250           section = &dwarf2_per_objfile->macro;
23251           section_name = ".debug_macro";
23252         }
23253       else
23254         {
23255           section = &dwarf2_per_objfile->macinfo;
23256           section_name = ".debug_macinfo";
23257         }
23258     }
23259
23260   dwarf2_read_section (objfile, section);
23261   if (section->buffer == NULL)
23262     {
23263       complaint (&symfile_complaints, _("missing %s section"), section_name);
23264       return;
23265     }
23266   abfd = get_section_bfd_owner (section);
23267
23268   /* First pass: Find the name of the base filename.
23269      This filename is needed in order to process all macros whose definition
23270      (or undefinition) comes from the command line.  These macros are defined
23271      before the first DW_MACINFO_start_file entry, and yet still need to be
23272      associated to the base file.
23273
23274      To determine the base file name, we scan the macro definitions until we
23275      reach the first DW_MACINFO_start_file entry.  We then initialize
23276      CURRENT_FILE accordingly so that any macro definition found before the
23277      first DW_MACINFO_start_file can still be associated to the base file.  */
23278
23279   mac_ptr = section->buffer + offset;
23280   mac_end = section->buffer + section->size;
23281
23282   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
23283                                       &offset_size, section_is_gnu);
23284   if (mac_ptr == NULL)
23285     {
23286       /* We already issued a complaint.  */
23287       return;
23288     }
23289
23290   do
23291     {
23292       /* Do we at least have room for a macinfo type byte?  */
23293       if (mac_ptr >= mac_end)
23294         {
23295           /* Complaint is printed during the second pass as GDB will probably
23296              stop the first pass earlier upon finding
23297              DW_MACINFO_start_file.  */
23298           break;
23299         }
23300
23301       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
23302       mac_ptr++;
23303
23304       /* Note that we rely on the fact that the corresponding GNU and
23305          DWARF constants are the same.  */
23306       switch (macinfo_type)
23307         {
23308           /* A zero macinfo type indicates the end of the macro
23309              information.  */
23310         case 0:
23311           break;
23312
23313         case DW_MACRO_define:
23314         case DW_MACRO_undef:
23315           /* Only skip the data by MAC_PTR.  */
23316           {
23317             unsigned int bytes_read;
23318
23319             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23320             mac_ptr += bytes_read;
23321             read_direct_string (abfd, mac_ptr, &bytes_read);
23322             mac_ptr += bytes_read;
23323           }
23324           break;
23325
23326         case DW_MACRO_start_file:
23327           {
23328             unsigned int bytes_read;
23329             int line, file;
23330
23331             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23332             mac_ptr += bytes_read;
23333             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23334             mac_ptr += bytes_read;
23335
23336             current_file = macro_start_file (file, line, current_file, lh);
23337           }
23338           break;
23339
23340         case DW_MACRO_end_file:
23341           /* No data to skip by MAC_PTR.  */
23342           break;
23343
23344         case DW_MACRO_define_strp:
23345         case DW_MACRO_undef_strp:
23346         case DW_MACRO_define_sup:
23347         case DW_MACRO_undef_sup:
23348           {
23349             unsigned int bytes_read;
23350
23351             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23352             mac_ptr += bytes_read;
23353             mac_ptr += offset_size;
23354           }
23355           break;
23356
23357         case DW_MACRO_import:
23358         case DW_MACRO_import_sup:
23359           /* Note that, according to the spec, a transparent include
23360              chain cannot call DW_MACRO_start_file.  So, we can just
23361              skip this opcode.  */
23362           mac_ptr += offset_size;
23363           break;
23364
23365         case DW_MACINFO_vendor_ext:
23366           /* Only skip the data by MAC_PTR.  */
23367           if (!section_is_gnu)
23368             {
23369               unsigned int bytes_read;
23370
23371               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23372               mac_ptr += bytes_read;
23373               read_direct_string (abfd, mac_ptr, &bytes_read);
23374               mac_ptr += bytes_read;
23375             }
23376           /* FALLTHROUGH */
23377
23378         default:
23379           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23380                                          mac_ptr, mac_end, abfd, offset_size,
23381                                          section);
23382           if (mac_ptr == NULL)
23383             return;
23384           break;
23385         }
23386     } while (macinfo_type != 0 && current_file == NULL);
23387
23388   /* Second pass: Process all entries.
23389
23390      Use the AT_COMMAND_LINE flag to determine whether we are still processing
23391      command-line macro definitions/undefinitions.  This flag is unset when we
23392      reach the first DW_MACINFO_start_file entry.  */
23393
23394   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
23395                                            htab_eq_pointer,
23396                                            NULL, xcalloc, xfree));
23397   mac_ptr = section->buffer + offset;
23398   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
23399   *slot = (void *) mac_ptr;
23400   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
23401                             current_file, lh, section,
23402                             section_is_gnu, 0, offset_size,
23403                             include_hash.get ());
23404 }
23405
23406 /* Check if the attribute's form is a DW_FORM_block*
23407    if so return true else false.  */
23408
23409 static int
23410 attr_form_is_block (const struct attribute *attr)
23411 {
23412   return (attr == NULL ? 0 :
23413       attr->form == DW_FORM_block1
23414       || attr->form == DW_FORM_block2
23415       || attr->form == DW_FORM_block4
23416       || attr->form == DW_FORM_block
23417       || attr->form == DW_FORM_exprloc);
23418 }
23419
23420 /* Return non-zero if ATTR's value is a section offset --- classes
23421    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
23422    You may use DW_UNSND (attr) to retrieve such offsets.
23423
23424    Section 7.5.4, "Attribute Encodings", explains that no attribute
23425    may have a value that belongs to more than one of these classes; it
23426    would be ambiguous if we did, because we use the same forms for all
23427    of them.  */
23428
23429 static int
23430 attr_form_is_section_offset (const struct attribute *attr)
23431 {
23432   return (attr->form == DW_FORM_data4
23433           || attr->form == DW_FORM_data8
23434           || attr->form == DW_FORM_sec_offset);
23435 }
23436
23437 /* Return non-zero if ATTR's value falls in the 'constant' class, or
23438    zero otherwise.  When this function returns true, you can apply
23439    dwarf2_get_attr_constant_value to it.
23440
23441    However, note that for some attributes you must check
23442    attr_form_is_section_offset before using this test.  DW_FORM_data4
23443    and DW_FORM_data8 are members of both the constant class, and of
23444    the classes that contain offsets into other debug sections
23445    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
23446    that, if an attribute's can be either a constant or one of the
23447    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
23448    taken as section offsets, not constants.
23449
23450    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
23451    cannot handle that.  */
23452
23453 static int
23454 attr_form_is_constant (const struct attribute *attr)
23455 {
23456   switch (attr->form)
23457     {
23458     case DW_FORM_sdata:
23459     case DW_FORM_udata:
23460     case DW_FORM_data1:
23461     case DW_FORM_data2:
23462     case DW_FORM_data4:
23463     case DW_FORM_data8:
23464     case DW_FORM_implicit_const:
23465       return 1;
23466     default:
23467       return 0;
23468     }
23469 }
23470
23471
23472 /* DW_ADDR is always stored already as sect_offset; despite for the forms
23473    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
23474
23475 static int
23476 attr_form_is_ref (const struct attribute *attr)
23477 {
23478   switch (attr->form)
23479     {
23480     case DW_FORM_ref_addr:
23481     case DW_FORM_ref1:
23482     case DW_FORM_ref2:
23483     case DW_FORM_ref4:
23484     case DW_FORM_ref8:
23485     case DW_FORM_ref_udata:
23486     case DW_FORM_GNU_ref_alt:
23487       return 1;
23488     default:
23489       return 0;
23490     }
23491 }
23492
23493 /* Return the .debug_loc section to use for CU.
23494    For DWO files use .debug_loc.dwo.  */
23495
23496 static struct dwarf2_section_info *
23497 cu_debug_loc_section (struct dwarf2_cu *cu)
23498 {
23499   if (cu->dwo_unit)
23500     {
23501       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
23502       
23503       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
23504     }
23505   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
23506                                   : &dwarf2_per_objfile->loc);
23507 }
23508
23509 /* A helper function that fills in a dwarf2_loclist_baton.  */
23510
23511 static void
23512 fill_in_loclist_baton (struct dwarf2_cu *cu,
23513                        struct dwarf2_loclist_baton *baton,
23514                        const struct attribute *attr)
23515 {
23516   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23517
23518   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
23519
23520   baton->per_cu = cu->per_cu;
23521   gdb_assert (baton->per_cu);
23522   /* We don't know how long the location list is, but make sure we
23523      don't run off the edge of the section.  */
23524   baton->size = section->size - DW_UNSND (attr);
23525   baton->data = section->buffer + DW_UNSND (attr);
23526   baton->base_address = cu->base_address;
23527   baton->from_dwo = cu->dwo_unit != NULL;
23528 }
23529
23530 static void
23531 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
23532                              struct dwarf2_cu *cu, int is_block)
23533 {
23534   struct objfile *objfile = dwarf2_per_objfile->objfile;
23535   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23536
23537   if (attr_form_is_section_offset (attr)
23538       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
23539          the section.  If so, fall through to the complaint in the
23540          other branch.  */
23541       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
23542     {
23543       struct dwarf2_loclist_baton *baton;
23544
23545       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
23546
23547       fill_in_loclist_baton (cu, baton, attr);
23548
23549       if (cu->base_known == 0)
23550         complaint (&symfile_complaints,
23551                    _("Location list used without "
23552                      "specifying the CU base address."));
23553
23554       SYMBOL_ACLASS_INDEX (sym) = (is_block
23555                                    ? dwarf2_loclist_block_index
23556                                    : dwarf2_loclist_index);
23557       SYMBOL_LOCATION_BATON (sym) = baton;
23558     }
23559   else
23560     {
23561       struct dwarf2_locexpr_baton *baton;
23562
23563       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
23564       baton->per_cu = cu->per_cu;
23565       gdb_assert (baton->per_cu);
23566
23567       if (attr_form_is_block (attr))
23568         {
23569           /* Note that we're just copying the block's data pointer
23570              here, not the actual data.  We're still pointing into the
23571              info_buffer for SYM's objfile; right now we never release
23572              that buffer, but when we do clean up properly this may
23573              need to change.  */
23574           baton->size = DW_BLOCK (attr)->size;
23575           baton->data = DW_BLOCK (attr)->data;
23576         }
23577       else
23578         {
23579           dwarf2_invalid_attrib_class_complaint ("location description",
23580                                                  SYMBOL_NATURAL_NAME (sym));
23581           baton->size = 0;
23582         }
23583
23584       SYMBOL_ACLASS_INDEX (sym) = (is_block
23585                                    ? dwarf2_locexpr_block_index
23586                                    : dwarf2_locexpr_index);
23587       SYMBOL_LOCATION_BATON (sym) = baton;
23588     }
23589 }
23590
23591 /* Return the OBJFILE associated with the compilation unit CU.  If CU
23592    came from a separate debuginfo file, then the master objfile is
23593    returned.  */
23594
23595 struct objfile *
23596 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
23597 {
23598   struct objfile *objfile = per_cu->objfile;
23599
23600   /* Return the master objfile, so that we can report and look up the
23601      correct file containing this variable.  */
23602   if (objfile->separate_debug_objfile_backlink)
23603     objfile = objfile->separate_debug_objfile_backlink;
23604
23605   return objfile;
23606 }
23607
23608 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
23609    (CU_HEADERP is unused in such case) or prepare a temporary copy at
23610    CU_HEADERP first.  */
23611
23612 static const struct comp_unit_head *
23613 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
23614                        struct dwarf2_per_cu_data *per_cu)
23615 {
23616   const gdb_byte *info_ptr;
23617
23618   if (per_cu->cu)
23619     return &per_cu->cu->header;
23620
23621   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
23622
23623   memset (cu_headerp, 0, sizeof (*cu_headerp));
23624   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
23625                        rcuh_kind::COMPILE);
23626
23627   return cu_headerp;
23628 }
23629
23630 /* Return the address size given in the compilation unit header for CU.  */
23631
23632 int
23633 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
23634 {
23635   struct comp_unit_head cu_header_local;
23636   const struct comp_unit_head *cu_headerp;
23637
23638   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23639
23640   return cu_headerp->addr_size;
23641 }
23642
23643 /* Return the offset size given in the compilation unit header for CU.  */
23644
23645 int
23646 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
23647 {
23648   struct comp_unit_head cu_header_local;
23649   const struct comp_unit_head *cu_headerp;
23650
23651   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23652
23653   return cu_headerp->offset_size;
23654 }
23655
23656 /* See its dwarf2loc.h declaration.  */
23657
23658 int
23659 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
23660 {
23661   struct comp_unit_head cu_header_local;
23662   const struct comp_unit_head *cu_headerp;
23663
23664   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23665
23666   if (cu_headerp->version == 2)
23667     return cu_headerp->addr_size;
23668   else
23669     return cu_headerp->offset_size;
23670 }
23671
23672 /* Return the text offset of the CU.  The returned offset comes from
23673    this CU's objfile.  If this objfile came from a separate debuginfo
23674    file, then the offset may be different from the corresponding
23675    offset in the parent objfile.  */
23676
23677 CORE_ADDR
23678 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
23679 {
23680   struct objfile *objfile = per_cu->objfile;
23681
23682   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23683 }
23684
23685 /* Return DWARF version number of PER_CU.  */
23686
23687 short
23688 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
23689 {
23690   return per_cu->dwarf_version;
23691 }
23692
23693 /* Locate the .debug_info compilation unit from CU's objfile which contains
23694    the DIE at OFFSET.  Raises an error on failure.  */
23695
23696 static struct dwarf2_per_cu_data *
23697 dwarf2_find_containing_comp_unit (sect_offset sect_off,
23698                                   unsigned int offset_in_dwz,
23699                                   struct objfile *objfile)
23700 {
23701   struct dwarf2_per_cu_data *this_cu;
23702   int low, high;
23703   const sect_offset *cu_off;
23704
23705   low = 0;
23706   high = dwarf2_per_objfile->n_comp_units - 1;
23707   while (high > low)
23708     {
23709       struct dwarf2_per_cu_data *mid_cu;
23710       int mid = low + (high - low) / 2;
23711
23712       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
23713       cu_off = &mid_cu->sect_off;
23714       if (mid_cu->is_dwz > offset_in_dwz
23715           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
23716         high = mid;
23717       else
23718         low = mid + 1;
23719     }
23720   gdb_assert (low == high);
23721   this_cu = dwarf2_per_objfile->all_comp_units[low];
23722   cu_off = &this_cu->sect_off;
23723   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
23724     {
23725       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
23726         error (_("Dwarf Error: could not find partial DIE containing "
23727                "offset 0x%x [in module %s]"),
23728                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
23729
23730       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
23731                   <= sect_off);
23732       return dwarf2_per_objfile->all_comp_units[low-1];
23733     }
23734   else
23735     {
23736       this_cu = dwarf2_per_objfile->all_comp_units[low];
23737       if (low == dwarf2_per_objfile->n_comp_units - 1
23738           && sect_off >= this_cu->sect_off + this_cu->length)
23739         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
23740       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
23741       return this_cu;
23742     }
23743 }
23744
23745 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
23746
23747 static void
23748 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
23749 {
23750   memset (cu, 0, sizeof (*cu));
23751   per_cu->cu = cu;
23752   cu->per_cu = per_cu;
23753   cu->objfile = per_cu->objfile;
23754   obstack_init (&cu->comp_unit_obstack);
23755 }
23756
23757 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
23758
23759 static void
23760 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
23761                        enum language pretend_language)
23762 {
23763   struct attribute *attr;
23764
23765   /* Set the language we're debugging.  */
23766   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
23767   if (attr)
23768     set_cu_language (DW_UNSND (attr), cu);
23769   else
23770     {
23771       cu->language = pretend_language;
23772       cu->language_defn = language_def (cu->language);
23773     }
23774
23775   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
23776 }
23777
23778 /* Release one cached compilation unit, CU.  We unlink it from the tree
23779    of compilation units, but we don't remove it from the read_in_chain;
23780    the caller is responsible for that.
23781    NOTE: DATA is a void * because this function is also used as a
23782    cleanup routine.  */
23783
23784 static void
23785 free_heap_comp_unit (void *data)
23786 {
23787   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23788
23789   gdb_assert (cu->per_cu != NULL);
23790   cu->per_cu->cu = NULL;
23791   cu->per_cu = NULL;
23792
23793   obstack_free (&cu->comp_unit_obstack, NULL);
23794
23795   xfree (cu);
23796 }
23797
23798 /* This cleanup function is passed the address of a dwarf2_cu on the stack
23799    when we're finished with it.  We can't free the pointer itself, but be
23800    sure to unlink it from the cache.  Also release any associated storage.  */
23801
23802 static void
23803 free_stack_comp_unit (void *data)
23804 {
23805   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23806
23807   gdb_assert (cu->per_cu != NULL);
23808   cu->per_cu->cu = NULL;
23809   cu->per_cu = NULL;
23810
23811   obstack_free (&cu->comp_unit_obstack, NULL);
23812   cu->partial_dies = NULL;
23813 }
23814
23815 /* Free all cached compilation units.  */
23816
23817 static void
23818 free_cached_comp_units (void *data)
23819 {
23820   dwarf2_per_objfile->free_cached_comp_units ();
23821 }
23822
23823 /* Increase the age counter on each cached compilation unit, and free
23824    any that are too old.  */
23825
23826 static void
23827 age_cached_comp_units (void)
23828 {
23829   struct dwarf2_per_cu_data *per_cu, **last_chain;
23830
23831   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
23832   per_cu = dwarf2_per_objfile->read_in_chain;
23833   while (per_cu != NULL)
23834     {
23835       per_cu->cu->last_used ++;
23836       if (per_cu->cu->last_used <= dwarf_max_cache_age)
23837         dwarf2_mark (per_cu->cu);
23838       per_cu = per_cu->cu->read_in_chain;
23839     }
23840
23841   per_cu = dwarf2_per_objfile->read_in_chain;
23842   last_chain = &dwarf2_per_objfile->read_in_chain;
23843   while (per_cu != NULL)
23844     {
23845       struct dwarf2_per_cu_data *next_cu;
23846
23847       next_cu = per_cu->cu->read_in_chain;
23848
23849       if (!per_cu->cu->mark)
23850         {
23851           free_heap_comp_unit (per_cu->cu);
23852           *last_chain = next_cu;
23853         }
23854       else
23855         last_chain = &per_cu->cu->read_in_chain;
23856
23857       per_cu = next_cu;
23858     }
23859 }
23860
23861 /* Remove a single compilation unit from the cache.  */
23862
23863 static void
23864 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
23865 {
23866   struct dwarf2_per_cu_data *per_cu, **last_chain;
23867
23868   per_cu = dwarf2_per_objfile->read_in_chain;
23869   last_chain = &dwarf2_per_objfile->read_in_chain;
23870   while (per_cu != NULL)
23871     {
23872       struct dwarf2_per_cu_data *next_cu;
23873
23874       next_cu = per_cu->cu->read_in_chain;
23875
23876       if (per_cu == target_per_cu)
23877         {
23878           free_heap_comp_unit (per_cu->cu);
23879           per_cu->cu = NULL;
23880           *last_chain = next_cu;
23881           break;
23882         }
23883       else
23884         last_chain = &per_cu->cu->read_in_chain;
23885
23886       per_cu = next_cu;
23887     }
23888 }
23889
23890 /* Release all extra memory associated with OBJFILE.  */
23891
23892 void
23893 dwarf2_free_objfile (struct objfile *objfile)
23894 {
23895   dwarf2_per_objfile
23896     = (struct dwarf2_per_objfile *) objfile_data (objfile,
23897                                                   dwarf2_objfile_data_key);
23898
23899   if (dwarf2_per_objfile == NULL)
23900     return;
23901
23902   dwarf2_per_objfile->~dwarf2_per_objfile ();
23903 }
23904
23905 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23906    We store these in a hash table separate from the DIEs, and preserve them
23907    when the DIEs are flushed out of cache.
23908
23909    The CU "per_cu" pointer is needed because offset alone is not enough to
23910    uniquely identify the type.  A file may have multiple .debug_types sections,
23911    or the type may come from a DWO file.  Furthermore, while it's more logical
23912    to use per_cu->section+offset, with Fission the section with the data is in
23913    the DWO file but we don't know that section at the point we need it.
23914    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23915    because we can enter the lookup routine, get_die_type_at_offset, from
23916    outside this file, and thus won't necessarily have PER_CU->cu.
23917    Fortunately, PER_CU is stable for the life of the objfile.  */
23918
23919 struct dwarf2_per_cu_offset_and_type
23920 {
23921   const struct dwarf2_per_cu_data *per_cu;
23922   sect_offset sect_off;
23923   struct type *type;
23924 };
23925
23926 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23927
23928 static hashval_t
23929 per_cu_offset_and_type_hash (const void *item)
23930 {
23931   const struct dwarf2_per_cu_offset_and_type *ofs
23932     = (const struct dwarf2_per_cu_offset_and_type *) item;
23933
23934   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23935 }
23936
23937 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23938
23939 static int
23940 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23941 {
23942   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23943     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23944   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23945     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23946
23947   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23948           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23949 }
23950
23951 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23952    table if necessary.  For convenience, return TYPE.
23953
23954    The DIEs reading must have careful ordering to:
23955     * Not cause infite loops trying to read in DIEs as a prerequisite for
23956       reading current DIE.
23957     * Not trying to dereference contents of still incompletely read in types
23958       while reading in other DIEs.
23959     * Enable referencing still incompletely read in types just by a pointer to
23960       the type without accessing its fields.
23961
23962    Therefore caller should follow these rules:
23963      * Try to fetch any prerequisite types we may need to build this DIE type
23964        before building the type and calling set_die_type.
23965      * After building type call set_die_type for current DIE as soon as
23966        possible before fetching more types to complete the current type.
23967      * Make the type as complete as possible before fetching more types.  */
23968
23969 static struct type *
23970 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23971 {
23972   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23973   struct objfile *objfile = cu->objfile;
23974   struct attribute *attr;
23975   struct dynamic_prop prop;
23976
23977   /* For Ada types, make sure that the gnat-specific data is always
23978      initialized (if not already set).  There are a few types where
23979      we should not be doing so, because the type-specific area is
23980      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23981      where the type-specific area is used to store the floatformat).
23982      But this is not a problem, because the gnat-specific information
23983      is actually not needed for these types.  */
23984   if (need_gnat_info (cu)
23985       && TYPE_CODE (type) != TYPE_CODE_FUNC
23986       && TYPE_CODE (type) != TYPE_CODE_FLT
23987       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23988       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23989       && TYPE_CODE (type) != TYPE_CODE_METHOD
23990       && !HAVE_GNAT_AUX_INFO (type))
23991     INIT_GNAT_SPECIFIC (type);
23992
23993   /* Read DW_AT_allocated and set in type.  */
23994   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23995   if (attr_form_is_block (attr))
23996     {
23997       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23998         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23999     }
24000   else if (attr != NULL)
24001     {
24002       complaint (&symfile_complaints,
24003                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
24004                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24005                  to_underlying (die->sect_off));
24006     }
24007
24008   /* Read DW_AT_associated and set in type.  */
24009   attr = dwarf2_attr (die, DW_AT_associated, cu);
24010   if (attr_form_is_block (attr))
24011     {
24012       if (attr_to_dynamic_prop (attr, die, cu, &prop))
24013         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
24014     }
24015   else if (attr != NULL)
24016     {
24017       complaint (&symfile_complaints,
24018                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
24019                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24020                  to_underlying (die->sect_off));
24021     }
24022
24023   /* Read DW_AT_data_location and set in type.  */
24024   attr = dwarf2_attr (die, DW_AT_data_location, cu);
24025   if (attr_to_dynamic_prop (attr, die, cu, &prop))
24026     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
24027
24028   if (dwarf2_per_objfile->die_type_hash == NULL)
24029     {
24030       dwarf2_per_objfile->die_type_hash =
24031         htab_create_alloc_ex (127,
24032                               per_cu_offset_and_type_hash,
24033                               per_cu_offset_and_type_eq,
24034                               NULL,
24035                               &objfile->objfile_obstack,
24036                               hashtab_obstack_allocate,
24037                               dummy_obstack_deallocate);
24038     }
24039
24040   ofs.per_cu = cu->per_cu;
24041   ofs.sect_off = die->sect_off;
24042   ofs.type = type;
24043   slot = (struct dwarf2_per_cu_offset_and_type **)
24044     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
24045   if (*slot)
24046     complaint (&symfile_complaints,
24047                _("A problem internal to GDB: DIE 0x%x has type already set"),
24048                to_underlying (die->sect_off));
24049   *slot = XOBNEW (&objfile->objfile_obstack,
24050                   struct dwarf2_per_cu_offset_and_type);
24051   **slot = ofs;
24052   return type;
24053 }
24054
24055 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
24056    or return NULL if the die does not have a saved type.  */
24057
24058 static struct type *
24059 get_die_type_at_offset (sect_offset sect_off,
24060                         struct dwarf2_per_cu_data *per_cu)
24061 {
24062   struct dwarf2_per_cu_offset_and_type *slot, ofs;
24063
24064   if (dwarf2_per_objfile->die_type_hash == NULL)
24065     return NULL;
24066
24067   ofs.per_cu = per_cu;
24068   ofs.sect_off = sect_off;
24069   slot = ((struct dwarf2_per_cu_offset_and_type *)
24070           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
24071   if (slot)
24072     return slot->type;
24073   else
24074     return NULL;
24075 }
24076
24077 /* Look up the type for DIE in CU in die_type_hash,
24078    or return NULL if DIE does not have a saved type.  */
24079
24080 static struct type *
24081 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
24082 {
24083   return get_die_type_at_offset (die->sect_off, cu->per_cu);
24084 }
24085
24086 /* Add a dependence relationship from CU to REF_PER_CU.  */
24087
24088 static void
24089 dwarf2_add_dependence (struct dwarf2_cu *cu,
24090                        struct dwarf2_per_cu_data *ref_per_cu)
24091 {
24092   void **slot;
24093
24094   if (cu->dependencies == NULL)
24095     cu->dependencies
24096       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
24097                               NULL, &cu->comp_unit_obstack,
24098                               hashtab_obstack_allocate,
24099                               dummy_obstack_deallocate);
24100
24101   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
24102   if (*slot == NULL)
24103     *slot = ref_per_cu;
24104 }
24105
24106 /* Subroutine of dwarf2_mark to pass to htab_traverse.
24107    Set the mark field in every compilation unit in the
24108    cache that we must keep because we are keeping CU.  */
24109
24110 static int
24111 dwarf2_mark_helper (void **slot, void *data)
24112 {
24113   struct dwarf2_per_cu_data *per_cu;
24114
24115   per_cu = (struct dwarf2_per_cu_data *) *slot;
24116
24117   /* cu->dependencies references may not yet have been ever read if QUIT aborts
24118      reading of the chain.  As such dependencies remain valid it is not much
24119      useful to track and undo them during QUIT cleanups.  */
24120   if (per_cu->cu == NULL)
24121     return 1;
24122
24123   if (per_cu->cu->mark)
24124     return 1;
24125   per_cu->cu->mark = 1;
24126
24127   if (per_cu->cu->dependencies != NULL)
24128     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
24129
24130   return 1;
24131 }
24132
24133 /* Set the mark field in CU and in every other compilation unit in the
24134    cache that we must keep because we are keeping CU.  */
24135
24136 static void
24137 dwarf2_mark (struct dwarf2_cu *cu)
24138 {
24139   if (cu->mark)
24140     return;
24141   cu->mark = 1;
24142   if (cu->dependencies != NULL)
24143     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
24144 }
24145
24146 static void
24147 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
24148 {
24149   while (per_cu)
24150     {
24151       per_cu->cu->mark = 0;
24152       per_cu = per_cu->cu->read_in_chain;
24153     }
24154 }
24155
24156 /* Trivial hash function for partial_die_info: the hash value of a DIE
24157    is its offset in .debug_info for this objfile.  */
24158
24159 static hashval_t
24160 partial_die_hash (const void *item)
24161 {
24162   const struct partial_die_info *part_die
24163     = (const struct partial_die_info *) item;
24164
24165   return to_underlying (part_die->sect_off);
24166 }
24167
24168 /* Trivial comparison function for partial_die_info structures: two DIEs
24169    are equal if they have the same offset.  */
24170
24171 static int
24172 partial_die_eq (const void *item_lhs, const void *item_rhs)
24173 {
24174   const struct partial_die_info *part_die_lhs
24175     = (const struct partial_die_info *) item_lhs;
24176   const struct partial_die_info *part_die_rhs
24177     = (const struct partial_die_info *) item_rhs;
24178
24179   return part_die_lhs->sect_off == part_die_rhs->sect_off;
24180 }
24181
24182 static struct cmd_list_element *set_dwarf_cmdlist;
24183 static struct cmd_list_element *show_dwarf_cmdlist;
24184
24185 static void
24186 set_dwarf_cmd (const char *args, int from_tty)
24187 {
24188   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
24189              gdb_stdout);
24190 }
24191
24192 static void
24193 show_dwarf_cmd (const char *args, int from_tty)
24194 {
24195   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
24196 }
24197
24198 /* Free data associated with OBJFILE, if necessary.  */
24199
24200 static void
24201 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
24202 {
24203   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
24204   int ix;
24205
24206   /* Make sure we don't accidentally use dwarf2_per_objfile while
24207      cleaning up.  */
24208   dwarf2_per_objfile = NULL;
24209
24210   for (ix = 0; ix < data->n_comp_units; ++ix)
24211    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
24212
24213   for (ix = 0; ix < data->n_type_units; ++ix)
24214     VEC_free (dwarf2_per_cu_ptr,
24215               data->all_type_units[ix]->per_cu.imported_symtabs);
24216   xfree (data->all_type_units);
24217
24218   VEC_free (dwarf2_section_info_def, data->types);
24219
24220   if (data->dwo_files)
24221     free_dwo_files (data->dwo_files, objfile);
24222   if (data->dwp_file)
24223     gdb_bfd_unref (data->dwp_file->dbfd);
24224
24225   if (data->dwz_file && data->dwz_file->dwz_bfd)
24226     gdb_bfd_unref (data->dwz_file->dwz_bfd);
24227
24228   if (data->index_table != NULL)
24229     data->index_table->~mapped_index ();
24230 }
24231
24232 \f
24233 /* The "save gdb-index" command.  */
24234
24235 /* In-memory buffer to prepare data to be written later to a file.  */
24236 class data_buf
24237 {
24238 public:
24239   /* Copy DATA to the end of the buffer.  */
24240   template<typename T>
24241   void append_data (const T &data)
24242   {
24243     std::copy (reinterpret_cast<const gdb_byte *> (&data),
24244                reinterpret_cast<const gdb_byte *> (&data + 1),
24245                grow (sizeof (data)));
24246   }
24247
24248   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
24249      terminating zero is appended too.  */
24250   void append_cstr0 (const char *cstr)
24251   {
24252     const size_t size = strlen (cstr) + 1;
24253     std::copy (cstr, cstr + size, grow (size));
24254   }
24255
24256   /* Accept a host-format integer in VAL and append it to the buffer
24257      as a target-format integer which is LEN bytes long.  */
24258   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
24259   {
24260     ::store_unsigned_integer (grow (len), len, byte_order, val);
24261   }
24262
24263   /* Return the size of the buffer.  */
24264   size_t size () const
24265   {
24266     return m_vec.size ();
24267   }
24268
24269   /* Write the buffer to FILE.  */
24270   void file_write (FILE *file) const
24271   {
24272     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
24273       error (_("couldn't write data to file"));
24274   }
24275
24276 private:
24277   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
24278      the start of the new block.  */
24279   gdb_byte *grow (size_t size)
24280   {
24281     m_vec.resize (m_vec.size () + size);
24282     return &*m_vec.end () - size;
24283   }
24284
24285   gdb::byte_vector m_vec;
24286 };
24287
24288 /* An entry in the symbol table.  */
24289 struct symtab_index_entry
24290 {
24291   /* The name of the symbol.  */
24292   const char *name;
24293   /* The offset of the name in the constant pool.  */
24294   offset_type index_offset;
24295   /* A sorted vector of the indices of all the CUs that hold an object
24296      of this name.  */
24297   std::vector<offset_type> cu_indices;
24298 };
24299
24300 /* The symbol table.  This is a power-of-2-sized hash table.  */
24301 struct mapped_symtab
24302 {
24303   mapped_symtab ()
24304   {
24305     data.resize (1024);
24306   }
24307
24308   offset_type n_elements = 0;
24309   std::vector<symtab_index_entry> data;
24310 };
24311
24312 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
24313    the slot.
24314    
24315    Function is used only during write_hash_table so no index format backward
24316    compatibility is needed.  */
24317
24318 static symtab_index_entry &
24319 find_slot (struct mapped_symtab *symtab, const char *name)
24320 {
24321   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
24322
24323   index = hash & (symtab->data.size () - 1);
24324   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
24325
24326   for (;;)
24327     {
24328       if (symtab->data[index].name == NULL
24329           || strcmp (name, symtab->data[index].name) == 0)
24330         return symtab->data[index];
24331       index = (index + step) & (symtab->data.size () - 1);
24332     }
24333 }
24334
24335 /* Expand SYMTAB's hash table.  */
24336
24337 static void
24338 hash_expand (struct mapped_symtab *symtab)
24339 {
24340   auto old_entries = std::move (symtab->data);
24341
24342   symtab->data.clear ();
24343   symtab->data.resize (old_entries.size () * 2);
24344
24345   for (auto &it : old_entries)
24346     if (it.name != NULL)
24347       {
24348         auto &ref = find_slot (symtab, it.name);
24349         ref = std::move (it);
24350       }
24351 }
24352
24353 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
24354    CU_INDEX is the index of the CU in which the symbol appears.
24355    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
24356
24357 static void
24358 add_index_entry (struct mapped_symtab *symtab, const char *name,
24359                  int is_static, gdb_index_symbol_kind kind,
24360                  offset_type cu_index)
24361 {
24362   offset_type cu_index_and_attrs;
24363
24364   ++symtab->n_elements;
24365   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
24366     hash_expand (symtab);
24367
24368   symtab_index_entry &slot = find_slot (symtab, name);
24369   if (slot.name == NULL)
24370     {
24371       slot.name = name;
24372       /* index_offset is set later.  */
24373     }
24374
24375   cu_index_and_attrs = 0;
24376   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
24377   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
24378   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
24379
24380   /* We don't want to record an index value twice as we want to avoid the
24381      duplication.
24382      We process all global symbols and then all static symbols
24383      (which would allow us to avoid the duplication by only having to check
24384      the last entry pushed), but a symbol could have multiple kinds in one CU.
24385      To keep things simple we don't worry about the duplication here and
24386      sort and uniqufy the list after we've processed all symbols.  */
24387   slot.cu_indices.push_back (cu_index_and_attrs);
24388 }
24389
24390 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
24391
24392 static void
24393 uniquify_cu_indices (struct mapped_symtab *symtab)
24394 {
24395   for (auto &entry : symtab->data)
24396     {
24397       if (entry.name != NULL && !entry.cu_indices.empty ())
24398         {
24399           auto &cu_indices = entry.cu_indices;
24400           std::sort (cu_indices.begin (), cu_indices.end ());
24401           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
24402           cu_indices.erase (from, cu_indices.end ());
24403         }
24404     }
24405 }
24406
24407 /* A form of 'const char *' suitable for container keys.  Only the
24408    pointer is stored.  The strings themselves are compared, not the
24409    pointers.  */
24410 class c_str_view
24411 {
24412 public:
24413   c_str_view (const char *cstr)
24414     : m_cstr (cstr)
24415   {}
24416
24417   bool operator== (const c_str_view &other) const
24418   {
24419     return strcmp (m_cstr, other.m_cstr) == 0;
24420   }
24421
24422 private:
24423   friend class c_str_view_hasher;
24424   const char *const m_cstr;
24425 };
24426
24427 /* A std::unordered_map::hasher for c_str_view that uses the right
24428    hash function for strings in a mapped index.  */
24429 class c_str_view_hasher
24430 {
24431 public:
24432   size_t operator () (const c_str_view &x) const
24433   {
24434     return mapped_index_string_hash (INT_MAX, x.m_cstr);
24435   }
24436 };
24437
24438 /* A std::unordered_map::hasher for std::vector<>.  */
24439 template<typename T>
24440 class vector_hasher
24441 {
24442 public:
24443   size_t operator () (const std::vector<T> &key) const
24444   {
24445     return iterative_hash (key.data (),
24446                            sizeof (key.front ()) * key.size (), 0);
24447   }
24448 };
24449
24450 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
24451    constant pool entries going into the data buffer CPOOL.  */
24452
24453 static void
24454 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
24455 {
24456   {
24457     /* Elements are sorted vectors of the indices of all the CUs that
24458        hold an object of this name.  */
24459     std::unordered_map<std::vector<offset_type>, offset_type,
24460                        vector_hasher<offset_type>>
24461       symbol_hash_table;
24462
24463     /* We add all the index vectors to the constant pool first, to
24464        ensure alignment is ok.  */
24465     for (symtab_index_entry &entry : symtab->data)
24466       {
24467         if (entry.name == NULL)
24468           continue;
24469         gdb_assert (entry.index_offset == 0);
24470
24471         /* Finding before inserting is faster than always trying to
24472            insert, because inserting always allocates a node, does the
24473            lookup, and then destroys the new node if another node
24474            already had the same key.  C++17 try_emplace will avoid
24475            this.  */
24476         const auto found
24477           = symbol_hash_table.find (entry.cu_indices);
24478         if (found != symbol_hash_table.end ())
24479           {
24480             entry.index_offset = found->second;
24481             continue;
24482           }
24483
24484         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
24485         entry.index_offset = cpool.size ();
24486         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
24487         for (const auto index : entry.cu_indices)
24488           cpool.append_data (MAYBE_SWAP (index));
24489       }
24490   }
24491
24492   /* Now write out the hash table.  */
24493   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
24494   for (const auto &entry : symtab->data)
24495     {
24496       offset_type str_off, vec_off;
24497
24498       if (entry.name != NULL)
24499         {
24500           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
24501           if (insertpair.second)
24502             cpool.append_cstr0 (entry.name);
24503           str_off = insertpair.first->second;
24504           vec_off = entry.index_offset;
24505         }
24506       else
24507         {
24508           /* While 0 is a valid constant pool index, it is not valid
24509              to have 0 for both offsets.  */
24510           str_off = 0;
24511           vec_off = 0;
24512         }
24513
24514       output.append_data (MAYBE_SWAP (str_off));
24515       output.append_data (MAYBE_SWAP (vec_off));
24516     }
24517 }
24518
24519 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
24520
24521 /* Helper struct for building the address table.  */
24522 struct addrmap_index_data
24523 {
24524   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
24525     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
24526   {}
24527
24528   struct objfile *objfile;
24529   data_buf &addr_vec;
24530   psym_index_map &cu_index_htab;
24531
24532   /* Non-zero if the previous_* fields are valid.
24533      We can't write an entry until we see the next entry (since it is only then
24534      that we know the end of the entry).  */
24535   int previous_valid;
24536   /* Index of the CU in the table of all CUs in the index file.  */
24537   unsigned int previous_cu_index;
24538   /* Start address of the CU.  */
24539   CORE_ADDR previous_cu_start;
24540 };
24541
24542 /* Write an address entry to ADDR_VEC.  */
24543
24544 static void
24545 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
24546                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
24547 {
24548   CORE_ADDR baseaddr;
24549
24550   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24551
24552   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
24553   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
24554   addr_vec.append_data (MAYBE_SWAP (cu_index));
24555 }
24556
24557 /* Worker function for traversing an addrmap to build the address table.  */
24558
24559 static int
24560 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
24561 {
24562   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
24563   struct partial_symtab *pst = (struct partial_symtab *) obj;
24564
24565   if (data->previous_valid)
24566     add_address_entry (data->objfile, data->addr_vec,
24567                        data->previous_cu_start, start_addr,
24568                        data->previous_cu_index);
24569
24570   data->previous_cu_start = start_addr;
24571   if (pst != NULL)
24572     {
24573       const auto it = data->cu_index_htab.find (pst);
24574       gdb_assert (it != data->cu_index_htab.cend ());
24575       data->previous_cu_index = it->second;
24576       data->previous_valid = 1;
24577     }
24578   else
24579     data->previous_valid = 0;
24580
24581   return 0;
24582 }
24583
24584 /* Write OBJFILE's address map to ADDR_VEC.
24585    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
24586    in the index file.  */
24587
24588 static void
24589 write_address_map (struct objfile *objfile, data_buf &addr_vec,
24590                    psym_index_map &cu_index_htab)
24591 {
24592   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
24593
24594   /* When writing the address table, we have to cope with the fact that
24595      the addrmap iterator only provides the start of a region; we have to
24596      wait until the next invocation to get the start of the next region.  */
24597
24598   addrmap_index_data.objfile = objfile;
24599   addrmap_index_data.previous_valid = 0;
24600
24601   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
24602                    &addrmap_index_data);
24603
24604   /* It's highly unlikely the last entry (end address = 0xff...ff)
24605      is valid, but we should still handle it.
24606      The end address is recorded as the start of the next region, but that
24607      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
24608      anyway.  */
24609   if (addrmap_index_data.previous_valid)
24610     add_address_entry (objfile, addr_vec,
24611                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
24612                        addrmap_index_data.previous_cu_index);
24613 }
24614
24615 /* Return the symbol kind of PSYM.  */
24616
24617 static gdb_index_symbol_kind
24618 symbol_kind (struct partial_symbol *psym)
24619 {
24620   domain_enum domain = PSYMBOL_DOMAIN (psym);
24621   enum address_class aclass = PSYMBOL_CLASS (psym);
24622
24623   switch (domain)
24624     {
24625     case VAR_DOMAIN:
24626       switch (aclass)
24627         {
24628         case LOC_BLOCK:
24629           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
24630         case LOC_TYPEDEF:
24631           return GDB_INDEX_SYMBOL_KIND_TYPE;
24632         case LOC_COMPUTED:
24633         case LOC_CONST_BYTES:
24634         case LOC_OPTIMIZED_OUT:
24635         case LOC_STATIC:
24636           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24637         case LOC_CONST:
24638           /* Note: It's currently impossible to recognize psyms as enum values
24639              short of reading the type info.  For now punt.  */
24640           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24641         default:
24642           /* There are other LOC_FOO values that one might want to classify
24643              as variables, but dwarf2read.c doesn't currently use them.  */
24644           return GDB_INDEX_SYMBOL_KIND_OTHER;
24645         }
24646     case STRUCT_DOMAIN:
24647       return GDB_INDEX_SYMBOL_KIND_TYPE;
24648     default:
24649       return GDB_INDEX_SYMBOL_KIND_OTHER;
24650     }
24651 }
24652
24653 /* Add a list of partial symbols to SYMTAB.  */
24654
24655 static void
24656 write_psymbols (struct mapped_symtab *symtab,
24657                 std::unordered_set<partial_symbol *> &psyms_seen,
24658                 struct partial_symbol **psymp,
24659                 int count,
24660                 offset_type cu_index,
24661                 int is_static)
24662 {
24663   for (; count-- > 0; ++psymp)
24664     {
24665       struct partial_symbol *psym = *psymp;
24666
24667       if (SYMBOL_LANGUAGE (psym) == language_ada)
24668         error (_("Ada is not currently supported by the index"));
24669
24670       /* Only add a given psymbol once.  */
24671       if (psyms_seen.insert (psym).second)
24672         {
24673           gdb_index_symbol_kind kind = symbol_kind (psym);
24674
24675           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
24676                            is_static, kind, cu_index);
24677         }
24678     }
24679 }
24680
24681 /* A helper struct used when iterating over debug_types.  */
24682 struct signatured_type_index_data
24683 {
24684   signatured_type_index_data (data_buf &types_list_,
24685                               std::unordered_set<partial_symbol *> &psyms_seen_)
24686     : types_list (types_list_), psyms_seen (psyms_seen_)
24687   {}
24688
24689   struct objfile *objfile;
24690   struct mapped_symtab *symtab;
24691   data_buf &types_list;
24692   std::unordered_set<partial_symbol *> &psyms_seen;
24693   int cu_index;
24694 };
24695
24696 /* A helper function that writes a single signatured_type to an
24697    obstack.  */
24698
24699 static int
24700 write_one_signatured_type (void **slot, void *d)
24701 {
24702   struct signatured_type_index_data *info
24703     = (struct signatured_type_index_data *) d;
24704   struct signatured_type *entry = (struct signatured_type *) *slot;
24705   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
24706
24707   write_psymbols (info->symtab,
24708                   info->psyms_seen,
24709                   &info->objfile->global_psymbols[psymtab->globals_offset],
24710                   psymtab->n_global_syms, info->cu_index,
24711                   0);
24712   write_psymbols (info->symtab,
24713                   info->psyms_seen,
24714                   &info->objfile->static_psymbols[psymtab->statics_offset],
24715                   psymtab->n_static_syms, info->cu_index,
24716                   1);
24717
24718   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24719                                 to_underlying (entry->per_cu.sect_off));
24720   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24721                                 to_underlying (entry->type_offset_in_tu));
24722   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
24723
24724   ++info->cu_index;
24725
24726   return 1;
24727 }
24728
24729 /* Recurse into all "included" dependencies and count their symbols as
24730    if they appeared in this psymtab.  */
24731
24732 static void
24733 recursively_count_psymbols (struct partial_symtab *psymtab,
24734                             size_t &psyms_seen)
24735 {
24736   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
24737     if (psymtab->dependencies[i]->user != NULL)
24738       recursively_count_psymbols (psymtab->dependencies[i],
24739                                   psyms_seen);
24740
24741   psyms_seen += psymtab->n_global_syms;
24742   psyms_seen += psymtab->n_static_syms;
24743 }
24744
24745 /* Recurse into all "included" dependencies and write their symbols as
24746    if they appeared in this psymtab.  */
24747
24748 static void
24749 recursively_write_psymbols (struct objfile *objfile,
24750                             struct partial_symtab *psymtab,
24751                             struct mapped_symtab *symtab,
24752                             std::unordered_set<partial_symbol *> &psyms_seen,
24753                             offset_type cu_index)
24754 {
24755   int i;
24756
24757   for (i = 0; i < psymtab->number_of_dependencies; ++i)
24758     if (psymtab->dependencies[i]->user != NULL)
24759       recursively_write_psymbols (objfile, psymtab->dependencies[i],
24760                                   symtab, psyms_seen, cu_index);
24761
24762   write_psymbols (symtab,
24763                   psyms_seen,
24764                   &objfile->global_psymbols[psymtab->globals_offset],
24765                   psymtab->n_global_syms, cu_index,
24766                   0);
24767   write_psymbols (symtab,
24768                   psyms_seen,
24769                   &objfile->static_psymbols[psymtab->statics_offset],
24770                   psymtab->n_static_syms, cu_index,
24771                   1);
24772 }
24773
24774 /* Create an index file for OBJFILE in the directory DIR.  */
24775
24776 static void
24777 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
24778 {
24779   if (dwarf2_per_objfile->using_index)
24780     error (_("Cannot use an index to create the index"));
24781
24782   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
24783     error (_("Cannot make an index when the file has multiple .debug_types sections"));
24784
24785   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
24786     return;
24787
24788   struct stat st;
24789   if (stat (objfile_name (objfile), &st) < 0)
24790     perror_with_name (objfile_name (objfile));
24791
24792   std::string filename (std::string (dir) + SLASH_STRING
24793                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
24794
24795   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
24796   if (!out_file)
24797     error (_("Can't open `%s' for writing"), filename.c_str ());
24798
24799   /* Order matters here; we want FILE to be closed before FILENAME is
24800      unlinked, because on MS-Windows one cannot delete a file that is
24801      still open.  (Don't call anything here that might throw until
24802      file_closer is created.)  */
24803   gdb::unlinker unlink_file (filename.c_str ());
24804   gdb_file_up close_out_file (out_file);
24805
24806   mapped_symtab symtab;
24807   data_buf cu_list;
24808
24809   /* While we're scanning CU's create a table that maps a psymtab pointer
24810      (which is what addrmap records) to its index (which is what is recorded
24811      in the index file).  This will later be needed to write the address
24812      table.  */
24813   psym_index_map cu_index_htab;
24814   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
24815
24816   /* The CU list is already sorted, so we don't need to do additional
24817      work here.  Also, the debug_types entries do not appear in
24818      all_comp_units, but only in their own hash table.  */
24819
24820   /* The psyms_seen set is potentially going to be largish (~40k
24821      elements when indexing a -g3 build of GDB itself).  Estimate the
24822      number of elements in order to avoid too many rehashes, which
24823      require rebuilding buckets and thus many trips to
24824      malloc/free.  */
24825   size_t psyms_count = 0;
24826   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24827     {
24828       struct dwarf2_per_cu_data *per_cu
24829         = dwarf2_per_objfile->all_comp_units[i];
24830       struct partial_symtab *psymtab = per_cu->v.psymtab;
24831
24832       if (psymtab != NULL && psymtab->user == NULL)
24833         recursively_count_psymbols (psymtab, psyms_count);
24834     }
24835   /* Generating an index for gdb itself shows a ratio of
24836      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
24837   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
24838   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24839     {
24840       struct dwarf2_per_cu_data *per_cu
24841         = dwarf2_per_objfile->all_comp_units[i];
24842       struct partial_symtab *psymtab = per_cu->v.psymtab;
24843
24844       /* CU of a shared file from 'dwz -m' may be unused by this main file.
24845          It may be referenced from a local scope but in such case it does not
24846          need to be present in .gdb_index.  */
24847       if (psymtab == NULL)
24848         continue;
24849
24850       if (psymtab->user == NULL)
24851         recursively_write_psymbols (objfile, psymtab, &symtab,
24852                                     psyms_seen, i);
24853
24854       const auto insertpair = cu_index_htab.emplace (psymtab, i);
24855       gdb_assert (insertpair.second);
24856
24857       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
24858                            to_underlying (per_cu->sect_off));
24859       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
24860     }
24861
24862   /* Dump the address map.  */
24863   data_buf addr_vec;
24864   write_address_map (objfile, addr_vec, cu_index_htab);
24865
24866   /* Write out the .debug_type entries, if any.  */
24867   data_buf types_cu_list;
24868   if (dwarf2_per_objfile->signatured_types)
24869     {
24870       signatured_type_index_data sig_data (types_cu_list,
24871                                            psyms_seen);
24872
24873       sig_data.objfile = objfile;
24874       sig_data.symtab = &symtab;
24875       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
24876       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
24877                               write_one_signatured_type, &sig_data);
24878     }
24879
24880   /* Now that we've processed all symbols we can shrink their cu_indices
24881      lists.  */
24882   uniquify_cu_indices (&symtab);
24883
24884   data_buf symtab_vec, constant_pool;
24885   write_hash_table (&symtab, symtab_vec, constant_pool);
24886
24887   data_buf contents;
24888   const offset_type size_of_contents = 6 * sizeof (offset_type);
24889   offset_type total_len = size_of_contents;
24890
24891   /* The version number.  */
24892   contents.append_data (MAYBE_SWAP (8));
24893
24894   /* The offset of the CU list from the start of the file.  */
24895   contents.append_data (MAYBE_SWAP (total_len));
24896   total_len += cu_list.size ();
24897
24898   /* The offset of the types CU list from the start of the file.  */
24899   contents.append_data (MAYBE_SWAP (total_len));
24900   total_len += types_cu_list.size ();
24901
24902   /* The offset of the address table from the start of the file.  */
24903   contents.append_data (MAYBE_SWAP (total_len));
24904   total_len += addr_vec.size ();
24905
24906   /* The offset of the symbol table from the start of the file.  */
24907   contents.append_data (MAYBE_SWAP (total_len));
24908   total_len += symtab_vec.size ();
24909
24910   /* The offset of the constant pool from the start of the file.  */
24911   contents.append_data (MAYBE_SWAP (total_len));
24912   total_len += constant_pool.size ();
24913
24914   gdb_assert (contents.size () == size_of_contents);
24915
24916   contents.file_write (out_file);
24917   cu_list.file_write (out_file);
24918   types_cu_list.file_write (out_file);
24919   addr_vec.file_write (out_file);
24920   symtab_vec.file_write (out_file);
24921   constant_pool.file_write (out_file);
24922
24923   /* We want to keep the file.  */
24924   unlink_file.keep ();
24925 }
24926
24927 /* Implementation of the `save gdb-index' command.
24928    
24929    Note that the file format used by this command is documented in the
24930    GDB manual.  Any changes here must be documented there.  */
24931
24932 static void
24933 save_gdb_index_command (const char *arg, int from_tty)
24934 {
24935   struct objfile *objfile;
24936
24937   if (!arg || !*arg)
24938     error (_("usage: save gdb-index DIRECTORY"));
24939
24940   ALL_OBJFILES (objfile)
24941   {
24942     struct stat st;
24943
24944     /* If the objfile does not correspond to an actual file, skip it.  */
24945     if (stat (objfile_name (objfile), &st) < 0)
24946       continue;
24947
24948     dwarf2_per_objfile
24949       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24950                                                     dwarf2_objfile_data_key);
24951     if (dwarf2_per_objfile)
24952       {
24953
24954         TRY
24955           {
24956             write_psymtabs_to_index (objfile, arg);
24957           }
24958         CATCH (except, RETURN_MASK_ERROR)
24959           {
24960             exception_fprintf (gdb_stderr, except,
24961                                _("Error while writing index for `%s': "),
24962                                objfile_name (objfile));
24963           }
24964         END_CATCH
24965       }
24966   }
24967 }
24968
24969 \f
24970
24971 int dwarf_always_disassemble;
24972
24973 static void
24974 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24975                                struct cmd_list_element *c, const char *value)
24976 {
24977   fprintf_filtered (file,
24978                     _("Whether to always disassemble "
24979                       "DWARF expressions is %s.\n"),
24980                     value);
24981 }
24982
24983 static void
24984 show_check_physname (struct ui_file *file, int from_tty,
24985                      struct cmd_list_element *c, const char *value)
24986 {
24987   fprintf_filtered (file,
24988                     _("Whether to check \"physname\" is %s.\n"),
24989                     value);
24990 }
24991
24992 void
24993 _initialize_dwarf2_read (void)
24994 {
24995   struct cmd_list_element *c;
24996
24997   dwarf2_objfile_data_key
24998     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24999
25000   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25001 Set DWARF specific variables.\n\
25002 Configure DWARF variables such as the cache size"),
25003                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25004                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25005
25006   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25007 Show DWARF specific variables\n\
25008 Show DWARF variables such as the cache size"),
25009                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25010                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25011
25012   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25013                             &dwarf_max_cache_age, _("\
25014 Set the upper bound on the age of cached DWARF compilation units."), _("\
25015 Show the upper bound on the age of cached DWARF compilation units."), _("\
25016 A higher limit means that cached compilation units will be stored\n\
25017 in memory longer, and more total memory will be used.  Zero disables\n\
25018 caching, which can slow down startup."),
25019                             NULL,
25020                             show_dwarf_max_cache_age,
25021                             &set_dwarf_cmdlist,
25022                             &show_dwarf_cmdlist);
25023
25024   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25025                            &dwarf_always_disassemble, _("\
25026 Set whether `info address' always disassembles DWARF expressions."), _("\
25027 Show whether `info address' always disassembles DWARF expressions."), _("\
25028 When enabled, DWARF expressions are always printed in an assembly-like\n\
25029 syntax.  When disabled, expressions will be printed in a more\n\
25030 conversational style, when possible."),
25031                            NULL,
25032                            show_dwarf_always_disassemble,
25033                            &set_dwarf_cmdlist,
25034                            &show_dwarf_cmdlist);
25035
25036   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25037 Set debugging of the DWARF reader."), _("\
25038 Show debugging of the DWARF reader."), _("\
25039 When enabled (non-zero), debugging messages are printed during DWARF\n\
25040 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25041 information.  A value greater than 1 provides more verbose information."),
25042                             NULL,
25043                             NULL,
25044                             &setdebuglist, &showdebuglist);
25045
25046   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25047 Set debugging of the DWARF DIE reader."), _("\
25048 Show debugging of the DWARF DIE reader."), _("\
25049 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25050 The value is the maximum depth to print."),
25051                              NULL,
25052                              NULL,
25053                              &setdebuglist, &showdebuglist);
25054
25055   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25056 Set debugging of the dwarf line reader."), _("\
25057 Show debugging of the dwarf line reader."), _("\
25058 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25059 A value of 1 (one) provides basic information.\n\
25060 A value greater than 1 provides more verbose information."),
25061                              NULL,
25062                              NULL,
25063                              &setdebuglist, &showdebuglist);
25064
25065   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25066 Set cross-checking of \"physname\" code against demangler."), _("\
25067 Show cross-checking of \"physname\" code against demangler."), _("\
25068 When enabled, GDB's internal \"physname\" code is checked against\n\
25069 the demangler."),
25070                            NULL, show_check_physname,
25071                            &setdebuglist, &showdebuglist);
25072
25073   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25074                            no_class, &use_deprecated_index_sections, _("\
25075 Set whether to use deprecated gdb_index sections."), _("\
25076 Show whether to use deprecated gdb_index sections."), _("\
25077 When enabled, deprecated .gdb_index sections are used anyway.\n\
25078 Normally they are ignored either because of a missing feature or\n\
25079 performance issue.\n\
25080 Warning: This option must be enabled before gdb reads the file."),
25081                            NULL,
25082                            NULL,
25083                            &setlist, &showlist);
25084
25085   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
25086                _("\
25087 Save a gdb-index file.\n\
25088 Usage: save gdb-index DIRECTORY"),
25089                &save_cmdlist);
25090   set_cmd_completer (c, filename_completer);
25091
25092   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25093                                                         &dwarf2_locexpr_funcs);
25094   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25095                                                         &dwarf2_loclist_funcs);
25096
25097   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25098                                         &dwarf2_block_frame_base_locexpr_funcs);
25099   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25100                                         &dwarf2_block_frame_base_loclist_funcs);
25101
25102 #if GDB_SELF_TEST
25103   selftests::register_test ("dw2_expand_symtabs_matching",
25104                             selftests::dw2_expand_symtabs_matching::run_test);
25105 #endif
25106 }