Remove symbolp vector
[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   /* Convenience method to get at the name of the symbol at IDX in the
260      symbol table.  */
261   const char *symbol_name_at (offset_type idx) const
262   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx]); }
263 };
264
265 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
266 DEF_VEC_P (dwarf2_per_cu_ptr);
267
268 struct tu_stats
269 {
270   int nr_uniq_abbrev_tables;
271   int nr_symtabs;
272   int nr_symtab_sharers;
273   int nr_stmt_less_type_units;
274   int nr_all_type_units_reallocs;
275 };
276
277 /* Collection of data recorded per objfile.
278    This hangs off of dwarf2_objfile_data_key.  */
279
280 struct dwarf2_per_objfile
281 {
282   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
283      dwarf2 section names, or is NULL if the standard ELF names are
284      used.  */
285   dwarf2_per_objfile (struct objfile *objfile,
286                       const dwarf2_debug_sections *names);
287
288   ~dwarf2_per_objfile ();
289
290   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
291
292   /* Free all cached compilation units.  */
293   void free_cached_comp_units ();
294 private:
295   /* This function is mapped across the sections and remembers the
296      offset and size of each of the debugging sections we are
297      interested in.  */
298   void locate_sections (bfd *abfd, asection *sectp,
299                         const dwarf2_debug_sections &names);
300
301 public:
302   dwarf2_section_info info {};
303   dwarf2_section_info abbrev {};
304   dwarf2_section_info line {};
305   dwarf2_section_info loc {};
306   dwarf2_section_info loclists {};
307   dwarf2_section_info macinfo {};
308   dwarf2_section_info macro {};
309   dwarf2_section_info str {};
310   dwarf2_section_info line_str {};
311   dwarf2_section_info ranges {};
312   dwarf2_section_info rnglists {};
313   dwarf2_section_info addr {};
314   dwarf2_section_info frame {};
315   dwarf2_section_info eh_frame {};
316   dwarf2_section_info gdb_index {};
317
318   VEC (dwarf2_section_info_def) *types = NULL;
319
320   /* Back link.  */
321   struct objfile *objfile = NULL;
322
323   /* Table of all the compilation units.  This is used to locate
324      the target compilation unit of a particular reference.  */
325   struct dwarf2_per_cu_data **all_comp_units = NULL;
326
327   /* The number of compilation units in ALL_COMP_UNITS.  */
328   int n_comp_units = 0;
329
330   /* The number of .debug_types-related CUs.  */
331   int n_type_units = 0;
332
333   /* The number of elements allocated in all_type_units.
334      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
335   int n_allocated_type_units = 0;
336
337   /* The .debug_types-related CUs (TUs).
338      This is stored in malloc space because we may realloc it.  */
339   struct signatured_type **all_type_units = NULL;
340
341   /* Table of struct type_unit_group objects.
342      The hash key is the DW_AT_stmt_list value.  */
343   htab_t type_unit_groups {};
344
345   /* A table mapping .debug_types signatures to its signatured_type entry.
346      This is NULL if the .debug_types section hasn't been read in yet.  */
347   htab_t signatured_types {};
348
349   /* Type unit statistics, to see how well the scaling improvements
350      are doing.  */
351   struct tu_stats tu_stats {};
352
353   /* A chain of compilation units that are currently read in, so that
354      they can be freed later.  */
355   dwarf2_per_cu_data *read_in_chain = NULL;
356
357   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
358      This is NULL if the table hasn't been allocated yet.  */
359   htab_t dwo_files {};
360
361   /* True if we've checked for whether there is a DWP file.  */
362   bool dwp_checked = false;
363
364   /* The DWP file if there is one, or NULL.  */
365   struct dwp_file *dwp_file = NULL;
366
367   /* The shared '.dwz' file, if one exists.  This is used when the
368      original data was compressed using 'dwz -m'.  */
369   struct dwz_file *dwz_file = NULL;
370
371   /* A flag indicating whether this objfile has a section loaded at a
372      VMA of 0.  */
373   bool has_section_at_zero = false;
374
375   /* True if we are using the mapped index,
376      or we are faking it for OBJF_READNOW's sake.  */
377   bool using_index = false;
378
379   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
380   mapped_index *index_table = NULL;
381
382   /* When using index_table, this keeps track of all quick_file_names entries.
383      TUs typically share line table entries with a CU, so we maintain a
384      separate table of all line table entries to support the sharing.
385      Note that while there can be way more TUs than CUs, we've already
386      sorted all the TUs into "type unit groups", grouped by their
387      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
388      CU and its associated TU group if there is one.  */
389   htab_t quick_file_names_table {};
390
391   /* Set during partial symbol reading, to prevent queueing of full
392      symbols.  */
393   bool reading_partial_symbols = false;
394
395   /* Table mapping type DIEs to their struct type *.
396      This is NULL if not allocated yet.
397      The mapping is done via (CU/TU + DIE offset) -> type.  */
398   htab_t die_type_hash {};
399
400   /* The CUs we recently read.  */
401   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
402
403   /* Table containing line_header indexed by offset and offset_in_dwz.  */
404   htab_t line_header_hash {};
405
406   /* Table containing all filenames.  This is an optional because the
407      table is lazily constructed on first access.  */
408   gdb::optional<filename_seen_cache> filenames_cache;
409 };
410
411 static struct dwarf2_per_objfile *dwarf2_per_objfile;
412
413 /* Default names of the debugging sections.  */
414
415 /* Note that if the debugging section has been compressed, it might
416    have a name like .zdebug_info.  */
417
418 static const struct dwarf2_debug_sections dwarf2_elf_names =
419 {
420   { ".debug_info", ".zdebug_info" },
421   { ".debug_abbrev", ".zdebug_abbrev" },
422   { ".debug_line", ".zdebug_line" },
423   { ".debug_loc", ".zdebug_loc" },
424   { ".debug_loclists", ".zdebug_loclists" },
425   { ".debug_macinfo", ".zdebug_macinfo" },
426   { ".debug_macro", ".zdebug_macro" },
427   { ".debug_str", ".zdebug_str" },
428   { ".debug_line_str", ".zdebug_line_str" },
429   { ".debug_ranges", ".zdebug_ranges" },
430   { ".debug_rnglists", ".zdebug_rnglists" },
431   { ".debug_types", ".zdebug_types" },
432   { ".debug_addr", ".zdebug_addr" },
433   { ".debug_frame", ".zdebug_frame" },
434   { ".eh_frame", NULL },
435   { ".gdb_index", ".zgdb_index" },
436   23
437 };
438
439 /* List of DWO/DWP sections.  */
440
441 static const struct dwop_section_names
442 {
443   struct dwarf2_section_names abbrev_dwo;
444   struct dwarf2_section_names info_dwo;
445   struct dwarf2_section_names line_dwo;
446   struct dwarf2_section_names loc_dwo;
447   struct dwarf2_section_names loclists_dwo;
448   struct dwarf2_section_names macinfo_dwo;
449   struct dwarf2_section_names macro_dwo;
450   struct dwarf2_section_names str_dwo;
451   struct dwarf2_section_names str_offsets_dwo;
452   struct dwarf2_section_names types_dwo;
453   struct dwarf2_section_names cu_index;
454   struct dwarf2_section_names tu_index;
455 }
456 dwop_section_names =
457 {
458   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
459   { ".debug_info.dwo", ".zdebug_info.dwo" },
460   { ".debug_line.dwo", ".zdebug_line.dwo" },
461   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
462   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
463   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
464   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
465   { ".debug_str.dwo", ".zdebug_str.dwo" },
466   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
467   { ".debug_types.dwo", ".zdebug_types.dwo" },
468   { ".debug_cu_index", ".zdebug_cu_index" },
469   { ".debug_tu_index", ".zdebug_tu_index" },
470 };
471
472 /* local data types */
473
474 /* The data in a compilation unit header, after target2host
475    translation, looks like this.  */
476 struct comp_unit_head
477 {
478   unsigned int length;
479   short version;
480   unsigned char addr_size;
481   unsigned char signed_addr_p;
482   sect_offset abbrev_sect_off;
483
484   /* Size of file offsets; either 4 or 8.  */
485   unsigned int offset_size;
486
487   /* Size of the length field; either 4 or 12.  */
488   unsigned int initial_length_size;
489
490   enum dwarf_unit_type unit_type;
491
492   /* Offset to the first byte of this compilation unit header in the
493      .debug_info section, for resolving relative reference dies.  */
494   sect_offset sect_off;
495
496   /* Offset to first die in this cu from the start of the cu.
497      This will be the first byte following the compilation unit header.  */
498   cu_offset first_die_cu_offset;
499
500   /* 64-bit signature of this type unit - it is valid only for
501      UNIT_TYPE DW_UT_type.  */
502   ULONGEST signature;
503
504   /* For types, offset in the type's DIE of the type defined by this TU.  */
505   cu_offset type_cu_offset_in_tu;
506 };
507
508 /* Type used for delaying computation of method physnames.
509    See comments for compute_delayed_physnames.  */
510 struct delayed_method_info
511 {
512   /* The type to which the method is attached, i.e., its parent class.  */
513   struct type *type;
514
515   /* The index of the method in the type's function fieldlists.  */
516   int fnfield_index;
517
518   /* The index of the method in the fieldlist.  */
519   int index;
520
521   /* The name of the DIE.  */
522   const char *name;
523
524   /*  The DIE associated with this method.  */
525   struct die_info *die;
526 };
527
528 typedef struct delayed_method_info delayed_method_info;
529 DEF_VEC_O (delayed_method_info);
530
531 /* Internal state when decoding a particular compilation unit.  */
532 struct dwarf2_cu
533 {
534   /* The objfile containing this compilation unit.  */
535   struct objfile *objfile;
536
537   /* The header of the compilation unit.  */
538   struct comp_unit_head header;
539
540   /* Base address of this compilation unit.  */
541   CORE_ADDR base_address;
542
543   /* Non-zero if base_address has been set.  */
544   int base_known;
545
546   /* The language we are debugging.  */
547   enum language language;
548   const struct language_defn *language_defn;
549
550   const char *producer;
551
552   /* The generic symbol table building routines have separate lists for
553      file scope symbols and all all other scopes (local scopes).  So
554      we need to select the right one to pass to add_symbol_to_list().
555      We do it by keeping a pointer to the correct list in list_in_scope.
556
557      FIXME: The original dwarf code just treated the file scope as the
558      first local scope, and all other local scopes as nested local
559      scopes, and worked fine.  Check to see if we really need to
560      distinguish these in buildsym.c.  */
561   struct pending **list_in_scope;
562
563   /* The abbrev table for this CU.
564      Normally this points to the abbrev table in the objfile.
565      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
566   struct abbrev_table *abbrev_table;
567
568   /* Hash table holding all the loaded partial DIEs
569      with partial_die->offset.SECT_OFF as hash.  */
570   htab_t partial_dies;
571
572   /* Storage for things with the same lifetime as this read-in compilation
573      unit, including partial DIEs.  */
574   struct obstack comp_unit_obstack;
575
576   /* When multiple dwarf2_cu structures are living in memory, this field
577      chains them all together, so that they can be released efficiently.
578      We will probably also want a generation counter so that most-recently-used
579      compilation units are cached...  */
580   struct dwarf2_per_cu_data *read_in_chain;
581
582   /* Backlink to our per_cu entry.  */
583   struct dwarf2_per_cu_data *per_cu;
584
585   /* How many compilation units ago was this CU last referenced?  */
586   int last_used;
587
588   /* A hash table of DIE cu_offset for following references with
589      die_info->offset.sect_off as hash.  */
590   htab_t die_hash;
591
592   /* Full DIEs if read in.  */
593   struct die_info *dies;
594
595   /* A set of pointers to dwarf2_per_cu_data objects for compilation
596      units referenced by this one.  Only set during full symbol processing;
597      partial symbol tables do not have dependencies.  */
598   htab_t dependencies;
599
600   /* Header data from the line table, during full symbol processing.  */
601   struct line_header *line_header;
602   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
603      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
604      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
605      to the line header as long as this DIE is being processed.  See
606      process_die_scope.  */
607   die_info *line_header_die_owner;
608
609   /* A list of methods which need to have physnames computed
610      after all type information has been read.  */
611   VEC (delayed_method_info) *method_list;
612
613   /* To be copied to symtab->call_site_htab.  */
614   htab_t call_site_htab;
615
616   /* Non-NULL if this CU came from a DWO file.
617      There is an invariant here that is important to remember:
618      Except for attributes copied from the top level DIE in the "main"
619      (or "stub") file in preparation for reading the DWO file
620      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
621      Either there isn't a DWO file (in which case this is NULL and the point
622      is moot), or there is and either we're not going to read it (in which
623      case this is NULL) or there is and we are reading it (in which case this
624      is non-NULL).  */
625   struct dwo_unit *dwo_unit;
626
627   /* The DW_AT_addr_base attribute if present, zero otherwise
628      (zero is a valid value though).
629      Note this value comes from the Fission stub CU/TU's DIE.  */
630   ULONGEST addr_base;
631
632   /* The DW_AT_ranges_base attribute if present, zero otherwise
633      (zero is a valid value though).
634      Note this value comes from the Fission stub CU/TU's DIE.
635      Also note that the value is zero in the non-DWO case so this value can
636      be used without needing to know whether DWO files are in use or not.
637      N.B. This does not apply to DW_AT_ranges appearing in
638      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
639      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
640      DW_AT_ranges_base *would* have to be applied, and we'd have to care
641      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
642   ULONGEST ranges_base;
643
644   /* Mark used when releasing cached dies.  */
645   unsigned int mark : 1;
646
647   /* This CU references .debug_loc.  See the symtab->locations_valid field.
648      This test is imperfect as there may exist optimized debug code not using
649      any location list and still facing inlining issues if handled as
650      unoptimized code.  For a future better test see GCC PR other/32998.  */
651   unsigned int has_loclist : 1;
652
653   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
654      if all the producer_is_* fields are valid.  This information is cached
655      because profiling CU expansion showed excessive time spent in
656      producer_is_gxx_lt_4_6.  */
657   unsigned int checked_producer : 1;
658   unsigned int producer_is_gxx_lt_4_6 : 1;
659   unsigned int producer_is_gcc_lt_4_3 : 1;
660   unsigned int producer_is_icc_lt_14 : 1;
661
662   /* When set, the file that we're processing is known to have
663      debugging info for C++ namespaces.  GCC 3.3.x did not produce
664      this information, but later versions do.  */
665
666   unsigned int processing_has_namespace_info : 1;
667 };
668
669 /* Persistent data held for a compilation unit, even when not
670    processing it.  We put a pointer to this structure in the
671    read_symtab_private field of the psymtab.  */
672
673 struct dwarf2_per_cu_data
674 {
675   /* The start offset and length of this compilation unit.
676      NOTE: Unlike comp_unit_head.length, this length includes
677      initial_length_size.
678      If the DIE refers to a DWO file, this is always of the original die,
679      not the DWO file.  */
680   sect_offset sect_off;
681   unsigned int length;
682
683   /* DWARF standard version this data has been read from (such as 4 or 5).  */
684   short dwarf_version;
685
686   /* Flag indicating this compilation unit will be read in before
687      any of the current compilation units are processed.  */
688   unsigned int queued : 1;
689
690   /* This flag will be set when reading partial DIEs if we need to load
691      absolutely all DIEs for this compilation unit, instead of just the ones
692      we think are interesting.  It gets set if we look for a DIE in the
693      hash table and don't find it.  */
694   unsigned int load_all_dies : 1;
695
696   /* Non-zero if this CU is from .debug_types.
697      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
698      this is non-zero.  */
699   unsigned int is_debug_types : 1;
700
701   /* Non-zero if this CU is from the .dwz file.  */
702   unsigned int is_dwz : 1;
703
704   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
705      This flag is only valid if is_debug_types is true.
706      We can't read a CU directly from a DWO file: There are required
707      attributes in the stub.  */
708   unsigned int reading_dwo_directly : 1;
709
710   /* Non-zero if the TU has been read.
711      This is used to assist the "Stay in DWO Optimization" for Fission:
712      When reading a DWO, it's faster to read TUs from the DWO instead of
713      fetching them from random other DWOs (due to comdat folding).
714      If the TU has already been read, the optimization is unnecessary
715      (and unwise - we don't want to change where gdb thinks the TU lives
716      "midflight").
717      This flag is only valid if is_debug_types is true.  */
718   unsigned int tu_read : 1;
719
720   /* The section this CU/TU lives in.
721      If the DIE refers to a DWO file, this is always the original die,
722      not the DWO file.  */
723   struct dwarf2_section_info *section;
724
725   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
726      of the CU cache it gets reset to NULL again.  This is left as NULL for
727      dummy CUs (a CU header, but nothing else).  */
728   struct dwarf2_cu *cu;
729
730   /* The corresponding objfile.
731      Normally we can get the objfile from dwarf2_per_objfile.
732      However we can enter this file with just a "per_cu" handle.  */
733   struct objfile *objfile;
734
735   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
736      is active.  Otherwise, the 'psymtab' field is active.  */
737   union
738   {
739     /* The partial symbol table associated with this compilation unit,
740        or NULL for unread partial units.  */
741     struct partial_symtab *psymtab;
742
743     /* Data needed by the "quick" functions.  */
744     struct dwarf2_per_cu_quick_data *quick;
745   } v;
746
747   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
748      while reading psymtabs, used to compute the psymtab dependencies,
749      and then cleared.  Then it is filled in again while reading full
750      symbols, and only deleted when the objfile is destroyed.
751
752      This is also used to work around a difference between the way gold
753      generates .gdb_index version <=7 and the way gdb does.  Arguably this
754      is a gold bug.  For symbols coming from TUs, gold records in the index
755      the CU that includes the TU instead of the TU itself.  This breaks
756      dw2_lookup_symbol: It assumes that if the index says symbol X lives
757      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
758      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
759      we need to look in TU Z to find X.  Fortunately, this is akin to
760      DW_TAG_imported_unit, so we just use the same mechanism: For
761      .gdb_index version <=7 this also records the TUs that the CU referred
762      to.  Concurrently with this change gdb was modified to emit version 8
763      indices so we only pay a price for gold generated indices.
764      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
765   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
766 };
767
768 /* Entry in the signatured_types hash table.  */
769
770 struct signatured_type
771 {
772   /* The "per_cu" object of this type.
773      This struct is used iff per_cu.is_debug_types.
774      N.B.: This is the first member so that it's easy to convert pointers
775      between them.  */
776   struct dwarf2_per_cu_data per_cu;
777
778   /* The type's signature.  */
779   ULONGEST signature;
780
781   /* Offset in the TU of the type's DIE, as read from the TU header.
782      If this TU is a DWO stub and the definition lives in a DWO file
783      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
784   cu_offset type_offset_in_tu;
785
786   /* Offset in the section of the type's DIE.
787      If the definition lives in a DWO file, this is the offset in the
788      .debug_types.dwo section.
789      The value is zero until the actual value is known.
790      Zero is otherwise not a valid section offset.  */
791   sect_offset type_offset_in_section;
792
793   /* Type units are grouped by their DW_AT_stmt_list entry so that they
794      can share them.  This points to the containing symtab.  */
795   struct type_unit_group *type_unit_group;
796
797   /* The type.
798      The first time we encounter this type we fully read it in and install it
799      in the symbol tables.  Subsequent times we only need the type.  */
800   struct type *type;
801
802   /* Containing DWO unit.
803      This field is valid iff per_cu.reading_dwo_directly.  */
804   struct dwo_unit *dwo_unit;
805 };
806
807 typedef struct signatured_type *sig_type_ptr;
808 DEF_VEC_P (sig_type_ptr);
809
810 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
811    This includes type_unit_group and quick_file_names.  */
812
813 struct stmt_list_hash
814 {
815   /* The DWO unit this table is from or NULL if there is none.  */
816   struct dwo_unit *dwo_unit;
817
818   /* Offset in .debug_line or .debug_line.dwo.  */
819   sect_offset line_sect_off;
820 };
821
822 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
823    an object of this type.  */
824
825 struct type_unit_group
826 {
827   /* dwarf2read.c's main "handle" on a TU symtab.
828      To simplify things we create an artificial CU that "includes" all the
829      type units using this stmt_list so that the rest of the code still has
830      a "per_cu" handle on the symtab.
831      This PER_CU is recognized by having no section.  */
832 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
833   struct dwarf2_per_cu_data per_cu;
834
835   /* The TUs that share this DW_AT_stmt_list entry.
836      This is added to while parsing type units to build partial symtabs,
837      and is deleted afterwards and not used again.  */
838   VEC (sig_type_ptr) *tus;
839
840   /* The compunit symtab.
841      Type units in a group needn't all be defined in the same source file,
842      so we create an essentially anonymous symtab as the compunit symtab.  */
843   struct compunit_symtab *compunit_symtab;
844
845   /* The data used to construct the hash key.  */
846   struct stmt_list_hash hash;
847
848   /* The number of symtabs from the line header.
849      The value here must match line_header.num_file_names.  */
850   unsigned int num_symtabs;
851
852   /* The symbol tables for this TU (obtained from the files listed in
853      DW_AT_stmt_list).
854      WARNING: The order of entries here must match the order of entries
855      in the line header.  After the first TU using this type_unit_group, the
856      line header for the subsequent TUs is recreated from this.  This is done
857      because we need to use the same symtabs for each TU using the same
858      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
859      there's no guarantee the line header doesn't have duplicate entries.  */
860   struct symtab **symtabs;
861 };
862
863 /* These sections are what may appear in a (real or virtual) DWO file.  */
864
865 struct dwo_sections
866 {
867   struct dwarf2_section_info abbrev;
868   struct dwarf2_section_info line;
869   struct dwarf2_section_info loc;
870   struct dwarf2_section_info loclists;
871   struct dwarf2_section_info macinfo;
872   struct dwarf2_section_info macro;
873   struct dwarf2_section_info str;
874   struct dwarf2_section_info str_offsets;
875   /* In the case of a virtual DWO file, these two are unused.  */
876   struct dwarf2_section_info info;
877   VEC (dwarf2_section_info_def) *types;
878 };
879
880 /* CUs/TUs in DWP/DWO files.  */
881
882 struct dwo_unit
883 {
884   /* Backlink to the containing struct dwo_file.  */
885   struct dwo_file *dwo_file;
886
887   /* The "id" that distinguishes this CU/TU.
888      .debug_info calls this "dwo_id", .debug_types calls this "signature".
889      Since signatures came first, we stick with it for consistency.  */
890   ULONGEST signature;
891
892   /* The section this CU/TU lives in, in the DWO file.  */
893   struct dwarf2_section_info *section;
894
895   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
896   sect_offset sect_off;
897   unsigned int length;
898
899   /* For types, offset in the type's DIE of the type defined by this TU.  */
900   cu_offset type_offset_in_tu;
901 };
902
903 /* include/dwarf2.h defines the DWP section codes.
904    It defines a max value but it doesn't define a min value, which we
905    use for error checking, so provide one.  */
906
907 enum dwp_v2_section_ids
908 {
909   DW_SECT_MIN = 1
910 };
911
912 /* Data for one DWO file.
913
914    This includes virtual DWO files (a virtual DWO file is a DWO file as it
915    appears in a DWP file).  DWP files don't really have DWO files per se -
916    comdat folding of types "loses" the DWO file they came from, and from
917    a high level view DWP files appear to contain a mass of random types.
918    However, to maintain consistency with the non-DWP case we pretend DWP
919    files contain virtual DWO files, and we assign each TU with one virtual
920    DWO file (generally based on the line and abbrev section offsets -
921    a heuristic that seems to work in practice).  */
922
923 struct dwo_file
924 {
925   /* The DW_AT_GNU_dwo_name attribute.
926      For virtual DWO files the name is constructed from the section offsets
927      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
928      from related CU+TUs.  */
929   const char *dwo_name;
930
931   /* The DW_AT_comp_dir attribute.  */
932   const char *comp_dir;
933
934   /* The bfd, when the file is open.  Otherwise this is NULL.
935      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
936   bfd *dbfd;
937
938   /* The sections that make up this DWO file.
939      Remember that for virtual DWO files in DWP V2, these are virtual
940      sections (for lack of a better name).  */
941   struct dwo_sections sections;
942
943   /* The CUs in the file.
944      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
945      an extension to handle LLVM's Link Time Optimization output (where
946      multiple source files may be compiled into a single object/dwo pair). */
947   htab_t cus;
948
949   /* Table of TUs in the file.
950      Each element is a struct dwo_unit.  */
951   htab_t tus;
952 };
953
954 /* These sections are what may appear in a DWP file.  */
955
956 struct dwp_sections
957 {
958   /* These are used by both DWP version 1 and 2.  */
959   struct dwarf2_section_info str;
960   struct dwarf2_section_info cu_index;
961   struct dwarf2_section_info tu_index;
962
963   /* These are only used by DWP version 2 files.
964      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
965      sections are referenced by section number, and are not recorded here.
966      In DWP version 2 there is at most one copy of all these sections, each
967      section being (effectively) comprised of the concatenation of all of the
968      individual sections that exist in the version 1 format.
969      To keep the code simple we treat each of these concatenated pieces as a
970      section itself (a virtual section?).  */
971   struct dwarf2_section_info abbrev;
972   struct dwarf2_section_info info;
973   struct dwarf2_section_info line;
974   struct dwarf2_section_info loc;
975   struct dwarf2_section_info macinfo;
976   struct dwarf2_section_info macro;
977   struct dwarf2_section_info str_offsets;
978   struct dwarf2_section_info types;
979 };
980
981 /* These sections are what may appear in a virtual DWO file in DWP version 1.
982    A virtual DWO file is a DWO file as it appears in a DWP file.  */
983
984 struct virtual_v1_dwo_sections
985 {
986   struct dwarf2_section_info abbrev;
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   /* Each DWP hash table entry records one CU or one TU.
993      That is recorded here, and copied to dwo_unit.section.  */
994   struct dwarf2_section_info info_or_types;
995 };
996
997 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
998    In version 2, the sections of the DWO files are concatenated together
999    and stored in one section of that name.  Thus each ELF section contains
1000    several "virtual" sections.  */
1001
1002 struct virtual_v2_dwo_sections
1003 {
1004   bfd_size_type abbrev_offset;
1005   bfd_size_type abbrev_size;
1006
1007   bfd_size_type line_offset;
1008   bfd_size_type line_size;
1009
1010   bfd_size_type loc_offset;
1011   bfd_size_type loc_size;
1012
1013   bfd_size_type macinfo_offset;
1014   bfd_size_type macinfo_size;
1015
1016   bfd_size_type macro_offset;
1017   bfd_size_type macro_size;
1018
1019   bfd_size_type str_offsets_offset;
1020   bfd_size_type str_offsets_size;
1021
1022   /* Each DWP hash table entry records one CU or one TU.
1023      That is recorded here, and copied to dwo_unit.section.  */
1024   bfd_size_type info_or_types_offset;
1025   bfd_size_type info_or_types_size;
1026 };
1027
1028 /* Contents of DWP hash tables.  */
1029
1030 struct dwp_hash_table
1031 {
1032   uint32_t version, nr_columns;
1033   uint32_t nr_units, nr_slots;
1034   const gdb_byte *hash_table, *unit_table;
1035   union
1036   {
1037     struct
1038     {
1039       const gdb_byte *indices;
1040     } v1;
1041     struct
1042     {
1043       /* This is indexed by column number and gives the id of the section
1044          in that column.  */
1045 #define MAX_NR_V2_DWO_SECTIONS \
1046   (1 /* .debug_info or .debug_types */ \
1047    + 1 /* .debug_abbrev */ \
1048    + 1 /* .debug_line */ \
1049    + 1 /* .debug_loc */ \
1050    + 1 /* .debug_str_offsets */ \
1051    + 1 /* .debug_macro or .debug_macinfo */)
1052       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1053       const gdb_byte *offsets;
1054       const gdb_byte *sizes;
1055     } v2;
1056   } section_pool;
1057 };
1058
1059 /* Data for one DWP file.  */
1060
1061 struct dwp_file
1062 {
1063   /* Name of the file.  */
1064   const char *name;
1065
1066   /* File format version.  */
1067   int version;
1068
1069   /* The bfd.  */
1070   bfd *dbfd;
1071
1072   /* Section info for this file.  */
1073   struct dwp_sections sections;
1074
1075   /* Table of CUs in the file.  */
1076   const struct dwp_hash_table *cus;
1077
1078   /* Table of TUs in the file.  */
1079   const struct dwp_hash_table *tus;
1080
1081   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1082   htab_t loaded_cus;
1083   htab_t loaded_tus;
1084
1085   /* Table to map ELF section numbers to their sections.
1086      This is only needed for the DWP V1 file format.  */
1087   unsigned int num_sections;
1088   asection **elf_sections;
1089 };
1090
1091 /* This represents a '.dwz' file.  */
1092
1093 struct dwz_file
1094 {
1095   /* A dwz file can only contain a few sections.  */
1096   struct dwarf2_section_info abbrev;
1097   struct dwarf2_section_info info;
1098   struct dwarf2_section_info str;
1099   struct dwarf2_section_info line;
1100   struct dwarf2_section_info macro;
1101   struct dwarf2_section_info gdb_index;
1102
1103   /* The dwz's BFD.  */
1104   bfd *dwz_bfd;
1105 };
1106
1107 /* Struct used to pass misc. parameters to read_die_and_children, et
1108    al.  which are used for both .debug_info and .debug_types dies.
1109    All parameters here are unchanging for the life of the call.  This
1110    struct exists to abstract away the constant parameters of die reading.  */
1111
1112 struct die_reader_specs
1113 {
1114   /* The bfd of die_section.  */
1115   bfd* abfd;
1116
1117   /* The CU of the DIE we are parsing.  */
1118   struct dwarf2_cu *cu;
1119
1120   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1121   struct dwo_file *dwo_file;
1122
1123   /* The section the die comes from.
1124      This is either .debug_info or .debug_types, or the .dwo variants.  */
1125   struct dwarf2_section_info *die_section;
1126
1127   /* die_section->buffer.  */
1128   const gdb_byte *buffer;
1129
1130   /* The end of the buffer.  */
1131   const gdb_byte *buffer_end;
1132
1133   /* The value of the DW_AT_comp_dir attribute.  */
1134   const char *comp_dir;
1135 };
1136
1137 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1138 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1139                                       const gdb_byte *info_ptr,
1140                                       struct die_info *comp_unit_die,
1141                                       int has_children,
1142                                       void *data);
1143
1144 /* A 1-based directory index.  This is a strong typedef to prevent
1145    accidentally using a directory index as a 0-based index into an
1146    array/vector.  */
1147 enum class dir_index : unsigned int {};
1148
1149 /* Likewise, a 1-based file name index.  */
1150 enum class file_name_index : unsigned int {};
1151
1152 struct file_entry
1153 {
1154   file_entry () = default;
1155
1156   file_entry (const char *name_, dir_index d_index_,
1157               unsigned int mod_time_, unsigned int length_)
1158     : name (name_),
1159       d_index (d_index_),
1160       mod_time (mod_time_),
1161       length (length_)
1162   {}
1163
1164   /* Return the include directory at D_INDEX stored in LH.  Returns
1165      NULL if D_INDEX is out of bounds.  */
1166   const char *include_dir (const line_header *lh) const;
1167
1168   /* The file name.  Note this is an observing pointer.  The memory is
1169      owned by debug_line_buffer.  */
1170   const char *name {};
1171
1172   /* The directory index (1-based).  */
1173   dir_index d_index {};
1174
1175   unsigned int mod_time {};
1176
1177   unsigned int length {};
1178
1179   /* True if referenced by the Line Number Program.  */
1180   bool included_p {};
1181
1182   /* The associated symbol table, if any.  */
1183   struct symtab *symtab {};
1184 };
1185
1186 /* The line number information for a compilation unit (found in the
1187    .debug_line section) begins with a "statement program header",
1188    which contains the following information.  */
1189 struct line_header
1190 {
1191   line_header ()
1192     : offset_in_dwz {}
1193   {}
1194
1195   /* Add an entry to the include directory table.  */
1196   void add_include_dir (const char *include_dir);
1197
1198   /* Add an entry to the file name table.  */
1199   void add_file_name (const char *name, dir_index d_index,
1200                       unsigned int mod_time, unsigned int length);
1201
1202   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1203      is out of bounds.  */
1204   const char *include_dir_at (dir_index index) const
1205   {
1206     /* Convert directory index number (1-based) to vector index
1207        (0-based).  */
1208     size_t vec_index = to_underlying (index) - 1;
1209
1210     if (vec_index >= include_dirs.size ())
1211       return NULL;
1212     return include_dirs[vec_index];
1213   }
1214
1215   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1216      is out of bounds.  */
1217   file_entry *file_name_at (file_name_index index)
1218   {
1219     /* Convert file name index number (1-based) to vector index
1220        (0-based).  */
1221     size_t vec_index = to_underlying (index) - 1;
1222
1223     if (vec_index >= file_names.size ())
1224       return NULL;
1225     return &file_names[vec_index];
1226   }
1227
1228   /* Const version of the above.  */
1229   const file_entry *file_name_at (unsigned int index) const
1230   {
1231     if (index >= file_names.size ())
1232       return NULL;
1233     return &file_names[index];
1234   }
1235
1236   /* Offset of line number information in .debug_line section.  */
1237   sect_offset sect_off {};
1238
1239   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1240   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1241
1242   unsigned int total_length {};
1243   unsigned short version {};
1244   unsigned int header_length {};
1245   unsigned char minimum_instruction_length {};
1246   unsigned char maximum_ops_per_instruction {};
1247   unsigned char default_is_stmt {};
1248   int line_base {};
1249   unsigned char line_range {};
1250   unsigned char opcode_base {};
1251
1252   /* standard_opcode_lengths[i] is the number of operands for the
1253      standard opcode whose value is i.  This means that
1254      standard_opcode_lengths[0] is unused, and the last meaningful
1255      element is standard_opcode_lengths[opcode_base - 1].  */
1256   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1257
1258   /* The include_directories table.  Note these are observing
1259      pointers.  The memory is owned by debug_line_buffer.  */
1260   std::vector<const char *> include_dirs;
1261
1262   /* The file_names table.  */
1263   std::vector<file_entry> file_names;
1264
1265   /* The start and end of the statement program following this
1266      header.  These point into dwarf2_per_objfile->line_buffer.  */
1267   const gdb_byte *statement_program_start {}, *statement_program_end {};
1268 };
1269
1270 typedef std::unique_ptr<line_header> line_header_up;
1271
1272 const char *
1273 file_entry::include_dir (const line_header *lh) const
1274 {
1275   return lh->include_dir_at (d_index);
1276 }
1277
1278 /* When we construct a partial symbol table entry we only
1279    need this much information.  */
1280 struct partial_die_info
1281   {
1282     /* Offset of this DIE.  */
1283     sect_offset sect_off;
1284
1285     /* DWARF-2 tag for this DIE.  */
1286     ENUM_BITFIELD(dwarf_tag) tag : 16;
1287
1288     /* Assorted flags describing the data found in this DIE.  */
1289     unsigned int has_children : 1;
1290     unsigned int is_external : 1;
1291     unsigned int is_declaration : 1;
1292     unsigned int has_type : 1;
1293     unsigned int has_specification : 1;
1294     unsigned int has_pc_info : 1;
1295     unsigned int may_be_inlined : 1;
1296
1297     /* This DIE has been marked DW_AT_main_subprogram.  */
1298     unsigned int main_subprogram : 1;
1299
1300     /* Flag set if the SCOPE field of this structure has been
1301        computed.  */
1302     unsigned int scope_set : 1;
1303
1304     /* Flag set if the DIE has a byte_size attribute.  */
1305     unsigned int has_byte_size : 1;
1306
1307     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1308     unsigned int has_const_value : 1;
1309
1310     /* Flag set if any of the DIE's children are template arguments.  */
1311     unsigned int has_template_arguments : 1;
1312
1313     /* Flag set if fixup_partial_die has been called on this die.  */
1314     unsigned int fixup_called : 1;
1315
1316     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1317     unsigned int is_dwz : 1;
1318
1319     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1320     unsigned int spec_is_dwz : 1;
1321
1322     /* The name of this DIE.  Normally the value of DW_AT_name, but
1323        sometimes a default name for unnamed DIEs.  */
1324     const char *name;
1325
1326     /* The linkage name, if present.  */
1327     const char *linkage_name;
1328
1329     /* The scope to prepend to our children.  This is generally
1330        allocated on the comp_unit_obstack, so will disappear
1331        when this compilation unit leaves the cache.  */
1332     const char *scope;
1333
1334     /* Some data associated with the partial DIE.  The tag determines
1335        which field is live.  */
1336     union
1337     {
1338       /* The location description associated with this DIE, if any.  */
1339       struct dwarf_block *locdesc;
1340       /* The offset of an import, for DW_TAG_imported_unit.  */
1341       sect_offset sect_off;
1342     } d;
1343
1344     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1345     CORE_ADDR lowpc;
1346     CORE_ADDR highpc;
1347
1348     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1349        DW_AT_sibling, if any.  */
1350     /* NOTE: This member isn't strictly necessary, read_partial_die could
1351        return DW_AT_sibling values to its caller load_partial_dies.  */
1352     const gdb_byte *sibling;
1353
1354     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1355        DW_AT_specification (or DW_AT_abstract_origin or
1356        DW_AT_extension).  */
1357     sect_offset spec_offset;
1358
1359     /* Pointers to this DIE's parent, first child, and next sibling,
1360        if any.  */
1361     struct partial_die_info *die_parent, *die_child, *die_sibling;
1362   };
1363
1364 /* This data structure holds the information of an abbrev.  */
1365 struct abbrev_info
1366   {
1367     unsigned int number;        /* number identifying abbrev */
1368     enum dwarf_tag tag;         /* dwarf tag */
1369     unsigned short has_children;                /* boolean */
1370     unsigned short num_attrs;   /* number of attributes */
1371     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1372     struct abbrev_info *next;   /* next in chain */
1373   };
1374
1375 struct attr_abbrev
1376   {
1377     ENUM_BITFIELD(dwarf_attribute) name : 16;
1378     ENUM_BITFIELD(dwarf_form) form : 16;
1379
1380     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1381     LONGEST implicit_const;
1382   };
1383
1384 /* Size of abbrev_table.abbrev_hash_table.  */
1385 #define ABBREV_HASH_SIZE 121
1386
1387 /* Top level data structure to contain an abbreviation table.  */
1388
1389 struct abbrev_table
1390 {
1391   /* Where the abbrev table came from.
1392      This is used as a sanity check when the table is used.  */
1393   sect_offset sect_off;
1394
1395   /* Storage for the abbrev table.  */
1396   struct obstack abbrev_obstack;
1397
1398   /* Hash table of abbrevs.
1399      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1400      It could be statically allocated, but the previous code didn't so we
1401      don't either.  */
1402   struct abbrev_info **abbrevs;
1403 };
1404
1405 /* Attributes have a name and a value.  */
1406 struct attribute
1407   {
1408     ENUM_BITFIELD(dwarf_attribute) name : 16;
1409     ENUM_BITFIELD(dwarf_form) form : 15;
1410
1411     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1412        field should be in u.str (existing only for DW_STRING) but it is kept
1413        here for better struct attribute alignment.  */
1414     unsigned int string_is_canonical : 1;
1415
1416     union
1417       {
1418         const char *str;
1419         struct dwarf_block *blk;
1420         ULONGEST unsnd;
1421         LONGEST snd;
1422         CORE_ADDR addr;
1423         ULONGEST signature;
1424       }
1425     u;
1426   };
1427
1428 /* This data structure holds a complete die structure.  */
1429 struct die_info
1430   {
1431     /* DWARF-2 tag for this DIE.  */
1432     ENUM_BITFIELD(dwarf_tag) tag : 16;
1433
1434     /* Number of attributes */
1435     unsigned char num_attrs;
1436
1437     /* True if we're presently building the full type name for the
1438        type derived from this DIE.  */
1439     unsigned char building_fullname : 1;
1440
1441     /* True if this die is in process.  PR 16581.  */
1442     unsigned char in_process : 1;
1443
1444     /* Abbrev number */
1445     unsigned int abbrev;
1446
1447     /* Offset in .debug_info or .debug_types section.  */
1448     sect_offset sect_off;
1449
1450     /* The dies in a compilation unit form an n-ary tree.  PARENT
1451        points to this die's parent; CHILD points to the first child of
1452        this node; and all the children of a given node are chained
1453        together via their SIBLING fields.  */
1454     struct die_info *child;     /* Its first child, if any.  */
1455     struct die_info *sibling;   /* Its next sibling, if any.  */
1456     struct die_info *parent;    /* Its parent, if any.  */
1457
1458     /* An array of attributes, with NUM_ATTRS elements.  There may be
1459        zero, but it's not common and zero-sized arrays are not
1460        sufficiently portable C.  */
1461     struct attribute attrs[1];
1462   };
1463
1464 /* Get at parts of an attribute structure.  */
1465
1466 #define DW_STRING(attr)    ((attr)->u.str)
1467 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1468 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1469 #define DW_BLOCK(attr)     ((attr)->u.blk)
1470 #define DW_SND(attr)       ((attr)->u.snd)
1471 #define DW_ADDR(attr)      ((attr)->u.addr)
1472 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1473
1474 /* Blocks are a bunch of untyped bytes.  */
1475 struct dwarf_block
1476   {
1477     size_t size;
1478
1479     /* Valid only if SIZE is not zero.  */
1480     const gdb_byte *data;
1481   };
1482
1483 #ifndef ATTR_ALLOC_CHUNK
1484 #define ATTR_ALLOC_CHUNK 4
1485 #endif
1486
1487 /* Allocate fields for structs, unions and enums in this size.  */
1488 #ifndef DW_FIELD_ALLOC_CHUNK
1489 #define DW_FIELD_ALLOC_CHUNK 4
1490 #endif
1491
1492 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1493    but this would require a corresponding change in unpack_field_as_long
1494    and friends.  */
1495 static int bits_per_byte = 8;
1496
1497 struct nextfield
1498 {
1499   struct nextfield *next;
1500   int accessibility;
1501   int virtuality;
1502   struct field field;
1503 };
1504
1505 struct nextfnfield
1506 {
1507   struct nextfnfield *next;
1508   struct fn_field fnfield;
1509 };
1510
1511 struct fnfieldlist
1512 {
1513   const char *name;
1514   int length;
1515   struct nextfnfield *head;
1516 };
1517
1518 struct typedef_field_list
1519 {
1520   struct typedef_field field;
1521   struct typedef_field_list *next;
1522 };
1523
1524 /* The routines that read and process dies for a C struct or C++ class
1525    pass lists of data member fields and lists of member function fields
1526    in an instance of a field_info structure, as defined below.  */
1527 struct field_info
1528   {
1529     /* List of data member and baseclasses fields.  */
1530     struct nextfield *fields, *baseclasses;
1531
1532     /* Number of fields (including baseclasses).  */
1533     int nfields;
1534
1535     /* Number of baseclasses.  */
1536     int nbaseclasses;
1537
1538     /* Set if the accesibility of one of the fields is not public.  */
1539     int non_public_fields;
1540
1541     /* Member function fieldlist array, contains name of possibly overloaded
1542        member function, number of overloaded member functions and a pointer
1543        to the head of the member function field chain.  */
1544     struct fnfieldlist *fnfieldlists;
1545
1546     /* Number of entries in the fnfieldlists array.  */
1547     int nfnfields;
1548
1549     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1550        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1551     struct typedef_field_list *typedef_field_list;
1552     unsigned typedef_field_list_count;
1553   };
1554
1555 /* One item on the queue of compilation units to read in full symbols
1556    for.  */
1557 struct dwarf2_queue_item
1558 {
1559   struct dwarf2_per_cu_data *per_cu;
1560   enum language pretend_language;
1561   struct dwarf2_queue_item *next;
1562 };
1563
1564 /* The current queue.  */
1565 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1566
1567 /* Loaded secondary compilation units are kept in memory until they
1568    have not been referenced for the processing of this many
1569    compilation units.  Set this to zero to disable caching.  Cache
1570    sizes of up to at least twenty will improve startup time for
1571    typical inter-CU-reference binaries, at an obvious memory cost.  */
1572 static int dwarf_max_cache_age = 5;
1573 static void
1574 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1575                           struct cmd_list_element *c, const char *value)
1576 {
1577   fprintf_filtered (file, _("The upper bound on the age of cached "
1578                             "DWARF compilation units is %s.\n"),
1579                     value);
1580 }
1581 \f
1582 /* local function prototypes */
1583
1584 static const char *get_section_name (const struct dwarf2_section_info *);
1585
1586 static const char *get_section_file_name (const struct dwarf2_section_info *);
1587
1588 static void dwarf2_find_base_address (struct die_info *die,
1589                                       struct dwarf2_cu *cu);
1590
1591 static struct partial_symtab *create_partial_symtab
1592   (struct dwarf2_per_cu_data *per_cu, const char *name);
1593
1594 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1595                                         const gdb_byte *info_ptr,
1596                                         struct die_info *type_unit_die,
1597                                         int has_children, void *data);
1598
1599 static void dwarf2_build_psymtabs_hard (struct objfile *);
1600
1601 static void scan_partial_symbols (struct partial_die_info *,
1602                                   CORE_ADDR *, CORE_ADDR *,
1603                                   int, struct dwarf2_cu *);
1604
1605 static void add_partial_symbol (struct partial_die_info *,
1606                                 struct dwarf2_cu *);
1607
1608 static void add_partial_namespace (struct partial_die_info *pdi,
1609                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1610                                    int set_addrmap, struct dwarf2_cu *cu);
1611
1612 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1613                                 CORE_ADDR *highpc, int set_addrmap,
1614                                 struct dwarf2_cu *cu);
1615
1616 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1617                                      struct dwarf2_cu *cu);
1618
1619 static void add_partial_subprogram (struct partial_die_info *pdi,
1620                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1621                                     int need_pc, struct dwarf2_cu *cu);
1622
1623 static void dwarf2_read_symtab (struct partial_symtab *,
1624                                 struct objfile *);
1625
1626 static void psymtab_to_symtab_1 (struct partial_symtab *);
1627
1628 static struct abbrev_info *abbrev_table_lookup_abbrev
1629   (const struct abbrev_table *, unsigned int);
1630
1631 static struct abbrev_table *abbrev_table_read_table
1632   (struct dwarf2_section_info *, sect_offset);
1633
1634 static void abbrev_table_free (struct abbrev_table *);
1635
1636 static void abbrev_table_free_cleanup (void *);
1637
1638 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1639                                  struct dwarf2_section_info *);
1640
1641 static void dwarf2_free_abbrev_table (void *);
1642
1643 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1644
1645 static struct partial_die_info *load_partial_dies
1646   (const struct die_reader_specs *, const gdb_byte *, int);
1647
1648 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1649                                          struct partial_die_info *,
1650                                          struct abbrev_info *,
1651                                          unsigned int,
1652                                          const gdb_byte *);
1653
1654 static struct partial_die_info *find_partial_die (sect_offset, int,
1655                                                   struct dwarf2_cu *);
1656
1657 static void fixup_partial_die (struct partial_die_info *,
1658                                struct dwarf2_cu *);
1659
1660 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1661                                        struct attribute *, struct attr_abbrev *,
1662                                        const gdb_byte *);
1663
1664 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1665
1666 static int read_1_signed_byte (bfd *, const gdb_byte *);
1667
1668 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1669
1670 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1671
1672 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1673
1674 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1675                                unsigned int *);
1676
1677 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1678
1679 static LONGEST read_checked_initial_length_and_offset
1680   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1681    unsigned int *, unsigned int *);
1682
1683 static LONGEST read_offset (bfd *, const gdb_byte *,
1684                             const struct comp_unit_head *,
1685                             unsigned int *);
1686
1687 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1688
1689 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1690                                        sect_offset);
1691
1692 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1693
1694 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1695
1696 static const char *read_indirect_string (bfd *, const gdb_byte *,
1697                                          const struct comp_unit_head *,
1698                                          unsigned int *);
1699
1700 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1701                                               const struct comp_unit_head *,
1702                                               unsigned int *);
1703
1704 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1705
1706 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1707
1708 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1709                                               const gdb_byte *,
1710                                               unsigned int *);
1711
1712 static const char *read_str_index (const struct die_reader_specs *reader,
1713                                    ULONGEST str_index);
1714
1715 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1716
1717 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1718                                       struct dwarf2_cu *);
1719
1720 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1721                                                 unsigned int);
1722
1723 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1724                                        struct dwarf2_cu *cu);
1725
1726 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1727                                struct dwarf2_cu *cu);
1728
1729 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1730
1731 static struct die_info *die_specification (struct die_info *die,
1732                                            struct dwarf2_cu **);
1733
1734 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1735                                                 struct dwarf2_cu *cu);
1736
1737 static void dwarf_decode_lines (struct line_header *, const char *,
1738                                 struct dwarf2_cu *, struct partial_symtab *,
1739                                 CORE_ADDR, int decode_mapping);
1740
1741 static void dwarf2_start_subfile (const char *, const char *);
1742
1743 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1744                                                     const char *, const char *,
1745                                                     CORE_ADDR);
1746
1747 static struct symbol *new_symbol (struct die_info *, struct type *,
1748                                   struct dwarf2_cu *);
1749
1750 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1751                                        struct dwarf2_cu *, struct symbol *);
1752
1753 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1754                                 struct dwarf2_cu *);
1755
1756 static void dwarf2_const_value_attr (const struct attribute *attr,
1757                                      struct type *type,
1758                                      const char *name,
1759                                      struct obstack *obstack,
1760                                      struct dwarf2_cu *cu, LONGEST *value,
1761                                      const gdb_byte **bytes,
1762                                      struct dwarf2_locexpr_baton **baton);
1763
1764 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1765
1766 static int need_gnat_info (struct dwarf2_cu *);
1767
1768 static struct type *die_descriptive_type (struct die_info *,
1769                                           struct dwarf2_cu *);
1770
1771 static void set_descriptive_type (struct type *, struct die_info *,
1772                                   struct dwarf2_cu *);
1773
1774 static struct type *die_containing_type (struct die_info *,
1775                                          struct dwarf2_cu *);
1776
1777 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1778                                      struct dwarf2_cu *);
1779
1780 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1781
1782 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1783
1784 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1785
1786 static char *typename_concat (struct obstack *obs, const char *prefix,
1787                               const char *suffix, int physname,
1788                               struct dwarf2_cu *cu);
1789
1790 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1791
1792 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1793
1794 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1795
1796 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1797
1798 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1799
1800 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1801                                struct dwarf2_cu *, struct partial_symtab *);
1802
1803 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1804    values.  Keep the items ordered with increasing constraints compliance.  */
1805 enum pc_bounds_kind
1806 {
1807   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1808   PC_BOUNDS_NOT_PRESENT,
1809
1810   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1811      were present but they do not form a valid range of PC addresses.  */
1812   PC_BOUNDS_INVALID,
1813
1814   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1815   PC_BOUNDS_RANGES,
1816
1817   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1818   PC_BOUNDS_HIGH_LOW,
1819 };
1820
1821 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1822                                                  CORE_ADDR *, CORE_ADDR *,
1823                                                  struct dwarf2_cu *,
1824                                                  struct partial_symtab *);
1825
1826 static void get_scope_pc_bounds (struct die_info *,
1827                                  CORE_ADDR *, CORE_ADDR *,
1828                                  struct dwarf2_cu *);
1829
1830 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1831                                         CORE_ADDR, struct dwarf2_cu *);
1832
1833 static void dwarf2_add_field (struct field_info *, struct die_info *,
1834                               struct dwarf2_cu *);
1835
1836 static void dwarf2_attach_fields_to_type (struct field_info *,
1837                                           struct type *, struct dwarf2_cu *);
1838
1839 static void dwarf2_add_member_fn (struct field_info *,
1840                                   struct die_info *, struct type *,
1841                                   struct dwarf2_cu *);
1842
1843 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1844                                              struct type *,
1845                                              struct dwarf2_cu *);
1846
1847 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1848
1849 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1850
1851 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1852
1853 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1854
1855 static struct using_direct **using_directives (enum language);
1856
1857 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1858
1859 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1860
1861 static struct type *read_module_type (struct die_info *die,
1862                                       struct dwarf2_cu *cu);
1863
1864 static const char *namespace_name (struct die_info *die,
1865                                    int *is_anonymous, struct dwarf2_cu *);
1866
1867 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1868
1869 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1870
1871 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1872                                                        struct dwarf2_cu *);
1873
1874 static struct die_info *read_die_and_siblings_1
1875   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1876    struct die_info *);
1877
1878 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1879                                                const gdb_byte *info_ptr,
1880                                                const gdb_byte **new_info_ptr,
1881                                                struct die_info *parent);
1882
1883 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1884                                         struct die_info **, const gdb_byte *,
1885                                         int *, int);
1886
1887 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1888                                       struct die_info **, const gdb_byte *,
1889                                       int *);
1890
1891 static void process_die (struct die_info *, struct dwarf2_cu *);
1892
1893 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1894                                              struct obstack *);
1895
1896 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1897
1898 static const char *dwarf2_full_name (const char *name,
1899                                      struct die_info *die,
1900                                      struct dwarf2_cu *cu);
1901
1902 static const char *dwarf2_physname (const char *name, struct die_info *die,
1903                                     struct dwarf2_cu *cu);
1904
1905 static struct die_info *dwarf2_extension (struct die_info *die,
1906                                           struct dwarf2_cu **);
1907
1908 static const char *dwarf_tag_name (unsigned int);
1909
1910 static const char *dwarf_attr_name (unsigned int);
1911
1912 static const char *dwarf_form_name (unsigned int);
1913
1914 static const char *dwarf_bool_name (unsigned int);
1915
1916 static const char *dwarf_type_encoding_name (unsigned int);
1917
1918 static struct die_info *sibling_die (struct die_info *);
1919
1920 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1921
1922 static void dump_die_for_error (struct die_info *);
1923
1924 static void dump_die_1 (struct ui_file *, int level, int max_level,
1925                         struct die_info *);
1926
1927 /*static*/ void dump_die (struct die_info *, int max_level);
1928
1929 static void store_in_ref_table (struct die_info *,
1930                                 struct dwarf2_cu *);
1931
1932 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1933
1934 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1935
1936 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1937                                                const struct attribute *,
1938                                                struct dwarf2_cu **);
1939
1940 static struct die_info *follow_die_ref (struct die_info *,
1941                                         const struct attribute *,
1942                                         struct dwarf2_cu **);
1943
1944 static struct die_info *follow_die_sig (struct die_info *,
1945                                         const struct attribute *,
1946                                         struct dwarf2_cu **);
1947
1948 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1949                                          struct dwarf2_cu *);
1950
1951 static struct type *get_DW_AT_signature_type (struct die_info *,
1952                                               const struct attribute *,
1953                                               struct dwarf2_cu *);
1954
1955 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1956
1957 static void read_signatured_type (struct signatured_type *);
1958
1959 static int attr_to_dynamic_prop (const struct attribute *attr,
1960                                  struct die_info *die, struct dwarf2_cu *cu,
1961                                  struct dynamic_prop *prop);
1962
1963 /* memory allocation interface */
1964
1965 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1966
1967 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1968
1969 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1970
1971 static int attr_form_is_block (const struct attribute *);
1972
1973 static int attr_form_is_section_offset (const struct attribute *);
1974
1975 static int attr_form_is_constant (const struct attribute *);
1976
1977 static int attr_form_is_ref (const struct attribute *);
1978
1979 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1980                                    struct dwarf2_loclist_baton *baton,
1981                                    const struct attribute *attr);
1982
1983 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1984                                          struct symbol *sym,
1985                                          struct dwarf2_cu *cu,
1986                                          int is_block);
1987
1988 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1989                                      const gdb_byte *info_ptr,
1990                                      struct abbrev_info *abbrev);
1991
1992 static void free_stack_comp_unit (void *);
1993
1994 static hashval_t partial_die_hash (const void *item);
1995
1996 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1997
1998 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1999   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2000
2001 static void init_one_comp_unit (struct dwarf2_cu *cu,
2002                                 struct dwarf2_per_cu_data *per_cu);
2003
2004 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2005                                    struct die_info *comp_unit_die,
2006                                    enum language pretend_language);
2007
2008 static void free_heap_comp_unit (void *);
2009
2010 static void free_cached_comp_units (void *);
2011
2012 static void age_cached_comp_units (void);
2013
2014 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2015
2016 static struct type *set_die_type (struct die_info *, struct type *,
2017                                   struct dwarf2_cu *);
2018
2019 static void create_all_comp_units (struct objfile *);
2020
2021 static int create_all_type_units (struct objfile *);
2022
2023 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2024                                  enum language);
2025
2026 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2027                                     enum language);
2028
2029 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2030                                     enum language);
2031
2032 static void dwarf2_add_dependence (struct dwarf2_cu *,
2033                                    struct dwarf2_per_cu_data *);
2034
2035 static void dwarf2_mark (struct dwarf2_cu *);
2036
2037 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2038
2039 static struct type *get_die_type_at_offset (sect_offset,
2040                                             struct dwarf2_per_cu_data *);
2041
2042 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2043
2044 static void dwarf2_release_queue (void *dummy);
2045
2046 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2047                              enum language pretend_language);
2048
2049 static void process_queue (void);
2050
2051 /* The return type of find_file_and_directory.  Note, the enclosed
2052    string pointers are only valid while this object is valid.  */
2053
2054 struct file_and_directory
2055 {
2056   /* The filename.  This is never NULL.  */
2057   const char *name;
2058
2059   /* The compilation directory.  NULL if not known.  If we needed to
2060      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2061      points directly to the DW_AT_comp_dir string attribute owned by
2062      the obstack that owns the DIE.  */
2063   const char *comp_dir;
2064
2065   /* If we needed to build a new string for comp_dir, this is what
2066      owns the storage.  */
2067   std::string comp_dir_storage;
2068 };
2069
2070 static file_and_directory find_file_and_directory (struct die_info *die,
2071                                                    struct dwarf2_cu *cu);
2072
2073 static char *file_full_name (int file, struct line_header *lh,
2074                              const char *comp_dir);
2075
2076 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2077 enum class rcuh_kind { COMPILE, TYPE };
2078
2079 static const gdb_byte *read_and_check_comp_unit_head
2080   (struct comp_unit_head *header,
2081    struct dwarf2_section_info *section,
2082    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2083    rcuh_kind section_kind);
2084
2085 static void init_cutu_and_read_dies
2086   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2087    int use_existing_cu, int keep,
2088    die_reader_func_ftype *die_reader_func, void *data);
2089
2090 static void init_cutu_and_read_dies_simple
2091   (struct dwarf2_per_cu_data *this_cu,
2092    die_reader_func_ftype *die_reader_func, void *data);
2093
2094 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2095
2096 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2097
2098 static struct dwo_unit *lookup_dwo_unit_in_dwp
2099   (struct dwp_file *dwp_file, const char *comp_dir,
2100    ULONGEST signature, int is_debug_types);
2101
2102 static struct dwp_file *get_dwp_file (void);
2103
2104 static struct dwo_unit *lookup_dwo_comp_unit
2105   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2106
2107 static struct dwo_unit *lookup_dwo_type_unit
2108   (struct signatured_type *, const char *, const char *);
2109
2110 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2111
2112 static void free_dwo_file_cleanup (void *);
2113
2114 static void process_cu_includes (void);
2115
2116 static void check_producer (struct dwarf2_cu *cu);
2117
2118 static void free_line_header_voidp (void *arg);
2119 \f
2120 /* Various complaints about symbol reading that don't abort the process.  */
2121
2122 static void
2123 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2124 {
2125   complaint (&symfile_complaints,
2126              _("statement list doesn't fit in .debug_line section"));
2127 }
2128
2129 static void
2130 dwarf2_debug_line_missing_file_complaint (void)
2131 {
2132   complaint (&symfile_complaints,
2133              _(".debug_line section has line data without a file"));
2134 }
2135
2136 static void
2137 dwarf2_debug_line_missing_end_sequence_complaint (void)
2138 {
2139   complaint (&symfile_complaints,
2140              _(".debug_line section has line "
2141                "program sequence without an end"));
2142 }
2143
2144 static void
2145 dwarf2_complex_location_expr_complaint (void)
2146 {
2147   complaint (&symfile_complaints, _("location expression too complex"));
2148 }
2149
2150 static void
2151 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2152                                               int arg3)
2153 {
2154   complaint (&symfile_complaints,
2155              _("const value length mismatch for '%s', got %d, expected %d"),
2156              arg1, arg2, arg3);
2157 }
2158
2159 static void
2160 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2161 {
2162   complaint (&symfile_complaints,
2163              _("debug info runs off end of %s section"
2164                " [in module %s]"),
2165              get_section_name (section),
2166              get_section_file_name (section));
2167 }
2168
2169 static void
2170 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2171 {
2172   complaint (&symfile_complaints,
2173              _("macro debug info contains a "
2174                "malformed macro definition:\n`%s'"),
2175              arg1);
2176 }
2177
2178 static void
2179 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2180 {
2181   complaint (&symfile_complaints,
2182              _("invalid attribute class or form for '%s' in '%s'"),
2183              arg1, arg2);
2184 }
2185
2186 /* Hash function for line_header_hash.  */
2187
2188 static hashval_t
2189 line_header_hash (const struct line_header *ofs)
2190 {
2191   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2192 }
2193
2194 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2195
2196 static hashval_t
2197 line_header_hash_voidp (const void *item)
2198 {
2199   const struct line_header *ofs = (const struct line_header *) item;
2200
2201   return line_header_hash (ofs);
2202 }
2203
2204 /* Equality function for line_header_hash.  */
2205
2206 static int
2207 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2208 {
2209   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2210   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2211
2212   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2213           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2214 }
2215
2216 \f
2217
2218 /* Read the given attribute value as an address, taking the attribute's
2219    form into account.  */
2220
2221 static CORE_ADDR
2222 attr_value_as_address (struct attribute *attr)
2223 {
2224   CORE_ADDR addr;
2225
2226   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2227     {
2228       /* Aside from a few clearly defined exceptions, attributes that
2229          contain an address must always be in DW_FORM_addr form.
2230          Unfortunately, some compilers happen to be violating this
2231          requirement by encoding addresses using other forms, such
2232          as DW_FORM_data4 for example.  For those broken compilers,
2233          we try to do our best, without any guarantee of success,
2234          to interpret the address correctly.  It would also be nice
2235          to generate a complaint, but that would require us to maintain
2236          a list of legitimate cases where a non-address form is allowed,
2237          as well as update callers to pass in at least the CU's DWARF
2238          version.  This is more overhead than what we're willing to
2239          expand for a pretty rare case.  */
2240       addr = DW_UNSND (attr);
2241     }
2242   else
2243     addr = DW_ADDR (attr);
2244
2245   return addr;
2246 }
2247
2248 /* The suffix for an index file.  */
2249 #define INDEX_SUFFIX ".gdb-index"
2250
2251 /* See declaration.  */
2252
2253 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2254                                         const dwarf2_debug_sections *names)
2255   : objfile (objfile_)
2256 {
2257   if (names == NULL)
2258     names = &dwarf2_elf_names;
2259
2260   bfd *obfd = objfile->obfd;
2261
2262   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2263     locate_sections (obfd, sec, *names);
2264 }
2265
2266 dwarf2_per_objfile::~dwarf2_per_objfile ()
2267 {
2268   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2269   free_cached_comp_units ();
2270
2271   if (quick_file_names_table)
2272     htab_delete (quick_file_names_table);
2273
2274   if (line_header_hash)
2275     htab_delete (line_header_hash);
2276
2277   /* Everything else should be on the objfile obstack.  */
2278 }
2279
2280 /* See declaration.  */
2281
2282 void
2283 dwarf2_per_objfile::free_cached_comp_units ()
2284 {
2285   dwarf2_per_cu_data *per_cu = read_in_chain;
2286   dwarf2_per_cu_data **last_chain = &read_in_chain;
2287   while (per_cu != NULL)
2288     {
2289       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2290
2291       free_heap_comp_unit (per_cu->cu);
2292       *last_chain = next_cu;
2293       per_cu = next_cu;
2294     }
2295 }
2296
2297 /* Try to locate the sections we need for DWARF 2 debugging
2298    information and return true if we have enough to do something.
2299    NAMES points to the dwarf2 section names, or is NULL if the standard
2300    ELF names are used.  */
2301
2302 int
2303 dwarf2_has_info (struct objfile *objfile,
2304                  const struct dwarf2_debug_sections *names)
2305 {
2306   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2307                         objfile_data (objfile, dwarf2_objfile_data_key));
2308   if (!dwarf2_per_objfile)
2309     {
2310       /* Initialize per-objfile state.  */
2311       struct dwarf2_per_objfile *data
2312         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2313
2314       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2315       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2316     }
2317   return (!dwarf2_per_objfile->info.is_virtual
2318           && dwarf2_per_objfile->info.s.section != NULL
2319           && !dwarf2_per_objfile->abbrev.is_virtual
2320           && dwarf2_per_objfile->abbrev.s.section != NULL);
2321 }
2322
2323 /* Return the containing section of virtual section SECTION.  */
2324
2325 static struct dwarf2_section_info *
2326 get_containing_section (const struct dwarf2_section_info *section)
2327 {
2328   gdb_assert (section->is_virtual);
2329   return section->s.containing_section;
2330 }
2331
2332 /* Return the bfd owner of SECTION.  */
2333
2334 static struct bfd *
2335 get_section_bfd_owner (const struct dwarf2_section_info *section)
2336 {
2337   if (section->is_virtual)
2338     {
2339       section = get_containing_section (section);
2340       gdb_assert (!section->is_virtual);
2341     }
2342   return section->s.section->owner;
2343 }
2344
2345 /* Return the bfd section of SECTION.
2346    Returns NULL if the section is not present.  */
2347
2348 static asection *
2349 get_section_bfd_section (const struct dwarf2_section_info *section)
2350 {
2351   if (section->is_virtual)
2352     {
2353       section = get_containing_section (section);
2354       gdb_assert (!section->is_virtual);
2355     }
2356   return section->s.section;
2357 }
2358
2359 /* Return the name of SECTION.  */
2360
2361 static const char *
2362 get_section_name (const struct dwarf2_section_info *section)
2363 {
2364   asection *sectp = get_section_bfd_section (section);
2365
2366   gdb_assert (sectp != NULL);
2367   return bfd_section_name (get_section_bfd_owner (section), sectp);
2368 }
2369
2370 /* Return the name of the file SECTION is in.  */
2371
2372 static const char *
2373 get_section_file_name (const struct dwarf2_section_info *section)
2374 {
2375   bfd *abfd = get_section_bfd_owner (section);
2376
2377   return bfd_get_filename (abfd);
2378 }
2379
2380 /* Return the id of SECTION.
2381    Returns 0 if SECTION doesn't exist.  */
2382
2383 static int
2384 get_section_id (const struct dwarf2_section_info *section)
2385 {
2386   asection *sectp = get_section_bfd_section (section);
2387
2388   if (sectp == NULL)
2389     return 0;
2390   return sectp->id;
2391 }
2392
2393 /* Return the flags of SECTION.
2394    SECTION (or containing section if this is a virtual section) must exist.  */
2395
2396 static int
2397 get_section_flags (const struct dwarf2_section_info *section)
2398 {
2399   asection *sectp = get_section_bfd_section (section);
2400
2401   gdb_assert (sectp != NULL);
2402   return bfd_get_section_flags (sectp->owner, sectp);
2403 }
2404
2405 /* When loading sections, we look either for uncompressed section or for
2406    compressed section names.  */
2407
2408 static int
2409 section_is_p (const char *section_name,
2410               const struct dwarf2_section_names *names)
2411 {
2412   if (names->normal != NULL
2413       && strcmp (section_name, names->normal) == 0)
2414     return 1;
2415   if (names->compressed != NULL
2416       && strcmp (section_name, names->compressed) == 0)
2417     return 1;
2418   return 0;
2419 }
2420
2421 /* See declaration.  */
2422
2423 void
2424 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2425                                      const dwarf2_debug_sections &names)
2426 {
2427   flagword aflag = bfd_get_section_flags (abfd, sectp);
2428
2429   if ((aflag & SEC_HAS_CONTENTS) == 0)
2430     {
2431     }
2432   else if (section_is_p (sectp->name, &names.info))
2433     {
2434       this->info.s.section = sectp;
2435       this->info.size = bfd_get_section_size (sectp);
2436     }
2437   else if (section_is_p (sectp->name, &names.abbrev))
2438     {
2439       this->abbrev.s.section = sectp;
2440       this->abbrev.size = bfd_get_section_size (sectp);
2441     }
2442   else if (section_is_p (sectp->name, &names.line))
2443     {
2444       this->line.s.section = sectp;
2445       this->line.size = bfd_get_section_size (sectp);
2446     }
2447   else if (section_is_p (sectp->name, &names.loc))
2448     {
2449       this->loc.s.section = sectp;
2450       this->loc.size = bfd_get_section_size (sectp);
2451     }
2452   else if (section_is_p (sectp->name, &names.loclists))
2453     {
2454       this->loclists.s.section = sectp;
2455       this->loclists.size = bfd_get_section_size (sectp);
2456     }
2457   else if (section_is_p (sectp->name, &names.macinfo))
2458     {
2459       this->macinfo.s.section = sectp;
2460       this->macinfo.size = bfd_get_section_size (sectp);
2461     }
2462   else if (section_is_p (sectp->name, &names.macro))
2463     {
2464       this->macro.s.section = sectp;
2465       this->macro.size = bfd_get_section_size (sectp);
2466     }
2467   else if (section_is_p (sectp->name, &names.str))
2468     {
2469       this->str.s.section = sectp;
2470       this->str.size = bfd_get_section_size (sectp);
2471     }
2472   else if (section_is_p (sectp->name, &names.line_str))
2473     {
2474       this->line_str.s.section = sectp;
2475       this->line_str.size = bfd_get_section_size (sectp);
2476     }
2477   else if (section_is_p (sectp->name, &names.addr))
2478     {
2479       this->addr.s.section = sectp;
2480       this->addr.size = bfd_get_section_size (sectp);
2481     }
2482   else if (section_is_p (sectp->name, &names.frame))
2483     {
2484       this->frame.s.section = sectp;
2485       this->frame.size = bfd_get_section_size (sectp);
2486     }
2487   else if (section_is_p (sectp->name, &names.eh_frame))
2488     {
2489       this->eh_frame.s.section = sectp;
2490       this->eh_frame.size = bfd_get_section_size (sectp);
2491     }
2492   else if (section_is_p (sectp->name, &names.ranges))
2493     {
2494       this->ranges.s.section = sectp;
2495       this->ranges.size = bfd_get_section_size (sectp);
2496     }
2497   else if (section_is_p (sectp->name, &names.rnglists))
2498     {
2499       this->rnglists.s.section = sectp;
2500       this->rnglists.size = bfd_get_section_size (sectp);
2501     }
2502   else if (section_is_p (sectp->name, &names.types))
2503     {
2504       struct dwarf2_section_info type_section;
2505
2506       memset (&type_section, 0, sizeof (type_section));
2507       type_section.s.section = sectp;
2508       type_section.size = bfd_get_section_size (sectp);
2509
2510       VEC_safe_push (dwarf2_section_info_def, this->types,
2511                      &type_section);
2512     }
2513   else if (section_is_p (sectp->name, &names.gdb_index))
2514     {
2515       this->gdb_index.s.section = sectp;
2516       this->gdb_index.size = bfd_get_section_size (sectp);
2517     }
2518
2519   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2520       && bfd_section_vma (abfd, sectp) == 0)
2521     this->has_section_at_zero = true;
2522 }
2523
2524 /* A helper function that decides whether a section is empty,
2525    or not present.  */
2526
2527 static int
2528 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2529 {
2530   if (section->is_virtual)
2531     return section->size == 0;
2532   return section->s.section == NULL || section->size == 0;
2533 }
2534
2535 /* Read the contents of the section INFO.
2536    OBJFILE is the main object file, but not necessarily the file where
2537    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2538    of the DWO file.
2539    If the section is compressed, uncompress it before returning.  */
2540
2541 static void
2542 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2543 {
2544   asection *sectp;
2545   bfd *abfd;
2546   gdb_byte *buf, *retbuf;
2547
2548   if (info->readin)
2549     return;
2550   info->buffer = NULL;
2551   info->readin = 1;
2552
2553   if (dwarf2_section_empty_p (info))
2554     return;
2555
2556   sectp = get_section_bfd_section (info);
2557
2558   /* If this is a virtual section we need to read in the real one first.  */
2559   if (info->is_virtual)
2560     {
2561       struct dwarf2_section_info *containing_section =
2562         get_containing_section (info);
2563
2564       gdb_assert (sectp != NULL);
2565       if ((sectp->flags & SEC_RELOC) != 0)
2566         {
2567           error (_("Dwarf Error: DWP format V2 with relocations is not"
2568                    " supported in section %s [in module %s]"),
2569                  get_section_name (info), get_section_file_name (info));
2570         }
2571       dwarf2_read_section (objfile, containing_section);
2572       /* Other code should have already caught virtual sections that don't
2573          fit.  */
2574       gdb_assert (info->virtual_offset + info->size
2575                   <= containing_section->size);
2576       /* If the real section is empty or there was a problem reading the
2577          section we shouldn't get here.  */
2578       gdb_assert (containing_section->buffer != NULL);
2579       info->buffer = containing_section->buffer + info->virtual_offset;
2580       return;
2581     }
2582
2583   /* If the section has relocations, we must read it ourselves.
2584      Otherwise we attach it to the BFD.  */
2585   if ((sectp->flags & SEC_RELOC) == 0)
2586     {
2587       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2588       return;
2589     }
2590
2591   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2592   info->buffer = buf;
2593
2594   /* When debugging .o files, we may need to apply relocations; see
2595      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2596      We never compress sections in .o files, so we only need to
2597      try this when the section is not compressed.  */
2598   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2599   if (retbuf != NULL)
2600     {
2601       info->buffer = retbuf;
2602       return;
2603     }
2604
2605   abfd = get_section_bfd_owner (info);
2606   gdb_assert (abfd != NULL);
2607
2608   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2609       || bfd_bread (buf, info->size, abfd) != info->size)
2610     {
2611       error (_("Dwarf Error: Can't read DWARF data"
2612                " in section %s [in module %s]"),
2613              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2614     }
2615 }
2616
2617 /* A helper function that returns the size of a section in a safe way.
2618    If you are positive that the section has been read before using the
2619    size, then it is safe to refer to the dwarf2_section_info object's
2620    "size" field directly.  In other cases, you must call this
2621    function, because for compressed sections the size field is not set
2622    correctly until the section has been read.  */
2623
2624 static bfd_size_type
2625 dwarf2_section_size (struct objfile *objfile,
2626                      struct dwarf2_section_info *info)
2627 {
2628   if (!info->readin)
2629     dwarf2_read_section (objfile, info);
2630   return info->size;
2631 }
2632
2633 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2634    SECTION_NAME.  */
2635
2636 void
2637 dwarf2_get_section_info (struct objfile *objfile,
2638                          enum dwarf2_section_enum sect,
2639                          asection **sectp, const gdb_byte **bufp,
2640                          bfd_size_type *sizep)
2641 {
2642   struct dwarf2_per_objfile *data
2643     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2644                                                   dwarf2_objfile_data_key);
2645   struct dwarf2_section_info *info;
2646
2647   /* We may see an objfile without any DWARF, in which case we just
2648      return nothing.  */
2649   if (data == NULL)
2650     {
2651       *sectp = NULL;
2652       *bufp = NULL;
2653       *sizep = 0;
2654       return;
2655     }
2656   switch (sect)
2657     {
2658     case DWARF2_DEBUG_FRAME:
2659       info = &data->frame;
2660       break;
2661     case DWARF2_EH_FRAME:
2662       info = &data->eh_frame;
2663       break;
2664     default:
2665       gdb_assert_not_reached ("unexpected section");
2666     }
2667
2668   dwarf2_read_section (objfile, info);
2669
2670   *sectp = get_section_bfd_section (info);
2671   *bufp = info->buffer;
2672   *sizep = info->size;
2673 }
2674
2675 /* A helper function to find the sections for a .dwz file.  */
2676
2677 static void
2678 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2679 {
2680   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2681
2682   /* Note that we only support the standard ELF names, because .dwz
2683      is ELF-only (at the time of writing).  */
2684   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2685     {
2686       dwz_file->abbrev.s.section = sectp;
2687       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2688     }
2689   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2690     {
2691       dwz_file->info.s.section = sectp;
2692       dwz_file->info.size = bfd_get_section_size (sectp);
2693     }
2694   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2695     {
2696       dwz_file->str.s.section = sectp;
2697       dwz_file->str.size = bfd_get_section_size (sectp);
2698     }
2699   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2700     {
2701       dwz_file->line.s.section = sectp;
2702       dwz_file->line.size = bfd_get_section_size (sectp);
2703     }
2704   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2705     {
2706       dwz_file->macro.s.section = sectp;
2707       dwz_file->macro.size = bfd_get_section_size (sectp);
2708     }
2709   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2710     {
2711       dwz_file->gdb_index.s.section = sectp;
2712       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2713     }
2714 }
2715
2716 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2717    there is no .gnu_debugaltlink section in the file.  Error if there
2718    is such a section but the file cannot be found.  */
2719
2720 static struct dwz_file *
2721 dwarf2_get_dwz_file (void)
2722 {
2723   const char *filename;
2724   struct dwz_file *result;
2725   bfd_size_type buildid_len_arg;
2726   size_t buildid_len;
2727   bfd_byte *buildid;
2728
2729   if (dwarf2_per_objfile->dwz_file != NULL)
2730     return dwarf2_per_objfile->dwz_file;
2731
2732   bfd_set_error (bfd_error_no_error);
2733   gdb::unique_xmalloc_ptr<char> data
2734     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2735                                   &buildid_len_arg, &buildid));
2736   if (data == NULL)
2737     {
2738       if (bfd_get_error () == bfd_error_no_error)
2739         return NULL;
2740       error (_("could not read '.gnu_debugaltlink' section: %s"),
2741              bfd_errmsg (bfd_get_error ()));
2742     }
2743
2744   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2745
2746   buildid_len = (size_t) buildid_len_arg;
2747
2748   filename = data.get ();
2749
2750   std::string abs_storage;
2751   if (!IS_ABSOLUTE_PATH (filename))
2752     {
2753       gdb::unique_xmalloc_ptr<char> abs
2754         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2755
2756       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2757       filename = abs_storage.c_str ();
2758     }
2759
2760   /* First try the file name given in the section.  If that doesn't
2761      work, try to use the build-id instead.  */
2762   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2763   if (dwz_bfd != NULL)
2764     {
2765       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2766         dwz_bfd.release ();
2767     }
2768
2769   if (dwz_bfd == NULL)
2770     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2771
2772   if (dwz_bfd == NULL)
2773     error (_("could not find '.gnu_debugaltlink' file for %s"),
2774            objfile_name (dwarf2_per_objfile->objfile));
2775
2776   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2777                            struct dwz_file);
2778   result->dwz_bfd = dwz_bfd.release ();
2779
2780   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2781
2782   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2783   dwarf2_per_objfile->dwz_file = result;
2784   return result;
2785 }
2786 \f
2787 /* DWARF quick_symbols_functions support.  */
2788
2789 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2790    unique line tables, so we maintain a separate table of all .debug_line
2791    derived entries to support the sharing.
2792    All the quick functions need is the list of file names.  We discard the
2793    line_header when we're done and don't need to record it here.  */
2794 struct quick_file_names
2795 {
2796   /* The data used to construct the hash key.  */
2797   struct stmt_list_hash hash;
2798
2799   /* The number of entries in file_names, real_names.  */
2800   unsigned int num_file_names;
2801
2802   /* The file names from the line table, after being run through
2803      file_full_name.  */
2804   const char **file_names;
2805
2806   /* The file names from the line table after being run through
2807      gdb_realpath.  These are computed lazily.  */
2808   const char **real_names;
2809 };
2810
2811 /* When using the index (and thus not using psymtabs), each CU has an
2812    object of this type.  This is used to hold information needed by
2813    the various "quick" methods.  */
2814 struct dwarf2_per_cu_quick_data
2815 {
2816   /* The file table.  This can be NULL if there was no file table
2817      or it's currently not read in.
2818      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2819   struct quick_file_names *file_names;
2820
2821   /* The corresponding symbol table.  This is NULL if symbols for this
2822      CU have not yet been read.  */
2823   struct compunit_symtab *compunit_symtab;
2824
2825   /* A temporary mark bit used when iterating over all CUs in
2826      expand_symtabs_matching.  */
2827   unsigned int mark : 1;
2828
2829   /* True if we've tried to read the file table and found there isn't one.
2830      There will be no point in trying to read it again next time.  */
2831   unsigned int no_file_data : 1;
2832 };
2833
2834 /* Utility hash function for a stmt_list_hash.  */
2835
2836 static hashval_t
2837 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2838 {
2839   hashval_t v = 0;
2840
2841   if (stmt_list_hash->dwo_unit != NULL)
2842     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2843   v += to_underlying (stmt_list_hash->line_sect_off);
2844   return v;
2845 }
2846
2847 /* Utility equality function for a stmt_list_hash.  */
2848
2849 static int
2850 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2851                     const struct stmt_list_hash *rhs)
2852 {
2853   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2854     return 0;
2855   if (lhs->dwo_unit != NULL
2856       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2857     return 0;
2858
2859   return lhs->line_sect_off == rhs->line_sect_off;
2860 }
2861
2862 /* Hash function for a quick_file_names.  */
2863
2864 static hashval_t
2865 hash_file_name_entry (const void *e)
2866 {
2867   const struct quick_file_names *file_data
2868     = (const struct quick_file_names *) e;
2869
2870   return hash_stmt_list_entry (&file_data->hash);
2871 }
2872
2873 /* Equality function for a quick_file_names.  */
2874
2875 static int
2876 eq_file_name_entry (const void *a, const void *b)
2877 {
2878   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2879   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2880
2881   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2882 }
2883
2884 /* Delete function for a quick_file_names.  */
2885
2886 static void
2887 delete_file_name_entry (void *e)
2888 {
2889   struct quick_file_names *file_data = (struct quick_file_names *) e;
2890   int i;
2891
2892   for (i = 0; i < file_data->num_file_names; ++i)
2893     {
2894       xfree ((void*) file_data->file_names[i]);
2895       if (file_data->real_names)
2896         xfree ((void*) file_data->real_names[i]);
2897     }
2898
2899   /* The space for the struct itself lives on objfile_obstack,
2900      so we don't free it here.  */
2901 }
2902
2903 /* Create a quick_file_names hash table.  */
2904
2905 static htab_t
2906 create_quick_file_names_table (unsigned int nr_initial_entries)
2907 {
2908   return htab_create_alloc (nr_initial_entries,
2909                             hash_file_name_entry, eq_file_name_entry,
2910                             delete_file_name_entry, xcalloc, xfree);
2911 }
2912
2913 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2914    have to be created afterwards.  You should call age_cached_comp_units after
2915    processing PER_CU->CU.  dw2_setup must have been already called.  */
2916
2917 static void
2918 load_cu (struct dwarf2_per_cu_data *per_cu)
2919 {
2920   if (per_cu->is_debug_types)
2921     load_full_type_unit (per_cu);
2922   else
2923     load_full_comp_unit (per_cu, language_minimal);
2924
2925   if (per_cu->cu == NULL)
2926     return;  /* Dummy CU.  */
2927
2928   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2929 }
2930
2931 /* Read in the symbols for PER_CU.  */
2932
2933 static void
2934 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2935 {
2936   struct cleanup *back_to;
2937
2938   /* Skip type_unit_groups, reading the type units they contain
2939      is handled elsewhere.  */
2940   if (IS_TYPE_UNIT_GROUP (per_cu))
2941     return;
2942
2943   back_to = make_cleanup (dwarf2_release_queue, NULL);
2944
2945   if (dwarf2_per_objfile->using_index
2946       ? per_cu->v.quick->compunit_symtab == NULL
2947       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2948     {
2949       queue_comp_unit (per_cu, language_minimal);
2950       load_cu (per_cu);
2951
2952       /* If we just loaded a CU from a DWO, and we're working with an index
2953          that may badly handle TUs, load all the TUs in that DWO as well.
2954          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2955       if (!per_cu->is_debug_types
2956           && per_cu->cu != NULL
2957           && per_cu->cu->dwo_unit != NULL
2958           && dwarf2_per_objfile->index_table != NULL
2959           && dwarf2_per_objfile->index_table->version <= 7
2960           /* DWP files aren't supported yet.  */
2961           && get_dwp_file () == NULL)
2962         queue_and_load_all_dwo_tus (per_cu);
2963     }
2964
2965   process_queue ();
2966
2967   /* Age the cache, releasing compilation units that have not
2968      been used recently.  */
2969   age_cached_comp_units ();
2970
2971   do_cleanups (back_to);
2972 }
2973
2974 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2975    the objfile from which this CU came.  Returns the resulting symbol
2976    table.  */
2977
2978 static struct compunit_symtab *
2979 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2980 {
2981   gdb_assert (dwarf2_per_objfile->using_index);
2982   if (!per_cu->v.quick->compunit_symtab)
2983     {
2984       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2985       scoped_restore decrementer = increment_reading_symtab ();
2986       dw2_do_instantiate_symtab (per_cu);
2987       process_cu_includes ();
2988       do_cleanups (back_to);
2989     }
2990
2991   return per_cu->v.quick->compunit_symtab;
2992 }
2993
2994 /* Return the CU/TU given its index.
2995
2996    This is intended for loops like:
2997
2998    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2999                     + dwarf2_per_objfile->n_type_units); ++i)
3000      {
3001        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3002
3003        ...;
3004      }
3005 */
3006
3007 static struct dwarf2_per_cu_data *
3008 dw2_get_cutu (int index)
3009 {
3010   if (index >= dwarf2_per_objfile->n_comp_units)
3011     {
3012       index -= dwarf2_per_objfile->n_comp_units;
3013       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3014       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3015     }
3016
3017   return dwarf2_per_objfile->all_comp_units[index];
3018 }
3019
3020 /* Return the CU given its index.
3021    This differs from dw2_get_cutu in that it's for when you know INDEX
3022    refers to a CU.  */
3023
3024 static struct dwarf2_per_cu_data *
3025 dw2_get_cu (int index)
3026 {
3027   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3028
3029   return dwarf2_per_objfile->all_comp_units[index];
3030 }
3031
3032 /* A helper for create_cus_from_index that handles a given list of
3033    CUs.  */
3034
3035 static void
3036 create_cus_from_index_list (struct objfile *objfile,
3037                             const gdb_byte *cu_list, offset_type n_elements,
3038                             struct dwarf2_section_info *section,
3039                             int is_dwz,
3040                             int base_offset)
3041 {
3042   offset_type i;
3043
3044   for (i = 0; i < n_elements; i += 2)
3045     {
3046       gdb_static_assert (sizeof (ULONGEST) >= 8);
3047
3048       sect_offset sect_off
3049         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3050       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3051       cu_list += 2 * 8;
3052
3053       dwarf2_per_cu_data *the_cu
3054         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3055                           struct dwarf2_per_cu_data);
3056       the_cu->sect_off = sect_off;
3057       the_cu->length = length;
3058       the_cu->objfile = objfile;
3059       the_cu->section = section;
3060       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3061                                         struct dwarf2_per_cu_quick_data);
3062       the_cu->is_dwz = is_dwz;
3063       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3064     }
3065 }
3066
3067 /* Read the CU list from the mapped index, and use it to create all
3068    the CU objects for this objfile.  */
3069
3070 static void
3071 create_cus_from_index (struct objfile *objfile,
3072                        const gdb_byte *cu_list, offset_type cu_list_elements,
3073                        const gdb_byte *dwz_list, offset_type dwz_elements)
3074 {
3075   struct dwz_file *dwz;
3076
3077   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3078   dwarf2_per_objfile->all_comp_units =
3079     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3080                dwarf2_per_objfile->n_comp_units);
3081
3082   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3083                               &dwarf2_per_objfile->info, 0, 0);
3084
3085   if (dwz_elements == 0)
3086     return;
3087
3088   dwz = dwarf2_get_dwz_file ();
3089   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3090                               cu_list_elements / 2);
3091 }
3092
3093 /* Create the signatured type hash table from the index.  */
3094
3095 static void
3096 create_signatured_type_table_from_index (struct objfile *objfile,
3097                                          struct dwarf2_section_info *section,
3098                                          const gdb_byte *bytes,
3099                                          offset_type elements)
3100 {
3101   offset_type i;
3102   htab_t sig_types_hash;
3103
3104   dwarf2_per_objfile->n_type_units
3105     = dwarf2_per_objfile->n_allocated_type_units
3106     = elements / 3;
3107   dwarf2_per_objfile->all_type_units =
3108     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3109
3110   sig_types_hash = allocate_signatured_type_table (objfile);
3111
3112   for (i = 0; i < elements; i += 3)
3113     {
3114       struct signatured_type *sig_type;
3115       ULONGEST signature;
3116       void **slot;
3117       cu_offset type_offset_in_tu;
3118
3119       gdb_static_assert (sizeof (ULONGEST) >= 8);
3120       sect_offset sect_off
3121         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3122       type_offset_in_tu
3123         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3124                                                 BFD_ENDIAN_LITTLE);
3125       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3126       bytes += 3 * 8;
3127
3128       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3129                                  struct signatured_type);
3130       sig_type->signature = signature;
3131       sig_type->type_offset_in_tu = type_offset_in_tu;
3132       sig_type->per_cu.is_debug_types = 1;
3133       sig_type->per_cu.section = section;
3134       sig_type->per_cu.sect_off = sect_off;
3135       sig_type->per_cu.objfile = objfile;
3136       sig_type->per_cu.v.quick
3137         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3138                           struct dwarf2_per_cu_quick_data);
3139
3140       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3141       *slot = sig_type;
3142
3143       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3144     }
3145
3146   dwarf2_per_objfile->signatured_types = sig_types_hash;
3147 }
3148
3149 /* Read the address map data from the mapped index, and use it to
3150    populate the objfile's psymtabs_addrmap.  */
3151
3152 static void
3153 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3154 {
3155   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3156   const gdb_byte *iter, *end;
3157   struct addrmap *mutable_map;
3158   CORE_ADDR baseaddr;
3159
3160   auto_obstack temp_obstack;
3161
3162   mutable_map = addrmap_create_mutable (&temp_obstack);
3163
3164   iter = index->address_table;
3165   end = iter + index->address_table_size;
3166
3167   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3168
3169   while (iter < end)
3170     {
3171       ULONGEST hi, lo, cu_index;
3172       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3173       iter += 8;
3174       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3175       iter += 8;
3176       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3177       iter += 4;
3178
3179       if (lo > hi)
3180         {
3181           complaint (&symfile_complaints,
3182                      _(".gdb_index address table has invalid range (%s - %s)"),
3183                      hex_string (lo), hex_string (hi));
3184           continue;
3185         }
3186
3187       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3188         {
3189           complaint (&symfile_complaints,
3190                      _(".gdb_index address table has invalid CU number %u"),
3191                      (unsigned) cu_index);
3192           continue;
3193         }
3194
3195       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3196       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3197       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3198     }
3199
3200   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3201                                                     &objfile->objfile_obstack);
3202 }
3203
3204 /* The hash function for strings in the mapped index.  This is the same as
3205    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3206    implementation.  This is necessary because the hash function is tied to the
3207    format of the mapped index file.  The hash values do not have to match with
3208    SYMBOL_HASH_NEXT.
3209    
3210    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3211
3212 static hashval_t
3213 mapped_index_string_hash (int index_version, const void *p)
3214 {
3215   const unsigned char *str = (const unsigned char *) p;
3216   hashval_t r = 0;
3217   unsigned char c;
3218
3219   while ((c = *str++) != 0)
3220     {
3221       if (index_version >= 5)
3222         c = tolower (c);
3223       r = r * 67 + c - 113;
3224     }
3225
3226   return r;
3227 }
3228
3229 /* Find a slot in the mapped index INDEX for the object named NAME.
3230    If NAME is found, set *VEC_OUT to point to the CU vector in the
3231    constant pool and return true.  If NAME cannot be found, return
3232    false.  */
3233
3234 static bool
3235 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3236                           offset_type **vec_out)
3237 {
3238   offset_type hash;
3239   offset_type slot, step;
3240   int (*cmp) (const char *, const char *);
3241
3242   gdb::unique_xmalloc_ptr<char> without_params;
3243   if (current_language->la_language == language_cplus
3244       || current_language->la_language == language_fortran
3245       || current_language->la_language == language_d)
3246     {
3247       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3248          not contain any.  */
3249
3250       if (strchr (name, '(') != NULL)
3251         {
3252           without_params = cp_remove_params (name);
3253
3254           if (without_params != NULL)
3255             name = without_params.get ();
3256         }
3257     }
3258
3259   /* Index version 4 did not support case insensitive searches.  But the
3260      indices for case insensitive languages are built in lowercase, therefore
3261      simulate our NAME being searched is also lowercased.  */
3262   hash = mapped_index_string_hash ((index->version == 4
3263                                     && case_sensitivity == case_sensitive_off
3264                                     ? 5 : index->version),
3265                                    name);
3266
3267   slot = hash & (index->symbol_table_slots - 1);
3268   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3269   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3270
3271   for (;;)
3272     {
3273       /* Convert a slot number to an offset into the table.  */
3274       offset_type i = 2 * slot;
3275       const char *str;
3276       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3277         return false;
3278
3279       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3280       if (!cmp (name, str))
3281         {
3282           *vec_out = (offset_type *) (index->constant_pool
3283                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3284           return true;
3285         }
3286
3287       slot = (slot + step) & (index->symbol_table_slots - 1);
3288     }
3289 }
3290
3291 /* A helper function that reads the .gdb_index from SECTION and fills
3292    in MAP.  FILENAME is the name of the file containing the section;
3293    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3294    ok to use deprecated sections.
3295
3296    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3297    out parameters that are filled in with information about the CU and
3298    TU lists in the section.
3299
3300    Returns 1 if all went well, 0 otherwise.  */
3301
3302 static int
3303 read_index_from_section (struct objfile *objfile,
3304                          const char *filename,
3305                          int deprecated_ok,
3306                          struct dwarf2_section_info *section,
3307                          struct mapped_index *map,
3308                          const gdb_byte **cu_list,
3309                          offset_type *cu_list_elements,
3310                          const gdb_byte **types_list,
3311                          offset_type *types_list_elements)
3312 {
3313   const gdb_byte *addr;
3314   offset_type version;
3315   offset_type *metadata;
3316   int i;
3317
3318   if (dwarf2_section_empty_p (section))
3319     return 0;
3320
3321   /* Older elfutils strip versions could keep the section in the main
3322      executable while splitting it for the separate debug info file.  */
3323   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3324     return 0;
3325
3326   dwarf2_read_section (objfile, section);
3327
3328   addr = section->buffer;
3329   /* Version check.  */
3330   version = MAYBE_SWAP (*(offset_type *) addr);
3331   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3332      causes the index to behave very poorly for certain requests.  Version 3
3333      contained incomplete addrmap.  So, it seems better to just ignore such
3334      indices.  */
3335   if (version < 4)
3336     {
3337       static int warning_printed = 0;
3338       if (!warning_printed)
3339         {
3340           warning (_("Skipping obsolete .gdb_index section in %s."),
3341                    filename);
3342           warning_printed = 1;
3343         }
3344       return 0;
3345     }
3346   /* Index version 4 uses a different hash function than index version
3347      5 and later.
3348
3349      Versions earlier than 6 did not emit psymbols for inlined
3350      functions.  Using these files will cause GDB not to be able to
3351      set breakpoints on inlined functions by name, so we ignore these
3352      indices unless the user has done
3353      "set use-deprecated-index-sections on".  */
3354   if (version < 6 && !deprecated_ok)
3355     {
3356       static int warning_printed = 0;
3357       if (!warning_printed)
3358         {
3359           warning (_("\
3360 Skipping deprecated .gdb_index section in %s.\n\
3361 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3362 to use the section anyway."),
3363                    filename);
3364           warning_printed = 1;
3365         }
3366       return 0;
3367     }
3368   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3369      of the TU (for symbols coming from TUs),
3370      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3371      Plus gold-generated indices can have duplicate entries for global symbols,
3372      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3373      These are just performance bugs, and we can't distinguish gdb-generated
3374      indices from gold-generated ones, so issue no warning here.  */
3375
3376   /* Indexes with higher version than the one supported by GDB may be no
3377      longer backward compatible.  */
3378   if (version > 8)
3379     return 0;
3380
3381   map->version = version;
3382   map->total_size = section->size;
3383
3384   metadata = (offset_type *) (addr + sizeof (offset_type));
3385
3386   i = 0;
3387   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3388   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3389                        / 8);
3390   ++i;
3391
3392   *types_list = addr + MAYBE_SWAP (metadata[i]);
3393   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3394                            - MAYBE_SWAP (metadata[i]))
3395                           / 8);
3396   ++i;
3397
3398   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3399   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3400                              - MAYBE_SWAP (metadata[i]));
3401   ++i;
3402
3403   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3404   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3405                               - MAYBE_SWAP (metadata[i]))
3406                              / (2 * sizeof (offset_type)));
3407   ++i;
3408
3409   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3410
3411   return 1;
3412 }
3413
3414
3415 /* Read the index file.  If everything went ok, initialize the "quick"
3416    elements of all the CUs and return 1.  Otherwise, return 0.  */
3417
3418 static int
3419 dwarf2_read_index (struct objfile *objfile)
3420 {
3421   struct mapped_index local_map, *map;
3422   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3423   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3424   struct dwz_file *dwz;
3425
3426   if (!read_index_from_section (objfile, objfile_name (objfile),
3427                                 use_deprecated_index_sections,
3428                                 &dwarf2_per_objfile->gdb_index, &local_map,
3429                                 &cu_list, &cu_list_elements,
3430                                 &types_list, &types_list_elements))
3431     return 0;
3432
3433   /* Don't use the index if it's empty.  */
3434   if (local_map.symbol_table_slots == 0)
3435     return 0;
3436
3437   /* If there is a .dwz file, read it so we can get its CU list as
3438      well.  */
3439   dwz = dwarf2_get_dwz_file ();
3440   if (dwz != NULL)
3441     {
3442       struct mapped_index dwz_map;
3443       const gdb_byte *dwz_types_ignore;
3444       offset_type dwz_types_elements_ignore;
3445
3446       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3447                                     1,
3448                                     &dwz->gdb_index, &dwz_map,
3449                                     &dwz_list, &dwz_list_elements,
3450                                     &dwz_types_ignore,
3451                                     &dwz_types_elements_ignore))
3452         {
3453           warning (_("could not read '.gdb_index' section from %s; skipping"),
3454                    bfd_get_filename (dwz->dwz_bfd));
3455           return 0;
3456         }
3457     }
3458
3459   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3460                          dwz_list_elements);
3461
3462   if (types_list_elements)
3463     {
3464       struct dwarf2_section_info *section;
3465
3466       /* We can only handle a single .debug_types when we have an
3467          index.  */
3468       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3469         return 0;
3470
3471       section = VEC_index (dwarf2_section_info_def,
3472                            dwarf2_per_objfile->types, 0);
3473
3474       create_signatured_type_table_from_index (objfile, section, types_list,
3475                                                types_list_elements);
3476     }
3477
3478   create_addrmap_from_index (objfile, &local_map);
3479
3480   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3481   map = new (map) mapped_index ();
3482   *map = local_map;
3483
3484   dwarf2_per_objfile->index_table = map;
3485   dwarf2_per_objfile->using_index = 1;
3486   dwarf2_per_objfile->quick_file_names_table =
3487     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3488
3489   return 1;
3490 }
3491
3492 /* A helper for the "quick" functions which sets the global
3493    dwarf2_per_objfile according to OBJFILE.  */
3494
3495 static void
3496 dw2_setup (struct objfile *objfile)
3497 {
3498   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3499                         objfile_data (objfile, dwarf2_objfile_data_key));
3500   gdb_assert (dwarf2_per_objfile);
3501 }
3502
3503 /* die_reader_func for dw2_get_file_names.  */
3504
3505 static void
3506 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3507                            const gdb_byte *info_ptr,
3508                            struct die_info *comp_unit_die,
3509                            int has_children,
3510                            void *data)
3511 {
3512   struct dwarf2_cu *cu = reader->cu;
3513   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3514   struct objfile *objfile = dwarf2_per_objfile->objfile;
3515   struct dwarf2_per_cu_data *lh_cu;
3516   struct attribute *attr;
3517   int i;
3518   void **slot;
3519   struct quick_file_names *qfn;
3520
3521   gdb_assert (! this_cu->is_debug_types);
3522
3523   /* Our callers never want to match partial units -- instead they
3524      will match the enclosing full CU.  */
3525   if (comp_unit_die->tag == DW_TAG_partial_unit)
3526     {
3527       this_cu->v.quick->no_file_data = 1;
3528       return;
3529     }
3530
3531   lh_cu = this_cu;
3532   slot = NULL;
3533
3534   line_header_up lh;
3535   sect_offset line_offset {};
3536
3537   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3538   if (attr)
3539     {
3540       struct quick_file_names find_entry;
3541
3542       line_offset = (sect_offset) DW_UNSND (attr);
3543
3544       /* We may have already read in this line header (TU line header sharing).
3545          If we have we're done.  */
3546       find_entry.hash.dwo_unit = cu->dwo_unit;
3547       find_entry.hash.line_sect_off = line_offset;
3548       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3549                              &find_entry, INSERT);
3550       if (*slot != NULL)
3551         {
3552           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3553           return;
3554         }
3555
3556       lh = dwarf_decode_line_header (line_offset, cu);
3557     }
3558   if (lh == NULL)
3559     {
3560       lh_cu->v.quick->no_file_data = 1;
3561       return;
3562     }
3563
3564   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3565   qfn->hash.dwo_unit = cu->dwo_unit;
3566   qfn->hash.line_sect_off = line_offset;
3567   gdb_assert (slot != NULL);
3568   *slot = qfn;
3569
3570   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3571
3572   qfn->num_file_names = lh->file_names.size ();
3573   qfn->file_names =
3574     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3575   for (i = 0; i < lh->file_names.size (); ++i)
3576     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3577   qfn->real_names = NULL;
3578
3579   lh_cu->v.quick->file_names = qfn;
3580 }
3581
3582 /* A helper for the "quick" functions which attempts to read the line
3583    table for THIS_CU.  */
3584
3585 static struct quick_file_names *
3586 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3587 {
3588   /* This should never be called for TUs.  */
3589   gdb_assert (! this_cu->is_debug_types);
3590   /* Nor type unit groups.  */
3591   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3592
3593   if (this_cu->v.quick->file_names != NULL)
3594     return this_cu->v.quick->file_names;
3595   /* If we know there is no line data, no point in looking again.  */
3596   if (this_cu->v.quick->no_file_data)
3597     return NULL;
3598
3599   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3600
3601   if (this_cu->v.quick->no_file_data)
3602     return NULL;
3603   return this_cu->v.quick->file_names;
3604 }
3605
3606 /* A helper for the "quick" functions which computes and caches the
3607    real path for a given file name from the line table.  */
3608
3609 static const char *
3610 dw2_get_real_path (struct objfile *objfile,
3611                    struct quick_file_names *qfn, int index)
3612 {
3613   if (qfn->real_names == NULL)
3614     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3615                                       qfn->num_file_names, const char *);
3616
3617   if (qfn->real_names[index] == NULL)
3618     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3619
3620   return qfn->real_names[index];
3621 }
3622
3623 static struct symtab *
3624 dw2_find_last_source_symtab (struct objfile *objfile)
3625 {
3626   struct compunit_symtab *cust;
3627   int index;
3628
3629   dw2_setup (objfile);
3630   index = dwarf2_per_objfile->n_comp_units - 1;
3631   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3632   if (cust == NULL)
3633     return NULL;
3634   return compunit_primary_filetab (cust);
3635 }
3636
3637 /* Traversal function for dw2_forget_cached_source_info.  */
3638
3639 static int
3640 dw2_free_cached_file_names (void **slot, void *info)
3641 {
3642   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3643
3644   if (file_data->real_names)
3645     {
3646       int i;
3647
3648       for (i = 0; i < file_data->num_file_names; ++i)
3649         {
3650           xfree ((void*) file_data->real_names[i]);
3651           file_data->real_names[i] = NULL;
3652         }
3653     }
3654
3655   return 1;
3656 }
3657
3658 static void
3659 dw2_forget_cached_source_info (struct objfile *objfile)
3660 {
3661   dw2_setup (objfile);
3662
3663   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3664                           dw2_free_cached_file_names, NULL);
3665 }
3666
3667 /* Helper function for dw2_map_symtabs_matching_filename that expands
3668    the symtabs and calls the iterator.  */
3669
3670 static int
3671 dw2_map_expand_apply (struct objfile *objfile,
3672                       struct dwarf2_per_cu_data *per_cu,
3673                       const char *name, const char *real_path,
3674                       gdb::function_view<bool (symtab *)> callback)
3675 {
3676   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3677
3678   /* Don't visit already-expanded CUs.  */
3679   if (per_cu->v.quick->compunit_symtab)
3680     return 0;
3681
3682   /* This may expand more than one symtab, and we want to iterate over
3683      all of them.  */
3684   dw2_instantiate_symtab (per_cu);
3685
3686   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3687                                     last_made, callback);
3688 }
3689
3690 /* Implementation of the map_symtabs_matching_filename method.  */
3691
3692 static bool
3693 dw2_map_symtabs_matching_filename
3694   (struct objfile *objfile, const char *name, const char *real_path,
3695    gdb::function_view<bool (symtab *)> callback)
3696 {
3697   int i;
3698   const char *name_basename = lbasename (name);
3699
3700   dw2_setup (objfile);
3701
3702   /* The rule is CUs specify all the files, including those used by
3703      any TU, so there's no need to scan TUs here.  */
3704
3705   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3706     {
3707       int j;
3708       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3709       struct quick_file_names *file_data;
3710
3711       /* We only need to look at symtabs not already expanded.  */
3712       if (per_cu->v.quick->compunit_symtab)
3713         continue;
3714
3715       file_data = dw2_get_file_names (per_cu);
3716       if (file_data == NULL)
3717         continue;
3718
3719       for (j = 0; j < file_data->num_file_names; ++j)
3720         {
3721           const char *this_name = file_data->file_names[j];
3722           const char *this_real_name;
3723
3724           if (compare_filenames_for_search (this_name, name))
3725             {
3726               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3727                                         callback))
3728                 return true;
3729               continue;
3730             }
3731
3732           /* Before we invoke realpath, which can get expensive when many
3733              files are involved, do a quick comparison of the basenames.  */
3734           if (! basenames_may_differ
3735               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3736             continue;
3737
3738           this_real_name = dw2_get_real_path (objfile, file_data, j);
3739           if (compare_filenames_for_search (this_real_name, name))
3740             {
3741               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3742                                         callback))
3743                 return true;
3744               continue;
3745             }
3746
3747           if (real_path != NULL)
3748             {
3749               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3750               gdb_assert (IS_ABSOLUTE_PATH (name));
3751               if (this_real_name != NULL
3752                   && FILENAME_CMP (real_path, this_real_name) == 0)
3753                 {
3754                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3755                                             callback))
3756                     return true;
3757                   continue;
3758                 }
3759             }
3760         }
3761     }
3762
3763   return false;
3764 }
3765
3766 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3767
3768 struct dw2_symtab_iterator
3769 {
3770   /* The internalized form of .gdb_index.  */
3771   struct mapped_index *index;
3772   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3773   int want_specific_block;
3774   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3775      Unused if !WANT_SPECIFIC_BLOCK.  */
3776   int block_index;
3777   /* The kind of symbol we're looking for.  */
3778   domain_enum domain;
3779   /* The list of CUs from the index entry of the symbol,
3780      or NULL if not found.  */
3781   offset_type *vec;
3782   /* The next element in VEC to look at.  */
3783   int next;
3784   /* The number of elements in VEC, or zero if there is no match.  */
3785   int length;
3786   /* Have we seen a global version of the symbol?
3787      If so we can ignore all further global instances.
3788      This is to work around gold/15646, inefficient gold-generated
3789      indices.  */
3790   int global_seen;
3791 };
3792
3793 /* Initialize the index symtab iterator ITER.
3794    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3795    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3796
3797 static void
3798 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3799                       struct mapped_index *index,
3800                       int want_specific_block,
3801                       int block_index,
3802                       domain_enum domain,
3803                       const char *name)
3804 {
3805   iter->index = index;
3806   iter->want_specific_block = want_specific_block;
3807   iter->block_index = block_index;
3808   iter->domain = domain;
3809   iter->next = 0;
3810   iter->global_seen = 0;
3811
3812   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3813     iter->length = MAYBE_SWAP (*iter->vec);
3814   else
3815     {
3816       iter->vec = NULL;
3817       iter->length = 0;
3818     }
3819 }
3820
3821 /* Return the next matching CU or NULL if there are no more.  */
3822
3823 static struct dwarf2_per_cu_data *
3824 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3825 {
3826   for ( ; iter->next < iter->length; ++iter->next)
3827     {
3828       offset_type cu_index_and_attrs =
3829         MAYBE_SWAP (iter->vec[iter->next + 1]);
3830       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3831       struct dwarf2_per_cu_data *per_cu;
3832       int want_static = iter->block_index != GLOBAL_BLOCK;
3833       /* This value is only valid for index versions >= 7.  */
3834       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3835       gdb_index_symbol_kind symbol_kind =
3836         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3837       /* Only check the symbol attributes if they're present.
3838          Indices prior to version 7 don't record them,
3839          and indices >= 7 may elide them for certain symbols
3840          (gold does this).  */
3841       int attrs_valid =
3842         (iter->index->version >= 7
3843          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3844
3845       /* Don't crash on bad data.  */
3846       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3847                        + dwarf2_per_objfile->n_type_units))
3848         {
3849           complaint (&symfile_complaints,
3850                      _(".gdb_index entry has bad CU index"
3851                        " [in module %s]"),
3852                      objfile_name (dwarf2_per_objfile->objfile));
3853           continue;
3854         }
3855
3856       per_cu = dw2_get_cutu (cu_index);
3857
3858       /* Skip if already read in.  */
3859       if (per_cu->v.quick->compunit_symtab)
3860         continue;
3861
3862       /* Check static vs global.  */
3863       if (attrs_valid)
3864         {
3865           if (iter->want_specific_block
3866               && want_static != is_static)
3867             continue;
3868           /* Work around gold/15646.  */
3869           if (!is_static && iter->global_seen)
3870             continue;
3871           if (!is_static)
3872             iter->global_seen = 1;
3873         }
3874
3875       /* Only check the symbol's kind if it has one.  */
3876       if (attrs_valid)
3877         {
3878           switch (iter->domain)
3879             {
3880             case VAR_DOMAIN:
3881               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3882                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3883                   /* Some types are also in VAR_DOMAIN.  */
3884                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3885                 continue;
3886               break;
3887             case STRUCT_DOMAIN:
3888               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3889                 continue;
3890               break;
3891             case LABEL_DOMAIN:
3892               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3893                 continue;
3894               break;
3895             default:
3896               break;
3897             }
3898         }
3899
3900       ++iter->next;
3901       return per_cu;
3902     }
3903
3904   return NULL;
3905 }
3906
3907 static struct compunit_symtab *
3908 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3909                    const char *name, domain_enum domain)
3910 {
3911   struct compunit_symtab *stab_best = NULL;
3912   struct mapped_index *index;
3913
3914   dw2_setup (objfile);
3915
3916   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3917
3918   index = dwarf2_per_objfile->index_table;
3919
3920   /* index is NULL if OBJF_READNOW.  */
3921   if (index)
3922     {
3923       struct dw2_symtab_iterator iter;
3924       struct dwarf2_per_cu_data *per_cu;
3925
3926       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3927
3928       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3929         {
3930           struct symbol *sym, *with_opaque = NULL;
3931           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3932           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3933           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3934
3935           sym = block_find_symbol (block, name, domain,
3936                                    block_find_non_opaque_type_preferred,
3937                                    &with_opaque);
3938
3939           /* Some caution must be observed with overloaded functions
3940              and methods, since the index will not contain any overload
3941              information (but NAME might contain it).  */
3942
3943           if (sym != NULL
3944               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3945             return stab;
3946           if (with_opaque != NULL
3947               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3948             stab_best = stab;
3949
3950           /* Keep looking through other CUs.  */
3951         }
3952     }
3953
3954   return stab_best;
3955 }
3956
3957 static void
3958 dw2_print_stats (struct objfile *objfile)
3959 {
3960   int i, total, count;
3961
3962   dw2_setup (objfile);
3963   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3964   count = 0;
3965   for (i = 0; i < total; ++i)
3966     {
3967       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3968
3969       if (!per_cu->v.quick->compunit_symtab)
3970         ++count;
3971     }
3972   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3973   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3974 }
3975
3976 /* This dumps minimal information about the index.
3977    It is called via "mt print objfiles".
3978    One use is to verify .gdb_index has been loaded by the
3979    gdb.dwarf2/gdb-index.exp testcase.  */
3980
3981 static void
3982 dw2_dump (struct objfile *objfile)
3983 {
3984   dw2_setup (objfile);
3985   gdb_assert (dwarf2_per_objfile->using_index);
3986   printf_filtered (".gdb_index:");
3987   if (dwarf2_per_objfile->index_table != NULL)
3988     {
3989       printf_filtered (" version %d\n",
3990                        dwarf2_per_objfile->index_table->version);
3991     }
3992   else
3993     printf_filtered (" faked for \"readnow\"\n");
3994   printf_filtered ("\n");
3995 }
3996
3997 static void
3998 dw2_relocate (struct objfile *objfile,
3999               const struct section_offsets *new_offsets,
4000               const struct section_offsets *delta)
4001 {
4002   /* There's nothing to relocate here.  */
4003 }
4004
4005 static void
4006 dw2_expand_symtabs_for_function (struct objfile *objfile,
4007                                  const char *func_name)
4008 {
4009   struct mapped_index *index;
4010
4011   dw2_setup (objfile);
4012
4013   index = dwarf2_per_objfile->index_table;
4014
4015   /* index is NULL if OBJF_READNOW.  */
4016   if (index)
4017     {
4018       struct dw2_symtab_iterator iter;
4019       struct dwarf2_per_cu_data *per_cu;
4020
4021       /* Note: It doesn't matter what we pass for block_index here.  */
4022       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4023                             func_name);
4024
4025       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4026         dw2_instantiate_symtab (per_cu);
4027     }
4028 }
4029
4030 static void
4031 dw2_expand_all_symtabs (struct objfile *objfile)
4032 {
4033   int i;
4034
4035   dw2_setup (objfile);
4036
4037   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4038                    + dwarf2_per_objfile->n_type_units); ++i)
4039     {
4040       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4041
4042       dw2_instantiate_symtab (per_cu);
4043     }
4044 }
4045
4046 static void
4047 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4048                                   const char *fullname)
4049 {
4050   int i;
4051
4052   dw2_setup (objfile);
4053
4054   /* We don't need to consider type units here.
4055      This is only called for examining code, e.g. expand_line_sal.
4056      There can be an order of magnitude (or more) more type units
4057      than comp units, and we avoid them if we can.  */
4058
4059   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4060     {
4061       int j;
4062       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4063       struct quick_file_names *file_data;
4064
4065       /* We only need to look at symtabs not already expanded.  */
4066       if (per_cu->v.quick->compunit_symtab)
4067         continue;
4068
4069       file_data = dw2_get_file_names (per_cu);
4070       if (file_data == NULL)
4071         continue;
4072
4073       for (j = 0; j < file_data->num_file_names; ++j)
4074         {
4075           const char *this_fullname = file_data->file_names[j];
4076
4077           if (filename_cmp (this_fullname, fullname) == 0)
4078             {
4079               dw2_instantiate_symtab (per_cu);
4080               break;
4081             }
4082         }
4083     }
4084 }
4085
4086 static void
4087 dw2_map_matching_symbols (struct objfile *objfile,
4088                           const char * name, domain_enum domain,
4089                           int global,
4090                           int (*callback) (struct block *,
4091                                            struct symbol *, void *),
4092                           void *data, symbol_name_match_type match,
4093                           symbol_compare_ftype *ordered_compare)
4094 {
4095   /* Currently unimplemented; used for Ada.  The function can be called if the
4096      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4097      does not look for non-Ada symbols this function should just return.  */
4098 }
4099
4100 /* Symbol name matcher for .gdb_index names.
4101
4102    Symbol names in .gdb_index have a few particularities:
4103
4104    - There's no indication of which is the language of each symbol.
4105
4106      Since each language has its own symbol name matching algorithm,
4107      and we don't know which language is the right one, we must match
4108      each symbol against all languages.  This would be a potential
4109      performance problem if it were not mitigated by the
4110      mapped_index::name_components lookup table, which significantly
4111      reduces the number of times we need to call into this matcher,
4112      making it a non-issue.
4113
4114    - Symbol names in the index have no overload (parameter)
4115      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4116      appear as "foo" in the index, for example.
4117
4118      This means that the lookup names passed to the symbol name
4119      matcher functions must have no parameter information either
4120      because (e.g.) symbol search name "foo" does not match
4121      lookup-name "foo(int)" [while swapping search name for lookup
4122      name would match].
4123 */
4124 class gdb_index_symbol_name_matcher
4125 {
4126 public:
4127   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4128   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4129
4130   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4131      Returns true if any matcher matches.  */
4132   bool matches (const char *symbol_name);
4133
4134 private:
4135   /* A reference to the lookup name we're matching against.  */
4136   const lookup_name_info &m_lookup_name;
4137
4138   /* A vector holding all the different symbol name matchers, for all
4139      languages.  */
4140   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4141 };
4142
4143 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4144   (const lookup_name_info &lookup_name)
4145     : m_lookup_name (lookup_name)
4146 {
4147   /* Prepare the vector of comparison functions upfront, to avoid
4148      doing the same work for each symbol.  Care is taken to avoid
4149      matching with the same matcher more than once if/when multiple
4150      languages use the same matcher function.  */
4151   auto &matchers = m_symbol_name_matcher_funcs;
4152   matchers.reserve (nr_languages);
4153
4154   matchers.push_back (default_symbol_name_matcher);
4155
4156   for (int i = 0; i < nr_languages; i++)
4157     {
4158       const language_defn *lang = language_def ((enum language) i);
4159       if (lang->la_get_symbol_name_matcher != NULL)
4160         {
4161           symbol_name_matcher_ftype *name_matcher
4162             = lang->la_get_symbol_name_matcher (m_lookup_name);
4163
4164           /* Don't insert the same comparison routine more than once.
4165              Note that we do this linear walk instead of a cheaper
4166              sorted insert, or use a std::set or something like that,
4167              because relative order of function addresses is not
4168              stable.  This is not a problem in practice because the
4169              number of supported languages is low, and the cost here
4170              is tiny compared to the number of searches we'll do
4171              afterwards using this object.  */
4172           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4173               == matchers.end ())
4174             matchers.push_back (name_matcher);
4175         }
4176     }
4177 }
4178
4179 bool
4180 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4181 {
4182   for (auto matches_name : m_symbol_name_matcher_funcs)
4183     if (matches_name (symbol_name, m_lookup_name, NULL))
4184       return true;
4185
4186   return false;
4187 }
4188
4189 /* Helper for dw2_expand_symtabs_matching that works with a
4190    mapped_index instead of the containing objfile.  This is split to a
4191    separate function in order to be able to unit test the
4192    name_components matching using a mock mapped_index.  For each
4193    symbol name that matches, calls MATCH_CALLBACK, passing it the
4194    symbol's index in the mapped_index symbol table.  */
4195
4196 static void
4197 dw2_expand_symtabs_matching_symbol
4198   (mapped_index &index,
4199    const lookup_name_info &lookup_name_in,
4200    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4201    enum search_domain kind,
4202    gdb::function_view<void (offset_type)> match_callback)
4203 {
4204   lookup_name_info lookup_name_without_params
4205     = lookup_name_in.make_ignore_params ();
4206   gdb_index_symbol_name_matcher lookup_name_matcher
4207     (lookup_name_without_params);
4208
4209   auto *name_cmp = case_sensitivity == case_sensitive_on ? strcmp : strcasecmp;
4210
4211   /* Build the symbol name component sorted vector, if we haven't yet.
4212      The code below only knows how to break apart components of C++
4213      symbol names (and other languages that use '::' as
4214      namespace/module separator).  If we add support for wild matching
4215      to some language that uses some other operator (E.g., Ada, Go and
4216      D use '.'), then we'll need to try splitting the symbol name
4217      according to that language too.  Note that Ada does support wild
4218      matching, but doesn't currently support .gdb_index.  */
4219   if (index.name_components.empty ())
4220     {
4221       for (size_t iter = 0; iter < index.symbol_table_slots; ++iter)
4222         {
4223           offset_type idx = 2 * iter;
4224
4225           if (index.symbol_table[idx] == 0
4226               && index.symbol_table[idx + 1] == 0)
4227             continue;
4228
4229           const char *name = index.symbol_name_at (idx);
4230
4231           /* Add each name component to the name component table.  */
4232           unsigned int previous_len = 0;
4233           for (unsigned int current_len = cp_find_first_component (name);
4234                name[current_len] != '\0';
4235                current_len += cp_find_first_component (name + current_len))
4236             {
4237               gdb_assert (name[current_len] == ':');
4238               index.name_components.push_back ({previous_len, idx});
4239               /* Skip the '::'.  */
4240               current_len += 2;
4241               previous_len = current_len;
4242             }
4243           index.name_components.push_back ({previous_len, idx});
4244         }
4245
4246       /* Sort name_components elements by name.  */
4247       auto name_comp_compare = [&] (const name_component &left,
4248                                     const name_component &right)
4249         {
4250           const char *left_qualified = index.symbol_name_at (left.idx);
4251           const char *right_qualified = index.symbol_name_at (right.idx);
4252
4253           const char *left_name = left_qualified + left.name_offset;
4254           const char *right_name = right_qualified + right.name_offset;
4255
4256           return name_cmp (left_name, right_name) < 0;
4257         };
4258
4259       std::sort (index.name_components.begin (),
4260                  index.name_components.end (),
4261                  name_comp_compare);
4262     }
4263
4264   const char *cplus
4265     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4266
4267   /* Comparison function object for lower_bound that matches against a
4268      given symbol name.  */
4269   auto lookup_compare_lower = [&] (const name_component &elem,
4270                                    const char *name)
4271     {
4272       const char *elem_qualified = index.symbol_name_at (elem.idx);
4273       const char *elem_name = elem_qualified + elem.name_offset;
4274       return name_cmp (elem_name, name) < 0;
4275     };
4276
4277   /* Comparison function object for upper_bound that matches against a
4278      given symbol name.  */
4279   auto lookup_compare_upper = [&] (const char *name,
4280                                    const name_component &elem)
4281     {
4282       const char *elem_qualified = index.symbol_name_at (elem.idx);
4283       const char *elem_name = elem_qualified + elem.name_offset;
4284       return name_cmp (name, elem_name) < 0;
4285     };
4286
4287   auto begin = index.name_components.begin ();
4288   auto end = index.name_components.end ();
4289
4290   /* Find the lower bound.  */
4291   auto lower = [&] ()
4292     {
4293       if (lookup_name_in.completion_mode () && cplus[0] == '\0')
4294         return begin;
4295       else
4296         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4297     } ();
4298
4299   /* Find the upper bound.  */
4300   auto upper = [&] ()
4301     {
4302       if (lookup_name_in.completion_mode ())
4303         {
4304           /* The string frobbing below won't work if the string is
4305              empty.  We don't need it then, anyway -- if we're
4306              completing an empty string, then we want to iterate over
4307              the whole range.  */
4308           if (cplus[0] == '\0')
4309             return end;
4310
4311           /* In completion mode, increment the last character because
4312              we want UPPER to point past all symbols names that have
4313              the same prefix.  */
4314           std::string after = cplus;
4315
4316           gdb_assert (after.back () != 0xff);
4317           after.back ()++;
4318
4319           return std::upper_bound (lower, end, after.c_str (),
4320                                    lookup_compare_upper);
4321         }
4322       else
4323         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4324     } ();
4325
4326   /* Now for each symbol name in range, check to see if we have a name
4327      match, and if so, call the MATCH_CALLBACK callback.  */
4328
4329   /* The same symbol may appear more than once in the range though.
4330      E.g., if we're looking for symbols that complete "w", and we have
4331      a symbol named "w1::w2", we'll find the two name components for
4332      that same symbol in the range.  To be sure we only call the
4333      callback once per symbol, we first collect the symbol name
4334      indexes that matched in a temporary vector and ignore
4335      duplicates.  */
4336   std::vector<offset_type> matches;
4337   matches.reserve (std::distance (lower, upper));
4338
4339   for (;lower != upper; ++lower)
4340     {
4341       const char *qualified = index.symbol_name_at (lower->idx);
4342
4343       if (!lookup_name_matcher.matches (qualified)
4344           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4345         continue;
4346
4347       matches.push_back (lower->idx);
4348     }
4349
4350   std::sort (matches.begin (), matches.end ());
4351
4352   /* Finally call the callback, once per match.  */
4353   ULONGEST prev = -1;
4354   for (offset_type idx : matches)
4355     {
4356       if (prev != idx)
4357         {
4358           match_callback (idx);
4359           prev = idx;
4360         }
4361     }
4362
4363   /* Above we use a type wider than idx's for 'prev', since 0 and
4364      (offset_type)-1 are both possible values.  */
4365   static_assert (sizeof (prev) > sizeof (offset_type), "");
4366 }
4367
4368 #if GDB_SELF_TEST
4369
4370 namespace selftests { namespace dw2_expand_symtabs_matching {
4371
4372 /* A wrapper around mapped_index that builds a mock mapped_index, from
4373    the symbol list passed as parameter to the constructor.  */
4374 class mock_mapped_index
4375 {
4376 public:
4377   template<size_t N>
4378   mock_mapped_index (const char *(&symbols)[N])
4379     : mock_mapped_index (symbols, N)
4380   {}
4381
4382   /* Access the built index.  */
4383   mapped_index &index ()
4384   { return m_index; }
4385
4386   /* Disable copy.  */
4387   mock_mapped_index(const mock_mapped_index &) = delete;
4388   void operator= (const mock_mapped_index &) = delete;
4389
4390 private:
4391   mock_mapped_index (const char **symbols, size_t symbols_size)
4392   {
4393     /* No string can live at offset zero.  Add a dummy entry.  */
4394     obstack_grow_str0 (&m_constant_pool, "");
4395
4396     for (size_t i = 0; i < symbols_size; i++)
4397       {
4398         const char *sym = symbols[i];
4399         size_t offset = obstack_object_size (&m_constant_pool);
4400         obstack_grow_str0 (&m_constant_pool, sym);
4401         m_symbol_table.push_back (offset);
4402         m_symbol_table.push_back (0);
4403       };
4404
4405     m_index.constant_pool = (const char *) obstack_base (&m_constant_pool);
4406     m_index.symbol_table = m_symbol_table.data ();
4407     m_index.symbol_table_slots = m_symbol_table.size () / 2;
4408   }
4409
4410 public:
4411   /* The built mapped_index.  */
4412   mapped_index m_index{};
4413
4414   /* The storage that the built mapped_index uses for symbol and
4415      constant pool tables.  */
4416   std::vector<offset_type> m_symbol_table;
4417   auto_obstack m_constant_pool;
4418 };
4419
4420 /* Convenience function that converts a NULL pointer to a "<null>"
4421    string, to pass to print routines.  */
4422
4423 static const char *
4424 string_or_null (const char *str)
4425 {
4426   return str != NULL ? str : "<null>";
4427 }
4428
4429 /* Check if a lookup_name_info built from
4430    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4431    index.  EXPECTED_LIST is the list of expected matches, in expected
4432    matching order.  If no match expected, then an empty list is
4433    specified.  Returns true on success.  On failure prints a warning
4434    indicating the file:line that failed, and returns false.  */
4435
4436 static bool
4437 check_match (const char *file, int line,
4438              mock_mapped_index &mock_index,
4439              const char *name, symbol_name_match_type match_type,
4440              bool completion_mode,
4441              std::initializer_list<const char *> expected_list)
4442 {
4443   lookup_name_info lookup_name (name, match_type, completion_mode);
4444
4445   bool matched = true;
4446
4447   auto mismatch = [&] (const char *expected_str,
4448                        const char *got)
4449   {
4450     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4451                "expected=\"%s\", got=\"%s\"\n"),
4452              file, line,
4453              (match_type == symbol_name_match_type::FULL
4454               ? "FULL" : "WILD"),
4455              name, string_or_null (expected_str), string_or_null (got));
4456     matched = false;
4457   };
4458
4459   auto expected_it = expected_list.begin ();
4460   auto expected_end = expected_list.end ();
4461
4462   dw2_expand_symtabs_matching_symbol (mock_index.index (), lookup_name,
4463                                       NULL, ALL_DOMAIN,
4464                                       [&] (offset_type idx)
4465   {
4466     const char *matched_name = mock_index.index ().symbol_name_at (idx);
4467     const char *expected_str
4468       = expected_it == expected_end ? NULL : *expected_it++;
4469
4470     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4471       mismatch (expected_str, matched_name);
4472   });
4473
4474   const char *expected_str
4475   = expected_it == expected_end ? NULL : *expected_it++;
4476   if (expected_str != NULL)
4477     mismatch (expected_str, NULL);
4478
4479   return matched;
4480 }
4481
4482 /* The symbols added to the mock mapped_index for testing (in
4483    canonical form).  */
4484 static const char *test_symbols[] = {
4485   "function",
4486   "std::bar",
4487   "std::zfunction",
4488   "std::zfunction2",
4489   "w1::w2",
4490   "ns::foo<char*>",
4491   "ns::foo<int>",
4492   "ns::foo<long>",
4493
4494   /* A name with all sorts of complications.  Starts with "z" to make
4495      it easier for the completion tests below.  */
4496 #define Z_SYM_NAME \
4497   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4498     "::tuple<(anonymous namespace)::ui*, " \
4499     "std::default_delete<(anonymous namespace)::ui>, void>"
4500
4501   Z_SYM_NAME
4502 };
4503
4504 static void
4505 run_test ()
4506 {
4507   mock_mapped_index mock_index (test_symbols);
4508
4509   /* We let all tests run until the end even if some fails, for debug
4510      convenience.  */
4511   bool any_mismatch = false;
4512
4513   /* Create the expected symbols list (an initializer_list).  Needed
4514      because lists have commas, and we need to pass them to CHECK,
4515      which is a macro.  */
4516 #define EXPECT(...) { __VA_ARGS__ }
4517
4518   /* Wrapper for check_match that passes down the current
4519      __FILE__/__LINE__.  */
4520 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4521   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4522                                 mock_index,                             \
4523                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4524                                 EXPECTED_LIST)
4525
4526   /* Identity checks.  */
4527   for (const char *sym : test_symbols)
4528     {
4529       /* Should be able to match all existing symbols.  */
4530       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4531                    EXPECT (sym));
4532
4533       /* Should be able to match all existing symbols with
4534          parameters.  */
4535       std::string with_params = std::string (sym) + "(int)";
4536       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4537                    EXPECT (sym));
4538
4539       /* Should be able to match all existing symbols with
4540          parameters and qualifiers.  */
4541       with_params = std::string (sym) + " ( int ) const";
4542       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4543                    EXPECT (sym));
4544
4545       /* This should really find sym, but cp-name-parser.y doesn't
4546          know about lvalue/rvalue qualifiers yet.  */
4547       with_params = std::string (sym) + " ( int ) &&";
4548       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4549                    {});
4550     }
4551
4552   /* Check that completion mode works at each prefix of the expected
4553      symbol name.  */
4554   {
4555     static const char str[] = "function(int)";
4556     size_t len = strlen (str);
4557     std::string lookup;
4558
4559     for (size_t i = 1; i < len; i++)
4560       {
4561         lookup.assign (str, i);
4562         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4563                      EXPECT ("function"));
4564       }
4565   }
4566
4567   /* While "w" is a prefix of both components, the match function
4568      should still only be called once.  */
4569   {
4570     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4571                  EXPECT ("w1::w2"));
4572   }
4573
4574   /* Same, with a "complicated" symbol.  */
4575   {
4576     static const char str[] = Z_SYM_NAME;
4577     size_t len = strlen (str);
4578     std::string lookup;
4579
4580     for (size_t i = 1; i < len; i++)
4581       {
4582         lookup.assign (str, i);
4583         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4584                      EXPECT (Z_SYM_NAME));
4585       }
4586   }
4587
4588   /* In FULL mode, an incomplete symbol doesn't match.  */
4589   {
4590     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4591                  {});
4592   }
4593
4594   /* A complete symbol with parameters matches any overload, since the
4595      index has no overload info.  */
4596   {
4597     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4598                  EXPECT ("std::zfunction", "std::zfunction2"));
4599   }
4600
4601   /* Check that whitespace is ignored appropriately.  A symbol with a
4602      template argument list. */
4603   {
4604     static const char expected[] = "ns::foo<int>";
4605     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4606                  EXPECT (expected));
4607   }
4608
4609   /* Check that whitespace is ignored appropriately.  A symbol with a
4610      template argument list that includes a pointer.  */
4611   {
4612     static const char expected[] = "ns::foo<char*>";
4613     /* Try both completion and non-completion modes.  */
4614     static const bool completion_mode[2] = {false, true};
4615     for (size_t i = 0; i < 2; i++)
4616       {
4617         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4618                      completion_mode[i], EXPECT (expected));
4619
4620         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4621                      completion_mode[i], EXPECT (expected));
4622       }
4623   }
4624
4625   {
4626     /* Check method qualifiers are ignored.  */
4627     static const char expected[] = "ns::foo<char*>";
4628     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4629                  symbol_name_match_type::FULL, true, EXPECT (expected));
4630     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4631                  symbol_name_match_type::FULL, true, EXPECT (expected));
4632   }
4633
4634   /* Test lookup names that don't match anything.  */
4635   {
4636     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4637                  {});
4638   }
4639
4640   SELF_CHECK (!any_mismatch);
4641
4642 #undef EXPECT
4643 #undef CHECK_MATCH
4644 }
4645
4646 }} // namespace selftests::dw2_expand_symtabs_matching
4647
4648 #endif /* GDB_SELF_TEST */
4649
4650 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4651    matched, to expand corresponding CUs that were marked.  IDX is the
4652    index of the symbol name that matched.  */
4653
4654 static void
4655 dw2_expand_marked_cus
4656   (mapped_index &index, offset_type idx,
4657    struct objfile *objfile,
4658    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4659    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4660    search_domain kind)
4661 {
4662   const char *name;
4663   offset_type *vec, vec_len, vec_idx;
4664   bool global_seen = false;
4665
4666   vec = (offset_type *) (index.constant_pool
4667                          + MAYBE_SWAP (index.symbol_table[idx + 1]));
4668   vec_len = MAYBE_SWAP (vec[0]);
4669   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4670     {
4671       struct dwarf2_per_cu_data *per_cu;
4672       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4673       /* This value is only valid for index versions >= 7.  */
4674       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4675       gdb_index_symbol_kind symbol_kind =
4676         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4677       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4678       /* Only check the symbol attributes if they're present.
4679          Indices prior to version 7 don't record them,
4680          and indices >= 7 may elide them for certain symbols
4681          (gold does this).  */
4682       int attrs_valid =
4683         (index.version >= 7
4684          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4685
4686       /* Work around gold/15646.  */
4687       if (attrs_valid)
4688         {
4689           if (!is_static && global_seen)
4690             continue;
4691           if (!is_static)
4692             global_seen = true;
4693         }
4694
4695       /* Only check the symbol's kind if it has one.  */
4696       if (attrs_valid)
4697         {
4698           switch (kind)
4699             {
4700             case VARIABLES_DOMAIN:
4701               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4702                 continue;
4703               break;
4704             case FUNCTIONS_DOMAIN:
4705               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4706                 continue;
4707               break;
4708             case TYPES_DOMAIN:
4709               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4710                 continue;
4711               break;
4712             default:
4713               break;
4714             }
4715         }
4716
4717       /* Don't crash on bad data.  */
4718       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4719                        + dwarf2_per_objfile->n_type_units))
4720         {
4721           complaint (&symfile_complaints,
4722                      _(".gdb_index entry has bad CU index"
4723                        " [in module %s]"), objfile_name (objfile));
4724           continue;
4725         }
4726
4727       per_cu = dw2_get_cutu (cu_index);
4728       if (file_matcher == NULL || per_cu->v.quick->mark)
4729         {
4730           int symtab_was_null =
4731             (per_cu->v.quick->compunit_symtab == NULL);
4732
4733           dw2_instantiate_symtab (per_cu);
4734
4735           if (expansion_notify != NULL
4736               && symtab_was_null
4737               && per_cu->v.quick->compunit_symtab != NULL)
4738             expansion_notify (per_cu->v.quick->compunit_symtab);
4739         }
4740     }
4741 }
4742
4743 static void
4744 dw2_expand_symtabs_matching
4745   (struct objfile *objfile,
4746    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4747    const lookup_name_info &lookup_name,
4748    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4749    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4750    enum search_domain kind)
4751 {
4752   int i;
4753   offset_type iter;
4754
4755   dw2_setup (objfile);
4756
4757   /* index_table is NULL if OBJF_READNOW.  */
4758   if (!dwarf2_per_objfile->index_table)
4759     return;
4760
4761   if (file_matcher != NULL)
4762     {
4763       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4764                                                 htab_eq_pointer,
4765                                                 NULL, xcalloc, xfree));
4766       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4767                                                     htab_eq_pointer,
4768                                                     NULL, xcalloc, xfree));
4769
4770       /* The rule is CUs specify all the files, including those used by
4771          any TU, so there's no need to scan TUs here.  */
4772
4773       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4774         {
4775           int j;
4776           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4777           struct quick_file_names *file_data;
4778           void **slot;
4779
4780           QUIT;
4781
4782           per_cu->v.quick->mark = 0;
4783
4784           /* We only need to look at symtabs not already expanded.  */
4785           if (per_cu->v.quick->compunit_symtab)
4786             continue;
4787
4788           file_data = dw2_get_file_names (per_cu);
4789           if (file_data == NULL)
4790             continue;
4791
4792           if (htab_find (visited_not_found.get (), file_data) != NULL)
4793             continue;
4794           else if (htab_find (visited_found.get (), file_data) != NULL)
4795             {
4796               per_cu->v.quick->mark = 1;
4797               continue;
4798             }
4799
4800           for (j = 0; j < file_data->num_file_names; ++j)
4801             {
4802               const char *this_real_name;
4803
4804               if (file_matcher (file_data->file_names[j], false))
4805                 {
4806                   per_cu->v.quick->mark = 1;
4807                   break;
4808                 }
4809
4810               /* Before we invoke realpath, which can get expensive when many
4811                  files are involved, do a quick comparison of the basenames.  */
4812               if (!basenames_may_differ
4813                   && !file_matcher (lbasename (file_data->file_names[j]),
4814                                     true))
4815                 continue;
4816
4817               this_real_name = dw2_get_real_path (objfile, file_data, j);
4818               if (file_matcher (this_real_name, false))
4819                 {
4820                   per_cu->v.quick->mark = 1;
4821                   break;
4822                 }
4823             }
4824
4825           slot = htab_find_slot (per_cu->v.quick->mark
4826                                  ? visited_found.get ()
4827                                  : visited_not_found.get (),
4828                                  file_data, INSERT);
4829           *slot = file_data;
4830         }
4831     }
4832
4833   mapped_index &index = *dwarf2_per_objfile->index_table;
4834
4835   dw2_expand_symtabs_matching_symbol (index, lookup_name,
4836                                       symbol_matcher,
4837                                       kind, [&] (offset_type idx)
4838     {
4839       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
4840                              expansion_notify, kind);
4841     });
4842 }
4843
4844 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4845    symtab.  */
4846
4847 static struct compunit_symtab *
4848 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4849                                           CORE_ADDR pc)
4850 {
4851   int i;
4852
4853   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4854       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4855     return cust;
4856
4857   if (cust->includes == NULL)
4858     return NULL;
4859
4860   for (i = 0; cust->includes[i]; ++i)
4861     {
4862       struct compunit_symtab *s = cust->includes[i];
4863
4864       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4865       if (s != NULL)
4866         return s;
4867     }
4868
4869   return NULL;
4870 }
4871
4872 static struct compunit_symtab *
4873 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4874                                   struct bound_minimal_symbol msymbol,
4875                                   CORE_ADDR pc,
4876                                   struct obj_section *section,
4877                                   int warn_if_readin)
4878 {
4879   struct dwarf2_per_cu_data *data;
4880   struct compunit_symtab *result;
4881
4882   dw2_setup (objfile);
4883
4884   if (!objfile->psymtabs_addrmap)
4885     return NULL;
4886
4887   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4888                                                      pc);
4889   if (!data)
4890     return NULL;
4891
4892   if (warn_if_readin && data->v.quick->compunit_symtab)
4893     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4894              paddress (get_objfile_arch (objfile), pc));
4895
4896   result
4897     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4898                                                 pc);
4899   gdb_assert (result != NULL);
4900   return result;
4901 }
4902
4903 static void
4904 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4905                           void *data, int need_fullname)
4906 {
4907   dw2_setup (objfile);
4908
4909   if (!dwarf2_per_objfile->filenames_cache)
4910     {
4911       dwarf2_per_objfile->filenames_cache.emplace ();
4912
4913       htab_up visited (htab_create_alloc (10,
4914                                           htab_hash_pointer, htab_eq_pointer,
4915                                           NULL, xcalloc, xfree));
4916
4917       /* The rule is CUs specify all the files, including those used
4918          by any TU, so there's no need to scan TUs here.  We can
4919          ignore file names coming from already-expanded CUs.  */
4920
4921       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4922         {
4923           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4924
4925           if (per_cu->v.quick->compunit_symtab)
4926             {
4927               void **slot = htab_find_slot (visited.get (),
4928                                             per_cu->v.quick->file_names,
4929                                             INSERT);
4930
4931               *slot = per_cu->v.quick->file_names;
4932             }
4933         }
4934
4935       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4936         {
4937           int j;
4938           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4939           struct quick_file_names *file_data;
4940           void **slot;
4941
4942           /* We only need to look at symtabs not already expanded.  */
4943           if (per_cu->v.quick->compunit_symtab)
4944             continue;
4945
4946           file_data = dw2_get_file_names (per_cu);
4947           if (file_data == NULL)
4948             continue;
4949
4950           slot = htab_find_slot (visited.get (), file_data, INSERT);
4951           if (*slot)
4952             {
4953               /* Already visited.  */
4954               continue;
4955             }
4956           *slot = file_data;
4957
4958           for (int j = 0; j < file_data->num_file_names; ++j)
4959             {
4960               const char *filename = file_data->file_names[j];
4961               dwarf2_per_objfile->filenames_cache->seen (filename);
4962             }
4963         }
4964     }
4965
4966   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4967     {
4968       gdb::unique_xmalloc_ptr<char> this_real_name;
4969
4970       if (need_fullname)
4971         this_real_name = gdb_realpath (filename);
4972       (*fun) (filename, this_real_name.get (), data);
4973     });
4974 }
4975
4976 static int
4977 dw2_has_symbols (struct objfile *objfile)
4978 {
4979   return 1;
4980 }
4981
4982 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4983 {
4984   dw2_has_symbols,
4985   dw2_find_last_source_symtab,
4986   dw2_forget_cached_source_info,
4987   dw2_map_symtabs_matching_filename,
4988   dw2_lookup_symbol,
4989   dw2_print_stats,
4990   dw2_dump,
4991   dw2_relocate,
4992   dw2_expand_symtabs_for_function,
4993   dw2_expand_all_symtabs,
4994   dw2_expand_symtabs_with_fullname,
4995   dw2_map_matching_symbols,
4996   dw2_expand_symtabs_matching,
4997   dw2_find_pc_sect_compunit_symtab,
4998   dw2_map_symbol_filenames
4999 };
5000
5001 /* Initialize for reading DWARF for this objfile.  Return 0 if this
5002    file will use psymtabs, or 1 if using the GNU index.  */
5003
5004 int
5005 dwarf2_initialize_objfile (struct objfile *objfile)
5006 {
5007   /* If we're about to read full symbols, don't bother with the
5008      indices.  In this case we also don't care if some other debug
5009      format is making psymtabs, because they are all about to be
5010      expanded anyway.  */
5011   if ((objfile->flags & OBJF_READNOW))
5012     {
5013       int i;
5014
5015       dwarf2_per_objfile->using_index = 1;
5016       create_all_comp_units (objfile);
5017       create_all_type_units (objfile);
5018       dwarf2_per_objfile->quick_file_names_table =
5019         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5020
5021       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
5022                        + dwarf2_per_objfile->n_type_units); ++i)
5023         {
5024           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5025
5026           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5027                                             struct dwarf2_per_cu_quick_data);
5028         }
5029
5030       /* Return 1 so that gdb sees the "quick" functions.  However,
5031          these functions will be no-ops because we will have expanded
5032          all symtabs.  */
5033       return 1;
5034     }
5035
5036   if (dwarf2_read_index (objfile))
5037     return 1;
5038
5039   return 0;
5040 }
5041
5042 \f
5043
5044 /* Build a partial symbol table.  */
5045
5046 void
5047 dwarf2_build_psymtabs (struct objfile *objfile)
5048 {
5049
5050   if (objfile->global_psymbols.capacity () == 0
5051       && objfile->static_psymbols.capacity () == 0)
5052     init_psymbol_list (objfile, 1024);
5053
5054   TRY
5055     {
5056       /* This isn't really ideal: all the data we allocate on the
5057          objfile's obstack is still uselessly kept around.  However,
5058          freeing it seems unsafe.  */
5059       psymtab_discarder psymtabs (objfile);
5060       dwarf2_build_psymtabs_hard (objfile);
5061       psymtabs.keep ();
5062     }
5063   CATCH (except, RETURN_MASK_ERROR)
5064     {
5065       exception_print (gdb_stderr, except);
5066     }
5067   END_CATCH
5068 }
5069
5070 /* Return the total length of the CU described by HEADER.  */
5071
5072 static unsigned int
5073 get_cu_length (const struct comp_unit_head *header)
5074 {
5075   return header->initial_length_size + header->length;
5076 }
5077
5078 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
5079
5080 static inline bool
5081 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
5082 {
5083   sect_offset bottom = cu_header->sect_off;
5084   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
5085
5086   return sect_off >= bottom && sect_off < top;
5087 }
5088
5089 /* Find the base address of the compilation unit for range lists and
5090    location lists.  It will normally be specified by DW_AT_low_pc.
5091    In DWARF-3 draft 4, the base address could be overridden by
5092    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
5093    compilation units with discontinuous ranges.  */
5094
5095 static void
5096 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
5097 {
5098   struct attribute *attr;
5099
5100   cu->base_known = 0;
5101   cu->base_address = 0;
5102
5103   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
5104   if (attr)
5105     {
5106       cu->base_address = attr_value_as_address (attr);
5107       cu->base_known = 1;
5108     }
5109   else
5110     {
5111       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
5112       if (attr)
5113         {
5114           cu->base_address = attr_value_as_address (attr);
5115           cu->base_known = 1;
5116         }
5117     }
5118 }
5119
5120 /* Read in the comp unit header information from the debug_info at info_ptr.
5121    Use rcuh_kind::COMPILE as the default type if not known by the caller.
5122    NOTE: This leaves members offset, first_die_offset to be filled in
5123    by the caller.  */
5124
5125 static const gdb_byte *
5126 read_comp_unit_head (struct comp_unit_head *cu_header,
5127                      const gdb_byte *info_ptr,
5128                      struct dwarf2_section_info *section,
5129                      rcuh_kind section_kind)
5130 {
5131   int signed_addr;
5132   unsigned int bytes_read;
5133   const char *filename = get_section_file_name (section);
5134   bfd *abfd = get_section_bfd_owner (section);
5135
5136   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
5137   cu_header->initial_length_size = bytes_read;
5138   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
5139   info_ptr += bytes_read;
5140   cu_header->version = read_2_bytes (abfd, info_ptr);
5141   info_ptr += 2;
5142   if (cu_header->version < 5)
5143     switch (section_kind)
5144       {
5145       case rcuh_kind::COMPILE:
5146         cu_header->unit_type = DW_UT_compile;
5147         break;
5148       case rcuh_kind::TYPE:
5149         cu_header->unit_type = DW_UT_type;
5150         break;
5151       default:
5152         internal_error (__FILE__, __LINE__,
5153                         _("read_comp_unit_head: invalid section_kind"));
5154       }
5155   else
5156     {
5157       cu_header->unit_type = static_cast<enum dwarf_unit_type>
5158                                                  (read_1_byte (abfd, info_ptr));
5159       info_ptr += 1;
5160       switch (cu_header->unit_type)
5161         {
5162         case DW_UT_compile:
5163           if (section_kind != rcuh_kind::COMPILE)
5164             error (_("Dwarf Error: wrong unit_type in compilation unit header "
5165                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
5166                    filename);
5167           break;
5168         case DW_UT_type:
5169           section_kind = rcuh_kind::TYPE;
5170           break;
5171         default:
5172           error (_("Dwarf Error: wrong unit_type in compilation unit header "
5173                  "(is %d, should be %d or %d) [in module %s]"),
5174                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
5175         }
5176
5177       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5178       info_ptr += 1;
5179     }
5180   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
5181                                                           cu_header,
5182                                                           &bytes_read);
5183   info_ptr += bytes_read;
5184   if (cu_header->version < 5)
5185     {
5186       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5187       info_ptr += 1;
5188     }
5189   signed_addr = bfd_get_sign_extend_vma (abfd);
5190   if (signed_addr < 0)
5191     internal_error (__FILE__, __LINE__,
5192                     _("read_comp_unit_head: dwarf from non elf file"));
5193   cu_header->signed_addr_p = signed_addr;
5194
5195   if (section_kind == rcuh_kind::TYPE)
5196     {
5197       LONGEST type_offset;
5198
5199       cu_header->signature = read_8_bytes (abfd, info_ptr);
5200       info_ptr += 8;
5201
5202       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
5203       info_ptr += bytes_read;
5204       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
5205       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
5206         error (_("Dwarf Error: Too big type_offset in compilation unit "
5207                "header (is %s) [in module %s]"), plongest (type_offset),
5208                filename);
5209     }
5210
5211   return info_ptr;
5212 }
5213
5214 /* Helper function that returns the proper abbrev section for
5215    THIS_CU.  */
5216
5217 static struct dwarf2_section_info *
5218 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
5219 {
5220   struct dwarf2_section_info *abbrev;
5221
5222   if (this_cu->is_dwz)
5223     abbrev = &dwarf2_get_dwz_file ()->abbrev;
5224   else
5225     abbrev = &dwarf2_per_objfile->abbrev;
5226
5227   return abbrev;
5228 }
5229
5230 /* Subroutine of read_and_check_comp_unit_head and
5231    read_and_check_type_unit_head to simplify them.
5232    Perform various error checking on the header.  */
5233
5234 static void
5235 error_check_comp_unit_head (struct comp_unit_head *header,
5236                             struct dwarf2_section_info *section,
5237                             struct dwarf2_section_info *abbrev_section)
5238 {
5239   const char *filename = get_section_file_name (section);
5240
5241   if (header->version < 2 || header->version > 5)
5242     error (_("Dwarf Error: wrong version in compilation unit header "
5243            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
5244            filename);
5245
5246   if (to_underlying (header->abbrev_sect_off)
5247       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
5248     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
5249            "(offset 0x%x + 6) [in module %s]"),
5250            to_underlying (header->abbrev_sect_off),
5251            to_underlying (header->sect_off),
5252            filename);
5253
5254   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
5255      avoid potential 32-bit overflow.  */
5256   if (((ULONGEST) header->sect_off + get_cu_length (header))
5257       > section->size)
5258     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
5259            "(offset 0x%x + 0) [in module %s]"),
5260            header->length, to_underlying (header->sect_off),
5261            filename);
5262 }
5263
5264 /* Read in a CU/TU header and perform some basic error checking.
5265    The contents of the header are stored in HEADER.
5266    The result is a pointer to the start of the first DIE.  */
5267
5268 static const gdb_byte *
5269 read_and_check_comp_unit_head (struct comp_unit_head *header,
5270                                struct dwarf2_section_info *section,
5271                                struct dwarf2_section_info *abbrev_section,
5272                                const gdb_byte *info_ptr,
5273                                rcuh_kind section_kind)
5274 {
5275   const gdb_byte *beg_of_comp_unit = info_ptr;
5276   bfd *abfd = get_section_bfd_owner (section);
5277
5278   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
5279
5280   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
5281
5282   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
5283
5284   error_check_comp_unit_head (header, section, abbrev_section);
5285
5286   return info_ptr;
5287 }
5288
5289 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5290
5291 static sect_offset
5292 read_abbrev_offset (struct dwarf2_section_info *section,
5293                     sect_offset sect_off)
5294 {
5295   bfd *abfd = get_section_bfd_owner (section);
5296   const gdb_byte *info_ptr;
5297   unsigned int initial_length_size, offset_size;
5298   uint16_t version;
5299
5300   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
5301   info_ptr = section->buffer + to_underlying (sect_off);
5302   read_initial_length (abfd, info_ptr, &initial_length_size);
5303   offset_size = initial_length_size == 4 ? 4 : 8;
5304   info_ptr += initial_length_size;
5305
5306   version = read_2_bytes (abfd, info_ptr);
5307   info_ptr += 2;
5308   if (version >= 5)
5309     {
5310       /* Skip unit type and address size.  */
5311       info_ptr += 2;
5312     }
5313
5314   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
5315 }
5316
5317 /* Allocate a new partial symtab for file named NAME and mark this new
5318    partial symtab as being an include of PST.  */
5319
5320 static void
5321 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
5322                                struct objfile *objfile)
5323 {
5324   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
5325
5326   if (!IS_ABSOLUTE_PATH (subpst->filename))
5327     {
5328       /* It shares objfile->objfile_obstack.  */
5329       subpst->dirname = pst->dirname;
5330     }
5331
5332   subpst->textlow = 0;
5333   subpst->texthigh = 0;
5334
5335   subpst->dependencies
5336     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
5337   subpst->dependencies[0] = pst;
5338   subpst->number_of_dependencies = 1;
5339
5340   subpst->globals_offset = 0;
5341   subpst->n_global_syms = 0;
5342   subpst->statics_offset = 0;
5343   subpst->n_static_syms = 0;
5344   subpst->compunit_symtab = NULL;
5345   subpst->read_symtab = pst->read_symtab;
5346   subpst->readin = 0;
5347
5348   /* No private part is necessary for include psymtabs.  This property
5349      can be used to differentiate between such include psymtabs and
5350      the regular ones.  */
5351   subpst->read_symtab_private = NULL;
5352 }
5353
5354 /* Read the Line Number Program data and extract the list of files
5355    included by the source file represented by PST.  Build an include
5356    partial symtab for each of these included files.  */
5357
5358 static void
5359 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5360                                struct die_info *die,
5361                                struct partial_symtab *pst)
5362 {
5363   line_header_up lh;
5364   struct attribute *attr;
5365
5366   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5367   if (attr)
5368     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
5369   if (lh == NULL)
5370     return;  /* No linetable, so no includes.  */
5371
5372   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
5373   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
5374 }
5375
5376 static hashval_t
5377 hash_signatured_type (const void *item)
5378 {
5379   const struct signatured_type *sig_type
5380     = (const struct signatured_type *) item;
5381
5382   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5383   return sig_type->signature;
5384 }
5385
5386 static int
5387 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5388 {
5389   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5390   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5391
5392   return lhs->signature == rhs->signature;
5393 }
5394
5395 /* Allocate a hash table for signatured types.  */
5396
5397 static htab_t
5398 allocate_signatured_type_table (struct objfile *objfile)
5399 {
5400   return htab_create_alloc_ex (41,
5401                                hash_signatured_type,
5402                                eq_signatured_type,
5403                                NULL,
5404                                &objfile->objfile_obstack,
5405                                hashtab_obstack_allocate,
5406                                dummy_obstack_deallocate);
5407 }
5408
5409 /* A helper function to add a signatured type CU to a table.  */
5410
5411 static int
5412 add_signatured_type_cu_to_table (void **slot, void *datum)
5413 {
5414   struct signatured_type *sigt = (struct signatured_type *) *slot;
5415   struct signatured_type ***datap = (struct signatured_type ***) datum;
5416
5417   **datap = sigt;
5418   ++*datap;
5419
5420   return 1;
5421 }
5422
5423 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5424    and fill them into TYPES_HTAB.  It will process only type units,
5425    therefore DW_UT_type.  */
5426
5427 static void
5428 create_debug_type_hash_table (struct dwo_file *dwo_file,
5429                               dwarf2_section_info *section, htab_t &types_htab,
5430                               rcuh_kind section_kind)
5431 {
5432   struct objfile *objfile = dwarf2_per_objfile->objfile;
5433   struct dwarf2_section_info *abbrev_section;
5434   bfd *abfd;
5435   const gdb_byte *info_ptr, *end_ptr;
5436
5437   abbrev_section = (dwo_file != NULL
5438                     ? &dwo_file->sections.abbrev
5439                     : &dwarf2_per_objfile->abbrev);
5440
5441   if (dwarf_read_debug)
5442     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
5443                         get_section_name (section),
5444                         get_section_file_name (abbrev_section));
5445
5446   dwarf2_read_section (objfile, section);
5447   info_ptr = section->buffer;
5448
5449   if (info_ptr == NULL)
5450     return;
5451
5452   /* We can't set abfd until now because the section may be empty or
5453      not present, in which case the bfd is unknown.  */
5454   abfd = get_section_bfd_owner (section);
5455
5456   /* We don't use init_cutu_and_read_dies_simple, or some such, here
5457      because we don't need to read any dies: the signature is in the
5458      header.  */
5459
5460   end_ptr = info_ptr + section->size;
5461   while (info_ptr < end_ptr)
5462     {
5463       struct signatured_type *sig_type;
5464       struct dwo_unit *dwo_tu;
5465       void **slot;
5466       const gdb_byte *ptr = info_ptr;
5467       struct comp_unit_head header;
5468       unsigned int length;
5469
5470       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5471
5472       /* Initialize it due to a false compiler warning.  */
5473       header.signature = -1;
5474       header.type_cu_offset_in_tu = (cu_offset) -1;
5475
5476       /* We need to read the type's signature in order to build the hash
5477          table, but we don't need anything else just yet.  */
5478
5479       ptr = read_and_check_comp_unit_head (&header, section,
5480                                            abbrev_section, ptr, section_kind);
5481
5482       length = get_cu_length (&header);
5483
5484       /* Skip dummy type units.  */
5485       if (ptr >= info_ptr + length
5486           || peek_abbrev_code (abfd, ptr) == 0
5487           || header.unit_type != DW_UT_type)
5488         {
5489           info_ptr += length;
5490           continue;
5491         }
5492
5493       if (types_htab == NULL)
5494         {
5495           if (dwo_file)
5496             types_htab = allocate_dwo_unit_table (objfile);
5497           else
5498             types_htab = allocate_signatured_type_table (objfile);
5499         }
5500
5501       if (dwo_file)
5502         {
5503           sig_type = NULL;
5504           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5505                                    struct dwo_unit);
5506           dwo_tu->dwo_file = dwo_file;
5507           dwo_tu->signature = header.signature;
5508           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5509           dwo_tu->section = section;
5510           dwo_tu->sect_off = sect_off;
5511           dwo_tu->length = length;
5512         }
5513       else
5514         {
5515           /* N.B.: type_offset is not usable if this type uses a DWO file.
5516              The real type_offset is in the DWO file.  */
5517           dwo_tu = NULL;
5518           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5519                                      struct signatured_type);
5520           sig_type->signature = header.signature;
5521           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
5522           sig_type->per_cu.objfile = objfile;
5523           sig_type->per_cu.is_debug_types = 1;
5524           sig_type->per_cu.section = section;
5525           sig_type->per_cu.sect_off = sect_off;
5526           sig_type->per_cu.length = length;
5527         }
5528
5529       slot = htab_find_slot (types_htab,
5530                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
5531                              INSERT);
5532       gdb_assert (slot != NULL);
5533       if (*slot != NULL)
5534         {
5535           sect_offset dup_sect_off;
5536
5537           if (dwo_file)
5538             {
5539               const struct dwo_unit *dup_tu
5540                 = (const struct dwo_unit *) *slot;
5541
5542               dup_sect_off = dup_tu->sect_off;
5543             }
5544           else
5545             {
5546               const struct signatured_type *dup_tu
5547                 = (const struct signatured_type *) *slot;
5548
5549               dup_sect_off = dup_tu->per_cu.sect_off;
5550             }
5551
5552           complaint (&symfile_complaints,
5553                      _("debug type entry at offset 0x%x is duplicate to"
5554                        " the entry at offset 0x%x, signature %s"),
5555                      to_underlying (sect_off), to_underlying (dup_sect_off),
5556                      hex_string (header.signature));
5557         }
5558       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
5559
5560       if (dwarf_read_debug > 1)
5561         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
5562                             to_underlying (sect_off),
5563                             hex_string (header.signature));
5564
5565       info_ptr += length;
5566     }
5567 }
5568
5569 /* Create the hash table of all entries in the .debug_types
5570    (or .debug_types.dwo) section(s).
5571    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
5572    otherwise it is NULL.
5573
5574    The result is a pointer to the hash table or NULL if there are no types.
5575
5576    Note: This function processes DWO files only, not DWP files.  */
5577
5578 static void
5579 create_debug_types_hash_table (struct dwo_file *dwo_file,
5580                                VEC (dwarf2_section_info_def) *types,
5581                                htab_t &types_htab)
5582 {
5583   int ix;
5584   struct dwarf2_section_info *section;
5585
5586   if (VEC_empty (dwarf2_section_info_def, types))
5587     return;
5588
5589   for (ix = 0;
5590        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5591        ++ix)
5592     create_debug_type_hash_table (dwo_file, section, types_htab,
5593                                   rcuh_kind::TYPE);
5594 }
5595
5596 /* Create the hash table of all entries in the .debug_types section,
5597    and initialize all_type_units.
5598    The result is zero if there is an error (e.g. missing .debug_types section),
5599    otherwise non-zero.  */
5600
5601 static int
5602 create_all_type_units (struct objfile *objfile)
5603 {
5604   htab_t types_htab = NULL;
5605   struct signatured_type **iter;
5606
5607   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5608                                 rcuh_kind::COMPILE);
5609   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5610   if (types_htab == NULL)
5611     {
5612       dwarf2_per_objfile->signatured_types = NULL;
5613       return 0;
5614     }
5615
5616   dwarf2_per_objfile->signatured_types = types_htab;
5617
5618   dwarf2_per_objfile->n_type_units
5619     = dwarf2_per_objfile->n_allocated_type_units
5620     = htab_elements (types_htab);
5621   dwarf2_per_objfile->all_type_units =
5622     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5623   iter = &dwarf2_per_objfile->all_type_units[0];
5624   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5625   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5626               == dwarf2_per_objfile->n_type_units);
5627
5628   return 1;
5629 }
5630
5631 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5632    If SLOT is non-NULL, it is the entry to use in the hash table.
5633    Otherwise we find one.  */
5634
5635 static struct signatured_type *
5636 add_type_unit (ULONGEST sig, void **slot)
5637 {
5638   struct objfile *objfile = dwarf2_per_objfile->objfile;
5639   int n_type_units = dwarf2_per_objfile->n_type_units;
5640   struct signatured_type *sig_type;
5641
5642   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5643   ++n_type_units;
5644   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5645     {
5646       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5647         dwarf2_per_objfile->n_allocated_type_units = 1;
5648       dwarf2_per_objfile->n_allocated_type_units *= 2;
5649       dwarf2_per_objfile->all_type_units
5650         = XRESIZEVEC (struct signatured_type *,
5651                       dwarf2_per_objfile->all_type_units,
5652                       dwarf2_per_objfile->n_allocated_type_units);
5653       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5654     }
5655   dwarf2_per_objfile->n_type_units = n_type_units;
5656
5657   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5658                              struct signatured_type);
5659   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5660   sig_type->signature = sig;
5661   sig_type->per_cu.is_debug_types = 1;
5662   if (dwarf2_per_objfile->using_index)
5663     {
5664       sig_type->per_cu.v.quick =
5665         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5666                         struct dwarf2_per_cu_quick_data);
5667     }
5668
5669   if (slot == NULL)
5670     {
5671       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5672                              sig_type, INSERT);
5673     }
5674   gdb_assert (*slot == NULL);
5675   *slot = sig_type;
5676   /* The rest of sig_type must be filled in by the caller.  */
5677   return sig_type;
5678 }
5679
5680 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5681    Fill in SIG_ENTRY with DWO_ENTRY.  */
5682
5683 static void
5684 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5685                                   struct signatured_type *sig_entry,
5686                                   struct dwo_unit *dwo_entry)
5687 {
5688   /* Make sure we're not clobbering something we don't expect to.  */
5689   gdb_assert (! sig_entry->per_cu.queued);
5690   gdb_assert (sig_entry->per_cu.cu == NULL);
5691   if (dwarf2_per_objfile->using_index)
5692     {
5693       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5694       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5695     }
5696   else
5697       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5698   gdb_assert (sig_entry->signature == dwo_entry->signature);
5699   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5700   gdb_assert (sig_entry->type_unit_group == NULL);
5701   gdb_assert (sig_entry->dwo_unit == NULL);
5702
5703   sig_entry->per_cu.section = dwo_entry->section;
5704   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5705   sig_entry->per_cu.length = dwo_entry->length;
5706   sig_entry->per_cu.reading_dwo_directly = 1;
5707   sig_entry->per_cu.objfile = objfile;
5708   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5709   sig_entry->dwo_unit = dwo_entry;
5710 }
5711
5712 /* Subroutine of lookup_signatured_type.
5713    If we haven't read the TU yet, create the signatured_type data structure
5714    for a TU to be read in directly from a DWO file, bypassing the stub.
5715    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5716    using .gdb_index, then when reading a CU we want to stay in the DWO file
5717    containing that CU.  Otherwise we could end up reading several other DWO
5718    files (due to comdat folding) to process the transitive closure of all the
5719    mentioned TUs, and that can be slow.  The current DWO file will have every
5720    type signature that it needs.
5721    We only do this for .gdb_index because in the psymtab case we already have
5722    to read all the DWOs to build the type unit groups.  */
5723
5724 static struct signatured_type *
5725 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5726 {
5727   struct objfile *objfile = dwarf2_per_objfile->objfile;
5728   struct dwo_file *dwo_file;
5729   struct dwo_unit find_dwo_entry, *dwo_entry;
5730   struct signatured_type find_sig_entry, *sig_entry;
5731   void **slot;
5732
5733   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5734
5735   /* If TU skeletons have been removed then we may not have read in any
5736      TUs yet.  */
5737   if (dwarf2_per_objfile->signatured_types == NULL)
5738     {
5739       dwarf2_per_objfile->signatured_types
5740         = allocate_signatured_type_table (objfile);
5741     }
5742
5743   /* We only ever need to read in one copy of a signatured type.
5744      Use the global signatured_types array to do our own comdat-folding
5745      of types.  If this is the first time we're reading this TU, and
5746      the TU has an entry in .gdb_index, replace the recorded data from
5747      .gdb_index with this TU.  */
5748
5749   find_sig_entry.signature = sig;
5750   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5751                          &find_sig_entry, INSERT);
5752   sig_entry = (struct signatured_type *) *slot;
5753
5754   /* We can get here with the TU already read, *or* in the process of being
5755      read.  Don't reassign the global entry to point to this DWO if that's
5756      the case.  Also note that if the TU is already being read, it may not
5757      have come from a DWO, the program may be a mix of Fission-compiled
5758      code and non-Fission-compiled code.  */
5759
5760   /* Have we already tried to read this TU?
5761      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5762      needn't exist in the global table yet).  */
5763   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5764     return sig_entry;
5765
5766   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5767      dwo_unit of the TU itself.  */
5768   dwo_file = cu->dwo_unit->dwo_file;
5769
5770   /* Ok, this is the first time we're reading this TU.  */
5771   if (dwo_file->tus == NULL)
5772     return NULL;
5773   find_dwo_entry.signature = sig;
5774   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5775   if (dwo_entry == NULL)
5776     return NULL;
5777
5778   /* If the global table doesn't have an entry for this TU, add one.  */
5779   if (sig_entry == NULL)
5780     sig_entry = add_type_unit (sig, slot);
5781
5782   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5783   sig_entry->per_cu.tu_read = 1;
5784   return sig_entry;
5785 }
5786
5787 /* Subroutine of lookup_signatured_type.
5788    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5789    then try the DWP file.  If the TU stub (skeleton) has been removed then
5790    it won't be in .gdb_index.  */
5791
5792 static struct signatured_type *
5793 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5794 {
5795   struct objfile *objfile = dwarf2_per_objfile->objfile;
5796   struct dwp_file *dwp_file = get_dwp_file ();
5797   struct dwo_unit *dwo_entry;
5798   struct signatured_type find_sig_entry, *sig_entry;
5799   void **slot;
5800
5801   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5802   gdb_assert (dwp_file != NULL);
5803
5804   /* If TU skeletons have been removed then we may not have read in any
5805      TUs yet.  */
5806   if (dwarf2_per_objfile->signatured_types == NULL)
5807     {
5808       dwarf2_per_objfile->signatured_types
5809         = allocate_signatured_type_table (objfile);
5810     }
5811
5812   find_sig_entry.signature = sig;
5813   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5814                          &find_sig_entry, INSERT);
5815   sig_entry = (struct signatured_type *) *slot;
5816
5817   /* Have we already tried to read this TU?
5818      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5819      needn't exist in the global table yet).  */
5820   if (sig_entry != NULL)
5821     return sig_entry;
5822
5823   if (dwp_file->tus == NULL)
5824     return NULL;
5825   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5826                                       sig, 1 /* is_debug_types */);
5827   if (dwo_entry == NULL)
5828     return NULL;
5829
5830   sig_entry = add_type_unit (sig, slot);
5831   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5832
5833   return sig_entry;
5834 }
5835
5836 /* Lookup a signature based type for DW_FORM_ref_sig8.
5837    Returns NULL if signature SIG is not present in the table.
5838    It is up to the caller to complain about this.  */
5839
5840 static struct signatured_type *
5841 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5842 {
5843   if (cu->dwo_unit
5844       && dwarf2_per_objfile->using_index)
5845     {
5846       /* We're in a DWO/DWP file, and we're using .gdb_index.
5847          These cases require special processing.  */
5848       if (get_dwp_file () == NULL)
5849         return lookup_dwo_signatured_type (cu, sig);
5850       else
5851         return lookup_dwp_signatured_type (cu, sig);
5852     }
5853   else
5854     {
5855       struct signatured_type find_entry, *entry;
5856
5857       if (dwarf2_per_objfile->signatured_types == NULL)
5858         return NULL;
5859       find_entry.signature = sig;
5860       entry = ((struct signatured_type *)
5861                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5862       return entry;
5863     }
5864 }
5865 \f
5866 /* Low level DIE reading support.  */
5867
5868 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5869
5870 static void
5871 init_cu_die_reader (struct die_reader_specs *reader,
5872                     struct dwarf2_cu *cu,
5873                     struct dwarf2_section_info *section,
5874                     struct dwo_file *dwo_file)
5875 {
5876   gdb_assert (section->readin && section->buffer != NULL);
5877   reader->abfd = get_section_bfd_owner (section);
5878   reader->cu = cu;
5879   reader->dwo_file = dwo_file;
5880   reader->die_section = section;
5881   reader->buffer = section->buffer;
5882   reader->buffer_end = section->buffer + section->size;
5883   reader->comp_dir = NULL;
5884 }
5885
5886 /* Subroutine of init_cutu_and_read_dies to simplify it.
5887    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5888    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5889    already.
5890
5891    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5892    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5893    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5894    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5895    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5896    STUB_COMP_DIR may be non-NULL.
5897    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5898    are filled in with the info of the DIE from the DWO file.
5899    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5900    provided an abbrev table to use.
5901    The result is non-zero if a valid (non-dummy) DIE was found.  */
5902
5903 static int
5904 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5905                         struct dwo_unit *dwo_unit,
5906                         int abbrev_table_provided,
5907                         struct die_info *stub_comp_unit_die,
5908                         const char *stub_comp_dir,
5909                         struct die_reader_specs *result_reader,
5910                         const gdb_byte **result_info_ptr,
5911                         struct die_info **result_comp_unit_die,
5912                         int *result_has_children)
5913 {
5914   struct objfile *objfile = dwarf2_per_objfile->objfile;
5915   struct dwarf2_cu *cu = this_cu->cu;
5916   struct dwarf2_section_info *section;
5917   bfd *abfd;
5918   const gdb_byte *begin_info_ptr, *info_ptr;
5919   ULONGEST signature; /* Or dwo_id.  */
5920   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5921   int i,num_extra_attrs;
5922   struct dwarf2_section_info *dwo_abbrev_section;
5923   struct attribute *attr;
5924   struct die_info *comp_unit_die;
5925
5926   /* At most one of these may be provided.  */
5927   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5928
5929   /* These attributes aren't processed until later:
5930      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5931      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5932      referenced later.  However, these attributes are found in the stub
5933      which we won't have later.  In order to not impose this complication
5934      on the rest of the code, we read them here and copy them to the
5935      DWO CU/TU die.  */
5936
5937   stmt_list = NULL;
5938   low_pc = NULL;
5939   high_pc = NULL;
5940   ranges = NULL;
5941   comp_dir = NULL;
5942
5943   if (stub_comp_unit_die != NULL)
5944     {
5945       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5946          DWO file.  */
5947       if (! this_cu->is_debug_types)
5948         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5949       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5950       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5951       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5952       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5953
5954       /* There should be a DW_AT_addr_base attribute here (if needed).
5955          We need the value before we can process DW_FORM_GNU_addr_index.  */
5956       cu->addr_base = 0;
5957       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5958       if (attr)
5959         cu->addr_base = DW_UNSND (attr);
5960
5961       /* There should be a DW_AT_ranges_base attribute here (if needed).
5962          We need the value before we can process DW_AT_ranges.  */
5963       cu->ranges_base = 0;
5964       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5965       if (attr)
5966         cu->ranges_base = DW_UNSND (attr);
5967     }
5968   else if (stub_comp_dir != NULL)
5969     {
5970       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5971       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5972       comp_dir->name = DW_AT_comp_dir;
5973       comp_dir->form = DW_FORM_string;
5974       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5975       DW_STRING (comp_dir) = stub_comp_dir;
5976     }
5977
5978   /* Set up for reading the DWO CU/TU.  */
5979   cu->dwo_unit = dwo_unit;
5980   section = dwo_unit->section;
5981   dwarf2_read_section (objfile, section);
5982   abfd = get_section_bfd_owner (section);
5983   begin_info_ptr = info_ptr = (section->buffer
5984                                + to_underlying (dwo_unit->sect_off));
5985   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5986   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5987
5988   if (this_cu->is_debug_types)
5989     {
5990       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5991
5992       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5993                                                 dwo_abbrev_section,
5994                                                 info_ptr, rcuh_kind::TYPE);
5995       /* This is not an assert because it can be caused by bad debug info.  */
5996       if (sig_type->signature != cu->header.signature)
5997         {
5998           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5999                    " TU at offset 0x%x [in module %s]"),
6000                  hex_string (sig_type->signature),
6001                  hex_string (cu->header.signature),
6002                  to_underlying (dwo_unit->sect_off),
6003                  bfd_get_filename (abfd));
6004         }
6005       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6006       /* For DWOs coming from DWP files, we don't know the CU length
6007          nor the type's offset in the TU until now.  */
6008       dwo_unit->length = get_cu_length (&cu->header);
6009       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6010
6011       /* Establish the type offset that can be used to lookup the type.
6012          For DWO files, we don't know it until now.  */
6013       sig_type->type_offset_in_section
6014         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6015     }
6016   else
6017     {
6018       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6019                                                 dwo_abbrev_section,
6020                                                 info_ptr, rcuh_kind::COMPILE);
6021       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6022       /* For DWOs coming from DWP files, we don't know the CU length
6023          until now.  */
6024       dwo_unit->length = get_cu_length (&cu->header);
6025     }
6026
6027   /* Replace the CU's original abbrev table with the DWO's.
6028      Reminder: We can't read the abbrev table until we've read the header.  */
6029   if (abbrev_table_provided)
6030     {
6031       /* Don't free the provided abbrev table, the caller of
6032          init_cutu_and_read_dies owns it.  */
6033       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6034       /* Ensure the DWO abbrev table gets freed.  */
6035       make_cleanup (dwarf2_free_abbrev_table, cu);
6036     }
6037   else
6038     {
6039       dwarf2_free_abbrev_table (cu);
6040       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6041       /* Leave any existing abbrev table cleanup as is.  */
6042     }
6043
6044   /* Read in the die, but leave space to copy over the attributes
6045      from the stub.  This has the benefit of simplifying the rest of
6046      the code - all the work to maintain the illusion of a single
6047      DW_TAG_{compile,type}_unit DIE is done here.  */
6048   num_extra_attrs = ((stmt_list != NULL)
6049                      + (low_pc != NULL)
6050                      + (high_pc != NULL)
6051                      + (ranges != NULL)
6052                      + (comp_dir != NULL));
6053   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6054                               result_has_children, num_extra_attrs);
6055
6056   /* Copy over the attributes from the stub to the DIE we just read in.  */
6057   comp_unit_die = *result_comp_unit_die;
6058   i = comp_unit_die->num_attrs;
6059   if (stmt_list != NULL)
6060     comp_unit_die->attrs[i++] = *stmt_list;
6061   if (low_pc != NULL)
6062     comp_unit_die->attrs[i++] = *low_pc;
6063   if (high_pc != NULL)
6064     comp_unit_die->attrs[i++] = *high_pc;
6065   if (ranges != NULL)
6066     comp_unit_die->attrs[i++] = *ranges;
6067   if (comp_dir != NULL)
6068     comp_unit_die->attrs[i++] = *comp_dir;
6069   comp_unit_die->num_attrs += num_extra_attrs;
6070
6071   if (dwarf_die_debug)
6072     {
6073       fprintf_unfiltered (gdb_stdlog,
6074                           "Read die from %s@0x%x of %s:\n",
6075                           get_section_name (section),
6076                           (unsigned) (begin_info_ptr - section->buffer),
6077                           bfd_get_filename (abfd));
6078       dump_die (comp_unit_die, dwarf_die_debug);
6079     }
6080
6081   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
6082      TUs by skipping the stub and going directly to the entry in the DWO file.
6083      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
6084      to get it via circuitous means.  Blech.  */
6085   if (comp_dir != NULL)
6086     result_reader->comp_dir = DW_STRING (comp_dir);
6087
6088   /* Skip dummy compilation units.  */
6089   if (info_ptr >= begin_info_ptr + dwo_unit->length
6090       || peek_abbrev_code (abfd, info_ptr) == 0)
6091     return 0;
6092
6093   *result_info_ptr = info_ptr;
6094   return 1;
6095 }
6096
6097 /* Subroutine of init_cutu_and_read_dies to simplify it.
6098    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
6099    Returns NULL if the specified DWO unit cannot be found.  */
6100
6101 static struct dwo_unit *
6102 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
6103                  struct die_info *comp_unit_die)
6104 {
6105   struct dwarf2_cu *cu = this_cu->cu;
6106   struct attribute *attr;
6107   ULONGEST signature;
6108   struct dwo_unit *dwo_unit;
6109   const char *comp_dir, *dwo_name;
6110
6111   gdb_assert (cu != NULL);
6112
6113   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
6114   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6115   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6116
6117   if (this_cu->is_debug_types)
6118     {
6119       struct signatured_type *sig_type;
6120
6121       /* Since this_cu is the first member of struct signatured_type,
6122          we can go from a pointer to one to a pointer to the other.  */
6123       sig_type = (struct signatured_type *) this_cu;
6124       signature = sig_type->signature;
6125       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
6126     }
6127   else
6128     {
6129       struct attribute *attr;
6130
6131       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6132       if (! attr)
6133         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
6134                  " [in module %s]"),
6135                dwo_name, objfile_name (this_cu->objfile));
6136       signature = DW_UNSND (attr);
6137       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
6138                                        signature);
6139     }
6140
6141   return dwo_unit;
6142 }
6143
6144 /* Subroutine of init_cutu_and_read_dies to simplify it.
6145    See it for a description of the parameters.
6146    Read a TU directly from a DWO file, bypassing the stub.
6147
6148    Note: This function could be a little bit simpler if we shared cleanups
6149    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
6150    to do, so we keep this function self-contained.  Or we could move this
6151    into our caller, but it's complex enough already.  */
6152
6153 static void
6154 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
6155                            int use_existing_cu, int keep,
6156                            die_reader_func_ftype *die_reader_func,
6157                            void *data)
6158 {
6159   struct dwarf2_cu *cu;
6160   struct signatured_type *sig_type;
6161   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6162   struct die_reader_specs reader;
6163   const gdb_byte *info_ptr;
6164   struct die_info *comp_unit_die;
6165   int has_children;
6166
6167   /* Verify we can do the following downcast, and that we have the
6168      data we need.  */
6169   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
6170   sig_type = (struct signatured_type *) this_cu;
6171   gdb_assert (sig_type->dwo_unit != NULL);
6172
6173   cleanups = make_cleanup (null_cleanup, NULL);
6174
6175   if (use_existing_cu && this_cu->cu != NULL)
6176     {
6177       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
6178       cu = this_cu->cu;
6179       /* There's no need to do the rereading_dwo_cu handling that
6180          init_cutu_and_read_dies does since we don't read the stub.  */
6181     }
6182   else
6183     {
6184       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6185       gdb_assert (this_cu->cu == NULL);
6186       cu = XNEW (struct dwarf2_cu);
6187       init_one_comp_unit (cu, this_cu);
6188       /* If an error occurs while loading, release our storage.  */
6189       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6190     }
6191
6192   /* A future optimization, if needed, would be to use an existing
6193      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
6194      could share abbrev tables.  */
6195
6196   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
6197                               0 /* abbrev_table_provided */,
6198                               NULL /* stub_comp_unit_die */,
6199                               sig_type->dwo_unit->dwo_file->comp_dir,
6200                               &reader, &info_ptr,
6201                               &comp_unit_die, &has_children) == 0)
6202     {
6203       /* Dummy die.  */
6204       do_cleanups (cleanups);
6205       return;
6206     }
6207
6208   /* All the "real" work is done here.  */
6209   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6210
6211   /* This duplicates the code in init_cutu_and_read_dies,
6212      but the alternative is making the latter more complex.
6213      This function is only for the special case of using DWO files directly:
6214      no point in overly complicating the general case just to handle this.  */
6215   if (free_cu_cleanup != NULL)
6216     {
6217       if (keep)
6218         {
6219           /* We've successfully allocated this compilation unit.  Let our
6220              caller clean it up when finished with it.  */
6221           discard_cleanups (free_cu_cleanup);
6222
6223           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6224              So we have to manually free the abbrev table.  */
6225           dwarf2_free_abbrev_table (cu);
6226
6227           /* Link this CU into read_in_chain.  */
6228           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6229           dwarf2_per_objfile->read_in_chain = this_cu;
6230         }
6231       else
6232         do_cleanups (free_cu_cleanup);
6233     }
6234
6235   do_cleanups (cleanups);
6236 }
6237
6238 /* Initialize a CU (or TU) and read its DIEs.
6239    If the CU defers to a DWO file, read the DWO file as well.
6240
6241    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
6242    Otherwise the table specified in the comp unit header is read in and used.
6243    This is an optimization for when we already have the abbrev table.
6244
6245    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
6246    Otherwise, a new CU is allocated with xmalloc.
6247
6248    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
6249    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
6250
6251    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6252    linker) then DIE_READER_FUNC will not get called.  */
6253
6254 static void
6255 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
6256                          struct abbrev_table *abbrev_table,
6257                          int use_existing_cu, int keep,
6258                          die_reader_func_ftype *die_reader_func,
6259                          void *data)
6260 {
6261   struct objfile *objfile = dwarf2_per_objfile->objfile;
6262   struct dwarf2_section_info *section = this_cu->section;
6263   bfd *abfd = get_section_bfd_owner (section);
6264   struct dwarf2_cu *cu;
6265   const gdb_byte *begin_info_ptr, *info_ptr;
6266   struct die_reader_specs reader;
6267   struct die_info *comp_unit_die;
6268   int has_children;
6269   struct attribute *attr;
6270   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6271   struct signatured_type *sig_type = NULL;
6272   struct dwarf2_section_info *abbrev_section;
6273   /* Non-zero if CU currently points to a DWO file and we need to
6274      reread it.  When this happens we need to reread the skeleton die
6275      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6276   int rereading_dwo_cu = 0;
6277
6278   if (dwarf_die_debug)
6279     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6280                         this_cu->is_debug_types ? "type" : "comp",
6281                         to_underlying (this_cu->sect_off));
6282
6283   if (use_existing_cu)
6284     gdb_assert (keep);
6285
6286   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6287      file (instead of going through the stub), short-circuit all of this.  */
6288   if (this_cu->reading_dwo_directly)
6289     {
6290       /* Narrow down the scope of possibilities to have to understand.  */
6291       gdb_assert (this_cu->is_debug_types);
6292       gdb_assert (abbrev_table == NULL);
6293       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
6294                                  die_reader_func, data);
6295       return;
6296     }
6297
6298   cleanups = make_cleanup (null_cleanup, NULL);
6299
6300   /* This is cheap if the section is already read in.  */
6301   dwarf2_read_section (objfile, section);
6302
6303   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6304
6305   abbrev_section = get_abbrev_section_for_cu (this_cu);
6306
6307   if (use_existing_cu && this_cu->cu != NULL)
6308     {
6309       cu = this_cu->cu;
6310       /* If this CU is from a DWO file we need to start over, we need to
6311          refetch the attributes from the skeleton CU.
6312          This could be optimized by retrieving those attributes from when we
6313          were here the first time: the previous comp_unit_die was stored in
6314          comp_unit_obstack.  But there's no data yet that we need this
6315          optimization.  */
6316       if (cu->dwo_unit != NULL)
6317         rereading_dwo_cu = 1;
6318     }
6319   else
6320     {
6321       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6322       gdb_assert (this_cu->cu == NULL);
6323       cu = XNEW (struct dwarf2_cu);
6324       init_one_comp_unit (cu, this_cu);
6325       /* If an error occurs while loading, release our storage.  */
6326       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6327     }
6328
6329   /* Get the header.  */
6330   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6331     {
6332       /* We already have the header, there's no need to read it in again.  */
6333       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6334     }
6335   else
6336     {
6337       if (this_cu->is_debug_types)
6338         {
6339           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6340                                                     abbrev_section, info_ptr,
6341                                                     rcuh_kind::TYPE);
6342
6343           /* Since per_cu is the first member of struct signatured_type,
6344              we can go from a pointer to one to a pointer to the other.  */
6345           sig_type = (struct signatured_type *) this_cu;
6346           gdb_assert (sig_type->signature == cu->header.signature);
6347           gdb_assert (sig_type->type_offset_in_tu
6348                       == cu->header.type_cu_offset_in_tu);
6349           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6350
6351           /* LENGTH has not been set yet for type units if we're
6352              using .gdb_index.  */
6353           this_cu->length = get_cu_length (&cu->header);
6354
6355           /* Establish the type offset that can be used to lookup the type.  */
6356           sig_type->type_offset_in_section =
6357             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6358
6359           this_cu->dwarf_version = cu->header.version;
6360         }
6361       else
6362         {
6363           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6364                                                     abbrev_section,
6365                                                     info_ptr,
6366                                                     rcuh_kind::COMPILE);
6367
6368           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6369           gdb_assert (this_cu->length == get_cu_length (&cu->header));
6370           this_cu->dwarf_version = cu->header.version;
6371         }
6372     }
6373
6374   /* Skip dummy compilation units.  */
6375   if (info_ptr >= begin_info_ptr + this_cu->length
6376       || peek_abbrev_code (abfd, info_ptr) == 0)
6377     {
6378       do_cleanups (cleanups);
6379       return;
6380     }
6381
6382   /* If we don't have them yet, read the abbrevs for this compilation unit.
6383      And if we need to read them now, make sure they're freed when we're
6384      done.  Note that it's important that if the CU had an abbrev table
6385      on entry we don't free it when we're done: Somewhere up the call stack
6386      it may be in use.  */
6387   if (abbrev_table != NULL)
6388     {
6389       gdb_assert (cu->abbrev_table == NULL);
6390       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6391       cu->abbrev_table = abbrev_table;
6392     }
6393   else if (cu->abbrev_table == NULL)
6394     {
6395       dwarf2_read_abbrevs (cu, abbrev_section);
6396       make_cleanup (dwarf2_free_abbrev_table, cu);
6397     }
6398   else if (rereading_dwo_cu)
6399     {
6400       dwarf2_free_abbrev_table (cu);
6401       dwarf2_read_abbrevs (cu, abbrev_section);
6402     }
6403
6404   /* Read the top level CU/TU die.  */
6405   init_cu_die_reader (&reader, cu, section, NULL);
6406   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6407
6408   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6409      from the DWO file.
6410      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6411      DWO CU, that this test will fail (the attribute will not be present).  */
6412   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6413   if (attr)
6414     {
6415       struct dwo_unit *dwo_unit;
6416       struct die_info *dwo_comp_unit_die;
6417
6418       if (has_children)
6419         {
6420           complaint (&symfile_complaints,
6421                      _("compilation unit with DW_AT_GNU_dwo_name"
6422                        " has children (offset 0x%x) [in module %s]"),
6423                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
6424         }
6425       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
6426       if (dwo_unit != NULL)
6427         {
6428           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
6429                                       abbrev_table != NULL,
6430                                       comp_unit_die, NULL,
6431                                       &reader, &info_ptr,
6432                                       &dwo_comp_unit_die, &has_children) == 0)
6433             {
6434               /* Dummy die.  */
6435               do_cleanups (cleanups);
6436               return;
6437             }
6438           comp_unit_die = dwo_comp_unit_die;
6439         }
6440       else
6441         {
6442           /* Yikes, we couldn't find the rest of the DIE, we only have
6443              the stub.  A complaint has already been logged.  There's
6444              not much more we can do except pass on the stub DIE to
6445              die_reader_func.  We don't want to throw an error on bad
6446              debug info.  */
6447         }
6448     }
6449
6450   /* All of the above is setup for this call.  Yikes.  */
6451   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6452
6453   /* Done, clean up.  */
6454   if (free_cu_cleanup != NULL)
6455     {
6456       if (keep)
6457         {
6458           /* We've successfully allocated this compilation unit.  Let our
6459              caller clean it up when finished with it.  */
6460           discard_cleanups (free_cu_cleanup);
6461
6462           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6463              So we have to manually free the abbrev table.  */
6464           dwarf2_free_abbrev_table (cu);
6465
6466           /* Link this CU into read_in_chain.  */
6467           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6468           dwarf2_per_objfile->read_in_chain = this_cu;
6469         }
6470       else
6471         do_cleanups (free_cu_cleanup);
6472     }
6473
6474   do_cleanups (cleanups);
6475 }
6476
6477 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
6478    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
6479    to have already done the lookup to find the DWO file).
6480
6481    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6482    THIS_CU->is_debug_types, but nothing else.
6483
6484    We fill in THIS_CU->length.
6485
6486    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6487    linker) then DIE_READER_FUNC will not get called.
6488
6489    THIS_CU->cu is always freed when done.
6490    This is done in order to not leave THIS_CU->cu in a state where we have
6491    to care whether it refers to the "main" CU or the DWO CU.  */
6492
6493 static void
6494 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
6495                                    struct dwo_file *dwo_file,
6496                                    die_reader_func_ftype *die_reader_func,
6497                                    void *data)
6498 {
6499   struct objfile *objfile = dwarf2_per_objfile->objfile;
6500   struct dwarf2_section_info *section = this_cu->section;
6501   bfd *abfd = get_section_bfd_owner (section);
6502   struct dwarf2_section_info *abbrev_section;
6503   struct dwarf2_cu cu;
6504   const gdb_byte *begin_info_ptr, *info_ptr;
6505   struct die_reader_specs reader;
6506   struct cleanup *cleanups;
6507   struct die_info *comp_unit_die;
6508   int has_children;
6509
6510   if (dwarf_die_debug)
6511     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6512                         this_cu->is_debug_types ? "type" : "comp",
6513                         to_underlying (this_cu->sect_off));
6514
6515   gdb_assert (this_cu->cu == NULL);
6516
6517   abbrev_section = (dwo_file != NULL
6518                     ? &dwo_file->sections.abbrev
6519                     : get_abbrev_section_for_cu (this_cu));
6520
6521   /* This is cheap if the section is already read in.  */
6522   dwarf2_read_section (objfile, section);
6523
6524   init_one_comp_unit (&cu, this_cu);
6525
6526   cleanups = make_cleanup (free_stack_comp_unit, &cu);
6527
6528   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6529   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
6530                                             abbrev_section, info_ptr,
6531                                             (this_cu->is_debug_types
6532                                              ? rcuh_kind::TYPE
6533                                              : rcuh_kind::COMPILE));
6534
6535   this_cu->length = get_cu_length (&cu.header);
6536
6537   /* Skip dummy compilation units.  */
6538   if (info_ptr >= begin_info_ptr + this_cu->length
6539       || peek_abbrev_code (abfd, info_ptr) == 0)
6540     {
6541       do_cleanups (cleanups);
6542       return;
6543     }
6544
6545   dwarf2_read_abbrevs (&cu, abbrev_section);
6546   make_cleanup (dwarf2_free_abbrev_table, &cu);
6547
6548   init_cu_die_reader (&reader, &cu, section, dwo_file);
6549   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6550
6551   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6552
6553   do_cleanups (cleanups);
6554 }
6555
6556 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
6557    does not lookup the specified DWO file.
6558    This cannot be used to read DWO files.
6559
6560    THIS_CU->cu is always freed when done.
6561    This is done in order to not leave THIS_CU->cu in a state where we have
6562    to care whether it refers to the "main" CU or the DWO CU.
6563    We can revisit this if the data shows there's a performance issue.  */
6564
6565 static void
6566 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
6567                                 die_reader_func_ftype *die_reader_func,
6568                                 void *data)
6569 {
6570   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
6571 }
6572 \f
6573 /* Type Unit Groups.
6574
6575    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6576    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6577    so that all types coming from the same compilation (.o file) are grouped
6578    together.  A future step could be to put the types in the same symtab as
6579    the CU the types ultimately came from.  */
6580
6581 static hashval_t
6582 hash_type_unit_group (const void *item)
6583 {
6584   const struct type_unit_group *tu_group
6585     = (const struct type_unit_group *) item;
6586
6587   return hash_stmt_list_entry (&tu_group->hash);
6588 }
6589
6590 static int
6591 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6592 {
6593   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6594   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6595
6596   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6597 }
6598
6599 /* Allocate a hash table for type unit groups.  */
6600
6601 static htab_t
6602 allocate_type_unit_groups_table (void)
6603 {
6604   return htab_create_alloc_ex (3,
6605                                hash_type_unit_group,
6606                                eq_type_unit_group,
6607                                NULL,
6608                                &dwarf2_per_objfile->objfile->objfile_obstack,
6609                                hashtab_obstack_allocate,
6610                                dummy_obstack_deallocate);
6611 }
6612
6613 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6614    partial symtabs.  We combine several TUs per psymtab to not let the size
6615    of any one psymtab grow too big.  */
6616 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6617 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6618
6619 /* Helper routine for get_type_unit_group.
6620    Create the type_unit_group object used to hold one or more TUs.  */
6621
6622 static struct type_unit_group *
6623 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6624 {
6625   struct objfile *objfile = dwarf2_per_objfile->objfile;
6626   struct dwarf2_per_cu_data *per_cu;
6627   struct type_unit_group *tu_group;
6628
6629   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6630                              struct type_unit_group);
6631   per_cu = &tu_group->per_cu;
6632   per_cu->objfile = objfile;
6633
6634   if (dwarf2_per_objfile->using_index)
6635     {
6636       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6637                                         struct dwarf2_per_cu_quick_data);
6638     }
6639   else
6640     {
6641       unsigned int line_offset = to_underlying (line_offset_struct);
6642       struct partial_symtab *pst;
6643       char *name;
6644
6645       /* Give the symtab a useful name for debug purposes.  */
6646       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6647         name = xstrprintf ("<type_units_%d>",
6648                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6649       else
6650         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6651
6652       pst = create_partial_symtab (per_cu, name);
6653       pst->anonymous = 1;
6654
6655       xfree (name);
6656     }
6657
6658   tu_group->hash.dwo_unit = cu->dwo_unit;
6659   tu_group->hash.line_sect_off = line_offset_struct;
6660
6661   return tu_group;
6662 }
6663
6664 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6665    STMT_LIST is a DW_AT_stmt_list attribute.  */
6666
6667 static struct type_unit_group *
6668 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6669 {
6670   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6671   struct type_unit_group *tu_group;
6672   void **slot;
6673   unsigned int line_offset;
6674   struct type_unit_group type_unit_group_for_lookup;
6675
6676   if (dwarf2_per_objfile->type_unit_groups == NULL)
6677     {
6678       dwarf2_per_objfile->type_unit_groups =
6679         allocate_type_unit_groups_table ();
6680     }
6681
6682   /* Do we need to create a new group, or can we use an existing one?  */
6683
6684   if (stmt_list)
6685     {
6686       line_offset = DW_UNSND (stmt_list);
6687       ++tu_stats->nr_symtab_sharers;
6688     }
6689   else
6690     {
6691       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6692          We can do various things here like create one group per TU or
6693          spread them over multiple groups to split up the expansion work.
6694          To avoid worst case scenarios (too many groups or too large groups)
6695          we, umm, group them in bunches.  */
6696       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6697                      | (tu_stats->nr_stmt_less_type_units
6698                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6699       ++tu_stats->nr_stmt_less_type_units;
6700     }
6701
6702   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6703   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6704   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6705                          &type_unit_group_for_lookup, INSERT);
6706   if (*slot != NULL)
6707     {
6708       tu_group = (struct type_unit_group *) *slot;
6709       gdb_assert (tu_group != NULL);
6710     }
6711   else
6712     {
6713       sect_offset line_offset_struct = (sect_offset) line_offset;
6714       tu_group = create_type_unit_group (cu, line_offset_struct);
6715       *slot = tu_group;
6716       ++tu_stats->nr_symtabs;
6717     }
6718
6719   return tu_group;
6720 }
6721 \f
6722 /* Partial symbol tables.  */
6723
6724 /* Create a psymtab named NAME and assign it to PER_CU.
6725
6726    The caller must fill in the following details:
6727    dirname, textlow, texthigh.  */
6728
6729 static struct partial_symtab *
6730 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6731 {
6732   struct objfile *objfile = per_cu->objfile;
6733   struct partial_symtab *pst;
6734
6735   pst = start_psymtab_common (objfile, name, 0,
6736                               objfile->global_psymbols,
6737                               objfile->static_psymbols);
6738
6739   pst->psymtabs_addrmap_supported = 1;
6740
6741   /* This is the glue that links PST into GDB's symbol API.  */
6742   pst->read_symtab_private = per_cu;
6743   pst->read_symtab = dwarf2_read_symtab;
6744   per_cu->v.psymtab = pst;
6745
6746   return pst;
6747 }
6748
6749 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6750    type.  */
6751
6752 struct process_psymtab_comp_unit_data
6753 {
6754   /* True if we are reading a DW_TAG_partial_unit.  */
6755
6756   int want_partial_unit;
6757
6758   /* The "pretend" language that is used if the CU doesn't declare a
6759      language.  */
6760
6761   enum language pretend_language;
6762 };
6763
6764 /* die_reader_func for process_psymtab_comp_unit.  */
6765
6766 static void
6767 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6768                                   const gdb_byte *info_ptr,
6769                                   struct die_info *comp_unit_die,
6770                                   int has_children,
6771                                   void *data)
6772 {
6773   struct dwarf2_cu *cu = reader->cu;
6774   struct objfile *objfile = cu->objfile;
6775   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6776   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6777   CORE_ADDR baseaddr;
6778   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6779   struct partial_symtab *pst;
6780   enum pc_bounds_kind cu_bounds_kind;
6781   const char *filename;
6782   struct process_psymtab_comp_unit_data *info
6783     = (struct process_psymtab_comp_unit_data *) data;
6784
6785   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6786     return;
6787
6788   gdb_assert (! per_cu->is_debug_types);
6789
6790   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6791
6792   cu->list_in_scope = &file_symbols;
6793
6794   /* Allocate a new partial symbol table structure.  */
6795   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6796   if (filename == NULL)
6797     filename = "";
6798
6799   pst = create_partial_symtab (per_cu, filename);
6800
6801   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6802   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6803
6804   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6805
6806   dwarf2_find_base_address (comp_unit_die, cu);
6807
6808   /* Possibly set the default values of LOWPC and HIGHPC from
6809      `DW_AT_ranges'.  */
6810   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6811                                          &best_highpc, cu, pst);
6812   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6813     /* Store the contiguous range if it is not empty; it can be empty for
6814        CUs with no code.  */
6815     addrmap_set_empty (objfile->psymtabs_addrmap,
6816                        gdbarch_adjust_dwarf2_addr (gdbarch,
6817                                                    best_lowpc + baseaddr),
6818                        gdbarch_adjust_dwarf2_addr (gdbarch,
6819                                                    best_highpc + baseaddr) - 1,
6820                        pst);
6821
6822   /* Check if comp unit has_children.
6823      If so, read the rest of the partial symbols from this comp unit.
6824      If not, there's no more debug_info for this comp unit.  */
6825   if (has_children)
6826     {
6827       struct partial_die_info *first_die;
6828       CORE_ADDR lowpc, highpc;
6829
6830       lowpc = ((CORE_ADDR) -1);
6831       highpc = ((CORE_ADDR) 0);
6832
6833       first_die = load_partial_dies (reader, info_ptr, 1);
6834
6835       scan_partial_symbols (first_die, &lowpc, &highpc,
6836                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6837
6838       /* If we didn't find a lowpc, set it to highpc to avoid
6839          complaints from `maint check'.  */
6840       if (lowpc == ((CORE_ADDR) -1))
6841         lowpc = highpc;
6842
6843       /* If the compilation unit didn't have an explicit address range,
6844          then use the information extracted from its child dies.  */
6845       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6846         {
6847           best_lowpc = lowpc;
6848           best_highpc = highpc;
6849         }
6850     }
6851   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6852   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6853
6854   end_psymtab_common (objfile, pst);
6855
6856   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6857     {
6858       int i;
6859       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6860       struct dwarf2_per_cu_data *iter;
6861
6862       /* Fill in 'dependencies' here; we fill in 'users' in a
6863          post-pass.  */
6864       pst->number_of_dependencies = len;
6865       pst->dependencies =
6866         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6867       for (i = 0;
6868            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6869                         i, iter);
6870            ++i)
6871         pst->dependencies[i] = iter->v.psymtab;
6872
6873       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6874     }
6875
6876   /* Get the list of files included in the current compilation unit,
6877      and build a psymtab for each of them.  */
6878   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6879
6880   if (dwarf_read_debug)
6881     {
6882       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6883
6884       fprintf_unfiltered (gdb_stdlog,
6885                           "Psymtab for %s unit @0x%x: %s - %s"
6886                           ", %d global, %d static syms\n",
6887                           per_cu->is_debug_types ? "type" : "comp",
6888                           to_underlying (per_cu->sect_off),
6889                           paddress (gdbarch, pst->textlow),
6890                           paddress (gdbarch, pst->texthigh),
6891                           pst->n_global_syms, pst->n_static_syms);
6892     }
6893 }
6894
6895 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6896    Process compilation unit THIS_CU for a psymtab.  */
6897
6898 static void
6899 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6900                            int want_partial_unit,
6901                            enum language pretend_language)
6902 {
6903   /* If this compilation unit was already read in, free the
6904      cached copy in order to read it in again.  This is
6905      necessary because we skipped some symbols when we first
6906      read in the compilation unit (see load_partial_dies).
6907      This problem could be avoided, but the benefit is unclear.  */
6908   if (this_cu->cu != NULL)
6909     free_one_cached_comp_unit (this_cu);
6910
6911   if (this_cu->is_debug_types)
6912     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6913                              NULL);
6914   else
6915     {
6916       process_psymtab_comp_unit_data info;
6917       info.want_partial_unit = want_partial_unit;
6918       info.pretend_language = pretend_language;
6919       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6920                                process_psymtab_comp_unit_reader, &info);
6921     }
6922
6923   /* Age out any secondary CUs.  */
6924   age_cached_comp_units ();
6925 }
6926
6927 /* Reader function for build_type_psymtabs.  */
6928
6929 static void
6930 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6931                             const gdb_byte *info_ptr,
6932                             struct die_info *type_unit_die,
6933                             int has_children,
6934                             void *data)
6935 {
6936   struct objfile *objfile = dwarf2_per_objfile->objfile;
6937   struct dwarf2_cu *cu = reader->cu;
6938   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6939   struct signatured_type *sig_type;
6940   struct type_unit_group *tu_group;
6941   struct attribute *attr;
6942   struct partial_die_info *first_die;
6943   CORE_ADDR lowpc, highpc;
6944   struct partial_symtab *pst;
6945
6946   gdb_assert (data == NULL);
6947   gdb_assert (per_cu->is_debug_types);
6948   sig_type = (struct signatured_type *) per_cu;
6949
6950   if (! has_children)
6951     return;
6952
6953   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6954   tu_group = get_type_unit_group (cu, attr);
6955
6956   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6957
6958   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6959   cu->list_in_scope = &file_symbols;
6960   pst = create_partial_symtab (per_cu, "");
6961   pst->anonymous = 1;
6962
6963   first_die = load_partial_dies (reader, info_ptr, 1);
6964
6965   lowpc = (CORE_ADDR) -1;
6966   highpc = (CORE_ADDR) 0;
6967   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6968
6969   end_psymtab_common (objfile, pst);
6970 }
6971
6972 /* Struct used to sort TUs by their abbreviation table offset.  */
6973
6974 struct tu_abbrev_offset
6975 {
6976   struct signatured_type *sig_type;
6977   sect_offset abbrev_offset;
6978 };
6979
6980 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6981
6982 static int
6983 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6984 {
6985   const struct tu_abbrev_offset * const *a
6986     = (const struct tu_abbrev_offset * const*) ap;
6987   const struct tu_abbrev_offset * const *b
6988     = (const struct tu_abbrev_offset * const*) bp;
6989   sect_offset aoff = (*a)->abbrev_offset;
6990   sect_offset boff = (*b)->abbrev_offset;
6991
6992   return (aoff > boff) - (aoff < boff);
6993 }
6994
6995 /* Efficiently read all the type units.
6996    This does the bulk of the work for build_type_psymtabs.
6997
6998    The efficiency is because we sort TUs by the abbrev table they use and
6999    only read each abbrev table once.  In one program there are 200K TUs
7000    sharing 8K abbrev tables.
7001
7002    The main purpose of this function is to support building the
7003    dwarf2_per_objfile->type_unit_groups table.
7004    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7005    can collapse the search space by grouping them by stmt_list.
7006    The savings can be significant, in the same program from above the 200K TUs
7007    share 8K stmt_list tables.
7008
7009    FUNC is expected to call get_type_unit_group, which will create the
7010    struct type_unit_group if necessary and add it to
7011    dwarf2_per_objfile->type_unit_groups.  */
7012
7013 static void
7014 build_type_psymtabs_1 (void)
7015 {
7016   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7017   struct cleanup *cleanups;
7018   struct abbrev_table *abbrev_table;
7019   sect_offset abbrev_offset;
7020   struct tu_abbrev_offset *sorted_by_abbrev;
7021   int i;
7022
7023   /* It's up to the caller to not call us multiple times.  */
7024   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
7025
7026   if (dwarf2_per_objfile->n_type_units == 0)
7027     return;
7028
7029   /* TUs typically share abbrev tables, and there can be way more TUs than
7030      abbrev tables.  Sort by abbrev table to reduce the number of times we
7031      read each abbrev table in.
7032      Alternatives are to punt or to maintain a cache of abbrev tables.
7033      This is simpler and efficient enough for now.
7034
7035      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7036      symtab to use).  Typically TUs with the same abbrev offset have the same
7037      stmt_list value too so in practice this should work well.
7038
7039      The basic algorithm here is:
7040
7041       sort TUs by abbrev table
7042       for each TU with same abbrev table:
7043         read abbrev table if first user
7044         read TU top level DIE
7045           [IWBN if DWO skeletons had DW_AT_stmt_list]
7046         call FUNC  */
7047
7048   if (dwarf_read_debug)
7049     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
7050
7051   /* Sort in a separate table to maintain the order of all_type_units
7052      for .gdb_index: TU indices directly index all_type_units.  */
7053   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
7054                               dwarf2_per_objfile->n_type_units);
7055   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7056     {
7057       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
7058
7059       sorted_by_abbrev[i].sig_type = sig_type;
7060       sorted_by_abbrev[i].abbrev_offset =
7061         read_abbrev_offset (sig_type->per_cu.section,
7062                             sig_type->per_cu.sect_off);
7063     }
7064   cleanups = make_cleanup (xfree, sorted_by_abbrev);
7065   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
7066          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
7067
7068   abbrev_offset = (sect_offset) ~(unsigned) 0;
7069   abbrev_table = NULL;
7070   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
7071
7072   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7073     {
7074       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
7075
7076       /* Switch to the next abbrev table if necessary.  */
7077       if (abbrev_table == NULL
7078           || tu->abbrev_offset != abbrev_offset)
7079         {
7080           if (abbrev_table != NULL)
7081             {
7082               abbrev_table_free (abbrev_table);
7083               /* Reset to NULL in case abbrev_table_read_table throws
7084                  an error: abbrev_table_free_cleanup will get called.  */
7085               abbrev_table = NULL;
7086             }
7087           abbrev_offset = tu->abbrev_offset;
7088           abbrev_table =
7089             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
7090                                      abbrev_offset);
7091           ++tu_stats->nr_uniq_abbrev_tables;
7092         }
7093
7094       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
7095                                build_type_psymtabs_reader, NULL);
7096     }
7097
7098   do_cleanups (cleanups);
7099 }
7100
7101 /* Print collected type unit statistics.  */
7102
7103 static void
7104 print_tu_stats (void)
7105 {
7106   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7107
7108   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
7109   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
7110                       dwarf2_per_objfile->n_type_units);
7111   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
7112                       tu_stats->nr_uniq_abbrev_tables);
7113   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
7114                       tu_stats->nr_symtabs);
7115   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
7116                       tu_stats->nr_symtab_sharers);
7117   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
7118                       tu_stats->nr_stmt_less_type_units);
7119   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
7120                       tu_stats->nr_all_type_units_reallocs);
7121 }
7122
7123 /* Traversal function for build_type_psymtabs.  */
7124
7125 static int
7126 build_type_psymtab_dependencies (void **slot, void *info)
7127 {
7128   struct objfile *objfile = dwarf2_per_objfile->objfile;
7129   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7130   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
7131   struct partial_symtab *pst = per_cu->v.psymtab;
7132   int len = VEC_length (sig_type_ptr, tu_group->tus);
7133   struct signatured_type *iter;
7134   int i;
7135
7136   gdb_assert (len > 0);
7137   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
7138
7139   pst->number_of_dependencies = len;
7140   pst->dependencies =
7141     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7142   for (i = 0;
7143        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
7144        ++i)
7145     {
7146       gdb_assert (iter->per_cu.is_debug_types);
7147       pst->dependencies[i] = iter->per_cu.v.psymtab;
7148       iter->type_unit_group = tu_group;
7149     }
7150
7151   VEC_free (sig_type_ptr, tu_group->tus);
7152
7153   return 1;
7154 }
7155
7156 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7157    Build partial symbol tables for the .debug_types comp-units.  */
7158
7159 static void
7160 build_type_psymtabs (struct objfile *objfile)
7161 {
7162   if (! create_all_type_units (objfile))
7163     return;
7164
7165   build_type_psymtabs_1 ();
7166 }
7167
7168 /* Traversal function for process_skeletonless_type_unit.
7169    Read a TU in a DWO file and build partial symbols for it.  */
7170
7171 static int
7172 process_skeletonless_type_unit (void **slot, void *info)
7173 {
7174   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7175   struct objfile *objfile = (struct objfile *) info;
7176   struct signatured_type find_entry, *entry;
7177
7178   /* If this TU doesn't exist in the global table, add it and read it in.  */
7179
7180   if (dwarf2_per_objfile->signatured_types == NULL)
7181     {
7182       dwarf2_per_objfile->signatured_types
7183         = allocate_signatured_type_table (objfile);
7184     }
7185
7186   find_entry.signature = dwo_unit->signature;
7187   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
7188                          INSERT);
7189   /* If we've already seen this type there's nothing to do.  What's happening
7190      is we're doing our own version of comdat-folding here.  */
7191   if (*slot != NULL)
7192     return 1;
7193
7194   /* This does the job that create_all_type_units would have done for
7195      this TU.  */
7196   entry = add_type_unit (dwo_unit->signature, slot);
7197   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
7198   *slot = entry;
7199
7200   /* This does the job that build_type_psymtabs_1 would have done.  */
7201   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
7202                            build_type_psymtabs_reader, NULL);
7203
7204   return 1;
7205 }
7206
7207 /* Traversal function for process_skeletonless_type_units.  */
7208
7209 static int
7210 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
7211 {
7212   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7213
7214   if (dwo_file->tus != NULL)
7215     {
7216       htab_traverse_noresize (dwo_file->tus,
7217                               process_skeletonless_type_unit, info);
7218     }
7219
7220   return 1;
7221 }
7222
7223 /* Scan all TUs of DWO files, verifying we've processed them.
7224    This is needed in case a TU was emitted without its skeleton.
7225    Note: This can't be done until we know what all the DWO files are.  */
7226
7227 static void
7228 process_skeletonless_type_units (struct objfile *objfile)
7229 {
7230   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
7231   if (get_dwp_file () == NULL
7232       && dwarf2_per_objfile->dwo_files != NULL)
7233     {
7234       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
7235                               process_dwo_file_for_skeletonless_type_units,
7236                               objfile);
7237     }
7238 }
7239
7240 /* Compute the 'user' field for each psymtab in OBJFILE.  */
7241
7242 static void
7243 set_partial_user (struct objfile *objfile)
7244 {
7245   int i;
7246
7247   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7248     {
7249       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7250       struct partial_symtab *pst = per_cu->v.psymtab;
7251       int j;
7252
7253       if (pst == NULL)
7254         continue;
7255
7256       for (j = 0; j < pst->number_of_dependencies; ++j)
7257         {
7258           /* Set the 'user' field only if it is not already set.  */
7259           if (pst->dependencies[j]->user == NULL)
7260             pst->dependencies[j]->user = pst;
7261         }
7262     }
7263 }
7264
7265 /* Build the partial symbol table by doing a quick pass through the
7266    .debug_info and .debug_abbrev sections.  */
7267
7268 static void
7269 dwarf2_build_psymtabs_hard (struct objfile *objfile)
7270 {
7271   struct cleanup *back_to;
7272   int i;
7273
7274   if (dwarf_read_debug)
7275     {
7276       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
7277                           objfile_name (objfile));
7278     }
7279
7280   dwarf2_per_objfile->reading_partial_symbols = 1;
7281
7282   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
7283
7284   /* Any cached compilation units will be linked by the per-objfile
7285      read_in_chain.  Make sure to free them when we're done.  */
7286   back_to = make_cleanup (free_cached_comp_units, NULL);
7287
7288   build_type_psymtabs (objfile);
7289
7290   create_all_comp_units (objfile);
7291
7292   /* Create a temporary address map on a temporary obstack.  We later
7293      copy this to the final obstack.  */
7294   auto_obstack temp_obstack;
7295
7296   scoped_restore save_psymtabs_addrmap
7297     = make_scoped_restore (&objfile->psymtabs_addrmap,
7298                            addrmap_create_mutable (&temp_obstack));
7299
7300   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7301     {
7302       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7303
7304       process_psymtab_comp_unit (per_cu, 0, language_minimal);
7305     }
7306
7307   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7308   process_skeletonless_type_units (objfile);
7309
7310   /* Now that all TUs have been processed we can fill in the dependencies.  */
7311   if (dwarf2_per_objfile->type_unit_groups != NULL)
7312     {
7313       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
7314                               build_type_psymtab_dependencies, NULL);
7315     }
7316
7317   if (dwarf_read_debug)
7318     print_tu_stats ();
7319
7320   set_partial_user (objfile);
7321
7322   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
7323                                                     &objfile->objfile_obstack);
7324   /* At this point we want to keep the address map.  */
7325   save_psymtabs_addrmap.release ();
7326
7327   do_cleanups (back_to);
7328
7329   if (dwarf_read_debug)
7330     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
7331                         objfile_name (objfile));
7332 }
7333
7334 /* die_reader_func for load_partial_comp_unit.  */
7335
7336 static void
7337 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
7338                                const gdb_byte *info_ptr,
7339                                struct die_info *comp_unit_die,
7340                                int has_children,
7341                                void *data)
7342 {
7343   struct dwarf2_cu *cu = reader->cu;
7344
7345   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
7346
7347   /* Check if comp unit has_children.
7348      If so, read the rest of the partial symbols from this comp unit.
7349      If not, there's no more debug_info for this comp unit.  */
7350   if (has_children)
7351     load_partial_dies (reader, info_ptr, 0);
7352 }
7353
7354 /* Load the partial DIEs for a secondary CU into memory.
7355    This is also used when rereading a primary CU with load_all_dies.  */
7356
7357 static void
7358 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
7359 {
7360   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7361                            load_partial_comp_unit_reader, NULL);
7362 }
7363
7364 static void
7365 read_comp_units_from_section (struct objfile *objfile,
7366                               struct dwarf2_section_info *section,
7367                               struct dwarf2_section_info *abbrev_section,
7368                               unsigned int is_dwz,
7369                               int *n_allocated,
7370                               int *n_comp_units,
7371                               struct dwarf2_per_cu_data ***all_comp_units)
7372 {
7373   const gdb_byte *info_ptr;
7374   bfd *abfd = get_section_bfd_owner (section);
7375
7376   if (dwarf_read_debug)
7377     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
7378                         get_section_name (section),
7379                         get_section_file_name (section));
7380
7381   dwarf2_read_section (objfile, section);
7382
7383   info_ptr = section->buffer;
7384
7385   while (info_ptr < section->buffer + section->size)
7386     {
7387       struct dwarf2_per_cu_data *this_cu;
7388
7389       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7390
7391       comp_unit_head cu_header;
7392       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
7393                                      info_ptr, rcuh_kind::COMPILE);
7394
7395       /* Save the compilation unit for later lookup.  */
7396       if (cu_header.unit_type != DW_UT_type)
7397         {
7398           this_cu = XOBNEW (&objfile->objfile_obstack,
7399                             struct dwarf2_per_cu_data);
7400           memset (this_cu, 0, sizeof (*this_cu));
7401         }
7402       else
7403         {
7404           auto sig_type = XOBNEW (&objfile->objfile_obstack,
7405                                   struct signatured_type);
7406           memset (sig_type, 0, sizeof (*sig_type));
7407           sig_type->signature = cu_header.signature;
7408           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7409           this_cu = &sig_type->per_cu;
7410         }
7411       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
7412       this_cu->sect_off = sect_off;
7413       this_cu->length = cu_header.length + cu_header.initial_length_size;
7414       this_cu->is_dwz = is_dwz;
7415       this_cu->objfile = objfile;
7416       this_cu->section = section;
7417
7418       if (*n_comp_units == *n_allocated)
7419         {
7420           *n_allocated *= 2;
7421           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
7422                                         *all_comp_units, *n_allocated);
7423         }
7424       (*all_comp_units)[*n_comp_units] = this_cu;
7425       ++*n_comp_units;
7426
7427       info_ptr = info_ptr + this_cu->length;
7428     }
7429 }
7430
7431 /* Create a list of all compilation units in OBJFILE.
7432    This is only done for -readnow and building partial symtabs.  */
7433
7434 static void
7435 create_all_comp_units (struct objfile *objfile)
7436 {
7437   int n_allocated;
7438   int n_comp_units;
7439   struct dwarf2_per_cu_data **all_comp_units;
7440   struct dwz_file *dwz;
7441
7442   n_comp_units = 0;
7443   n_allocated = 10;
7444   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
7445
7446   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
7447                                 &dwarf2_per_objfile->abbrev, 0,
7448                                 &n_allocated, &n_comp_units, &all_comp_units);
7449
7450   dwz = dwarf2_get_dwz_file ();
7451   if (dwz != NULL)
7452     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
7453                                   &n_allocated, &n_comp_units,
7454                                   &all_comp_units);
7455
7456   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
7457                                                   struct dwarf2_per_cu_data *,
7458                                                   n_comp_units);
7459   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
7460           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
7461   xfree (all_comp_units);
7462   dwarf2_per_objfile->n_comp_units = n_comp_units;
7463 }
7464
7465 /* Process all loaded DIEs for compilation unit CU, starting at
7466    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7467    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7468    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7469    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7470
7471 static void
7472 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7473                       CORE_ADDR *highpc, int set_addrmap,
7474                       struct dwarf2_cu *cu)
7475 {
7476   struct partial_die_info *pdi;
7477
7478   /* Now, march along the PDI's, descending into ones which have
7479      interesting children but skipping the children of the other ones,
7480      until we reach the end of the compilation unit.  */
7481
7482   pdi = first_die;
7483
7484   while (pdi != NULL)
7485     {
7486       fixup_partial_die (pdi, cu);
7487
7488       /* Anonymous namespaces or modules have no name but have interesting
7489          children, so we need to look at them.  Ditto for anonymous
7490          enums.  */
7491
7492       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
7493           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7494           || pdi->tag == DW_TAG_imported_unit)
7495         {
7496           switch (pdi->tag)
7497             {
7498             case DW_TAG_subprogram:
7499               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7500               break;
7501             case DW_TAG_constant:
7502             case DW_TAG_variable:
7503             case DW_TAG_typedef:
7504             case DW_TAG_union_type:
7505               if (!pdi->is_declaration)
7506                 {
7507                   add_partial_symbol (pdi, cu);
7508                 }
7509               break;
7510             case DW_TAG_class_type:
7511             case DW_TAG_interface_type:
7512             case DW_TAG_structure_type:
7513               if (!pdi->is_declaration)
7514                 {
7515                   add_partial_symbol (pdi, cu);
7516                 }
7517               if (cu->language == language_rust && pdi->has_children)
7518                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7519                                       set_addrmap, cu);
7520               break;
7521             case DW_TAG_enumeration_type:
7522               if (!pdi->is_declaration)
7523                 add_partial_enumeration (pdi, cu);
7524               break;
7525             case DW_TAG_base_type:
7526             case DW_TAG_subrange_type:
7527               /* File scope base type definitions are added to the partial
7528                  symbol table.  */
7529               add_partial_symbol (pdi, cu);
7530               break;
7531             case DW_TAG_namespace:
7532               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7533               break;
7534             case DW_TAG_module:
7535               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7536               break;
7537             case DW_TAG_imported_unit:
7538               {
7539                 struct dwarf2_per_cu_data *per_cu;
7540
7541                 /* For now we don't handle imported units in type units.  */
7542                 if (cu->per_cu->is_debug_types)
7543                   {
7544                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7545                              " supported in type units [in module %s]"),
7546                            objfile_name (cu->objfile));
7547                   }
7548
7549                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
7550                                                            pdi->is_dwz,
7551                                                            cu->objfile);
7552
7553                 /* Go read the partial unit, if needed.  */
7554                 if (per_cu->v.psymtab == NULL)
7555                   process_psymtab_comp_unit (per_cu, 1, cu->language);
7556
7557                 VEC_safe_push (dwarf2_per_cu_ptr,
7558                                cu->per_cu->imported_symtabs, per_cu);
7559               }
7560               break;
7561             case DW_TAG_imported_declaration:
7562               add_partial_symbol (pdi, cu);
7563               break;
7564             default:
7565               break;
7566             }
7567         }
7568
7569       /* If the die has a sibling, skip to the sibling.  */
7570
7571       pdi = pdi->die_sibling;
7572     }
7573 }
7574
7575 /* Functions used to compute the fully scoped name of a partial DIE.
7576
7577    Normally, this is simple.  For C++, the parent DIE's fully scoped
7578    name is concatenated with "::" and the partial DIE's name.
7579    Enumerators are an exception; they use the scope of their parent
7580    enumeration type, i.e. the name of the enumeration type is not
7581    prepended to the enumerator.
7582
7583    There are two complexities.  One is DW_AT_specification; in this
7584    case "parent" means the parent of the target of the specification,
7585    instead of the direct parent of the DIE.  The other is compilers
7586    which do not emit DW_TAG_namespace; in this case we try to guess
7587    the fully qualified name of structure types from their members'
7588    linkage names.  This must be done using the DIE's children rather
7589    than the children of any DW_AT_specification target.  We only need
7590    to do this for structures at the top level, i.e. if the target of
7591    any DW_AT_specification (if any; otherwise the DIE itself) does not
7592    have a parent.  */
7593
7594 /* Compute the scope prefix associated with PDI's parent, in
7595    compilation unit CU.  The result will be allocated on CU's
7596    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7597    field.  NULL is returned if no prefix is necessary.  */
7598 static const char *
7599 partial_die_parent_scope (struct partial_die_info *pdi,
7600                           struct dwarf2_cu *cu)
7601 {
7602   const char *grandparent_scope;
7603   struct partial_die_info *parent, *real_pdi;
7604
7605   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7606      then this means the parent of the specification DIE.  */
7607
7608   real_pdi = pdi;
7609   while (real_pdi->has_specification)
7610     real_pdi = find_partial_die (real_pdi->spec_offset,
7611                                  real_pdi->spec_is_dwz, cu);
7612
7613   parent = real_pdi->die_parent;
7614   if (parent == NULL)
7615     return NULL;
7616
7617   if (parent->scope_set)
7618     return parent->scope;
7619
7620   fixup_partial_die (parent, cu);
7621
7622   grandparent_scope = partial_die_parent_scope (parent, cu);
7623
7624   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7625      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7626      Work around this problem here.  */
7627   if (cu->language == language_cplus
7628       && parent->tag == DW_TAG_namespace
7629       && strcmp (parent->name, "::") == 0
7630       && grandparent_scope == NULL)
7631     {
7632       parent->scope = NULL;
7633       parent->scope_set = 1;
7634       return NULL;
7635     }
7636
7637   if (pdi->tag == DW_TAG_enumerator)
7638     /* Enumerators should not get the name of the enumeration as a prefix.  */
7639     parent->scope = grandparent_scope;
7640   else if (parent->tag == DW_TAG_namespace
7641       || parent->tag == DW_TAG_module
7642       || parent->tag == DW_TAG_structure_type
7643       || parent->tag == DW_TAG_class_type
7644       || parent->tag == DW_TAG_interface_type
7645       || parent->tag == DW_TAG_union_type
7646       || parent->tag == DW_TAG_enumeration_type)
7647     {
7648       if (grandparent_scope == NULL)
7649         parent->scope = parent->name;
7650       else
7651         parent->scope = typename_concat (&cu->comp_unit_obstack,
7652                                          grandparent_scope,
7653                                          parent->name, 0, cu);
7654     }
7655   else
7656     {
7657       /* FIXME drow/2004-04-01: What should we be doing with
7658          function-local names?  For partial symbols, we should probably be
7659          ignoring them.  */
7660       complaint (&symfile_complaints,
7661                  _("unhandled containing DIE tag %d for DIE at %d"),
7662                  parent->tag, to_underlying (pdi->sect_off));
7663       parent->scope = grandparent_scope;
7664     }
7665
7666   parent->scope_set = 1;
7667   return parent->scope;
7668 }
7669
7670 /* Return the fully scoped name associated with PDI, from compilation unit
7671    CU.  The result will be allocated with malloc.  */
7672
7673 static char *
7674 partial_die_full_name (struct partial_die_info *pdi,
7675                        struct dwarf2_cu *cu)
7676 {
7677   const char *parent_scope;
7678
7679   /* If this is a template instantiation, we can not work out the
7680      template arguments from partial DIEs.  So, unfortunately, we have
7681      to go through the full DIEs.  At least any work we do building
7682      types here will be reused if full symbols are loaded later.  */
7683   if (pdi->has_template_arguments)
7684     {
7685       fixup_partial_die (pdi, cu);
7686
7687       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7688         {
7689           struct die_info *die;
7690           struct attribute attr;
7691           struct dwarf2_cu *ref_cu = cu;
7692
7693           /* DW_FORM_ref_addr is using section offset.  */
7694           attr.name = (enum dwarf_attribute) 0;
7695           attr.form = DW_FORM_ref_addr;
7696           attr.u.unsnd = to_underlying (pdi->sect_off);
7697           die = follow_die_ref (NULL, &attr, &ref_cu);
7698
7699           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7700         }
7701     }
7702
7703   parent_scope = partial_die_parent_scope (pdi, cu);
7704   if (parent_scope == NULL)
7705     return NULL;
7706   else
7707     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7708 }
7709
7710 static void
7711 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7712 {
7713   struct objfile *objfile = cu->objfile;
7714   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7715   CORE_ADDR addr = 0;
7716   const char *actual_name = NULL;
7717   CORE_ADDR baseaddr;
7718   char *built_actual_name;
7719
7720   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7721
7722   built_actual_name = partial_die_full_name (pdi, cu);
7723   if (built_actual_name != NULL)
7724     actual_name = built_actual_name;
7725
7726   if (actual_name == NULL)
7727     actual_name = pdi->name;
7728
7729   switch (pdi->tag)
7730     {
7731     case DW_TAG_subprogram:
7732       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7733       if (pdi->is_external || cu->language == language_ada)
7734         {
7735           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7736              of the global scope.  But in Ada, we want to be able to access
7737              nested procedures globally.  So all Ada subprograms are stored
7738              in the global scope.  */
7739           add_psymbol_to_list (actual_name, strlen (actual_name),
7740                                built_actual_name != NULL,
7741                                VAR_DOMAIN, LOC_BLOCK,
7742                                &objfile->global_psymbols,
7743                                addr, cu->language, objfile);
7744         }
7745       else
7746         {
7747           add_psymbol_to_list (actual_name, strlen (actual_name),
7748                                built_actual_name != NULL,
7749                                VAR_DOMAIN, LOC_BLOCK,
7750                                &objfile->static_psymbols,
7751                                addr, cu->language, objfile);
7752         }
7753
7754       if (pdi->main_subprogram && actual_name != NULL)
7755         set_objfile_main_name (objfile, actual_name, cu->language);
7756       break;
7757     case DW_TAG_constant:
7758       {
7759         std::vector<partial_symbol *> *list;
7760
7761         if (pdi->is_external)
7762           list = &objfile->global_psymbols;
7763         else
7764           list = &objfile->static_psymbols;
7765         add_psymbol_to_list (actual_name, strlen (actual_name),
7766                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7767                              list, 0, cu->language, objfile);
7768       }
7769       break;
7770     case DW_TAG_variable:
7771       if (pdi->d.locdesc)
7772         addr = decode_locdesc (pdi->d.locdesc, cu);
7773
7774       if (pdi->d.locdesc
7775           && addr == 0
7776           && !dwarf2_per_objfile->has_section_at_zero)
7777         {
7778           /* A global or static variable may also have been stripped
7779              out by the linker if unused, in which case its address
7780              will be nullified; do not add such variables into partial
7781              symbol table then.  */
7782         }
7783       else if (pdi->is_external)
7784         {
7785           /* Global Variable.
7786              Don't enter into the minimal symbol tables as there is
7787              a minimal symbol table entry from the ELF symbols already.
7788              Enter into partial symbol table if it has a location
7789              descriptor or a type.
7790              If the location descriptor is missing, new_symbol will create
7791              a LOC_UNRESOLVED symbol, the address of the variable will then
7792              be determined from the minimal symbol table whenever the variable
7793              is referenced.
7794              The address for the partial symbol table entry is not
7795              used by GDB, but it comes in handy for debugging partial symbol
7796              table building.  */
7797
7798           if (pdi->d.locdesc || pdi->has_type)
7799             add_psymbol_to_list (actual_name, strlen (actual_name),
7800                                  built_actual_name != NULL,
7801                                  VAR_DOMAIN, LOC_STATIC,
7802                                  &objfile->global_psymbols,
7803                                  addr + baseaddr,
7804                                  cu->language, objfile);
7805         }
7806       else
7807         {
7808           int has_loc = pdi->d.locdesc != NULL;
7809
7810           /* Static Variable.  Skip symbols whose value we cannot know (those
7811              without location descriptors or constant values).  */
7812           if (!has_loc && !pdi->has_const_value)
7813             {
7814               xfree (built_actual_name);
7815               return;
7816             }
7817
7818           add_psymbol_to_list (actual_name, strlen (actual_name),
7819                                built_actual_name != NULL,
7820                                VAR_DOMAIN, LOC_STATIC,
7821                                &objfile->static_psymbols,
7822                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7823                                cu->language, objfile);
7824         }
7825       break;
7826     case DW_TAG_typedef:
7827     case DW_TAG_base_type:
7828     case DW_TAG_subrange_type:
7829       add_psymbol_to_list (actual_name, strlen (actual_name),
7830                            built_actual_name != NULL,
7831                            VAR_DOMAIN, LOC_TYPEDEF,
7832                            &objfile->static_psymbols,
7833                            0, cu->language, objfile);
7834       break;
7835     case DW_TAG_imported_declaration:
7836     case DW_TAG_namespace:
7837       add_psymbol_to_list (actual_name, strlen (actual_name),
7838                            built_actual_name != NULL,
7839                            VAR_DOMAIN, LOC_TYPEDEF,
7840                            &objfile->global_psymbols,
7841                            0, cu->language, objfile);
7842       break;
7843     case DW_TAG_module:
7844       add_psymbol_to_list (actual_name, strlen (actual_name),
7845                            built_actual_name != NULL,
7846                            MODULE_DOMAIN, LOC_TYPEDEF,
7847                            &objfile->global_psymbols,
7848                            0, cu->language, objfile);
7849       break;
7850     case DW_TAG_class_type:
7851     case DW_TAG_interface_type:
7852     case DW_TAG_structure_type:
7853     case DW_TAG_union_type:
7854     case DW_TAG_enumeration_type:
7855       /* Skip external references.  The DWARF standard says in the section
7856          about "Structure, Union, and Class Type Entries": "An incomplete
7857          structure, union or class type is represented by a structure,
7858          union or class entry that does not have a byte size attribute
7859          and that has a DW_AT_declaration attribute."  */
7860       if (!pdi->has_byte_size && pdi->is_declaration)
7861         {
7862           xfree (built_actual_name);
7863           return;
7864         }
7865
7866       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7867          static vs. global.  */
7868       add_psymbol_to_list (actual_name, strlen (actual_name),
7869                            built_actual_name != NULL,
7870                            STRUCT_DOMAIN, LOC_TYPEDEF,
7871                            cu->language == language_cplus
7872                            ? &objfile->global_psymbols
7873                            : &objfile->static_psymbols,
7874                            0, cu->language, objfile);
7875
7876       break;
7877     case DW_TAG_enumerator:
7878       add_psymbol_to_list (actual_name, strlen (actual_name),
7879                            built_actual_name != NULL,
7880                            VAR_DOMAIN, LOC_CONST,
7881                            cu->language == language_cplus
7882                            ? &objfile->global_psymbols
7883                            : &objfile->static_psymbols,
7884                            0, cu->language, objfile);
7885       break;
7886     default:
7887       break;
7888     }
7889
7890   xfree (built_actual_name);
7891 }
7892
7893 /* Read a partial die corresponding to a namespace; also, add a symbol
7894    corresponding to that namespace to the symbol table.  NAMESPACE is
7895    the name of the enclosing namespace.  */
7896
7897 static void
7898 add_partial_namespace (struct partial_die_info *pdi,
7899                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7900                        int set_addrmap, struct dwarf2_cu *cu)
7901 {
7902   /* Add a symbol for the namespace.  */
7903
7904   add_partial_symbol (pdi, cu);
7905
7906   /* Now scan partial symbols in that namespace.  */
7907
7908   if (pdi->has_children)
7909     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7910 }
7911
7912 /* Read a partial die corresponding to a Fortran module.  */
7913
7914 static void
7915 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7916                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7917 {
7918   /* Add a symbol for the namespace.  */
7919
7920   add_partial_symbol (pdi, cu);
7921
7922   /* Now scan partial symbols in that module.  */
7923
7924   if (pdi->has_children)
7925     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7926 }
7927
7928 /* Read a partial die corresponding to a subprogram and create a partial
7929    symbol for that subprogram.  When the CU language allows it, this
7930    routine also defines a partial symbol for each nested subprogram
7931    that this subprogram contains.  If SET_ADDRMAP is true, record the
7932    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7933    and highest PC values found in PDI.
7934
7935    PDI may also be a lexical block, in which case we simply search
7936    recursively for subprograms defined inside that lexical block.
7937    Again, this is only performed when the CU language allows this
7938    type of definitions.  */
7939
7940 static void
7941 add_partial_subprogram (struct partial_die_info *pdi,
7942                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7943                         int set_addrmap, struct dwarf2_cu *cu)
7944 {
7945   if (pdi->tag == DW_TAG_subprogram)
7946     {
7947       if (pdi->has_pc_info)
7948         {
7949           if (pdi->lowpc < *lowpc)
7950             *lowpc = pdi->lowpc;
7951           if (pdi->highpc > *highpc)
7952             *highpc = pdi->highpc;
7953           if (set_addrmap)
7954             {
7955               struct objfile *objfile = cu->objfile;
7956               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7957               CORE_ADDR baseaddr;
7958               CORE_ADDR highpc;
7959               CORE_ADDR lowpc;
7960
7961               baseaddr = ANOFFSET (objfile->section_offsets,
7962                                    SECT_OFF_TEXT (objfile));
7963               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7964                                                   pdi->lowpc + baseaddr);
7965               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7966                                                    pdi->highpc + baseaddr);
7967               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7968                                  cu->per_cu->v.psymtab);
7969             }
7970         }
7971
7972       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7973         {
7974           if (!pdi->is_declaration)
7975             /* Ignore subprogram DIEs that do not have a name, they are
7976                illegal.  Do not emit a complaint at this point, we will
7977                do so when we convert this psymtab into a symtab.  */
7978             if (pdi->name)
7979               add_partial_symbol (pdi, cu);
7980         }
7981     }
7982
7983   if (! pdi->has_children)
7984     return;
7985
7986   if (cu->language == language_ada)
7987     {
7988       pdi = pdi->die_child;
7989       while (pdi != NULL)
7990         {
7991           fixup_partial_die (pdi, cu);
7992           if (pdi->tag == DW_TAG_subprogram
7993               || pdi->tag == DW_TAG_lexical_block)
7994             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7995           pdi = pdi->die_sibling;
7996         }
7997     }
7998 }
7999
8000 /* Read a partial die corresponding to an enumeration type.  */
8001
8002 static void
8003 add_partial_enumeration (struct partial_die_info *enum_pdi,
8004                          struct dwarf2_cu *cu)
8005 {
8006   struct partial_die_info *pdi;
8007
8008   if (enum_pdi->name != NULL)
8009     add_partial_symbol (enum_pdi, cu);
8010
8011   pdi = enum_pdi->die_child;
8012   while (pdi)
8013     {
8014       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
8015         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
8016       else
8017         add_partial_symbol (pdi, cu);
8018       pdi = pdi->die_sibling;
8019     }
8020 }
8021
8022 /* Return the initial uleb128 in the die at INFO_PTR.  */
8023
8024 static unsigned int
8025 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8026 {
8027   unsigned int bytes_read;
8028
8029   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8030 }
8031
8032 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
8033    Return the corresponding abbrev, or NULL if the number is zero (indicating
8034    an empty DIE).  In either case *BYTES_READ will be set to the length of
8035    the initial number.  */
8036
8037 static struct abbrev_info *
8038 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
8039                  struct dwarf2_cu *cu)
8040 {
8041   bfd *abfd = cu->objfile->obfd;
8042   unsigned int abbrev_number;
8043   struct abbrev_info *abbrev;
8044
8045   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8046
8047   if (abbrev_number == 0)
8048     return NULL;
8049
8050   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
8051   if (!abbrev)
8052     {
8053       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8054                " at offset 0x%x [in module %s]"),
8055              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8056              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
8057     }
8058
8059   return abbrev;
8060 }
8061
8062 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8063    Returns a pointer to the end of a series of DIEs, terminated by an empty
8064    DIE.  Any children of the skipped DIEs will also be skipped.  */
8065
8066 static const gdb_byte *
8067 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8068 {
8069   struct dwarf2_cu *cu = reader->cu;
8070   struct abbrev_info *abbrev;
8071   unsigned int bytes_read;
8072
8073   while (1)
8074     {
8075       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
8076       if (abbrev == NULL)
8077         return info_ptr + bytes_read;
8078       else
8079         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8080     }
8081 }
8082
8083 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8084    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8085    abbrev corresponding to that skipped uleb128 should be passed in
8086    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8087    children.  */
8088
8089 static const gdb_byte *
8090 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8091               struct abbrev_info *abbrev)
8092 {
8093   unsigned int bytes_read;
8094   struct attribute attr;
8095   bfd *abfd = reader->abfd;
8096   struct dwarf2_cu *cu = reader->cu;
8097   const gdb_byte *buffer = reader->buffer;
8098   const gdb_byte *buffer_end = reader->buffer_end;
8099   unsigned int form, i;
8100
8101   for (i = 0; i < abbrev->num_attrs; i++)
8102     {
8103       /* The only abbrev we care about is DW_AT_sibling.  */
8104       if (abbrev->attrs[i].name == DW_AT_sibling)
8105         {
8106           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
8107           if (attr.form == DW_FORM_ref_addr)
8108             complaint (&symfile_complaints,
8109                        _("ignoring absolute DW_AT_sibling"));
8110           else
8111             {
8112               sect_offset off = dwarf2_get_ref_die_offset (&attr);
8113               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8114
8115               if (sibling_ptr < info_ptr)
8116                 complaint (&symfile_complaints,
8117                            _("DW_AT_sibling points backwards"));
8118               else if (sibling_ptr > reader->buffer_end)
8119                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
8120               else
8121                 return sibling_ptr;
8122             }
8123         }
8124
8125       /* If it isn't DW_AT_sibling, skip this attribute.  */
8126       form = abbrev->attrs[i].form;
8127     skip_attribute:
8128       switch (form)
8129         {
8130         case DW_FORM_ref_addr:
8131           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8132              and later it is offset sized.  */
8133           if (cu->header.version == 2)
8134             info_ptr += cu->header.addr_size;
8135           else
8136             info_ptr += cu->header.offset_size;
8137           break;
8138         case DW_FORM_GNU_ref_alt:
8139           info_ptr += cu->header.offset_size;
8140           break;
8141         case DW_FORM_addr:
8142           info_ptr += cu->header.addr_size;
8143           break;
8144         case DW_FORM_data1:
8145         case DW_FORM_ref1:
8146         case DW_FORM_flag:
8147           info_ptr += 1;
8148           break;
8149         case DW_FORM_flag_present:
8150         case DW_FORM_implicit_const:
8151           break;
8152         case DW_FORM_data2:
8153         case DW_FORM_ref2:
8154           info_ptr += 2;
8155           break;
8156         case DW_FORM_data4:
8157         case DW_FORM_ref4:
8158           info_ptr += 4;
8159           break;
8160         case DW_FORM_data8:
8161         case DW_FORM_ref8:
8162         case DW_FORM_ref_sig8:
8163           info_ptr += 8;
8164           break;
8165         case DW_FORM_data16:
8166           info_ptr += 16;
8167           break;
8168         case DW_FORM_string:
8169           read_direct_string (abfd, info_ptr, &bytes_read);
8170           info_ptr += bytes_read;
8171           break;
8172         case DW_FORM_sec_offset:
8173         case DW_FORM_strp:
8174         case DW_FORM_GNU_strp_alt:
8175           info_ptr += cu->header.offset_size;
8176           break;
8177         case DW_FORM_exprloc:
8178         case DW_FORM_block:
8179           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8180           info_ptr += bytes_read;
8181           break;
8182         case DW_FORM_block1:
8183           info_ptr += 1 + read_1_byte (abfd, info_ptr);
8184           break;
8185         case DW_FORM_block2:
8186           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8187           break;
8188         case DW_FORM_block4:
8189           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8190           break;
8191         case DW_FORM_sdata:
8192         case DW_FORM_udata:
8193         case DW_FORM_ref_udata:
8194         case DW_FORM_GNU_addr_index:
8195         case DW_FORM_GNU_str_index:
8196           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
8197           break;
8198         case DW_FORM_indirect:
8199           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8200           info_ptr += bytes_read;
8201           /* We need to continue parsing from here, so just go back to
8202              the top.  */
8203           goto skip_attribute;
8204
8205         default:
8206           error (_("Dwarf Error: Cannot handle %s "
8207                    "in DWARF reader [in module %s]"),
8208                  dwarf_form_name (form),
8209                  bfd_get_filename (abfd));
8210         }
8211     }
8212
8213   if (abbrev->has_children)
8214     return skip_children (reader, info_ptr);
8215   else
8216     return info_ptr;
8217 }
8218
8219 /* Locate ORIG_PDI's sibling.
8220    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
8221
8222 static const gdb_byte *
8223 locate_pdi_sibling (const struct die_reader_specs *reader,
8224                     struct partial_die_info *orig_pdi,
8225                     const gdb_byte *info_ptr)
8226 {
8227   /* Do we know the sibling already?  */
8228
8229   if (orig_pdi->sibling)
8230     return orig_pdi->sibling;
8231
8232   /* Are there any children to deal with?  */
8233
8234   if (!orig_pdi->has_children)
8235     return info_ptr;
8236
8237   /* Skip the children the long way.  */
8238
8239   return skip_children (reader, info_ptr);
8240 }
8241
8242 /* Expand this partial symbol table into a full symbol table.  SELF is
8243    not NULL.  */
8244
8245 static void
8246 dwarf2_read_symtab (struct partial_symtab *self,
8247                     struct objfile *objfile)
8248 {
8249   if (self->readin)
8250     {
8251       warning (_("bug: psymtab for %s is already read in."),
8252                self->filename);
8253     }
8254   else
8255     {
8256       if (info_verbose)
8257         {
8258           printf_filtered (_("Reading in symbols for %s..."),
8259                            self->filename);
8260           gdb_flush (gdb_stdout);
8261         }
8262
8263       /* Restore our global data.  */
8264       dwarf2_per_objfile
8265         = (struct dwarf2_per_objfile *) objfile_data (objfile,
8266                                                       dwarf2_objfile_data_key);
8267
8268       /* If this psymtab is constructed from a debug-only objfile, the
8269          has_section_at_zero flag will not necessarily be correct.  We
8270          can get the correct value for this flag by looking at the data
8271          associated with the (presumably stripped) associated objfile.  */
8272       if (objfile->separate_debug_objfile_backlink)
8273         {
8274           struct dwarf2_per_objfile *dpo_backlink
8275             = ((struct dwarf2_per_objfile *)
8276                objfile_data (objfile->separate_debug_objfile_backlink,
8277                              dwarf2_objfile_data_key));
8278
8279           dwarf2_per_objfile->has_section_at_zero
8280             = dpo_backlink->has_section_at_zero;
8281         }
8282
8283       dwarf2_per_objfile->reading_partial_symbols = 0;
8284
8285       psymtab_to_symtab_1 (self);
8286
8287       /* Finish up the debug error message.  */
8288       if (info_verbose)
8289         printf_filtered (_("done.\n"));
8290     }
8291
8292   process_cu_includes ();
8293 }
8294 \f
8295 /* Reading in full CUs.  */
8296
8297 /* Add PER_CU to the queue.  */
8298
8299 static void
8300 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
8301                  enum language pretend_language)
8302 {
8303   struct dwarf2_queue_item *item;
8304
8305   per_cu->queued = 1;
8306   item = XNEW (struct dwarf2_queue_item);
8307   item->per_cu = per_cu;
8308   item->pretend_language = pretend_language;
8309   item->next = NULL;
8310
8311   if (dwarf2_queue == NULL)
8312     dwarf2_queue = item;
8313   else
8314     dwarf2_queue_tail->next = item;
8315
8316   dwarf2_queue_tail = item;
8317 }
8318
8319 /* If PER_CU is not yet queued, add it to the queue.
8320    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8321    dependency.
8322    The result is non-zero if PER_CU was queued, otherwise the result is zero
8323    meaning either PER_CU is already queued or it is already loaded.
8324
8325    N.B. There is an invariant here that if a CU is queued then it is loaded.
8326    The caller is required to load PER_CU if we return non-zero.  */
8327
8328 static int
8329 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8330                        struct dwarf2_per_cu_data *per_cu,
8331                        enum language pretend_language)
8332 {
8333   /* We may arrive here during partial symbol reading, if we need full
8334      DIEs to process an unusual case (e.g. template arguments).  Do
8335      not queue PER_CU, just tell our caller to load its DIEs.  */
8336   if (dwarf2_per_objfile->reading_partial_symbols)
8337     {
8338       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
8339         return 1;
8340       return 0;
8341     }
8342
8343   /* Mark the dependence relation so that we don't flush PER_CU
8344      too early.  */
8345   if (dependent_cu != NULL)
8346     dwarf2_add_dependence (dependent_cu, per_cu);
8347
8348   /* If it's already on the queue, we have nothing to do.  */
8349   if (per_cu->queued)
8350     return 0;
8351
8352   /* If the compilation unit is already loaded, just mark it as
8353      used.  */
8354   if (per_cu->cu != NULL)
8355     {
8356       per_cu->cu->last_used = 0;
8357       return 0;
8358     }
8359
8360   /* Add it to the queue.  */
8361   queue_comp_unit (per_cu, pretend_language);
8362
8363   return 1;
8364 }
8365
8366 /* Process the queue.  */
8367
8368 static void
8369 process_queue (void)
8370 {
8371   struct dwarf2_queue_item *item, *next_item;
8372
8373   if (dwarf_read_debug)
8374     {
8375       fprintf_unfiltered (gdb_stdlog,
8376                           "Expanding one or more symtabs of objfile %s ...\n",
8377                           objfile_name (dwarf2_per_objfile->objfile));
8378     }
8379
8380   /* The queue starts out with one item, but following a DIE reference
8381      may load a new CU, adding it to the end of the queue.  */
8382   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
8383     {
8384       if ((dwarf2_per_objfile->using_index
8385            ? !item->per_cu->v.quick->compunit_symtab
8386            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
8387           /* Skip dummy CUs.  */
8388           && item->per_cu->cu != NULL)
8389         {
8390           struct dwarf2_per_cu_data *per_cu = item->per_cu;
8391           unsigned int debug_print_threshold;
8392           char buf[100];
8393
8394           if (per_cu->is_debug_types)
8395             {
8396               struct signatured_type *sig_type =
8397                 (struct signatured_type *) per_cu;
8398
8399               sprintf (buf, "TU %s at offset 0x%x",
8400                        hex_string (sig_type->signature),
8401                        to_underlying (per_cu->sect_off));
8402               /* There can be 100s of TUs.
8403                  Only print them in verbose mode.  */
8404               debug_print_threshold = 2;
8405             }
8406           else
8407             {
8408               sprintf (buf, "CU at offset 0x%x",
8409                        to_underlying (per_cu->sect_off));
8410               debug_print_threshold = 1;
8411             }
8412
8413           if (dwarf_read_debug >= debug_print_threshold)
8414             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
8415
8416           if (per_cu->is_debug_types)
8417             process_full_type_unit (per_cu, item->pretend_language);
8418           else
8419             process_full_comp_unit (per_cu, item->pretend_language);
8420
8421           if (dwarf_read_debug >= debug_print_threshold)
8422             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
8423         }
8424
8425       item->per_cu->queued = 0;
8426       next_item = item->next;
8427       xfree (item);
8428     }
8429
8430   dwarf2_queue_tail = NULL;
8431
8432   if (dwarf_read_debug)
8433     {
8434       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
8435                           objfile_name (dwarf2_per_objfile->objfile));
8436     }
8437 }
8438
8439 /* Free all allocated queue entries.  This function only releases anything if
8440    an error was thrown; if the queue was processed then it would have been
8441    freed as we went along.  */
8442
8443 static void
8444 dwarf2_release_queue (void *dummy)
8445 {
8446   struct dwarf2_queue_item *item, *last;
8447
8448   item = dwarf2_queue;
8449   while (item)
8450     {
8451       /* Anything still marked queued is likely to be in an
8452          inconsistent state, so discard it.  */
8453       if (item->per_cu->queued)
8454         {
8455           if (item->per_cu->cu != NULL)
8456             free_one_cached_comp_unit (item->per_cu);
8457           item->per_cu->queued = 0;
8458         }
8459
8460       last = item;
8461       item = item->next;
8462       xfree (last);
8463     }
8464
8465   dwarf2_queue = dwarf2_queue_tail = NULL;
8466 }
8467
8468 /* Read in full symbols for PST, and anything it depends on.  */
8469
8470 static void
8471 psymtab_to_symtab_1 (struct partial_symtab *pst)
8472 {
8473   struct dwarf2_per_cu_data *per_cu;
8474   int i;
8475
8476   if (pst->readin)
8477     return;
8478
8479   for (i = 0; i < pst->number_of_dependencies; i++)
8480     if (!pst->dependencies[i]->readin
8481         && pst->dependencies[i]->user == NULL)
8482       {
8483         /* Inform about additional files that need to be read in.  */
8484         if (info_verbose)
8485           {
8486             /* FIXME: i18n: Need to make this a single string.  */
8487             fputs_filtered (" ", gdb_stdout);
8488             wrap_here ("");
8489             fputs_filtered ("and ", gdb_stdout);
8490             wrap_here ("");
8491             printf_filtered ("%s...", pst->dependencies[i]->filename);
8492             wrap_here ("");     /* Flush output.  */
8493             gdb_flush (gdb_stdout);
8494           }
8495         psymtab_to_symtab_1 (pst->dependencies[i]);
8496       }
8497
8498   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
8499
8500   if (per_cu == NULL)
8501     {
8502       /* It's an include file, no symbols to read for it.
8503          Everything is in the parent symtab.  */
8504       pst->readin = 1;
8505       return;
8506     }
8507
8508   dw2_do_instantiate_symtab (per_cu);
8509 }
8510
8511 /* Trivial hash function for die_info: the hash value of a DIE
8512    is its offset in .debug_info for this objfile.  */
8513
8514 static hashval_t
8515 die_hash (const void *item)
8516 {
8517   const struct die_info *die = (const struct die_info *) item;
8518
8519   return to_underlying (die->sect_off);
8520 }
8521
8522 /* Trivial comparison function for die_info structures: two DIEs
8523    are equal if they have the same offset.  */
8524
8525 static int
8526 die_eq (const void *item_lhs, const void *item_rhs)
8527 {
8528   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8529   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8530
8531   return die_lhs->sect_off == die_rhs->sect_off;
8532 }
8533
8534 /* die_reader_func for load_full_comp_unit.
8535    This is identical to read_signatured_type_reader,
8536    but is kept separate for now.  */
8537
8538 static void
8539 load_full_comp_unit_reader (const struct die_reader_specs *reader,
8540                             const gdb_byte *info_ptr,
8541                             struct die_info *comp_unit_die,
8542                             int has_children,
8543                             void *data)
8544 {
8545   struct dwarf2_cu *cu = reader->cu;
8546   enum language *language_ptr = (enum language *) data;
8547
8548   gdb_assert (cu->die_hash == NULL);
8549   cu->die_hash =
8550     htab_create_alloc_ex (cu->header.length / 12,
8551                           die_hash,
8552                           die_eq,
8553                           NULL,
8554                           &cu->comp_unit_obstack,
8555                           hashtab_obstack_allocate,
8556                           dummy_obstack_deallocate);
8557
8558   if (has_children)
8559     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
8560                                                   &info_ptr, comp_unit_die);
8561   cu->dies = comp_unit_die;
8562   /* comp_unit_die is not stored in die_hash, no need.  */
8563
8564   /* We try not to read any attributes in this function, because not
8565      all CUs needed for references have been loaded yet, and symbol
8566      table processing isn't initialized.  But we have to set the CU language,
8567      or we won't be able to build types correctly.
8568      Similarly, if we do not read the producer, we can not apply
8569      producer-specific interpretation.  */
8570   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8571 }
8572
8573 /* Load the DIEs associated with PER_CU into memory.  */
8574
8575 static void
8576 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8577                      enum language pretend_language)
8578 {
8579   gdb_assert (! this_cu->is_debug_types);
8580
8581   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8582                            load_full_comp_unit_reader, &pretend_language);
8583 }
8584
8585 /* Add a DIE to the delayed physname list.  */
8586
8587 static void
8588 add_to_method_list (struct type *type, int fnfield_index, int index,
8589                     const char *name, struct die_info *die,
8590                     struct dwarf2_cu *cu)
8591 {
8592   struct delayed_method_info mi;
8593   mi.type = type;
8594   mi.fnfield_index = fnfield_index;
8595   mi.index = index;
8596   mi.name = name;
8597   mi.die = die;
8598   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8599 }
8600
8601 /* A cleanup for freeing the delayed method list.  */
8602
8603 static void
8604 free_delayed_list (void *ptr)
8605 {
8606   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8607   if (cu->method_list != NULL)
8608     {
8609       VEC_free (delayed_method_info, cu->method_list);
8610       cu->method_list = NULL;
8611     }
8612 }
8613
8614 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8615    "const" / "volatile".  If so, decrements LEN by the length of the
8616    modifier and return true.  Otherwise return false.  */
8617
8618 template<size_t N>
8619 static bool
8620 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8621 {
8622   size_t mod_len = sizeof (mod) - 1;
8623   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8624     {
8625       len -= mod_len;
8626       return true;
8627     }
8628   return false;
8629 }
8630
8631 /* Compute the physnames of any methods on the CU's method list.
8632
8633    The computation of method physnames is delayed in order to avoid the
8634    (bad) condition that one of the method's formal parameters is of an as yet
8635    incomplete type.  */
8636
8637 static void
8638 compute_delayed_physnames (struct dwarf2_cu *cu)
8639 {
8640   int i;
8641   struct delayed_method_info *mi;
8642
8643   /* Only C++ delays computing physnames.  */
8644   if (VEC_empty (delayed_method_info, cu->method_list))
8645     return;
8646   gdb_assert (cu->language == language_cplus);
8647
8648   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8649     {
8650       const char *physname;
8651       struct fn_fieldlist *fn_flp
8652         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8653       physname = dwarf2_physname (mi->name, mi->die, cu);
8654       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8655         = physname ? physname : "";
8656
8657       /* Since there's no tag to indicate whether a method is a
8658          const/volatile overload, extract that information out of the
8659          demangled name.  */
8660       if (physname != NULL)
8661         {
8662           size_t len = strlen (physname);
8663
8664           while (1)
8665             {
8666               if (physname[len] == ')') /* shortcut */
8667                 break;
8668               else if (check_modifier (physname, len, " const"))
8669                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8670               else if (check_modifier (physname, len, " volatile"))
8671                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8672               else
8673                 break;
8674             }
8675         }
8676     }
8677 }
8678
8679 /* Go objects should be embedded in a DW_TAG_module DIE,
8680    and it's not clear if/how imported objects will appear.
8681    To keep Go support simple until that's worked out,
8682    go back through what we've read and create something usable.
8683    We could do this while processing each DIE, and feels kinda cleaner,
8684    but that way is more invasive.
8685    This is to, for example, allow the user to type "p var" or "b main"
8686    without having to specify the package name, and allow lookups
8687    of module.object to work in contexts that use the expression
8688    parser.  */
8689
8690 static void
8691 fixup_go_packaging (struct dwarf2_cu *cu)
8692 {
8693   char *package_name = NULL;
8694   struct pending *list;
8695   int i;
8696
8697   for (list = global_symbols; list != NULL; list = list->next)
8698     {
8699       for (i = 0; i < list->nsyms; ++i)
8700         {
8701           struct symbol *sym = list->symbol[i];
8702
8703           if (SYMBOL_LANGUAGE (sym) == language_go
8704               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8705             {
8706               char *this_package_name = go_symbol_package_name (sym);
8707
8708               if (this_package_name == NULL)
8709                 continue;
8710               if (package_name == NULL)
8711                 package_name = this_package_name;
8712               else
8713                 {
8714                   if (strcmp (package_name, this_package_name) != 0)
8715                     complaint (&symfile_complaints,
8716                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8717                                (symbol_symtab (sym) != NULL
8718                                 ? symtab_to_filename_for_display
8719                                     (symbol_symtab (sym))
8720                                 : objfile_name (cu->objfile)),
8721                                this_package_name, package_name);
8722                   xfree (this_package_name);
8723                 }
8724             }
8725         }
8726     }
8727
8728   if (package_name != NULL)
8729     {
8730       struct objfile *objfile = cu->objfile;
8731       const char *saved_package_name
8732         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8733                                         package_name,
8734                                         strlen (package_name));
8735       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8736                                      saved_package_name);
8737       struct symbol *sym;
8738
8739       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8740
8741       sym = allocate_symbol (objfile);
8742       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8743       SYMBOL_SET_NAMES (sym, saved_package_name,
8744                         strlen (saved_package_name), 0, objfile);
8745       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8746          e.g., "main" finds the "main" module and not C's main().  */
8747       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8748       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8749       SYMBOL_TYPE (sym) = type;
8750
8751       add_symbol_to_list (sym, &global_symbols);
8752
8753       xfree (package_name);
8754     }
8755 }
8756
8757 /* Return the symtab for PER_CU.  This works properly regardless of
8758    whether we're using the index or psymtabs.  */
8759
8760 static struct compunit_symtab *
8761 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8762 {
8763   return (dwarf2_per_objfile->using_index
8764           ? per_cu->v.quick->compunit_symtab
8765           : per_cu->v.psymtab->compunit_symtab);
8766 }
8767
8768 /* A helper function for computing the list of all symbol tables
8769    included by PER_CU.  */
8770
8771 static void
8772 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8773                                 htab_t all_children, htab_t all_type_symtabs,
8774                                 struct dwarf2_per_cu_data *per_cu,
8775                                 struct compunit_symtab *immediate_parent)
8776 {
8777   void **slot;
8778   int ix;
8779   struct compunit_symtab *cust;
8780   struct dwarf2_per_cu_data *iter;
8781
8782   slot = htab_find_slot (all_children, per_cu, INSERT);
8783   if (*slot != NULL)
8784     {
8785       /* This inclusion and its children have been processed.  */
8786       return;
8787     }
8788
8789   *slot = per_cu;
8790   /* Only add a CU if it has a symbol table.  */
8791   cust = get_compunit_symtab (per_cu);
8792   if (cust != NULL)
8793     {
8794       /* If this is a type unit only add its symbol table if we haven't
8795          seen it yet (type unit per_cu's can share symtabs).  */
8796       if (per_cu->is_debug_types)
8797         {
8798           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8799           if (*slot == NULL)
8800             {
8801               *slot = cust;
8802               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8803               if (cust->user == NULL)
8804                 cust->user = immediate_parent;
8805             }
8806         }
8807       else
8808         {
8809           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8810           if (cust->user == NULL)
8811             cust->user = immediate_parent;
8812         }
8813     }
8814
8815   for (ix = 0;
8816        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8817        ++ix)
8818     {
8819       recursively_compute_inclusions (result, all_children,
8820                                       all_type_symtabs, iter, cust);
8821     }
8822 }
8823
8824 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8825    PER_CU.  */
8826
8827 static void
8828 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8829 {
8830   gdb_assert (! per_cu->is_debug_types);
8831
8832   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8833     {
8834       int ix, len;
8835       struct dwarf2_per_cu_data *per_cu_iter;
8836       struct compunit_symtab *compunit_symtab_iter;
8837       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8838       htab_t all_children, all_type_symtabs;
8839       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8840
8841       /* If we don't have a symtab, we can just skip this case.  */
8842       if (cust == NULL)
8843         return;
8844
8845       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8846                                         NULL, xcalloc, xfree);
8847       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8848                                             NULL, xcalloc, xfree);
8849
8850       for (ix = 0;
8851            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8852                         ix, per_cu_iter);
8853            ++ix)
8854         {
8855           recursively_compute_inclusions (&result_symtabs, all_children,
8856                                           all_type_symtabs, per_cu_iter,
8857                                           cust);
8858         }
8859
8860       /* Now we have a transitive closure of all the included symtabs.  */
8861       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8862       cust->includes
8863         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8864                      struct compunit_symtab *, len + 1);
8865       for (ix = 0;
8866            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8867                         compunit_symtab_iter);
8868            ++ix)
8869         cust->includes[ix] = compunit_symtab_iter;
8870       cust->includes[len] = NULL;
8871
8872       VEC_free (compunit_symtab_ptr, result_symtabs);
8873       htab_delete (all_children);
8874       htab_delete (all_type_symtabs);
8875     }
8876 }
8877
8878 /* Compute the 'includes' field for the symtabs of all the CUs we just
8879    read.  */
8880
8881 static void
8882 process_cu_includes (void)
8883 {
8884   int ix;
8885   struct dwarf2_per_cu_data *iter;
8886
8887   for (ix = 0;
8888        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8889                     ix, iter);
8890        ++ix)
8891     {
8892       if (! iter->is_debug_types)
8893         compute_compunit_symtab_includes (iter);
8894     }
8895
8896   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8897 }
8898
8899 /* Generate full symbol information for PER_CU, whose DIEs have
8900    already been loaded into memory.  */
8901
8902 static void
8903 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8904                         enum language pretend_language)
8905 {
8906   struct dwarf2_cu *cu = per_cu->cu;
8907   struct objfile *objfile = per_cu->objfile;
8908   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8909   CORE_ADDR lowpc, highpc;
8910   struct compunit_symtab *cust;
8911   struct cleanup *delayed_list_cleanup;
8912   CORE_ADDR baseaddr;
8913   struct block *static_block;
8914   CORE_ADDR addr;
8915
8916   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8917
8918   buildsym_init ();
8919   scoped_free_pendings free_pending;
8920   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8921
8922   cu->list_in_scope = &file_symbols;
8923
8924   cu->language = pretend_language;
8925   cu->language_defn = language_def (cu->language);
8926
8927   /* Do line number decoding in read_file_scope () */
8928   process_die (cu->dies, cu);
8929
8930   /* For now fudge the Go package.  */
8931   if (cu->language == language_go)
8932     fixup_go_packaging (cu);
8933
8934   /* Now that we have processed all the DIEs in the CU, all the types 
8935      should be complete, and it should now be safe to compute all of the
8936      physnames.  */
8937   compute_delayed_physnames (cu);
8938   do_cleanups (delayed_list_cleanup);
8939
8940   /* Some compilers don't define a DW_AT_high_pc attribute for the
8941      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8942      it, by scanning the DIE's below the compilation unit.  */
8943   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8944
8945   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8946   static_block = end_symtab_get_static_block (addr, 0, 1);
8947
8948   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8949      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8950      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8951      addrmap to help ensure it has an accurate map of pc values belonging to
8952      this comp unit.  */
8953   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8954
8955   cust = end_symtab_from_static_block (static_block,
8956                                        SECT_OFF_TEXT (objfile), 0);
8957
8958   if (cust != NULL)
8959     {
8960       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8961
8962       /* Set symtab language to language from DW_AT_language.  If the
8963          compilation is from a C file generated by language preprocessors, do
8964          not set the language if it was already deduced by start_subfile.  */
8965       if (!(cu->language == language_c
8966             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8967         COMPUNIT_FILETABS (cust)->language = cu->language;
8968
8969       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8970          produce DW_AT_location with location lists but it can be possibly
8971          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8972          there were bugs in prologue debug info, fixed later in GCC-4.5
8973          by "unwind info for epilogues" patch (which is not directly related).
8974
8975          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8976          needed, it would be wrong due to missing DW_AT_producer there.
8977
8978          Still one can confuse GDB by using non-standard GCC compilation
8979          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8980          */ 
8981       if (cu->has_loclist && gcc_4_minor >= 5)
8982         cust->locations_valid = 1;
8983
8984       if (gcc_4_minor >= 5)
8985         cust->epilogue_unwind_valid = 1;
8986
8987       cust->call_site_htab = cu->call_site_htab;
8988     }
8989
8990   if (dwarf2_per_objfile->using_index)
8991     per_cu->v.quick->compunit_symtab = cust;
8992   else
8993     {
8994       struct partial_symtab *pst = per_cu->v.psymtab;
8995       pst->compunit_symtab = cust;
8996       pst->readin = 1;
8997     }
8998
8999   /* Push it for inclusion processing later.  */
9000   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
9001 }
9002
9003 /* Generate full symbol information for type unit PER_CU, whose DIEs have
9004    already been loaded into memory.  */
9005
9006 static void
9007 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
9008                         enum language pretend_language)
9009 {
9010   struct dwarf2_cu *cu = per_cu->cu;
9011   struct objfile *objfile = per_cu->objfile;
9012   struct compunit_symtab *cust;
9013   struct cleanup *delayed_list_cleanup;
9014   struct signatured_type *sig_type;
9015
9016   gdb_assert (per_cu->is_debug_types);
9017   sig_type = (struct signatured_type *) per_cu;
9018
9019   buildsym_init ();
9020   scoped_free_pendings free_pending;
9021   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
9022
9023   cu->list_in_scope = &file_symbols;
9024
9025   cu->language = pretend_language;
9026   cu->language_defn = language_def (cu->language);
9027
9028   /* The symbol tables are set up in read_type_unit_scope.  */
9029   process_die (cu->dies, cu);
9030
9031   /* For now fudge the Go package.  */
9032   if (cu->language == language_go)
9033     fixup_go_packaging (cu);
9034
9035   /* Now that we have processed all the DIEs in the CU, all the types 
9036      should be complete, and it should now be safe to compute all of the
9037      physnames.  */
9038   compute_delayed_physnames (cu);
9039   do_cleanups (delayed_list_cleanup);
9040
9041   /* TUs share symbol tables.
9042      If this is the first TU to use this symtab, complete the construction
9043      of it with end_expandable_symtab.  Otherwise, complete the addition of
9044      this TU's symbols to the existing symtab.  */
9045   if (sig_type->type_unit_group->compunit_symtab == NULL)
9046     {
9047       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
9048       sig_type->type_unit_group->compunit_symtab = cust;
9049
9050       if (cust != NULL)
9051         {
9052           /* Set symtab language to language from DW_AT_language.  If the
9053              compilation is from a C file generated by language preprocessors,
9054              do not set the language if it was already deduced by
9055              start_subfile.  */
9056           if (!(cu->language == language_c
9057                 && COMPUNIT_FILETABS (cust)->language != language_c))
9058             COMPUNIT_FILETABS (cust)->language = cu->language;
9059         }
9060     }
9061   else
9062     {
9063       augment_type_symtab ();
9064       cust = sig_type->type_unit_group->compunit_symtab;
9065     }
9066
9067   if (dwarf2_per_objfile->using_index)
9068     per_cu->v.quick->compunit_symtab = cust;
9069   else
9070     {
9071       struct partial_symtab *pst = per_cu->v.psymtab;
9072       pst->compunit_symtab = cust;
9073       pst->readin = 1;
9074     }
9075 }
9076
9077 /* Process an imported unit DIE.  */
9078
9079 static void
9080 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
9081 {
9082   struct attribute *attr;
9083
9084   /* For now we don't handle imported units in type units.  */
9085   if (cu->per_cu->is_debug_types)
9086     {
9087       error (_("Dwarf Error: DW_TAG_imported_unit is not"
9088                " supported in type units [in module %s]"),
9089              objfile_name (cu->objfile));
9090     }
9091
9092   attr = dwarf2_attr (die, DW_AT_import, cu);
9093   if (attr != NULL)
9094     {
9095       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9096       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
9097       dwarf2_per_cu_data *per_cu
9098         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
9099
9100       /* If necessary, add it to the queue and load its DIEs.  */
9101       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
9102         load_full_comp_unit (per_cu, cu->language);
9103
9104       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
9105                      per_cu);
9106     }
9107 }
9108
9109 /* RAII object that represents a process_die scope: i.e.,
9110    starts/finishes processing a DIE.  */
9111 class process_die_scope
9112 {
9113 public:
9114   process_die_scope (die_info *die, dwarf2_cu *cu)
9115     : m_die (die), m_cu (cu)
9116   {
9117     /* We should only be processing DIEs not already in process.  */
9118     gdb_assert (!m_die->in_process);
9119     m_die->in_process = true;
9120   }
9121
9122   ~process_die_scope ()
9123   {
9124     m_die->in_process = false;
9125
9126     /* If we're done processing the DIE for the CU that owns the line
9127        header, we don't need the line header anymore.  */
9128     if (m_cu->line_header_die_owner == m_die)
9129       {
9130         delete m_cu->line_header;
9131         m_cu->line_header = NULL;
9132         m_cu->line_header_die_owner = NULL;
9133       }
9134   }
9135
9136 private:
9137   die_info *m_die;
9138   dwarf2_cu *m_cu;
9139 };
9140
9141 /* Process a die and its children.  */
9142
9143 static void
9144 process_die (struct die_info *die, struct dwarf2_cu *cu)
9145 {
9146   process_die_scope scope (die, cu);
9147
9148   switch (die->tag)
9149     {
9150     case DW_TAG_padding:
9151       break;
9152     case DW_TAG_compile_unit:
9153     case DW_TAG_partial_unit:
9154       read_file_scope (die, cu);
9155       break;
9156     case DW_TAG_type_unit:
9157       read_type_unit_scope (die, cu);
9158       break;
9159     case DW_TAG_subprogram:
9160     case DW_TAG_inlined_subroutine:
9161       read_func_scope (die, cu);
9162       break;
9163     case DW_TAG_lexical_block:
9164     case DW_TAG_try_block:
9165     case DW_TAG_catch_block:
9166       read_lexical_block_scope (die, cu);
9167       break;
9168     case DW_TAG_call_site:
9169     case DW_TAG_GNU_call_site:
9170       read_call_site_scope (die, cu);
9171       break;
9172     case DW_TAG_class_type:
9173     case DW_TAG_interface_type:
9174     case DW_TAG_structure_type:
9175     case DW_TAG_union_type:
9176       process_structure_scope (die, cu);
9177       break;
9178     case DW_TAG_enumeration_type:
9179       process_enumeration_scope (die, cu);
9180       break;
9181
9182     /* These dies have a type, but processing them does not create
9183        a symbol or recurse to process the children.  Therefore we can
9184        read them on-demand through read_type_die.  */
9185     case DW_TAG_subroutine_type:
9186     case DW_TAG_set_type:
9187     case DW_TAG_array_type:
9188     case DW_TAG_pointer_type:
9189     case DW_TAG_ptr_to_member_type:
9190     case DW_TAG_reference_type:
9191     case DW_TAG_rvalue_reference_type:
9192     case DW_TAG_string_type:
9193       break;
9194
9195     case DW_TAG_base_type:
9196     case DW_TAG_subrange_type:
9197     case DW_TAG_typedef:
9198       /* Add a typedef symbol for the type definition, if it has a
9199          DW_AT_name.  */
9200       new_symbol (die, read_type_die (die, cu), cu);
9201       break;
9202     case DW_TAG_common_block:
9203       read_common_block (die, cu);
9204       break;
9205     case DW_TAG_common_inclusion:
9206       break;
9207     case DW_TAG_namespace:
9208       cu->processing_has_namespace_info = 1;
9209       read_namespace (die, cu);
9210       break;
9211     case DW_TAG_module:
9212       cu->processing_has_namespace_info = 1;
9213       read_module (die, cu);
9214       break;
9215     case DW_TAG_imported_declaration:
9216       cu->processing_has_namespace_info = 1;
9217       if (read_namespace_alias (die, cu))
9218         break;
9219       /* The declaration is not a global namespace alias: fall through.  */
9220     case DW_TAG_imported_module:
9221       cu->processing_has_namespace_info = 1;
9222       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
9223                                  || cu->language != language_fortran))
9224         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
9225                    dwarf_tag_name (die->tag));
9226       read_import_statement (die, cu);
9227       break;
9228
9229     case DW_TAG_imported_unit:
9230       process_imported_unit_die (die, cu);
9231       break;
9232
9233     default:
9234       new_symbol (die, NULL, cu);
9235       break;
9236     }
9237 }
9238 \f
9239 /* DWARF name computation.  */
9240
9241 /* A helper function for dwarf2_compute_name which determines whether DIE
9242    needs to have the name of the scope prepended to the name listed in the
9243    die.  */
9244
9245 static int
9246 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
9247 {
9248   struct attribute *attr;
9249
9250   switch (die->tag)
9251     {
9252     case DW_TAG_namespace:
9253     case DW_TAG_typedef:
9254     case DW_TAG_class_type:
9255     case DW_TAG_interface_type:
9256     case DW_TAG_structure_type:
9257     case DW_TAG_union_type:
9258     case DW_TAG_enumeration_type:
9259     case DW_TAG_enumerator:
9260     case DW_TAG_subprogram:
9261     case DW_TAG_inlined_subroutine:
9262     case DW_TAG_member:
9263     case DW_TAG_imported_declaration:
9264       return 1;
9265
9266     case DW_TAG_variable:
9267     case DW_TAG_constant:
9268       /* We only need to prefix "globally" visible variables.  These include
9269          any variable marked with DW_AT_external or any variable that
9270          lives in a namespace.  [Variables in anonymous namespaces
9271          require prefixing, but they are not DW_AT_external.]  */
9272
9273       if (dwarf2_attr (die, DW_AT_specification, cu))
9274         {
9275           struct dwarf2_cu *spec_cu = cu;
9276
9277           return die_needs_namespace (die_specification (die, &spec_cu),
9278                                       spec_cu);
9279         }
9280
9281       attr = dwarf2_attr (die, DW_AT_external, cu);
9282       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9283           && die->parent->tag != DW_TAG_module)
9284         return 0;
9285       /* A variable in a lexical block of some kind does not need a
9286          namespace, even though in C++ such variables may be external
9287          and have a mangled name.  */
9288       if (die->parent->tag ==  DW_TAG_lexical_block
9289           || die->parent->tag ==  DW_TAG_try_block
9290           || die->parent->tag ==  DW_TAG_catch_block
9291           || die->parent->tag == DW_TAG_subprogram)
9292         return 0;
9293       return 1;
9294
9295     default:
9296       return 0;
9297     }
9298 }
9299
9300 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9301    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9302    defined for the given DIE.  */
9303
9304 static struct attribute *
9305 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9306 {
9307   struct attribute *attr;
9308
9309   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9310   if (attr == NULL)
9311     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9312
9313   return attr;
9314 }
9315
9316 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9317    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9318    defined for the given DIE.  */
9319
9320 static const char *
9321 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9322 {
9323   const char *linkage_name;
9324
9325   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9326   if (linkage_name == NULL)
9327     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9328
9329   return linkage_name;
9330 }
9331
9332 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9333    compute the physname for the object, which include a method's:
9334    - formal parameters (C++),
9335    - receiver type (Go),
9336
9337    The term "physname" is a bit confusing.
9338    For C++, for example, it is the demangled name.
9339    For Go, for example, it's the mangled name.
9340
9341    For Ada, return the DIE's linkage name rather than the fully qualified
9342    name.  PHYSNAME is ignored..
9343
9344    The result is allocated on the objfile_obstack and canonicalized.  */
9345
9346 static const char *
9347 dwarf2_compute_name (const char *name,
9348                      struct die_info *die, struct dwarf2_cu *cu,
9349                      int physname)
9350 {
9351   struct objfile *objfile = cu->objfile;
9352
9353   if (name == NULL)
9354     name = dwarf2_name (die, cu);
9355
9356   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9357      but otherwise compute it by typename_concat inside GDB.
9358      FIXME: Actually this is not really true, or at least not always true.
9359      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
9360      Fortran names because there is no mangling standard.  So new_symbol_full
9361      will set the demangled name to the result of dwarf2_full_name, and it is
9362      the demangled name that GDB uses if it exists.  */
9363   if (cu->language == language_ada
9364       || (cu->language == language_fortran && physname))
9365     {
9366       /* For Ada unit, we prefer the linkage name over the name, as
9367          the former contains the exported name, which the user expects
9368          to be able to reference.  Ideally, we want the user to be able
9369          to reference this entity using either natural or linkage name,
9370          but we haven't started looking at this enhancement yet.  */
9371       const char *linkage_name = dw2_linkage_name (die, cu);
9372
9373       if (linkage_name != NULL)
9374         return linkage_name;
9375     }
9376
9377   /* These are the only languages we know how to qualify names in.  */
9378   if (name != NULL
9379       && (cu->language == language_cplus
9380           || cu->language == language_fortran || cu->language == language_d
9381           || cu->language == language_rust))
9382     {
9383       if (die_needs_namespace (die, cu))
9384         {
9385           long length;
9386           const char *prefix;
9387           const char *canonical_name = NULL;
9388
9389           string_file buf;
9390
9391           prefix = determine_prefix (die, cu);
9392           if (*prefix != '\0')
9393             {
9394               char *prefixed_name = typename_concat (NULL, prefix, name,
9395                                                      physname, cu);
9396
9397               buf.puts (prefixed_name);
9398               xfree (prefixed_name);
9399             }
9400           else
9401             buf.puts (name);
9402
9403           /* Template parameters may be specified in the DIE's DW_AT_name, or
9404              as children with DW_TAG_template_type_param or
9405              DW_TAG_value_type_param.  If the latter, add them to the name
9406              here.  If the name already has template parameters, then
9407              skip this step; some versions of GCC emit both, and
9408              it is more efficient to use the pre-computed name.
9409
9410              Something to keep in mind about this process: it is very
9411              unlikely, or in some cases downright impossible, to produce
9412              something that will match the mangled name of a function.
9413              If the definition of the function has the same debug info,
9414              we should be able to match up with it anyway.  But fallbacks
9415              using the minimal symbol, for instance to find a method
9416              implemented in a stripped copy of libstdc++, will not work.
9417              If we do not have debug info for the definition, we will have to
9418              match them up some other way.
9419
9420              When we do name matching there is a related problem with function
9421              templates; two instantiated function templates are allowed to
9422              differ only by their return types, which we do not add here.  */
9423
9424           if (cu->language == language_cplus && strchr (name, '<') == NULL)
9425             {
9426               struct attribute *attr;
9427               struct die_info *child;
9428               int first = 1;
9429
9430               die->building_fullname = 1;
9431
9432               for (child = die->child; child != NULL; child = child->sibling)
9433                 {
9434                   struct type *type;
9435                   LONGEST value;
9436                   const gdb_byte *bytes;
9437                   struct dwarf2_locexpr_baton *baton;
9438                   struct value *v;
9439
9440                   if (child->tag != DW_TAG_template_type_param
9441                       && child->tag != DW_TAG_template_value_param)
9442                     continue;
9443
9444                   if (first)
9445                     {
9446                       buf.puts ("<");
9447                       first = 0;
9448                     }
9449                   else
9450                     buf.puts (", ");
9451
9452                   attr = dwarf2_attr (child, DW_AT_type, cu);
9453                   if (attr == NULL)
9454                     {
9455                       complaint (&symfile_complaints,
9456                                  _("template parameter missing DW_AT_type"));
9457                       buf.puts ("UNKNOWN_TYPE");
9458                       continue;
9459                     }
9460                   type = die_type (child, cu);
9461
9462                   if (child->tag == DW_TAG_template_type_param)
9463                     {
9464                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
9465                       continue;
9466                     }
9467
9468                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
9469                   if (attr == NULL)
9470                     {
9471                       complaint (&symfile_complaints,
9472                                  _("template parameter missing "
9473                                    "DW_AT_const_value"));
9474                       buf.puts ("UNKNOWN_VALUE");
9475                       continue;
9476                     }
9477
9478                   dwarf2_const_value_attr (attr, type, name,
9479                                            &cu->comp_unit_obstack, cu,
9480                                            &value, &bytes, &baton);
9481
9482                   if (TYPE_NOSIGN (type))
9483                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
9484                        changed, this can use value_print instead.  */
9485                     c_printchar (value, type, &buf);
9486                   else
9487                     {
9488                       struct value_print_options opts;
9489
9490                       if (baton != NULL)
9491                         v = dwarf2_evaluate_loc_desc (type, NULL,
9492                                                       baton->data,
9493                                                       baton->size,
9494                                                       baton->per_cu);
9495                       else if (bytes != NULL)
9496                         {
9497                           v = allocate_value (type);
9498                           memcpy (value_contents_writeable (v), bytes,
9499                                   TYPE_LENGTH (type));
9500                         }
9501                       else
9502                         v = value_from_longest (type, value);
9503
9504                       /* Specify decimal so that we do not depend on
9505                          the radix.  */
9506                       get_formatted_print_options (&opts, 'd');
9507                       opts.raw = 1;
9508                       value_print (v, &buf, &opts);
9509                       release_value (v);
9510                       value_free (v);
9511                     }
9512                 }
9513
9514               die->building_fullname = 0;
9515
9516               if (!first)
9517                 {
9518                   /* Close the argument list, with a space if necessary
9519                      (nested templates).  */
9520                   if (!buf.empty () && buf.string ().back () == '>')
9521                     buf.puts (" >");
9522                   else
9523                     buf.puts (">");
9524                 }
9525             }
9526
9527           /* For C++ methods, append formal parameter type
9528              information, if PHYSNAME.  */
9529
9530           if (physname && die->tag == DW_TAG_subprogram
9531               && cu->language == language_cplus)
9532             {
9533               struct type *type = read_type_die (die, cu);
9534
9535               c_type_print_args (type, &buf, 1, cu->language,
9536                                  &type_print_raw_options);
9537
9538               if (cu->language == language_cplus)
9539                 {
9540                   /* Assume that an artificial first parameter is
9541                      "this", but do not crash if it is not.  RealView
9542                      marks unnamed (and thus unused) parameters as
9543                      artificial; there is no way to differentiate
9544                      the two cases.  */
9545                   if (TYPE_NFIELDS (type) > 0
9546                       && TYPE_FIELD_ARTIFICIAL (type, 0)
9547                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
9548                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
9549                                                                         0))))
9550                     buf.puts (" const");
9551                 }
9552             }
9553
9554           const std::string &intermediate_name = buf.string ();
9555
9556           if (cu->language == language_cplus)
9557             canonical_name
9558               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
9559                                           &objfile->per_bfd->storage_obstack);
9560
9561           /* If we only computed INTERMEDIATE_NAME, or if
9562              INTERMEDIATE_NAME is already canonical, then we need to
9563              copy it to the appropriate obstack.  */
9564           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9565             name = ((const char *)
9566                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
9567                                    intermediate_name.c_str (),
9568                                    intermediate_name.length ()));
9569           else
9570             name = canonical_name;
9571         }
9572     }
9573
9574   return name;
9575 }
9576
9577 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9578    If scope qualifiers are appropriate they will be added.  The result
9579    will be allocated on the storage_obstack, or NULL if the DIE does
9580    not have a name.  NAME may either be from a previous call to
9581    dwarf2_name or NULL.
9582
9583    The output string will be canonicalized (if C++).  */
9584
9585 static const char *
9586 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9587 {
9588   return dwarf2_compute_name (name, die, cu, 0);
9589 }
9590
9591 /* Construct a physname for the given DIE in CU.  NAME may either be
9592    from a previous call to dwarf2_name or NULL.  The result will be
9593    allocated on the objfile_objstack or NULL if the DIE does not have a
9594    name.
9595
9596    The output string will be canonicalized (if C++).  */
9597
9598 static const char *
9599 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9600 {
9601   struct objfile *objfile = cu->objfile;
9602   const char *retval, *mangled = NULL, *canon = NULL;
9603   int need_copy = 1;
9604
9605   /* In this case dwarf2_compute_name is just a shortcut not building anything
9606      on its own.  */
9607   if (!die_needs_namespace (die, cu))
9608     return dwarf2_compute_name (name, die, cu, 1);
9609
9610   mangled = dw2_linkage_name (die, cu);
9611
9612   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9613      See https://github.com/rust-lang/rust/issues/32925.  */
9614   if (cu->language == language_rust && mangled != NULL
9615       && strchr (mangled, '{') != NULL)
9616     mangled = NULL;
9617
9618   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9619      has computed.  */
9620   gdb::unique_xmalloc_ptr<char> demangled;
9621   if (mangled != NULL)
9622     {
9623       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9624          type.  It is easier for GDB users to search for such functions as
9625          `name(params)' than `long name(params)'.  In such case the minimal
9626          symbol names do not match the full symbol names but for template
9627          functions there is never a need to look up their definition from their
9628          declaration so the only disadvantage remains the minimal symbol
9629          variant `long name(params)' does not have the proper inferior type.
9630          */
9631
9632       if (cu->language == language_go)
9633         {
9634           /* This is a lie, but we already lie to the caller new_symbol_full.
9635              new_symbol_full assumes we return the mangled name.
9636              This just undoes that lie until things are cleaned up.  */
9637         }
9638       else
9639         {
9640           demangled.reset (gdb_demangle (mangled,
9641                                          (DMGL_PARAMS | DMGL_ANSI
9642                                           | DMGL_RET_DROP)));
9643         }
9644       if (demangled)
9645         canon = demangled.get ();
9646       else
9647         {
9648           canon = mangled;
9649           need_copy = 0;
9650         }
9651     }
9652
9653   if (canon == NULL || check_physname)
9654     {
9655       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9656
9657       if (canon != NULL && strcmp (physname, canon) != 0)
9658         {
9659           /* It may not mean a bug in GDB.  The compiler could also
9660              compute DW_AT_linkage_name incorrectly.  But in such case
9661              GDB would need to be bug-to-bug compatible.  */
9662
9663           complaint (&symfile_complaints,
9664                      _("Computed physname <%s> does not match demangled <%s> "
9665                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9666                      physname, canon, mangled, to_underlying (die->sect_off),
9667                      objfile_name (objfile));
9668
9669           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9670              is available here - over computed PHYSNAME.  It is safer
9671              against both buggy GDB and buggy compilers.  */
9672
9673           retval = canon;
9674         }
9675       else
9676         {
9677           retval = physname;
9678           need_copy = 0;
9679         }
9680     }
9681   else
9682     retval = canon;
9683
9684   if (need_copy)
9685     retval = ((const char *)
9686               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9687                              retval, strlen (retval)));
9688
9689   return retval;
9690 }
9691
9692 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9693    a new symbol for it.
9694
9695    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9696
9697 static int
9698 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9699 {
9700   struct attribute *attr;
9701
9702   /* If the die does not have a name, this is not a namespace
9703      alias.  */
9704   attr = dwarf2_attr (die, DW_AT_name, cu);
9705   if (attr != NULL)
9706     {
9707       int num;
9708       struct die_info *d = die;
9709       struct dwarf2_cu *imported_cu = cu;
9710
9711       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9712          keep inspecting DIEs until we hit the underlying import.  */
9713 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9714       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9715         {
9716           attr = dwarf2_attr (d, DW_AT_import, cu);
9717           if (attr == NULL)
9718             break;
9719
9720           d = follow_die_ref (d, attr, &imported_cu);
9721           if (d->tag != DW_TAG_imported_declaration)
9722             break;
9723         }
9724
9725       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9726         {
9727           complaint (&symfile_complaints,
9728                      _("DIE at 0x%x has too many recursively imported "
9729                        "declarations"), to_underlying (d->sect_off));
9730           return 0;
9731         }
9732
9733       if (attr != NULL)
9734         {
9735           struct type *type;
9736           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9737
9738           type = get_die_type_at_offset (sect_off, cu->per_cu);
9739           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9740             {
9741               /* This declaration is a global namespace alias.  Add
9742                  a symbol for it whose type is the aliased namespace.  */
9743               new_symbol (die, type, cu);
9744               return 1;
9745             }
9746         }
9747     }
9748
9749   return 0;
9750 }
9751
9752 /* Return the using directives repository (global or local?) to use in the
9753    current context for LANGUAGE.
9754
9755    For Ada, imported declarations can materialize renamings, which *may* be
9756    global.  However it is impossible (for now?) in DWARF to distinguish
9757    "external" imported declarations and "static" ones.  As all imported
9758    declarations seem to be static in all other languages, make them all CU-wide
9759    global only in Ada.  */
9760
9761 static struct using_direct **
9762 using_directives (enum language language)
9763 {
9764   if (language == language_ada && context_stack_depth == 0)
9765     return &global_using_directives;
9766   else
9767     return &local_using_directives;
9768 }
9769
9770 /* Read the import statement specified by the given die and record it.  */
9771
9772 static void
9773 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9774 {
9775   struct objfile *objfile = cu->objfile;
9776   struct attribute *import_attr;
9777   struct die_info *imported_die, *child_die;
9778   struct dwarf2_cu *imported_cu;
9779   const char *imported_name;
9780   const char *imported_name_prefix;
9781   const char *canonical_name;
9782   const char *import_alias;
9783   const char *imported_declaration = NULL;
9784   const char *import_prefix;
9785   std::vector<const char *> excludes;
9786
9787   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9788   if (import_attr == NULL)
9789     {
9790       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9791                  dwarf_tag_name (die->tag));
9792       return;
9793     }
9794
9795   imported_cu = cu;
9796   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9797   imported_name = dwarf2_name (imported_die, imported_cu);
9798   if (imported_name == NULL)
9799     {
9800       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9801
9802         The import in the following code:
9803         namespace A
9804           {
9805             typedef int B;
9806           }
9807
9808         int main ()
9809           {
9810             using A::B;
9811             B b;
9812             return b;
9813           }
9814
9815         ...
9816          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9817             <52>   DW_AT_decl_file   : 1
9818             <53>   DW_AT_decl_line   : 6
9819             <54>   DW_AT_import      : <0x75>
9820          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9821             <59>   DW_AT_name        : B
9822             <5b>   DW_AT_decl_file   : 1
9823             <5c>   DW_AT_decl_line   : 2
9824             <5d>   DW_AT_type        : <0x6e>
9825         ...
9826          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9827             <76>   DW_AT_byte_size   : 4
9828             <77>   DW_AT_encoding    : 5        (signed)
9829
9830         imports the wrong die ( 0x75 instead of 0x58 ).
9831         This case will be ignored until the gcc bug is fixed.  */
9832       return;
9833     }
9834
9835   /* Figure out the local name after import.  */
9836   import_alias = dwarf2_name (die, cu);
9837
9838   /* Figure out where the statement is being imported to.  */
9839   import_prefix = determine_prefix (die, cu);
9840
9841   /* Figure out what the scope of the imported die is and prepend it
9842      to the name of the imported die.  */
9843   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9844
9845   if (imported_die->tag != DW_TAG_namespace
9846       && imported_die->tag != DW_TAG_module)
9847     {
9848       imported_declaration = imported_name;
9849       canonical_name = imported_name_prefix;
9850     }
9851   else if (strlen (imported_name_prefix) > 0)
9852     canonical_name = obconcat (&objfile->objfile_obstack,
9853                                imported_name_prefix,
9854                                (cu->language == language_d ? "." : "::"),
9855                                imported_name, (char *) NULL);
9856   else
9857     canonical_name = imported_name;
9858
9859   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9860     for (child_die = die->child; child_die && child_die->tag;
9861          child_die = sibling_die (child_die))
9862       {
9863         /* DWARF-4: A Fortran use statement with a “rename list” may be
9864            represented by an imported module entry with an import attribute
9865            referring to the module and owned entries corresponding to those
9866            entities that are renamed as part of being imported.  */
9867
9868         if (child_die->tag != DW_TAG_imported_declaration)
9869           {
9870             complaint (&symfile_complaints,
9871                        _("child DW_TAG_imported_declaration expected "
9872                          "- DIE at 0x%x [in module %s]"),
9873                        to_underlying (child_die->sect_off), objfile_name (objfile));
9874             continue;
9875           }
9876
9877         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9878         if (import_attr == NULL)
9879           {
9880             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9881                        dwarf_tag_name (child_die->tag));
9882             continue;
9883           }
9884
9885         imported_cu = cu;
9886         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9887                                               &imported_cu);
9888         imported_name = dwarf2_name (imported_die, imported_cu);
9889         if (imported_name == NULL)
9890           {
9891             complaint (&symfile_complaints,
9892                        _("child DW_TAG_imported_declaration has unknown "
9893                          "imported name - DIE at 0x%x [in module %s]"),
9894                        to_underlying (child_die->sect_off), objfile_name (objfile));
9895             continue;
9896           }
9897
9898         excludes.push_back (imported_name);
9899
9900         process_die (child_die, cu);
9901       }
9902
9903   add_using_directive (using_directives (cu->language),
9904                        import_prefix,
9905                        canonical_name,
9906                        import_alias,
9907                        imported_declaration,
9908                        excludes,
9909                        0,
9910                        &objfile->objfile_obstack);
9911 }
9912
9913 /* ICC<14 does not output the required DW_AT_declaration on incomplete
9914    types, but gives them a size of zero.  Starting with version 14,
9915    ICC is compatible with GCC.  */
9916
9917 static int
9918 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
9919 {
9920   if (!cu->checked_producer)
9921     check_producer (cu);
9922
9923   return cu->producer_is_icc_lt_14;
9924 }
9925
9926 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9927    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9928    this, it was first present in GCC release 4.3.0.  */
9929
9930 static int
9931 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9932 {
9933   if (!cu->checked_producer)
9934     check_producer (cu);
9935
9936   return cu->producer_is_gcc_lt_4_3;
9937 }
9938
9939 static file_and_directory
9940 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9941 {
9942   file_and_directory res;
9943
9944   /* Find the filename.  Do not use dwarf2_name here, since the filename
9945      is not a source language identifier.  */
9946   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9947   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9948
9949   if (res.comp_dir == NULL
9950       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9951       && IS_ABSOLUTE_PATH (res.name))
9952     {
9953       res.comp_dir_storage = ldirname (res.name);
9954       if (!res.comp_dir_storage.empty ())
9955         res.comp_dir = res.comp_dir_storage.c_str ();
9956     }
9957   if (res.comp_dir != NULL)
9958     {
9959       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9960          directory, get rid of it.  */
9961       const char *cp = strchr (res.comp_dir, ':');
9962
9963       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9964         res.comp_dir = cp + 1;
9965     }
9966
9967   if (res.name == NULL)
9968     res.name = "<unknown>";
9969
9970   return res;
9971 }
9972
9973 /* Handle DW_AT_stmt_list for a compilation unit.
9974    DIE is the DW_TAG_compile_unit die for CU.
9975    COMP_DIR is the compilation directory.  LOWPC is passed to
9976    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9977
9978 static void
9979 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9980                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9981 {
9982   struct objfile *objfile = dwarf2_per_objfile->objfile;
9983   struct attribute *attr;
9984   struct line_header line_header_local;
9985   hashval_t line_header_local_hash;
9986   unsigned u;
9987   void **slot;
9988   int decode_mapping;
9989
9990   gdb_assert (! cu->per_cu->is_debug_types);
9991
9992   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9993   if (attr == NULL)
9994     return;
9995
9996   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9997
9998   /* The line header hash table is only created if needed (it exists to
9999      prevent redundant reading of the line table for partial_units).
10000      If we're given a partial_unit, we'll need it.  If we're given a
10001      compile_unit, then use the line header hash table if it's already
10002      created, but don't create one just yet.  */
10003
10004   if (dwarf2_per_objfile->line_header_hash == NULL
10005       && die->tag == DW_TAG_partial_unit)
10006     {
10007       dwarf2_per_objfile->line_header_hash
10008         = htab_create_alloc_ex (127, line_header_hash_voidp,
10009                                 line_header_eq_voidp,
10010                                 free_line_header_voidp,
10011                                 &objfile->objfile_obstack,
10012                                 hashtab_obstack_allocate,
10013                                 dummy_obstack_deallocate);
10014     }
10015
10016   line_header_local.sect_off = line_offset;
10017   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
10018   line_header_local_hash = line_header_hash (&line_header_local);
10019   if (dwarf2_per_objfile->line_header_hash != NULL)
10020     {
10021       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10022                                        &line_header_local,
10023                                        line_header_local_hash, NO_INSERT);
10024
10025       /* For DW_TAG_compile_unit we need info like symtab::linetable which
10026          is not present in *SLOT (since if there is something in *SLOT then
10027          it will be for a partial_unit).  */
10028       if (die->tag == DW_TAG_partial_unit && slot != NULL)
10029         {
10030           gdb_assert (*slot != NULL);
10031           cu->line_header = (struct line_header *) *slot;
10032           return;
10033         }
10034     }
10035
10036   /* dwarf_decode_line_header does not yet provide sufficient information.
10037      We always have to call also dwarf_decode_lines for it.  */
10038   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
10039   if (lh == NULL)
10040     return;
10041
10042   cu->line_header = lh.release ();
10043   cu->line_header_die_owner = die;
10044
10045   if (dwarf2_per_objfile->line_header_hash == NULL)
10046     slot = NULL;
10047   else
10048     {
10049       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10050                                        &line_header_local,
10051                                        line_header_local_hash, INSERT);
10052       gdb_assert (slot != NULL);
10053     }
10054   if (slot != NULL && *slot == NULL)
10055     {
10056       /* This newly decoded line number information unit will be owned
10057          by line_header_hash hash table.  */
10058       *slot = cu->line_header;
10059       cu->line_header_die_owner = NULL;
10060     }
10061   else
10062     {
10063       /* We cannot free any current entry in (*slot) as that struct line_header
10064          may be already used by multiple CUs.  Create only temporary decoded
10065          line_header for this CU - it may happen at most once for each line
10066          number information unit.  And if we're not using line_header_hash
10067          then this is what we want as well.  */
10068       gdb_assert (die->tag != DW_TAG_partial_unit);
10069     }
10070   decode_mapping = (die->tag != DW_TAG_partial_unit);
10071   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
10072                       decode_mapping);
10073
10074 }
10075
10076 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
10077
10078 static void
10079 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
10080 {
10081   struct objfile *objfile = dwarf2_per_objfile->objfile;
10082   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10083   CORE_ADDR lowpc = ((CORE_ADDR) -1);
10084   CORE_ADDR highpc = ((CORE_ADDR) 0);
10085   struct attribute *attr;
10086   struct die_info *child_die;
10087   CORE_ADDR baseaddr;
10088
10089   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10090
10091   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
10092
10093   /* If we didn't find a lowpc, set it to highpc to avoid complaints
10094      from finish_block.  */
10095   if (lowpc == ((CORE_ADDR) -1))
10096     lowpc = highpc;
10097   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
10098
10099   file_and_directory fnd = find_file_and_directory (die, cu);
10100
10101   prepare_one_comp_unit (cu, die, cu->language);
10102
10103   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
10104      standardised yet.  As a workaround for the language detection we fall
10105      back to the DW_AT_producer string.  */
10106   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
10107     cu->language = language_opencl;
10108
10109   /* Similar hack for Go.  */
10110   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
10111     set_cu_language (DW_LANG_Go, cu);
10112
10113   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
10114
10115   /* Decode line number information if present.  We do this before
10116      processing child DIEs, so that the line header table is available
10117      for DW_AT_decl_file.  */
10118   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
10119
10120   /* Process all dies in compilation unit.  */
10121   if (die->child != NULL)
10122     {
10123       child_die = die->child;
10124       while (child_die && child_die->tag)
10125         {
10126           process_die (child_die, cu);
10127           child_die = sibling_die (child_die);
10128         }
10129     }
10130
10131   /* Decode macro information, if present.  Dwarf 2 macro information
10132      refers to information in the line number info statement program
10133      header, so we can only read it if we've read the header
10134      successfully.  */
10135   attr = dwarf2_attr (die, DW_AT_macros, cu);
10136   if (attr == NULL)
10137     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
10138   if (attr && cu->line_header)
10139     {
10140       if (dwarf2_attr (die, DW_AT_macro_info, cu))
10141         complaint (&symfile_complaints,
10142                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
10143
10144       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
10145     }
10146   else
10147     {
10148       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
10149       if (attr && cu->line_header)
10150         {
10151           unsigned int macro_offset = DW_UNSND (attr);
10152
10153           dwarf_decode_macros (cu, macro_offset, 0);
10154         }
10155     }
10156 }
10157
10158 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
10159    Create the set of symtabs used by this TU, or if this TU is sharing
10160    symtabs with another TU and the symtabs have already been created
10161    then restore those symtabs in the line header.
10162    We don't need the pc/line-number mapping for type units.  */
10163
10164 static void
10165 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
10166 {
10167   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
10168   struct type_unit_group *tu_group;
10169   int first_time;
10170   struct attribute *attr;
10171   unsigned int i;
10172   struct signatured_type *sig_type;
10173
10174   gdb_assert (per_cu->is_debug_types);
10175   sig_type = (struct signatured_type *) per_cu;
10176
10177   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10178
10179   /* If we're using .gdb_index (includes -readnow) then
10180      per_cu->type_unit_group may not have been set up yet.  */
10181   if (sig_type->type_unit_group == NULL)
10182     sig_type->type_unit_group = get_type_unit_group (cu, attr);
10183   tu_group = sig_type->type_unit_group;
10184
10185   /* If we've already processed this stmt_list there's no real need to
10186      do it again, we could fake it and just recreate the part we need
10187      (file name,index -> symtab mapping).  If data shows this optimization
10188      is useful we can do it then.  */
10189   first_time = tu_group->compunit_symtab == NULL;
10190
10191   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
10192      debug info.  */
10193   line_header_up lh;
10194   if (attr != NULL)
10195     {
10196       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10197       lh = dwarf_decode_line_header (line_offset, cu);
10198     }
10199   if (lh == NULL)
10200     {
10201       if (first_time)
10202         dwarf2_start_symtab (cu, "", NULL, 0);
10203       else
10204         {
10205           gdb_assert (tu_group->symtabs == NULL);
10206           restart_symtab (tu_group->compunit_symtab, "", 0);
10207         }
10208       return;
10209     }
10210
10211   cu->line_header = lh.release ();
10212   cu->line_header_die_owner = die;
10213
10214   if (first_time)
10215     {
10216       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
10217
10218       /* Note: We don't assign tu_group->compunit_symtab yet because we're
10219          still initializing it, and our caller (a few levels up)
10220          process_full_type_unit still needs to know if this is the first
10221          time.  */
10222
10223       tu_group->num_symtabs = cu->line_header->file_names.size ();
10224       tu_group->symtabs = XNEWVEC (struct symtab *,
10225                                    cu->line_header->file_names.size ());
10226
10227       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10228         {
10229           file_entry &fe = cu->line_header->file_names[i];
10230
10231           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
10232
10233           if (current_subfile->symtab == NULL)
10234             {
10235               /* NOTE: start_subfile will recognize when it's been
10236                  passed a file it has already seen.  So we can't
10237                  assume there's a simple mapping from
10238                  cu->line_header->file_names to subfiles, plus
10239                  cu->line_header->file_names may contain dups.  */
10240               current_subfile->symtab
10241                 = allocate_symtab (cust, current_subfile->name);
10242             }
10243
10244           fe.symtab = current_subfile->symtab;
10245           tu_group->symtabs[i] = fe.symtab;
10246         }
10247     }
10248   else
10249     {
10250       restart_symtab (tu_group->compunit_symtab, "", 0);
10251
10252       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10253         {
10254           file_entry &fe = cu->line_header->file_names[i];
10255
10256           fe.symtab = tu_group->symtabs[i];
10257         }
10258     }
10259
10260   /* The main symtab is allocated last.  Type units don't have DW_AT_name
10261      so they don't have a "real" (so to speak) symtab anyway.
10262      There is later code that will assign the main symtab to all symbols
10263      that don't have one.  We need to handle the case of a symbol with a
10264      missing symtab (DW_AT_decl_file) anyway.  */
10265 }
10266
10267 /* Process DW_TAG_type_unit.
10268    For TUs we want to skip the first top level sibling if it's not the
10269    actual type being defined by this TU.  In this case the first top
10270    level sibling is there to provide context only.  */
10271
10272 static void
10273 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10274 {
10275   struct die_info *child_die;
10276
10277   prepare_one_comp_unit (cu, die, language_minimal);
10278
10279   /* Initialize (or reinitialize) the machinery for building symtabs.
10280      We do this before processing child DIEs, so that the line header table
10281      is available for DW_AT_decl_file.  */
10282   setup_type_unit_groups (die, cu);
10283
10284   if (die->child != NULL)
10285     {
10286       child_die = die->child;
10287       while (child_die && child_die->tag)
10288         {
10289           process_die (child_die, cu);
10290           child_die = sibling_die (child_die);
10291         }
10292     }
10293 }
10294 \f
10295 /* DWO/DWP files.
10296
10297    http://gcc.gnu.org/wiki/DebugFission
10298    http://gcc.gnu.org/wiki/DebugFissionDWP
10299
10300    To simplify handling of both DWO files ("object" files with the DWARF info)
10301    and DWP files (a file with the DWOs packaged up into one file), we treat
10302    DWP files as having a collection of virtual DWO files.  */
10303
10304 static hashval_t
10305 hash_dwo_file (const void *item)
10306 {
10307   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10308   hashval_t hash;
10309
10310   hash = htab_hash_string (dwo_file->dwo_name);
10311   if (dwo_file->comp_dir != NULL)
10312     hash += htab_hash_string (dwo_file->comp_dir);
10313   return hash;
10314 }
10315
10316 static int
10317 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10318 {
10319   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10320   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10321
10322   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10323     return 0;
10324   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10325     return lhs->comp_dir == rhs->comp_dir;
10326   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10327 }
10328
10329 /* Allocate a hash table for DWO files.  */
10330
10331 static htab_t
10332 allocate_dwo_file_hash_table (void)
10333 {
10334   struct objfile *objfile = dwarf2_per_objfile->objfile;
10335
10336   return htab_create_alloc_ex (41,
10337                                hash_dwo_file,
10338                                eq_dwo_file,
10339                                NULL,
10340                                &objfile->objfile_obstack,
10341                                hashtab_obstack_allocate,
10342                                dummy_obstack_deallocate);
10343 }
10344
10345 /* Lookup DWO file DWO_NAME.  */
10346
10347 static void **
10348 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
10349 {
10350   struct dwo_file find_entry;
10351   void **slot;
10352
10353   if (dwarf2_per_objfile->dwo_files == NULL)
10354     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
10355
10356   memset (&find_entry, 0, sizeof (find_entry));
10357   find_entry.dwo_name = dwo_name;
10358   find_entry.comp_dir = comp_dir;
10359   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
10360
10361   return slot;
10362 }
10363
10364 static hashval_t
10365 hash_dwo_unit (const void *item)
10366 {
10367   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10368
10369   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10370   return dwo_unit->signature;
10371 }
10372
10373 static int
10374 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10375 {
10376   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10377   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10378
10379   /* The signature is assumed to be unique within the DWO file.
10380      So while object file CU dwo_id's always have the value zero,
10381      that's OK, assuming each object file DWO file has only one CU,
10382      and that's the rule for now.  */
10383   return lhs->signature == rhs->signature;
10384 }
10385
10386 /* Allocate a hash table for DWO CUs,TUs.
10387    There is one of these tables for each of CUs,TUs for each DWO file.  */
10388
10389 static htab_t
10390 allocate_dwo_unit_table (struct objfile *objfile)
10391 {
10392   /* Start out with a pretty small number.
10393      Generally DWO files contain only one CU and maybe some TUs.  */
10394   return htab_create_alloc_ex (3,
10395                                hash_dwo_unit,
10396                                eq_dwo_unit,
10397                                NULL,
10398                                &objfile->objfile_obstack,
10399                                hashtab_obstack_allocate,
10400                                dummy_obstack_deallocate);
10401 }
10402
10403 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
10404
10405 struct create_dwo_cu_data
10406 {
10407   struct dwo_file *dwo_file;
10408   struct dwo_unit dwo_unit;
10409 };
10410
10411 /* die_reader_func for create_dwo_cu.  */
10412
10413 static void
10414 create_dwo_cu_reader (const struct die_reader_specs *reader,
10415                       const gdb_byte *info_ptr,
10416                       struct die_info *comp_unit_die,
10417                       int has_children,
10418                       void *datap)
10419 {
10420   struct dwarf2_cu *cu = reader->cu;
10421   sect_offset sect_off = cu->per_cu->sect_off;
10422   struct dwarf2_section_info *section = cu->per_cu->section;
10423   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
10424   struct dwo_file *dwo_file = data->dwo_file;
10425   struct dwo_unit *dwo_unit = &data->dwo_unit;
10426   struct attribute *attr;
10427
10428   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
10429   if (attr == NULL)
10430     {
10431       complaint (&symfile_complaints,
10432                  _("Dwarf Error: debug entry at offset 0x%x is missing"
10433                    " its dwo_id [in module %s]"),
10434                  to_underlying (sect_off), dwo_file->dwo_name);
10435       return;
10436     }
10437
10438   dwo_unit->dwo_file = dwo_file;
10439   dwo_unit->signature = DW_UNSND (attr);
10440   dwo_unit->section = section;
10441   dwo_unit->sect_off = sect_off;
10442   dwo_unit->length = cu->per_cu->length;
10443
10444   if (dwarf_read_debug)
10445     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
10446                         to_underlying (sect_off),
10447                         hex_string (dwo_unit->signature));
10448 }
10449
10450 /* Create the dwo_units for the CUs in a DWO_FILE.
10451    Note: This function processes DWO files only, not DWP files.  */
10452
10453 static void
10454 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
10455                        htab_t &cus_htab)
10456 {
10457   struct objfile *objfile = dwarf2_per_objfile->objfile;
10458   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
10459   const gdb_byte *info_ptr, *end_ptr;
10460
10461   dwarf2_read_section (objfile, &section);
10462   info_ptr = section.buffer;
10463
10464   if (info_ptr == NULL)
10465     return;
10466
10467   if (dwarf_read_debug)
10468     {
10469       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
10470                           get_section_name (&section),
10471                           get_section_file_name (&section));
10472     }
10473
10474   end_ptr = info_ptr + section.size;
10475   while (info_ptr < end_ptr)
10476     {
10477       struct dwarf2_per_cu_data per_cu;
10478       struct create_dwo_cu_data create_dwo_cu_data;
10479       struct dwo_unit *dwo_unit;
10480       void **slot;
10481       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10482
10483       memset (&create_dwo_cu_data.dwo_unit, 0,
10484               sizeof (create_dwo_cu_data.dwo_unit));
10485       memset (&per_cu, 0, sizeof (per_cu));
10486       per_cu.objfile = objfile;
10487       per_cu.is_debug_types = 0;
10488       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10489       per_cu.section = &section;
10490       create_dwo_cu_data.dwo_file = &dwo_file;
10491
10492       init_cutu_and_read_dies_no_follow (
10493           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
10494       info_ptr += per_cu.length;
10495
10496       // If the unit could not be parsed, skip it.
10497       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
10498         continue;
10499
10500       if (cus_htab == NULL)
10501         cus_htab = allocate_dwo_unit_table (objfile);
10502
10503       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10504       *dwo_unit = create_dwo_cu_data.dwo_unit;
10505       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
10506       gdb_assert (slot != NULL);
10507       if (*slot != NULL)
10508         {
10509           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10510           sect_offset dup_sect_off = dup_cu->sect_off;
10511
10512           complaint (&symfile_complaints,
10513                      _("debug cu entry at offset 0x%x is duplicate to"
10514                        " the entry at offset 0x%x, signature %s"),
10515                      to_underlying (sect_off), to_underlying (dup_sect_off),
10516                      hex_string (dwo_unit->signature));
10517         }
10518       *slot = (void *)dwo_unit;
10519     }
10520 }
10521
10522 /* DWP file .debug_{cu,tu}_index section format:
10523    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10524
10525    DWP Version 1:
10526
10527    Both index sections have the same format, and serve to map a 64-bit
10528    signature to a set of section numbers.  Each section begins with a header,
10529    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10530    indexes, and a pool of 32-bit section numbers.  The index sections will be
10531    aligned at 8-byte boundaries in the file.
10532
10533    The index section header consists of:
10534
10535     V, 32 bit version number
10536     -, 32 bits unused
10537     N, 32 bit number of compilation units or type units in the index
10538     M, 32 bit number of slots in the hash table
10539
10540    Numbers are recorded using the byte order of the application binary.
10541
10542    The hash table begins at offset 16 in the section, and consists of an array
10543    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
10544    order of the application binary).  Unused slots in the hash table are 0.
10545    (We rely on the extreme unlikeliness of a signature being exactly 0.)
10546
10547    The parallel table begins immediately after the hash table
10548    (at offset 16 + 8 * M from the beginning of the section), and consists of an
10549    array of 32-bit indexes (using the byte order of the application binary),
10550    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
10551    table contains a 32-bit index into the pool of section numbers.  For unused
10552    hash table slots, the corresponding entry in the parallel table will be 0.
10553
10554    The pool of section numbers begins immediately following the hash table
10555    (at offset 16 + 12 * M from the beginning of the section).  The pool of
10556    section numbers consists of an array of 32-bit words (using the byte order
10557    of the application binary).  Each item in the array is indexed starting
10558    from 0.  The hash table entry provides the index of the first section
10559    number in the set.  Additional section numbers in the set follow, and the
10560    set is terminated by a 0 entry (section number 0 is not used in ELF).
10561
10562    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
10563    section must be the first entry in the set, and the .debug_abbrev.dwo must
10564    be the second entry. Other members of the set may follow in any order.
10565
10566    ---
10567
10568    DWP Version 2:
10569
10570    DWP Version 2 combines all the .debug_info, etc. sections into one,
10571    and the entries in the index tables are now offsets into these sections.
10572    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10573    section.
10574
10575    Index Section Contents:
10576     Header
10577     Hash Table of Signatures   dwp_hash_table.hash_table
10578     Parallel Table of Indices  dwp_hash_table.unit_table
10579     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10580     Table of Section Sizes     dwp_hash_table.v2.sizes
10581
10582    The index section header consists of:
10583
10584     V, 32 bit version number
10585     L, 32 bit number of columns in the table of section offsets
10586     N, 32 bit number of compilation units or type units in the index
10587     M, 32 bit number of slots in the hash table
10588
10589    Numbers are recorded using the byte order of the application binary.
10590
10591    The hash table has the same format as version 1.
10592    The parallel table of indices has the same format as version 1,
10593    except that the entries are origin-1 indices into the table of sections
10594    offsets and the table of section sizes.
10595
10596    The table of offsets begins immediately following the parallel table
10597    (at offset 16 + 12 * M from the beginning of the section).  The table is
10598    a two-dimensional array of 32-bit words (using the byte order of the
10599    application binary), with L columns and N+1 rows, in row-major order.
10600    Each row in the array is indexed starting from 0.  The first row provides
10601    a key to the remaining rows: each column in this row provides an identifier
10602    for a debug section, and the offsets in the same column of subsequent rows
10603    refer to that section.  The section identifiers are:
10604
10605     DW_SECT_INFO         1  .debug_info.dwo
10606     DW_SECT_TYPES        2  .debug_types.dwo
10607     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10608     DW_SECT_LINE         4  .debug_line.dwo
10609     DW_SECT_LOC          5  .debug_loc.dwo
10610     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10611     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10612     DW_SECT_MACRO        8  .debug_macro.dwo
10613
10614    The offsets provided by the CU and TU index sections are the base offsets
10615    for the contributions made by each CU or TU to the corresponding section
10616    in the package file.  Each CU and TU header contains an abbrev_offset
10617    field, used to find the abbreviations table for that CU or TU within the
10618    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10619    be interpreted as relative to the base offset given in the index section.
10620    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10621    should be interpreted as relative to the base offset for .debug_line.dwo,
10622    and offsets into other debug sections obtained from DWARF attributes should
10623    also be interpreted as relative to the corresponding base offset.
10624
10625    The table of sizes begins immediately following the table of offsets.
10626    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10627    with L columns and N rows, in row-major order.  Each row in the array is
10628    indexed starting from 1 (row 0 is shared by the two tables).
10629
10630    ---
10631
10632    Hash table lookup is handled the same in version 1 and 2:
10633
10634    We assume that N and M will not exceed 2^32 - 1.
10635    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10636
10637    Given a 64-bit compilation unit signature or a type signature S, an entry
10638    in the hash table is located as follows:
10639
10640    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10641       the low-order k bits all set to 1.
10642
10643    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10644
10645    3) If the hash table entry at index H matches the signature, use that
10646       entry.  If the hash table entry at index H is unused (all zeroes),
10647       terminate the search: the signature is not present in the table.
10648
10649    4) Let H = (H + H') modulo M. Repeat at Step 3.
10650
10651    Because M > N and H' and M are relatively prime, the search is guaranteed
10652    to stop at an unused slot or find the match.  */
10653
10654 /* Create a hash table to map DWO IDs to their CU/TU entry in
10655    .debug_{info,types}.dwo in DWP_FILE.
10656    Returns NULL if there isn't one.
10657    Note: This function processes DWP files only, not DWO files.  */
10658
10659 static struct dwp_hash_table *
10660 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10661 {
10662   struct objfile *objfile = dwarf2_per_objfile->objfile;
10663   bfd *dbfd = dwp_file->dbfd;
10664   const gdb_byte *index_ptr, *index_end;
10665   struct dwarf2_section_info *index;
10666   uint32_t version, nr_columns, nr_units, nr_slots;
10667   struct dwp_hash_table *htab;
10668
10669   if (is_debug_types)
10670     index = &dwp_file->sections.tu_index;
10671   else
10672     index = &dwp_file->sections.cu_index;
10673
10674   if (dwarf2_section_empty_p (index))
10675     return NULL;
10676   dwarf2_read_section (objfile, index);
10677
10678   index_ptr = index->buffer;
10679   index_end = index_ptr + index->size;
10680
10681   version = read_4_bytes (dbfd, index_ptr);
10682   index_ptr += 4;
10683   if (version == 2)
10684     nr_columns = read_4_bytes (dbfd, index_ptr);
10685   else
10686     nr_columns = 0;
10687   index_ptr += 4;
10688   nr_units = read_4_bytes (dbfd, index_ptr);
10689   index_ptr += 4;
10690   nr_slots = read_4_bytes (dbfd, index_ptr);
10691   index_ptr += 4;
10692
10693   if (version != 1 && version != 2)
10694     {
10695       error (_("Dwarf Error: unsupported DWP file version (%s)"
10696                " [in module %s]"),
10697              pulongest (version), dwp_file->name);
10698     }
10699   if (nr_slots != (nr_slots & -nr_slots))
10700     {
10701       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10702                " is not power of 2 [in module %s]"),
10703              pulongest (nr_slots), dwp_file->name);
10704     }
10705
10706   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10707   htab->version = version;
10708   htab->nr_columns = nr_columns;
10709   htab->nr_units = nr_units;
10710   htab->nr_slots = nr_slots;
10711   htab->hash_table = index_ptr;
10712   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10713
10714   /* Exit early if the table is empty.  */
10715   if (nr_slots == 0 || nr_units == 0
10716       || (version == 2 && nr_columns == 0))
10717     {
10718       /* All must be zero.  */
10719       if (nr_slots != 0 || nr_units != 0
10720           || (version == 2 && nr_columns != 0))
10721         {
10722           complaint (&symfile_complaints,
10723                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10724                        " all zero [in modules %s]"),
10725                      dwp_file->name);
10726         }
10727       return htab;
10728     }
10729
10730   if (version == 1)
10731     {
10732       htab->section_pool.v1.indices =
10733         htab->unit_table + sizeof (uint32_t) * nr_slots;
10734       /* It's harder to decide whether the section is too small in v1.
10735          V1 is deprecated anyway so we punt.  */
10736     }
10737   else
10738     {
10739       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10740       int *ids = htab->section_pool.v2.section_ids;
10741       /* Reverse map for error checking.  */
10742       int ids_seen[DW_SECT_MAX + 1];
10743       int i;
10744
10745       if (nr_columns < 2)
10746         {
10747           error (_("Dwarf Error: bad DWP hash table, too few columns"
10748                    " in section table [in module %s]"),
10749                  dwp_file->name);
10750         }
10751       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10752         {
10753           error (_("Dwarf Error: bad DWP hash table, too many columns"
10754                    " in section table [in module %s]"),
10755                  dwp_file->name);
10756         }
10757       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10758       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10759       for (i = 0; i < nr_columns; ++i)
10760         {
10761           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10762
10763           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10764             {
10765               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10766                        " in section table [in module %s]"),
10767                      id, dwp_file->name);
10768             }
10769           if (ids_seen[id] != -1)
10770             {
10771               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10772                        " id %d in section table [in module %s]"),
10773                      id, dwp_file->name);
10774             }
10775           ids_seen[id] = i;
10776           ids[i] = id;
10777         }
10778       /* Must have exactly one info or types section.  */
10779       if (((ids_seen[DW_SECT_INFO] != -1)
10780            + (ids_seen[DW_SECT_TYPES] != -1))
10781           != 1)
10782         {
10783           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10784                    " DWO info/types section [in module %s]"),
10785                  dwp_file->name);
10786         }
10787       /* Must have an abbrev section.  */
10788       if (ids_seen[DW_SECT_ABBREV] == -1)
10789         {
10790           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10791                    " section [in module %s]"),
10792                  dwp_file->name);
10793         }
10794       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10795       htab->section_pool.v2.sizes =
10796         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10797                                          * nr_units * nr_columns);
10798       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10799                                           * nr_units * nr_columns))
10800           > index_end)
10801         {
10802           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10803                    " [in module %s]"),
10804                  dwp_file->name);
10805         }
10806     }
10807
10808   return htab;
10809 }
10810
10811 /* Update SECTIONS with the data from SECTP.
10812
10813    This function is like the other "locate" section routines that are
10814    passed to bfd_map_over_sections, but in this context the sections to
10815    read comes from the DWP V1 hash table, not the full ELF section table.
10816
10817    The result is non-zero for success, or zero if an error was found.  */
10818
10819 static int
10820 locate_v1_virtual_dwo_sections (asection *sectp,
10821                                 struct virtual_v1_dwo_sections *sections)
10822 {
10823   const struct dwop_section_names *names = &dwop_section_names;
10824
10825   if (section_is_p (sectp->name, &names->abbrev_dwo))
10826     {
10827       /* There can be only one.  */
10828       if (sections->abbrev.s.section != NULL)
10829         return 0;
10830       sections->abbrev.s.section = sectp;
10831       sections->abbrev.size = bfd_get_section_size (sectp);
10832     }
10833   else if (section_is_p (sectp->name, &names->info_dwo)
10834            || section_is_p (sectp->name, &names->types_dwo))
10835     {
10836       /* There can be only one.  */
10837       if (sections->info_or_types.s.section != NULL)
10838         return 0;
10839       sections->info_or_types.s.section = sectp;
10840       sections->info_or_types.size = bfd_get_section_size (sectp);
10841     }
10842   else if (section_is_p (sectp->name, &names->line_dwo))
10843     {
10844       /* There can be only one.  */
10845       if (sections->line.s.section != NULL)
10846         return 0;
10847       sections->line.s.section = sectp;
10848       sections->line.size = bfd_get_section_size (sectp);
10849     }
10850   else if (section_is_p (sectp->name, &names->loc_dwo))
10851     {
10852       /* There can be only one.  */
10853       if (sections->loc.s.section != NULL)
10854         return 0;
10855       sections->loc.s.section = sectp;
10856       sections->loc.size = bfd_get_section_size (sectp);
10857     }
10858   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10859     {
10860       /* There can be only one.  */
10861       if (sections->macinfo.s.section != NULL)
10862         return 0;
10863       sections->macinfo.s.section = sectp;
10864       sections->macinfo.size = bfd_get_section_size (sectp);
10865     }
10866   else if (section_is_p (sectp->name, &names->macro_dwo))
10867     {
10868       /* There can be only one.  */
10869       if (sections->macro.s.section != NULL)
10870         return 0;
10871       sections->macro.s.section = sectp;
10872       sections->macro.size = bfd_get_section_size (sectp);
10873     }
10874   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10875     {
10876       /* There can be only one.  */
10877       if (sections->str_offsets.s.section != NULL)
10878         return 0;
10879       sections->str_offsets.s.section = sectp;
10880       sections->str_offsets.size = bfd_get_section_size (sectp);
10881     }
10882   else
10883     {
10884       /* No other kind of section is valid.  */
10885       return 0;
10886     }
10887
10888   return 1;
10889 }
10890
10891 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10892    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10893    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10894    This is for DWP version 1 files.  */
10895
10896 static struct dwo_unit *
10897 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10898                            uint32_t unit_index,
10899                            const char *comp_dir,
10900                            ULONGEST signature, int is_debug_types)
10901 {
10902   struct objfile *objfile = dwarf2_per_objfile->objfile;
10903   const struct dwp_hash_table *dwp_htab =
10904     is_debug_types ? dwp_file->tus : dwp_file->cus;
10905   bfd *dbfd = dwp_file->dbfd;
10906   const char *kind = is_debug_types ? "TU" : "CU";
10907   struct dwo_file *dwo_file;
10908   struct dwo_unit *dwo_unit;
10909   struct virtual_v1_dwo_sections sections;
10910   void **dwo_file_slot;
10911   int i;
10912
10913   gdb_assert (dwp_file->version == 1);
10914
10915   if (dwarf_read_debug)
10916     {
10917       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10918                           kind,
10919                           pulongest (unit_index), hex_string (signature),
10920                           dwp_file->name);
10921     }
10922
10923   /* Fetch the sections of this DWO unit.
10924      Put a limit on the number of sections we look for so that bad data
10925      doesn't cause us to loop forever.  */
10926
10927 #define MAX_NR_V1_DWO_SECTIONS \
10928   (1 /* .debug_info or .debug_types */ \
10929    + 1 /* .debug_abbrev */ \
10930    + 1 /* .debug_line */ \
10931    + 1 /* .debug_loc */ \
10932    + 1 /* .debug_str_offsets */ \
10933    + 1 /* .debug_macro or .debug_macinfo */ \
10934    + 1 /* trailing zero */)
10935
10936   memset (&sections, 0, sizeof (sections));
10937
10938   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10939     {
10940       asection *sectp;
10941       uint32_t section_nr =
10942         read_4_bytes (dbfd,
10943                       dwp_htab->section_pool.v1.indices
10944                       + (unit_index + i) * sizeof (uint32_t));
10945
10946       if (section_nr == 0)
10947         break;
10948       if (section_nr >= dwp_file->num_sections)
10949         {
10950           error (_("Dwarf Error: bad DWP hash table, section number too large"
10951                    " [in module %s]"),
10952                  dwp_file->name);
10953         }
10954
10955       sectp = dwp_file->elf_sections[section_nr];
10956       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10957         {
10958           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10959                    " [in module %s]"),
10960                  dwp_file->name);
10961         }
10962     }
10963
10964   if (i < 2
10965       || dwarf2_section_empty_p (&sections.info_or_types)
10966       || dwarf2_section_empty_p (&sections.abbrev))
10967     {
10968       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10969                " [in module %s]"),
10970              dwp_file->name);
10971     }
10972   if (i == MAX_NR_V1_DWO_SECTIONS)
10973     {
10974       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10975                " [in module %s]"),
10976              dwp_file->name);
10977     }
10978
10979   /* It's easier for the rest of the code if we fake a struct dwo_file and
10980      have dwo_unit "live" in that.  At least for now.
10981
10982      The DWP file can be made up of a random collection of CUs and TUs.
10983      However, for each CU + set of TUs that came from the same original DWO
10984      file, we can combine them back into a virtual DWO file to save space
10985      (fewer struct dwo_file objects to allocate).  Remember that for really
10986      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10987
10988   std::string virtual_dwo_name =
10989     string_printf ("virtual-dwo/%d-%d-%d-%d",
10990                    get_section_id (&sections.abbrev),
10991                    get_section_id (&sections.line),
10992                    get_section_id (&sections.loc),
10993                    get_section_id (&sections.str_offsets));
10994   /* Can we use an existing virtual DWO file?  */
10995   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10996   /* Create one if necessary.  */
10997   if (*dwo_file_slot == NULL)
10998     {
10999       if (dwarf_read_debug)
11000         {
11001           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11002                               virtual_dwo_name.c_str ());
11003         }
11004       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11005       dwo_file->dwo_name
11006         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11007                                         virtual_dwo_name.c_str (),
11008                                         virtual_dwo_name.size ());
11009       dwo_file->comp_dir = comp_dir;
11010       dwo_file->sections.abbrev = sections.abbrev;
11011       dwo_file->sections.line = sections.line;
11012       dwo_file->sections.loc = sections.loc;
11013       dwo_file->sections.macinfo = sections.macinfo;
11014       dwo_file->sections.macro = sections.macro;
11015       dwo_file->sections.str_offsets = sections.str_offsets;
11016       /* The "str" section is global to the entire DWP file.  */
11017       dwo_file->sections.str = dwp_file->sections.str;
11018       /* The info or types section is assigned below to dwo_unit,
11019          there's no need to record it in dwo_file.
11020          Also, we can't simply record type sections in dwo_file because
11021          we record a pointer into the vector in dwo_unit.  As we collect more
11022          types we'll grow the vector and eventually have to reallocate space
11023          for it, invalidating all copies of pointers into the previous
11024          contents.  */
11025       *dwo_file_slot = dwo_file;
11026     }
11027   else
11028     {
11029       if (dwarf_read_debug)
11030         {
11031           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11032                               virtual_dwo_name.c_str ());
11033         }
11034       dwo_file = (struct dwo_file *) *dwo_file_slot;
11035     }
11036
11037   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11038   dwo_unit->dwo_file = dwo_file;
11039   dwo_unit->signature = signature;
11040   dwo_unit->section =
11041     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11042   *dwo_unit->section = sections.info_or_types;
11043   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11044
11045   return dwo_unit;
11046 }
11047
11048 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
11049    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
11050    piece within that section used by a TU/CU, return a virtual section
11051    of just that piece.  */
11052
11053 static struct dwarf2_section_info
11054 create_dwp_v2_section (struct dwarf2_section_info *section,
11055                        bfd_size_type offset, bfd_size_type size)
11056 {
11057   struct dwarf2_section_info result;
11058   asection *sectp;
11059
11060   gdb_assert (section != NULL);
11061   gdb_assert (!section->is_virtual);
11062
11063   memset (&result, 0, sizeof (result));
11064   result.s.containing_section = section;
11065   result.is_virtual = 1;
11066
11067   if (size == 0)
11068     return result;
11069
11070   sectp = get_section_bfd_section (section);
11071
11072   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
11073      bounds of the real section.  This is a pretty-rare event, so just
11074      flag an error (easier) instead of a warning and trying to cope.  */
11075   if (sectp == NULL
11076       || offset + size > bfd_get_section_size (sectp))
11077     {
11078       bfd *abfd = sectp->owner;
11079
11080       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
11081                " in section %s [in module %s]"),
11082              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
11083              objfile_name (dwarf2_per_objfile->objfile));
11084     }
11085
11086   result.virtual_offset = offset;
11087   result.size = size;
11088   return result;
11089 }
11090
11091 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11092    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11093    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11094    This is for DWP version 2 files.  */
11095
11096 static struct dwo_unit *
11097 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
11098                            uint32_t unit_index,
11099                            const char *comp_dir,
11100                            ULONGEST signature, int is_debug_types)
11101 {
11102   struct objfile *objfile = dwarf2_per_objfile->objfile;
11103   const struct dwp_hash_table *dwp_htab =
11104     is_debug_types ? dwp_file->tus : dwp_file->cus;
11105   bfd *dbfd = dwp_file->dbfd;
11106   const char *kind = is_debug_types ? "TU" : "CU";
11107   struct dwo_file *dwo_file;
11108   struct dwo_unit *dwo_unit;
11109   struct virtual_v2_dwo_sections sections;
11110   void **dwo_file_slot;
11111   int i;
11112
11113   gdb_assert (dwp_file->version == 2);
11114
11115   if (dwarf_read_debug)
11116     {
11117       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
11118                           kind,
11119                           pulongest (unit_index), hex_string (signature),
11120                           dwp_file->name);
11121     }
11122
11123   /* Fetch the section offsets of this DWO unit.  */
11124
11125   memset (&sections, 0, sizeof (sections));
11126
11127   for (i = 0; i < dwp_htab->nr_columns; ++i)
11128     {
11129       uint32_t offset = read_4_bytes (dbfd,
11130                                       dwp_htab->section_pool.v2.offsets
11131                                       + (((unit_index - 1) * dwp_htab->nr_columns
11132                                           + i)
11133                                          * sizeof (uint32_t)));
11134       uint32_t size = read_4_bytes (dbfd,
11135                                     dwp_htab->section_pool.v2.sizes
11136                                     + (((unit_index - 1) * dwp_htab->nr_columns
11137                                         + i)
11138                                        * sizeof (uint32_t)));
11139
11140       switch (dwp_htab->section_pool.v2.section_ids[i])
11141         {
11142         case DW_SECT_INFO:
11143         case DW_SECT_TYPES:
11144           sections.info_or_types_offset = offset;
11145           sections.info_or_types_size = size;
11146           break;
11147         case DW_SECT_ABBREV:
11148           sections.abbrev_offset = offset;
11149           sections.abbrev_size = size;
11150           break;
11151         case DW_SECT_LINE:
11152           sections.line_offset = offset;
11153           sections.line_size = size;
11154           break;
11155         case DW_SECT_LOC:
11156           sections.loc_offset = offset;
11157           sections.loc_size = size;
11158           break;
11159         case DW_SECT_STR_OFFSETS:
11160           sections.str_offsets_offset = offset;
11161           sections.str_offsets_size = size;
11162           break;
11163         case DW_SECT_MACINFO:
11164           sections.macinfo_offset = offset;
11165           sections.macinfo_size = size;
11166           break;
11167         case DW_SECT_MACRO:
11168           sections.macro_offset = offset;
11169           sections.macro_size = size;
11170           break;
11171         }
11172     }
11173
11174   /* It's easier for the rest of the code if we fake a struct dwo_file and
11175      have dwo_unit "live" in that.  At least for now.
11176
11177      The DWP file can be made up of a random collection of CUs and TUs.
11178      However, for each CU + set of TUs that came from the same original DWO
11179      file, we can combine them back into a virtual DWO file to save space
11180      (fewer struct dwo_file objects to allocate).  Remember that for really
11181      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11182
11183   std::string virtual_dwo_name =
11184     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
11185                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11186                    (long) (sections.line_size ? sections.line_offset : 0),
11187                    (long) (sections.loc_size ? sections.loc_offset : 0),
11188                    (long) (sections.str_offsets_size
11189                            ? sections.str_offsets_offset : 0));
11190   /* Can we use an existing virtual DWO file?  */
11191   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
11192   /* Create one if necessary.  */
11193   if (*dwo_file_slot == NULL)
11194     {
11195       if (dwarf_read_debug)
11196         {
11197           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11198                               virtual_dwo_name.c_str ());
11199         }
11200       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11201       dwo_file->dwo_name
11202         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11203                                         virtual_dwo_name.c_str (),
11204                                         virtual_dwo_name.size ());
11205       dwo_file->comp_dir = comp_dir;
11206       dwo_file->sections.abbrev =
11207         create_dwp_v2_section (&dwp_file->sections.abbrev,
11208                                sections.abbrev_offset, sections.abbrev_size);
11209       dwo_file->sections.line =
11210         create_dwp_v2_section (&dwp_file->sections.line,
11211                                sections.line_offset, sections.line_size);
11212       dwo_file->sections.loc =
11213         create_dwp_v2_section (&dwp_file->sections.loc,
11214                                sections.loc_offset, sections.loc_size);
11215       dwo_file->sections.macinfo =
11216         create_dwp_v2_section (&dwp_file->sections.macinfo,
11217                                sections.macinfo_offset, sections.macinfo_size);
11218       dwo_file->sections.macro =
11219         create_dwp_v2_section (&dwp_file->sections.macro,
11220                                sections.macro_offset, sections.macro_size);
11221       dwo_file->sections.str_offsets =
11222         create_dwp_v2_section (&dwp_file->sections.str_offsets,
11223                                sections.str_offsets_offset,
11224                                sections.str_offsets_size);
11225       /* The "str" section is global to the entire DWP file.  */
11226       dwo_file->sections.str = dwp_file->sections.str;
11227       /* The info or types section is assigned below to dwo_unit,
11228          there's no need to record it in dwo_file.
11229          Also, we can't simply record type sections in dwo_file because
11230          we record a pointer into the vector in dwo_unit.  As we collect more
11231          types we'll grow the vector and eventually have to reallocate space
11232          for it, invalidating all copies of pointers into the previous
11233          contents.  */
11234       *dwo_file_slot = dwo_file;
11235     }
11236   else
11237     {
11238       if (dwarf_read_debug)
11239         {
11240           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11241                               virtual_dwo_name.c_str ());
11242         }
11243       dwo_file = (struct dwo_file *) *dwo_file_slot;
11244     }
11245
11246   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11247   dwo_unit->dwo_file = dwo_file;
11248   dwo_unit->signature = signature;
11249   dwo_unit->section =
11250     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11251   *dwo_unit->section = create_dwp_v2_section (is_debug_types
11252                                               ? &dwp_file->sections.types
11253                                               : &dwp_file->sections.info,
11254                                               sections.info_or_types_offset,
11255                                               sections.info_or_types_size);
11256   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11257
11258   return dwo_unit;
11259 }
11260
11261 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
11262    Returns NULL if the signature isn't found.  */
11263
11264 static struct dwo_unit *
11265 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
11266                         ULONGEST signature, int is_debug_types)
11267 {
11268   const struct dwp_hash_table *dwp_htab =
11269     is_debug_types ? dwp_file->tus : dwp_file->cus;
11270   bfd *dbfd = dwp_file->dbfd;
11271   uint32_t mask = dwp_htab->nr_slots - 1;
11272   uint32_t hash = signature & mask;
11273   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11274   unsigned int i;
11275   void **slot;
11276   struct dwo_unit find_dwo_cu;
11277
11278   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11279   find_dwo_cu.signature = signature;
11280   slot = htab_find_slot (is_debug_types
11281                          ? dwp_file->loaded_tus
11282                          : dwp_file->loaded_cus,
11283                          &find_dwo_cu, INSERT);
11284
11285   if (*slot != NULL)
11286     return (struct dwo_unit *) *slot;
11287
11288   /* Use a for loop so that we don't loop forever on bad debug info.  */
11289   for (i = 0; i < dwp_htab->nr_slots; ++i)
11290     {
11291       ULONGEST signature_in_table;
11292
11293       signature_in_table =
11294         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11295       if (signature_in_table == signature)
11296         {
11297           uint32_t unit_index =
11298             read_4_bytes (dbfd,
11299                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11300
11301           if (dwp_file->version == 1)
11302             {
11303               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
11304                                                  comp_dir, signature,
11305                                                  is_debug_types);
11306             }
11307           else
11308             {
11309               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
11310                                                  comp_dir, signature,
11311                                                  is_debug_types);
11312             }
11313           return (struct dwo_unit *) *slot;
11314         }
11315       if (signature_in_table == 0)
11316         return NULL;
11317       hash = (hash + hash2) & mask;
11318     }
11319
11320   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11321            " [in module %s]"),
11322          dwp_file->name);
11323 }
11324
11325 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11326    Open the file specified by FILE_NAME and hand it off to BFD for
11327    preliminary analysis.  Return a newly initialized bfd *, which
11328    includes a canonicalized copy of FILE_NAME.
11329    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11330    SEARCH_CWD is true if the current directory is to be searched.
11331    It will be searched before debug-file-directory.
11332    If successful, the file is added to the bfd include table of the
11333    objfile's bfd (see gdb_bfd_record_inclusion).
11334    If unable to find/open the file, return NULL.
11335    NOTE: This function is derived from symfile_bfd_open.  */
11336
11337 static gdb_bfd_ref_ptr
11338 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
11339 {
11340   int desc, flags;
11341   char *absolute_name;
11342   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
11343      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
11344      to debug_file_directory.  */
11345   char *search_path;
11346   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
11347
11348   if (search_cwd)
11349     {
11350       if (*debug_file_directory != '\0')
11351         search_path = concat (".", dirname_separator_string,
11352                               debug_file_directory, (char *) NULL);
11353       else
11354         search_path = xstrdup (".");
11355     }
11356   else
11357     search_path = xstrdup (debug_file_directory);
11358
11359   flags = OPF_RETURN_REALPATH;
11360   if (is_dwp)
11361     flags |= OPF_SEARCH_IN_PATH;
11362   desc = openp (search_path, flags, file_name,
11363                 O_RDONLY | O_BINARY, &absolute_name);
11364   xfree (search_path);
11365   if (desc < 0)
11366     return NULL;
11367
11368   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
11369   xfree (absolute_name);
11370   if (sym_bfd == NULL)
11371     return NULL;
11372   bfd_set_cacheable (sym_bfd.get (), 1);
11373
11374   if (!bfd_check_format (sym_bfd.get (), bfd_object))
11375     return NULL;
11376
11377   /* Success.  Record the bfd as having been included by the objfile's bfd.
11378      This is important because things like demangled_names_hash lives in the
11379      objfile's per_bfd space and may have references to things like symbol
11380      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
11381   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
11382
11383   return sym_bfd;
11384 }
11385
11386 /* Try to open DWO file FILE_NAME.
11387    COMP_DIR is the DW_AT_comp_dir attribute.
11388    The result is the bfd handle of the file.
11389    If there is a problem finding or opening the file, return NULL.
11390    Upon success, the canonicalized path of the file is stored in the bfd,
11391    same as symfile_bfd_open.  */
11392
11393 static gdb_bfd_ref_ptr
11394 open_dwo_file (const char *file_name, const char *comp_dir)
11395 {
11396   if (IS_ABSOLUTE_PATH (file_name))
11397     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
11398
11399   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
11400
11401   if (comp_dir != NULL)
11402     {
11403       char *path_to_try = concat (comp_dir, SLASH_STRING,
11404                                   file_name, (char *) NULL);
11405
11406       /* NOTE: If comp_dir is a relative path, this will also try the
11407          search path, which seems useful.  */
11408       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
11409                                                 1 /*search_cwd*/));
11410       xfree (path_to_try);
11411       if (abfd != NULL)
11412         return abfd;
11413     }
11414
11415   /* That didn't work, try debug-file-directory, which, despite its name,
11416      is a list of paths.  */
11417
11418   if (*debug_file_directory == '\0')
11419     return NULL;
11420
11421   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
11422 }
11423
11424 /* This function is mapped across the sections and remembers the offset and
11425    size of each of the DWO debugging sections we are interested in.  */
11426
11427 static void
11428 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
11429 {
11430   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
11431   const struct dwop_section_names *names = &dwop_section_names;
11432
11433   if (section_is_p (sectp->name, &names->abbrev_dwo))
11434     {
11435       dwo_sections->abbrev.s.section = sectp;
11436       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
11437     }
11438   else if (section_is_p (sectp->name, &names->info_dwo))
11439     {
11440       dwo_sections->info.s.section = sectp;
11441       dwo_sections->info.size = bfd_get_section_size (sectp);
11442     }
11443   else if (section_is_p (sectp->name, &names->line_dwo))
11444     {
11445       dwo_sections->line.s.section = sectp;
11446       dwo_sections->line.size = bfd_get_section_size (sectp);
11447     }
11448   else if (section_is_p (sectp->name, &names->loc_dwo))
11449     {
11450       dwo_sections->loc.s.section = sectp;
11451       dwo_sections->loc.size = bfd_get_section_size (sectp);
11452     }
11453   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11454     {
11455       dwo_sections->macinfo.s.section = sectp;
11456       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
11457     }
11458   else if (section_is_p (sectp->name, &names->macro_dwo))
11459     {
11460       dwo_sections->macro.s.section = sectp;
11461       dwo_sections->macro.size = bfd_get_section_size (sectp);
11462     }
11463   else if (section_is_p (sectp->name, &names->str_dwo))
11464     {
11465       dwo_sections->str.s.section = sectp;
11466       dwo_sections->str.size = bfd_get_section_size (sectp);
11467     }
11468   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11469     {
11470       dwo_sections->str_offsets.s.section = sectp;
11471       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
11472     }
11473   else if (section_is_p (sectp->name, &names->types_dwo))
11474     {
11475       struct dwarf2_section_info type_section;
11476
11477       memset (&type_section, 0, sizeof (type_section));
11478       type_section.s.section = sectp;
11479       type_section.size = bfd_get_section_size (sectp);
11480       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
11481                      &type_section);
11482     }
11483 }
11484
11485 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
11486    by PER_CU.  This is for the non-DWP case.
11487    The result is NULL if DWO_NAME can't be found.  */
11488
11489 static struct dwo_file *
11490 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
11491                         const char *dwo_name, const char *comp_dir)
11492 {
11493   struct objfile *objfile = dwarf2_per_objfile->objfile;
11494   struct dwo_file *dwo_file;
11495   struct cleanup *cleanups;
11496
11497   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
11498   if (dbfd == NULL)
11499     {
11500       if (dwarf_read_debug)
11501         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
11502       return NULL;
11503     }
11504   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11505   dwo_file->dwo_name = dwo_name;
11506   dwo_file->comp_dir = comp_dir;
11507   dwo_file->dbfd = dbfd.release ();
11508
11509   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
11510
11511   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
11512                          &dwo_file->sections);
11513
11514   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
11515
11516   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
11517                                  dwo_file->tus);
11518
11519   discard_cleanups (cleanups);
11520
11521   if (dwarf_read_debug)
11522     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
11523
11524   return dwo_file;
11525 }
11526
11527 /* This function is mapped across the sections and remembers the offset and
11528    size of each of the DWP debugging sections common to version 1 and 2 that
11529    we are interested in.  */
11530
11531 static void
11532 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
11533                                    void *dwp_file_ptr)
11534 {
11535   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11536   const struct dwop_section_names *names = &dwop_section_names;
11537   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11538
11539   /* Record the ELF section number for later lookup: this is what the
11540      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11541   gdb_assert (elf_section_nr < dwp_file->num_sections);
11542   dwp_file->elf_sections[elf_section_nr] = sectp;
11543
11544   /* Look for specific sections that we need.  */
11545   if (section_is_p (sectp->name, &names->str_dwo))
11546     {
11547       dwp_file->sections.str.s.section = sectp;
11548       dwp_file->sections.str.size = bfd_get_section_size (sectp);
11549     }
11550   else if (section_is_p (sectp->name, &names->cu_index))
11551     {
11552       dwp_file->sections.cu_index.s.section = sectp;
11553       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
11554     }
11555   else if (section_is_p (sectp->name, &names->tu_index))
11556     {
11557       dwp_file->sections.tu_index.s.section = sectp;
11558       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
11559     }
11560 }
11561
11562 /* This function is mapped across the sections and remembers the offset and
11563    size of each of the DWP version 2 debugging sections that we are interested
11564    in.  This is split into a separate function because we don't know if we
11565    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11566
11567 static void
11568 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11569 {
11570   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11571   const struct dwop_section_names *names = &dwop_section_names;
11572   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11573
11574   /* Record the ELF section number for later lookup: this is what the
11575      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11576   gdb_assert (elf_section_nr < dwp_file->num_sections);
11577   dwp_file->elf_sections[elf_section_nr] = sectp;
11578
11579   /* Look for specific sections that we need.  */
11580   if (section_is_p (sectp->name, &names->abbrev_dwo))
11581     {
11582       dwp_file->sections.abbrev.s.section = sectp;
11583       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11584     }
11585   else if (section_is_p (sectp->name, &names->info_dwo))
11586     {
11587       dwp_file->sections.info.s.section = sectp;
11588       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11589     }
11590   else if (section_is_p (sectp->name, &names->line_dwo))
11591     {
11592       dwp_file->sections.line.s.section = sectp;
11593       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11594     }
11595   else if (section_is_p (sectp->name, &names->loc_dwo))
11596     {
11597       dwp_file->sections.loc.s.section = sectp;
11598       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11599     }
11600   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11601     {
11602       dwp_file->sections.macinfo.s.section = sectp;
11603       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11604     }
11605   else if (section_is_p (sectp->name, &names->macro_dwo))
11606     {
11607       dwp_file->sections.macro.s.section = sectp;
11608       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11609     }
11610   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11611     {
11612       dwp_file->sections.str_offsets.s.section = sectp;
11613       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11614     }
11615   else if (section_is_p (sectp->name, &names->types_dwo))
11616     {
11617       dwp_file->sections.types.s.section = sectp;
11618       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11619     }
11620 }
11621
11622 /* Hash function for dwp_file loaded CUs/TUs.  */
11623
11624 static hashval_t
11625 hash_dwp_loaded_cutus (const void *item)
11626 {
11627   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11628
11629   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11630   return dwo_unit->signature;
11631 }
11632
11633 /* Equality function for dwp_file loaded CUs/TUs.  */
11634
11635 static int
11636 eq_dwp_loaded_cutus (const void *a, const void *b)
11637 {
11638   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11639   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11640
11641   return dua->signature == dub->signature;
11642 }
11643
11644 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11645
11646 static htab_t
11647 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11648 {
11649   return htab_create_alloc_ex (3,
11650                                hash_dwp_loaded_cutus,
11651                                eq_dwp_loaded_cutus,
11652                                NULL,
11653                                &objfile->objfile_obstack,
11654                                hashtab_obstack_allocate,
11655                                dummy_obstack_deallocate);
11656 }
11657
11658 /* Try to open DWP file FILE_NAME.
11659    The result is the bfd handle of the file.
11660    If there is a problem finding or opening the file, return NULL.
11661    Upon success, the canonicalized path of the file is stored in the bfd,
11662    same as symfile_bfd_open.  */
11663
11664 static gdb_bfd_ref_ptr
11665 open_dwp_file (const char *file_name)
11666 {
11667   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11668                                             1 /*search_cwd*/));
11669   if (abfd != NULL)
11670     return abfd;
11671
11672   /* Work around upstream bug 15652.
11673      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11674      [Whether that's a "bug" is debatable, but it is getting in our way.]
11675      We have no real idea where the dwp file is, because gdb's realpath-ing
11676      of the executable's path may have discarded the needed info.
11677      [IWBN if the dwp file name was recorded in the executable, akin to
11678      .gnu_debuglink, but that doesn't exist yet.]
11679      Strip the directory from FILE_NAME and search again.  */
11680   if (*debug_file_directory != '\0')
11681     {
11682       /* Don't implicitly search the current directory here.
11683          If the user wants to search "." to handle this case,
11684          it must be added to debug-file-directory.  */
11685       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11686                                  0 /*search_cwd*/);
11687     }
11688
11689   return NULL;
11690 }
11691
11692 /* Initialize the use of the DWP file for the current objfile.
11693    By convention the name of the DWP file is ${objfile}.dwp.
11694    The result is NULL if it can't be found.  */
11695
11696 static struct dwp_file *
11697 open_and_init_dwp_file (void)
11698 {
11699   struct objfile *objfile = dwarf2_per_objfile->objfile;
11700   struct dwp_file *dwp_file;
11701
11702   /* Try to find first .dwp for the binary file before any symbolic links
11703      resolving.  */
11704
11705   /* If the objfile is a debug file, find the name of the real binary
11706      file and get the name of dwp file from there.  */
11707   std::string dwp_name;
11708   if (objfile->separate_debug_objfile_backlink != NULL)
11709     {
11710       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11711       const char *backlink_basename = lbasename (backlink->original_name);
11712
11713       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11714     }
11715   else
11716     dwp_name = objfile->original_name;
11717
11718   dwp_name += ".dwp";
11719
11720   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11721   if (dbfd == NULL
11722       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11723     {
11724       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11725       dwp_name = objfile_name (objfile);
11726       dwp_name += ".dwp";
11727       dbfd = open_dwp_file (dwp_name.c_str ());
11728     }
11729
11730   if (dbfd == NULL)
11731     {
11732       if (dwarf_read_debug)
11733         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11734       return NULL;
11735     }
11736   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11737   dwp_file->name = bfd_get_filename (dbfd.get ());
11738   dwp_file->dbfd = dbfd.release ();
11739
11740   /* +1: section 0 is unused */
11741   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11742   dwp_file->elf_sections =
11743     OBSTACK_CALLOC (&objfile->objfile_obstack,
11744                     dwp_file->num_sections, asection *);
11745
11746   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11747                          dwp_file);
11748
11749   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11750
11751   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11752
11753   /* The DWP file version is stored in the hash table.  Oh well.  */
11754   if (dwp_file->cus && dwp_file->tus
11755       && dwp_file->cus->version != dwp_file->tus->version)
11756     {
11757       /* Technically speaking, we should try to limp along, but this is
11758          pretty bizarre.  We use pulongest here because that's the established
11759          portability solution (e.g, we cannot use %u for uint32_t).  */
11760       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11761                " TU version %s [in DWP file %s]"),
11762              pulongest (dwp_file->cus->version),
11763              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11764     }
11765
11766   if (dwp_file->cus)
11767     dwp_file->version = dwp_file->cus->version;
11768   else if (dwp_file->tus)
11769     dwp_file->version = dwp_file->tus->version;
11770   else
11771     dwp_file->version = 2;
11772
11773   if (dwp_file->version == 2)
11774     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11775                            dwp_file);
11776
11777   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11778   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11779
11780   if (dwarf_read_debug)
11781     {
11782       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11783       fprintf_unfiltered (gdb_stdlog,
11784                           "    %s CUs, %s TUs\n",
11785                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11786                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11787     }
11788
11789   return dwp_file;
11790 }
11791
11792 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11793
11794 static struct dwp_file *
11795 get_dwp_file (void)
11796 {
11797   if (! dwarf2_per_objfile->dwp_checked)
11798     {
11799       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11800       dwarf2_per_objfile->dwp_checked = 1;
11801     }
11802   return dwarf2_per_objfile->dwp_file;
11803 }
11804
11805 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11806    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11807    or in the DWP file for the objfile, referenced by THIS_UNIT.
11808    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11809    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11810
11811    This is called, for example, when wanting to read a variable with a
11812    complex location.  Therefore we don't want to do file i/o for every call.
11813    Therefore we don't want to look for a DWO file on every call.
11814    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11815    then we check if we've already seen DWO_NAME, and only THEN do we check
11816    for a DWO file.
11817
11818    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11819    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11820
11821 static struct dwo_unit *
11822 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11823                  const char *dwo_name, const char *comp_dir,
11824                  ULONGEST signature, int is_debug_types)
11825 {
11826   struct objfile *objfile = dwarf2_per_objfile->objfile;
11827   const char *kind = is_debug_types ? "TU" : "CU";
11828   void **dwo_file_slot;
11829   struct dwo_file *dwo_file;
11830   struct dwp_file *dwp_file;
11831
11832   /* First see if there's a DWP file.
11833      If we have a DWP file but didn't find the DWO inside it, don't
11834      look for the original DWO file.  It makes gdb behave differently
11835      depending on whether one is debugging in the build tree.  */
11836
11837   dwp_file = get_dwp_file ();
11838   if (dwp_file != NULL)
11839     {
11840       const struct dwp_hash_table *dwp_htab =
11841         is_debug_types ? dwp_file->tus : dwp_file->cus;
11842
11843       if (dwp_htab != NULL)
11844         {
11845           struct dwo_unit *dwo_cutu =
11846             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11847                                     signature, is_debug_types);
11848
11849           if (dwo_cutu != NULL)
11850             {
11851               if (dwarf_read_debug)
11852                 {
11853                   fprintf_unfiltered (gdb_stdlog,
11854                                       "Virtual DWO %s %s found: @%s\n",
11855                                       kind, hex_string (signature),
11856                                       host_address_to_string (dwo_cutu));
11857                 }
11858               return dwo_cutu;
11859             }
11860         }
11861     }
11862   else
11863     {
11864       /* No DWP file, look for the DWO file.  */
11865
11866       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11867       if (*dwo_file_slot == NULL)
11868         {
11869           /* Read in the file and build a table of the CUs/TUs it contains.  */
11870           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11871         }
11872       /* NOTE: This will be NULL if unable to open the file.  */
11873       dwo_file = (struct dwo_file *) *dwo_file_slot;
11874
11875       if (dwo_file != NULL)
11876         {
11877           struct dwo_unit *dwo_cutu = NULL;
11878
11879           if (is_debug_types && dwo_file->tus)
11880             {
11881               struct dwo_unit find_dwo_cutu;
11882
11883               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11884               find_dwo_cutu.signature = signature;
11885               dwo_cutu
11886                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11887             }
11888           else if (!is_debug_types && dwo_file->cus)
11889             {
11890               struct dwo_unit find_dwo_cutu;
11891
11892               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11893               find_dwo_cutu.signature = signature;
11894               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11895                                                        &find_dwo_cutu);
11896             }
11897
11898           if (dwo_cutu != NULL)
11899             {
11900               if (dwarf_read_debug)
11901                 {
11902                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11903                                       kind, dwo_name, hex_string (signature),
11904                                       host_address_to_string (dwo_cutu));
11905                 }
11906               return dwo_cutu;
11907             }
11908         }
11909     }
11910
11911   /* We didn't find it.  This could mean a dwo_id mismatch, or
11912      someone deleted the DWO/DWP file, or the search path isn't set up
11913      correctly to find the file.  */
11914
11915   if (dwarf_read_debug)
11916     {
11917       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11918                           kind, dwo_name, hex_string (signature));
11919     }
11920
11921   /* This is a warning and not a complaint because it can be caused by
11922      pilot error (e.g., user accidentally deleting the DWO).  */
11923   {
11924     /* Print the name of the DWP file if we looked there, helps the user
11925        better diagnose the problem.  */
11926     std::string dwp_text;
11927
11928     if (dwp_file != NULL)
11929       dwp_text = string_printf (" [in DWP file %s]",
11930                                 lbasename (dwp_file->name));
11931
11932     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11933                " [in module %s]"),
11934              kind, dwo_name, hex_string (signature),
11935              dwp_text.c_str (),
11936              this_unit->is_debug_types ? "TU" : "CU",
11937              to_underlying (this_unit->sect_off), objfile_name (objfile));
11938   }
11939   return NULL;
11940 }
11941
11942 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11943    See lookup_dwo_cutu_unit for details.  */
11944
11945 static struct dwo_unit *
11946 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11947                       const char *dwo_name, const char *comp_dir,
11948                       ULONGEST signature)
11949 {
11950   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11951 }
11952
11953 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11954    See lookup_dwo_cutu_unit for details.  */
11955
11956 static struct dwo_unit *
11957 lookup_dwo_type_unit (struct signatured_type *this_tu,
11958                       const char *dwo_name, const char *comp_dir)
11959 {
11960   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11961 }
11962
11963 /* Traversal function for queue_and_load_all_dwo_tus.  */
11964
11965 static int
11966 queue_and_load_dwo_tu (void **slot, void *info)
11967 {
11968   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11969   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11970   ULONGEST signature = dwo_unit->signature;
11971   struct signatured_type *sig_type =
11972     lookup_dwo_signatured_type (per_cu->cu, signature);
11973
11974   if (sig_type != NULL)
11975     {
11976       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11977
11978       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11979          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11980          while processing PER_CU.  */
11981       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11982         load_full_type_unit (sig_cu);
11983       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11984     }
11985
11986   return 1;
11987 }
11988
11989 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11990    The DWO may have the only definition of the type, though it may not be
11991    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11992    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11993
11994 static void
11995 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11996 {
11997   struct dwo_unit *dwo_unit;
11998   struct dwo_file *dwo_file;
11999
12000   gdb_assert (!per_cu->is_debug_types);
12001   gdb_assert (get_dwp_file () == NULL);
12002   gdb_assert (per_cu->cu != NULL);
12003
12004   dwo_unit = per_cu->cu->dwo_unit;
12005   gdb_assert (dwo_unit != NULL);
12006
12007   dwo_file = dwo_unit->dwo_file;
12008   if (dwo_file->tus != NULL)
12009     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
12010 }
12011
12012 /* Free all resources associated with DWO_FILE.
12013    Close the DWO file and munmap the sections.
12014    All memory should be on the objfile obstack.  */
12015
12016 static void
12017 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
12018 {
12019
12020   /* Note: dbfd is NULL for virtual DWO files.  */
12021   gdb_bfd_unref (dwo_file->dbfd);
12022
12023   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
12024 }
12025
12026 /* Wrapper for free_dwo_file for use in cleanups.  */
12027
12028 static void
12029 free_dwo_file_cleanup (void *arg)
12030 {
12031   struct dwo_file *dwo_file = (struct dwo_file *) arg;
12032   struct objfile *objfile = dwarf2_per_objfile->objfile;
12033
12034   free_dwo_file (dwo_file, objfile);
12035 }
12036
12037 /* Traversal function for free_dwo_files.  */
12038
12039 static int
12040 free_dwo_file_from_slot (void **slot, void *info)
12041 {
12042   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
12043   struct objfile *objfile = (struct objfile *) info;
12044
12045   free_dwo_file (dwo_file, objfile);
12046
12047   return 1;
12048 }
12049
12050 /* Free all resources associated with DWO_FILES.  */
12051
12052 static void
12053 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
12054 {
12055   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
12056 }
12057 \f
12058 /* Read in various DIEs.  */
12059
12060 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
12061    Inherit only the children of the DW_AT_abstract_origin DIE not being
12062    already referenced by DW_AT_abstract_origin from the children of the
12063    current DIE.  */
12064
12065 static void
12066 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
12067 {
12068   struct die_info *child_die;
12069   sect_offset *offsetp;
12070   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
12071   struct die_info *origin_die;
12072   /* Iterator of the ORIGIN_DIE children.  */
12073   struct die_info *origin_child_die;
12074   struct attribute *attr;
12075   struct dwarf2_cu *origin_cu;
12076   struct pending **origin_previous_list_in_scope;
12077
12078   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12079   if (!attr)
12080     return;
12081
12082   /* Note that following die references may follow to a die in a
12083      different cu.  */
12084
12085   origin_cu = cu;
12086   origin_die = follow_die_ref (die, attr, &origin_cu);
12087
12088   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
12089      symbols in.  */
12090   origin_previous_list_in_scope = origin_cu->list_in_scope;
12091   origin_cu->list_in_scope = cu->list_in_scope;
12092
12093   if (die->tag != origin_die->tag
12094       && !(die->tag == DW_TAG_inlined_subroutine
12095            && origin_die->tag == DW_TAG_subprogram))
12096     complaint (&symfile_complaints,
12097                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
12098                to_underlying (die->sect_off),
12099                to_underlying (origin_die->sect_off));
12100
12101   std::vector<sect_offset> offsets;
12102
12103   for (child_die = die->child;
12104        child_die && child_die->tag;
12105        child_die = sibling_die (child_die))
12106     {
12107       struct die_info *child_origin_die;
12108       struct dwarf2_cu *child_origin_cu;
12109
12110       /* We are trying to process concrete instance entries:
12111          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
12112          it's not relevant to our analysis here. i.e. detecting DIEs that are
12113          present in the abstract instance but not referenced in the concrete
12114          one.  */
12115       if (child_die->tag == DW_TAG_call_site
12116           || child_die->tag == DW_TAG_GNU_call_site)
12117         continue;
12118
12119       /* For each CHILD_DIE, find the corresponding child of
12120          ORIGIN_DIE.  If there is more than one layer of
12121          DW_AT_abstract_origin, follow them all; there shouldn't be,
12122          but GCC versions at least through 4.4 generate this (GCC PR
12123          40573).  */
12124       child_origin_die = child_die;
12125       child_origin_cu = cu;
12126       while (1)
12127         {
12128           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
12129                               child_origin_cu);
12130           if (attr == NULL)
12131             break;
12132           child_origin_die = follow_die_ref (child_origin_die, attr,
12133                                              &child_origin_cu);
12134         }
12135
12136       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
12137          counterpart may exist.  */
12138       if (child_origin_die != child_die)
12139         {
12140           if (child_die->tag != child_origin_die->tag
12141               && !(child_die->tag == DW_TAG_inlined_subroutine
12142                    && child_origin_die->tag == DW_TAG_subprogram))
12143             complaint (&symfile_complaints,
12144                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12145                          "different tags"),
12146                        to_underlying (child_die->sect_off),
12147                        to_underlying (child_origin_die->sect_off));
12148           if (child_origin_die->parent != origin_die)
12149             complaint (&symfile_complaints,
12150                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12151                          "different parents"),
12152                        to_underlying (child_die->sect_off),
12153                        to_underlying (child_origin_die->sect_off));
12154           else
12155             offsets.push_back (child_origin_die->sect_off);
12156         }
12157     }
12158   std::sort (offsets.begin (), offsets.end ());
12159   sect_offset *offsets_end = offsets.data () + offsets.size ();
12160   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
12161     if (offsetp[-1] == *offsetp)
12162       complaint (&symfile_complaints,
12163                  _("Multiple children of DIE 0x%x refer "
12164                    "to DIE 0x%x as their abstract origin"),
12165                  to_underlying (die->sect_off), to_underlying (*offsetp));
12166
12167   offsetp = offsets.data ();
12168   origin_child_die = origin_die->child;
12169   while (origin_child_die && origin_child_die->tag)
12170     {
12171       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
12172       while (offsetp < offsets_end
12173              && *offsetp < origin_child_die->sect_off)
12174         offsetp++;
12175       if (offsetp >= offsets_end
12176           || *offsetp > origin_child_die->sect_off)
12177         {
12178           /* Found that ORIGIN_CHILD_DIE is really not referenced.
12179              Check whether we're already processing ORIGIN_CHILD_DIE.
12180              This can happen with mutually referenced abstract_origins.
12181              PR 16581.  */
12182           if (!origin_child_die->in_process)
12183             process_die (origin_child_die, origin_cu);
12184         }
12185       origin_child_die = sibling_die (origin_child_die);
12186     }
12187   origin_cu->list_in_scope = origin_previous_list_in_scope;
12188 }
12189
12190 static void
12191 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
12192 {
12193   struct objfile *objfile = cu->objfile;
12194   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12195   struct context_stack *newobj;
12196   CORE_ADDR lowpc;
12197   CORE_ADDR highpc;
12198   struct die_info *child_die;
12199   struct attribute *attr, *call_line, *call_file;
12200   const char *name;
12201   CORE_ADDR baseaddr;
12202   struct block *block;
12203   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
12204   std::vector<struct symbol *> template_args;
12205   struct template_symbol *templ_func = NULL;
12206
12207   if (inlined_func)
12208     {
12209       /* If we do not have call site information, we can't show the
12210          caller of this inlined function.  That's too confusing, so
12211          only use the scope for local variables.  */
12212       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
12213       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
12214       if (call_line == NULL || call_file == NULL)
12215         {
12216           read_lexical_block_scope (die, cu);
12217           return;
12218         }
12219     }
12220
12221   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12222
12223   name = dwarf2_name (die, cu);
12224
12225   /* Ignore functions with missing or empty names.  These are actually
12226      illegal according to the DWARF standard.  */
12227   if (name == NULL)
12228     {
12229       complaint (&symfile_complaints,
12230                  _("missing name for subprogram DIE at %d"),
12231                  to_underlying (die->sect_off));
12232       return;
12233     }
12234
12235   /* Ignore functions with missing or invalid low and high pc attributes.  */
12236   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
12237       <= PC_BOUNDS_INVALID)
12238     {
12239       attr = dwarf2_attr (die, DW_AT_external, cu);
12240       if (!attr || !DW_UNSND (attr))
12241         complaint (&symfile_complaints,
12242                    _("cannot get low and high bounds "
12243                      "for subprogram DIE at %d"),
12244                    to_underlying (die->sect_off));
12245       return;
12246     }
12247
12248   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12249   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12250
12251   /* If we have any template arguments, then we must allocate a
12252      different sort of symbol.  */
12253   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
12254     {
12255       if (child_die->tag == DW_TAG_template_type_param
12256           || child_die->tag == DW_TAG_template_value_param)
12257         {
12258           templ_func = allocate_template_symbol (objfile);
12259           templ_func->base.is_cplus_template_function = 1;
12260           break;
12261         }
12262     }
12263
12264   newobj = push_context (0, lowpc);
12265   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
12266                                (struct symbol *) templ_func);
12267
12268   /* If there is a location expression for DW_AT_frame_base, record
12269      it.  */
12270   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
12271   if (attr)
12272     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
12273
12274   /* If there is a location for the static link, record it.  */
12275   newobj->static_link = NULL;
12276   attr = dwarf2_attr (die, DW_AT_static_link, cu);
12277   if (attr)
12278     {
12279       newobj->static_link
12280         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
12281       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
12282     }
12283
12284   cu->list_in_scope = &local_symbols;
12285
12286   if (die->child != NULL)
12287     {
12288       child_die = die->child;
12289       while (child_die && child_die->tag)
12290         {
12291           if (child_die->tag == DW_TAG_template_type_param
12292               || child_die->tag == DW_TAG_template_value_param)
12293             {
12294               struct symbol *arg = new_symbol (child_die, NULL, cu);
12295
12296               if (arg != NULL)
12297                 template_args.push_back (arg);
12298             }
12299           else
12300             process_die (child_die, cu);
12301           child_die = sibling_die (child_die);
12302         }
12303     }
12304
12305   inherit_abstract_dies (die, cu);
12306
12307   /* If we have a DW_AT_specification, we might need to import using
12308      directives from the context of the specification DIE.  See the
12309      comment in determine_prefix.  */
12310   if (cu->language == language_cplus
12311       && dwarf2_attr (die, DW_AT_specification, cu))
12312     {
12313       struct dwarf2_cu *spec_cu = cu;
12314       struct die_info *spec_die = die_specification (die, &spec_cu);
12315
12316       while (spec_die)
12317         {
12318           child_die = spec_die->child;
12319           while (child_die && child_die->tag)
12320             {
12321               if (child_die->tag == DW_TAG_imported_module)
12322                 process_die (child_die, spec_cu);
12323               child_die = sibling_die (child_die);
12324             }
12325
12326           /* In some cases, GCC generates specification DIEs that
12327              themselves contain DW_AT_specification attributes.  */
12328           spec_die = die_specification (spec_die, &spec_cu);
12329         }
12330     }
12331
12332   newobj = pop_context ();
12333   /* Make a block for the local symbols within.  */
12334   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
12335                         newobj->static_link, lowpc, highpc);
12336
12337   /* For C++, set the block's scope.  */
12338   if ((cu->language == language_cplus
12339        || cu->language == language_fortran
12340        || cu->language == language_d
12341        || cu->language == language_rust)
12342       && cu->processing_has_namespace_info)
12343     block_set_scope (block, determine_prefix (die, cu),
12344                      &objfile->objfile_obstack);
12345
12346   /* If we have address ranges, record them.  */
12347   dwarf2_record_block_ranges (die, block, baseaddr, cu);
12348
12349   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
12350
12351   /* Attach template arguments to function.  */
12352   if (!template_args.empty ())
12353     {
12354       gdb_assert (templ_func != NULL);
12355
12356       templ_func->n_template_arguments = template_args.size ();
12357       templ_func->template_arguments
12358         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
12359                      templ_func->n_template_arguments);
12360       memcpy (templ_func->template_arguments,
12361               template_args.data (),
12362               (templ_func->n_template_arguments * sizeof (struct symbol *)));
12363     }
12364
12365   /* In C++, we can have functions nested inside functions (e.g., when
12366      a function declares a class that has methods).  This means that
12367      when we finish processing a function scope, we may need to go
12368      back to building a containing block's symbol lists.  */
12369   local_symbols = newobj->locals;
12370   local_using_directives = newobj->local_using_directives;
12371
12372   /* If we've finished processing a top-level function, subsequent
12373      symbols go in the file symbol list.  */
12374   if (outermost_context_p ())
12375     cu->list_in_scope = &file_symbols;
12376 }
12377
12378 /* Process all the DIES contained within a lexical block scope.  Start
12379    a new scope, process the dies, and then close the scope.  */
12380
12381 static void
12382 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
12383 {
12384   struct objfile *objfile = cu->objfile;
12385   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12386   struct context_stack *newobj;
12387   CORE_ADDR lowpc, highpc;
12388   struct die_info *child_die;
12389   CORE_ADDR baseaddr;
12390
12391   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12392
12393   /* Ignore blocks with missing or invalid low and high pc attributes.  */
12394   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
12395      as multiple lexical blocks?  Handling children in a sane way would
12396      be nasty.  Might be easier to properly extend generic blocks to
12397      describe ranges.  */
12398   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
12399     {
12400     case PC_BOUNDS_NOT_PRESENT:
12401       /* DW_TAG_lexical_block has no attributes, process its children as if
12402          there was no wrapping by that DW_TAG_lexical_block.
12403          GCC does no longer produces such DWARF since GCC r224161.  */
12404       for (child_die = die->child;
12405            child_die != NULL && child_die->tag;
12406            child_die = sibling_die (child_die))
12407         process_die (child_die, cu);
12408       return;
12409     case PC_BOUNDS_INVALID:
12410       return;
12411     }
12412   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12413   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12414
12415   push_context (0, lowpc);
12416   if (die->child != NULL)
12417     {
12418       child_die = die->child;
12419       while (child_die && child_die->tag)
12420         {
12421           process_die (child_die, cu);
12422           child_die = sibling_die (child_die);
12423         }
12424     }
12425   inherit_abstract_dies (die, cu);
12426   newobj = pop_context ();
12427
12428   if (local_symbols != NULL || local_using_directives != NULL)
12429     {
12430       struct block *block
12431         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
12432                         newobj->start_addr, highpc);
12433
12434       /* Note that recording ranges after traversing children, as we
12435          do here, means that recording a parent's ranges entails
12436          walking across all its children's ranges as they appear in
12437          the address map, which is quadratic behavior.
12438
12439          It would be nicer to record the parent's ranges before
12440          traversing its children, simply overriding whatever you find
12441          there.  But since we don't even decide whether to create a
12442          block until after we've traversed its children, that's hard
12443          to do.  */
12444       dwarf2_record_block_ranges (die, block, baseaddr, cu);
12445     }
12446   local_symbols = newobj->locals;
12447   local_using_directives = newobj->local_using_directives;
12448 }
12449
12450 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
12451
12452 static void
12453 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
12454 {
12455   struct objfile *objfile = cu->objfile;
12456   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12457   CORE_ADDR pc, baseaddr;
12458   struct attribute *attr;
12459   struct call_site *call_site, call_site_local;
12460   void **slot;
12461   int nparams;
12462   struct die_info *child_die;
12463
12464   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12465
12466   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
12467   if (attr == NULL)
12468     {
12469       /* This was a pre-DWARF-5 GNU extension alias
12470          for DW_AT_call_return_pc.  */
12471       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12472     }
12473   if (!attr)
12474     {
12475       complaint (&symfile_complaints,
12476                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
12477                    "DIE 0x%x [in module %s]"),
12478                  to_underlying (die->sect_off), objfile_name (objfile));
12479       return;
12480     }
12481   pc = attr_value_as_address (attr) + baseaddr;
12482   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
12483
12484   if (cu->call_site_htab == NULL)
12485     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
12486                                                NULL, &objfile->objfile_obstack,
12487                                                hashtab_obstack_allocate, NULL);
12488   call_site_local.pc = pc;
12489   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
12490   if (*slot != NULL)
12491     {
12492       complaint (&symfile_complaints,
12493                  _("Duplicate PC %s for DW_TAG_call_site "
12494                    "DIE 0x%x [in module %s]"),
12495                  paddress (gdbarch, pc), to_underlying (die->sect_off),
12496                  objfile_name (objfile));
12497       return;
12498     }
12499
12500   /* Count parameters at the caller.  */
12501
12502   nparams = 0;
12503   for (child_die = die->child; child_die && child_die->tag;
12504        child_die = sibling_die (child_die))
12505     {
12506       if (child_die->tag != DW_TAG_call_site_parameter
12507           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12508         {
12509           complaint (&symfile_complaints,
12510                      _("Tag %d is not DW_TAG_call_site_parameter in "
12511                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12512                      child_die->tag, to_underlying (child_die->sect_off),
12513                      objfile_name (objfile));
12514           continue;
12515         }
12516
12517       nparams++;
12518     }
12519
12520   call_site
12521     = ((struct call_site *)
12522        obstack_alloc (&objfile->objfile_obstack,
12523                       sizeof (*call_site)
12524                       + (sizeof (*call_site->parameter) * (nparams - 1))));
12525   *slot = call_site;
12526   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
12527   call_site->pc = pc;
12528
12529   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
12530       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
12531     {
12532       struct die_info *func_die;
12533
12534       /* Skip also over DW_TAG_inlined_subroutine.  */
12535       for (func_die = die->parent;
12536            func_die && func_die->tag != DW_TAG_subprogram
12537            && func_die->tag != DW_TAG_subroutine_type;
12538            func_die = func_die->parent);
12539
12540       /* DW_AT_call_all_calls is a superset
12541          of DW_AT_call_all_tail_calls.  */
12542       if (func_die
12543           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12544           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12545           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12546           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12547         {
12548           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12549              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12550              both the initial caller containing the real return address PC and
12551              the final callee containing the current PC of a chain of tail
12552              calls do not need to have the tail call list complete.  But any
12553              function candidate for a virtual tail call frame searched via
12554              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12555              determined unambiguously.  */
12556         }
12557       else
12558         {
12559           struct type *func_type = NULL;
12560
12561           if (func_die)
12562             func_type = get_die_type (func_die, cu);
12563           if (func_type != NULL)
12564             {
12565               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12566
12567               /* Enlist this call site to the function.  */
12568               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12569               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12570             }
12571           else
12572             complaint (&symfile_complaints,
12573                        _("Cannot find function owning DW_TAG_call_site "
12574                          "DIE 0x%x [in module %s]"),
12575                        to_underlying (die->sect_off), objfile_name (objfile));
12576         }
12577     }
12578
12579   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12580   if (attr == NULL)
12581     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12582   if (attr == NULL)
12583     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12584   if (attr == NULL)
12585     {
12586       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12587       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12588     }
12589   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12590   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12591     /* Keep NULL DWARF_BLOCK.  */;
12592   else if (attr_form_is_block (attr))
12593     {
12594       struct dwarf2_locexpr_baton *dlbaton;
12595
12596       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12597       dlbaton->data = DW_BLOCK (attr)->data;
12598       dlbaton->size = DW_BLOCK (attr)->size;
12599       dlbaton->per_cu = cu->per_cu;
12600
12601       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12602     }
12603   else if (attr_form_is_ref (attr))
12604     {
12605       struct dwarf2_cu *target_cu = cu;
12606       struct die_info *target_die;
12607
12608       target_die = follow_die_ref (die, attr, &target_cu);
12609       gdb_assert (target_cu->objfile == objfile);
12610       if (die_is_declaration (target_die, target_cu))
12611         {
12612           const char *target_physname;
12613
12614           /* Prefer the mangled name; otherwise compute the demangled one.  */
12615           target_physname = dw2_linkage_name (target_die, target_cu);
12616           if (target_physname == NULL)
12617             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12618           if (target_physname == NULL)
12619             complaint (&symfile_complaints,
12620                        _("DW_AT_call_target target DIE has invalid "
12621                          "physname, for referencing DIE 0x%x [in module %s]"),
12622                        to_underlying (die->sect_off), objfile_name (objfile));
12623           else
12624             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12625         }
12626       else
12627         {
12628           CORE_ADDR lowpc;
12629
12630           /* DW_AT_entry_pc should be preferred.  */
12631           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12632               <= PC_BOUNDS_INVALID)
12633             complaint (&symfile_complaints,
12634                        _("DW_AT_call_target target DIE has invalid "
12635                          "low pc, for referencing DIE 0x%x [in module %s]"),
12636                        to_underlying (die->sect_off), objfile_name (objfile));
12637           else
12638             {
12639               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12640               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12641             }
12642         }
12643     }
12644   else
12645     complaint (&symfile_complaints,
12646                _("DW_TAG_call_site DW_AT_call_target is neither "
12647                  "block nor reference, for DIE 0x%x [in module %s]"),
12648                to_underlying (die->sect_off), objfile_name (objfile));
12649
12650   call_site->per_cu = cu->per_cu;
12651
12652   for (child_die = die->child;
12653        child_die && child_die->tag;
12654        child_die = sibling_die (child_die))
12655     {
12656       struct call_site_parameter *parameter;
12657       struct attribute *loc, *origin;
12658
12659       if (child_die->tag != DW_TAG_call_site_parameter
12660           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12661         {
12662           /* Already printed the complaint above.  */
12663           continue;
12664         }
12665
12666       gdb_assert (call_site->parameter_count < nparams);
12667       parameter = &call_site->parameter[call_site->parameter_count];
12668
12669       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12670          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12671          register is contained in DW_AT_call_value.  */
12672
12673       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12674       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12675       if (origin == NULL)
12676         {
12677           /* This was a pre-DWARF-5 GNU extension alias
12678              for DW_AT_call_parameter.  */
12679           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12680         }
12681       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12682         {
12683           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12684
12685           sect_offset sect_off
12686             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12687           if (!offset_in_cu_p (&cu->header, sect_off))
12688             {
12689               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12690                  binding can be done only inside one CU.  Such referenced DIE
12691                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12692               complaint (&symfile_complaints,
12693                          _("DW_AT_call_parameter offset is not in CU for "
12694                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12695                          to_underlying (child_die->sect_off),
12696                          objfile_name (objfile));
12697               continue;
12698             }
12699           parameter->u.param_cu_off
12700             = (cu_offset) (sect_off - cu->header.sect_off);
12701         }
12702       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12703         {
12704           complaint (&symfile_complaints,
12705                      _("No DW_FORM_block* DW_AT_location for "
12706                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12707                      to_underlying (child_die->sect_off), objfile_name (objfile));
12708           continue;
12709         }
12710       else
12711         {
12712           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12713             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12714           if (parameter->u.dwarf_reg != -1)
12715             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12716           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12717                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12718                                              &parameter->u.fb_offset))
12719             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12720           else
12721             {
12722               complaint (&symfile_complaints,
12723                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12724                            "for DW_FORM_block* DW_AT_location is supported for "
12725                            "DW_TAG_call_site child DIE 0x%x "
12726                            "[in module %s]"),
12727                          to_underlying (child_die->sect_off),
12728                          objfile_name (objfile));
12729               continue;
12730             }
12731         }
12732
12733       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12734       if (attr == NULL)
12735         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12736       if (!attr_form_is_block (attr))
12737         {
12738           complaint (&symfile_complaints,
12739                      _("No DW_FORM_block* DW_AT_call_value for "
12740                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12741                      to_underlying (child_die->sect_off),
12742                      objfile_name (objfile));
12743           continue;
12744         }
12745       parameter->value = DW_BLOCK (attr)->data;
12746       parameter->value_size = DW_BLOCK (attr)->size;
12747
12748       /* Parameters are not pre-cleared by memset above.  */
12749       parameter->data_value = NULL;
12750       parameter->data_value_size = 0;
12751       call_site->parameter_count++;
12752
12753       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12754       if (attr == NULL)
12755         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12756       if (attr)
12757         {
12758           if (!attr_form_is_block (attr))
12759             complaint (&symfile_complaints,
12760                        _("No DW_FORM_block* DW_AT_call_data_value for "
12761                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12762                        to_underlying (child_die->sect_off),
12763                        objfile_name (objfile));
12764           else
12765             {
12766               parameter->data_value = DW_BLOCK (attr)->data;
12767               parameter->data_value_size = DW_BLOCK (attr)->size;
12768             }
12769         }
12770     }
12771 }
12772
12773 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12774    reading .debug_rnglists.
12775    Callback's type should be:
12776     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12777    Return true if the attributes are present and valid, otherwise,
12778    return false.  */
12779
12780 template <typename Callback>
12781 static bool
12782 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12783                          Callback &&callback)
12784 {
12785   struct objfile *objfile = cu->objfile;
12786   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12787   struct comp_unit_head *cu_header = &cu->header;
12788   bfd *obfd = objfile->obfd;
12789   unsigned int addr_size = cu_header->addr_size;
12790   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12791   /* Base address selection entry.  */
12792   CORE_ADDR base;
12793   int found_base;
12794   unsigned int dummy;
12795   const gdb_byte *buffer;
12796   CORE_ADDR low = 0;
12797   CORE_ADDR high = 0;
12798   CORE_ADDR baseaddr;
12799   bool overflow = false;
12800
12801   found_base = cu->base_known;
12802   base = cu->base_address;
12803
12804   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12805   if (offset >= dwarf2_per_objfile->rnglists.size)
12806     {
12807       complaint (&symfile_complaints,
12808                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12809                  offset);
12810       return false;
12811     }
12812   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12813
12814   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12815
12816   while (1)
12817     {
12818       /* Initialize it due to a false compiler warning.  */
12819       CORE_ADDR range_beginning = 0, range_end = 0;
12820       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12821                                  + dwarf2_per_objfile->rnglists.size);
12822       unsigned int bytes_read;
12823
12824       if (buffer == buf_end)
12825         {
12826           overflow = true;
12827           break;
12828         }
12829       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12830       switch (rlet)
12831         {
12832         case DW_RLE_end_of_list:
12833           break;
12834         case DW_RLE_base_address:
12835           if (buffer + cu->header.addr_size > buf_end)
12836             {
12837               overflow = true;
12838               break;
12839             }
12840           base = read_address (obfd, buffer, cu, &bytes_read);
12841           found_base = 1;
12842           buffer += bytes_read;
12843           break;
12844         case DW_RLE_start_length:
12845           if (buffer + cu->header.addr_size > buf_end)
12846             {
12847               overflow = true;
12848               break;
12849             }
12850           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12851           buffer += bytes_read;
12852           range_end = (range_beginning
12853                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12854           buffer += bytes_read;
12855           if (buffer > buf_end)
12856             {
12857               overflow = true;
12858               break;
12859             }
12860           break;
12861         case DW_RLE_offset_pair:
12862           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12863           buffer += bytes_read;
12864           if (buffer > buf_end)
12865             {
12866               overflow = true;
12867               break;
12868             }
12869           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12870           buffer += bytes_read;
12871           if (buffer > buf_end)
12872             {
12873               overflow = true;
12874               break;
12875             }
12876           break;
12877         case DW_RLE_start_end:
12878           if (buffer + 2 * cu->header.addr_size > buf_end)
12879             {
12880               overflow = true;
12881               break;
12882             }
12883           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12884           buffer += bytes_read;
12885           range_end = read_address (obfd, buffer, cu, &bytes_read);
12886           buffer += bytes_read;
12887           break;
12888         default:
12889           complaint (&symfile_complaints,
12890                      _("Invalid .debug_rnglists data (no base address)"));
12891           return false;
12892         }
12893       if (rlet == DW_RLE_end_of_list || overflow)
12894         break;
12895       if (rlet == DW_RLE_base_address)
12896         continue;
12897
12898       if (!found_base)
12899         {
12900           /* We have no valid base address for the ranges
12901              data.  */
12902           complaint (&symfile_complaints,
12903                      _("Invalid .debug_rnglists data (no base address)"));
12904           return false;
12905         }
12906
12907       if (range_beginning > range_end)
12908         {
12909           /* Inverted range entries are invalid.  */
12910           complaint (&symfile_complaints,
12911                      _("Invalid .debug_rnglists data (inverted range)"));
12912           return false;
12913         }
12914
12915       /* Empty range entries have no effect.  */
12916       if (range_beginning == range_end)
12917         continue;
12918
12919       range_beginning += base;
12920       range_end += base;
12921
12922       /* A not-uncommon case of bad debug info.
12923          Don't pollute the addrmap with bad data.  */
12924       if (range_beginning + baseaddr == 0
12925           && !dwarf2_per_objfile->has_section_at_zero)
12926         {
12927           complaint (&symfile_complaints,
12928                      _(".debug_rnglists entry has start address of zero"
12929                        " [in module %s]"), objfile_name (objfile));
12930           continue;
12931         }
12932
12933       callback (range_beginning, range_end);
12934     }
12935
12936   if (overflow)
12937     {
12938       complaint (&symfile_complaints,
12939                  _("Offset %d is not terminated "
12940                    "for DW_AT_ranges attribute"),
12941                  offset);
12942       return false;
12943     }
12944
12945   return true;
12946 }
12947
12948 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12949    Callback's type should be:
12950     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12951    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12952
12953 template <typename Callback>
12954 static int
12955 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12956                        Callback &&callback)
12957 {
12958   struct objfile *objfile = cu->objfile;
12959   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12960   struct comp_unit_head *cu_header = &cu->header;
12961   bfd *obfd = objfile->obfd;
12962   unsigned int addr_size = cu_header->addr_size;
12963   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12964   /* Base address selection entry.  */
12965   CORE_ADDR base;
12966   int found_base;
12967   unsigned int dummy;
12968   const gdb_byte *buffer;
12969   CORE_ADDR baseaddr;
12970
12971   if (cu_header->version >= 5)
12972     return dwarf2_rnglists_process (offset, cu, callback);
12973
12974   found_base = cu->base_known;
12975   base = cu->base_address;
12976
12977   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12978   if (offset >= dwarf2_per_objfile->ranges.size)
12979     {
12980       complaint (&symfile_complaints,
12981                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12982                  offset);
12983       return 0;
12984     }
12985   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12986
12987   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12988
12989   while (1)
12990     {
12991       CORE_ADDR range_beginning, range_end;
12992
12993       range_beginning = read_address (obfd, buffer, cu, &dummy);
12994       buffer += addr_size;
12995       range_end = read_address (obfd, buffer, cu, &dummy);
12996       buffer += addr_size;
12997       offset += 2 * addr_size;
12998
12999       /* An end of list marker is a pair of zero addresses.  */
13000       if (range_beginning == 0 && range_end == 0)
13001         /* Found the end of list entry.  */
13002         break;
13003
13004       /* Each base address selection entry is a pair of 2 values.
13005          The first is the largest possible address, the second is
13006          the base address.  Check for a base address here.  */
13007       if ((range_beginning & mask) == mask)
13008         {
13009           /* If we found the largest possible address, then we already
13010              have the base address in range_end.  */
13011           base = range_end;
13012           found_base = 1;
13013           continue;
13014         }
13015
13016       if (!found_base)
13017         {
13018           /* We have no valid base address for the ranges
13019              data.  */
13020           complaint (&symfile_complaints,
13021                      _("Invalid .debug_ranges data (no base address)"));
13022           return 0;
13023         }
13024
13025       if (range_beginning > range_end)
13026         {
13027           /* Inverted range entries are invalid.  */
13028           complaint (&symfile_complaints,
13029                      _("Invalid .debug_ranges data (inverted range)"));
13030           return 0;
13031         }
13032
13033       /* Empty range entries have no effect.  */
13034       if (range_beginning == range_end)
13035         continue;
13036
13037       range_beginning += base;
13038       range_end += base;
13039
13040       /* A not-uncommon case of bad debug info.
13041          Don't pollute the addrmap with bad data.  */
13042       if (range_beginning + baseaddr == 0
13043           && !dwarf2_per_objfile->has_section_at_zero)
13044         {
13045           complaint (&symfile_complaints,
13046                      _(".debug_ranges entry has start address of zero"
13047                        " [in module %s]"), objfile_name (objfile));
13048           continue;
13049         }
13050
13051       callback (range_beginning, range_end);
13052     }
13053
13054   return 1;
13055 }
13056
13057 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
13058    Return 1 if the attributes are present and valid, otherwise, return 0.
13059    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
13060
13061 static int
13062 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
13063                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
13064                     struct partial_symtab *ranges_pst)
13065 {
13066   struct objfile *objfile = cu->objfile;
13067   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13068   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
13069                                        SECT_OFF_TEXT (objfile));
13070   int low_set = 0;
13071   CORE_ADDR low = 0;
13072   CORE_ADDR high = 0;
13073   int retval;
13074
13075   retval = dwarf2_ranges_process (offset, cu,
13076     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
13077     {
13078       if (ranges_pst != NULL)
13079         {
13080           CORE_ADDR lowpc;
13081           CORE_ADDR highpc;
13082
13083           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13084                                               range_beginning + baseaddr);
13085           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13086                                                range_end + baseaddr);
13087           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
13088                              ranges_pst);
13089         }
13090
13091       /* FIXME: This is recording everything as a low-high
13092          segment of consecutive addresses.  We should have a
13093          data structure for discontiguous block ranges
13094          instead.  */
13095       if (! low_set)
13096         {
13097           low = range_beginning;
13098           high = range_end;
13099           low_set = 1;
13100         }
13101       else
13102         {
13103           if (range_beginning < low)
13104             low = range_beginning;
13105           if (range_end > high)
13106             high = range_end;
13107         }
13108     });
13109   if (!retval)
13110     return 0;
13111
13112   if (! low_set)
13113     /* If the first entry is an end-of-list marker, the range
13114        describes an empty scope, i.e. no instructions.  */
13115     return 0;
13116
13117   if (low_return)
13118     *low_return = low;
13119   if (high_return)
13120     *high_return = high;
13121   return 1;
13122 }
13123
13124 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
13125    definition for the return value.  *LOWPC and *HIGHPC are set iff
13126    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
13127
13128 static enum pc_bounds_kind
13129 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
13130                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
13131                       struct partial_symtab *pst)
13132 {
13133   struct attribute *attr;
13134   struct attribute *attr_high;
13135   CORE_ADDR low = 0;
13136   CORE_ADDR high = 0;
13137   enum pc_bounds_kind ret;
13138
13139   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13140   if (attr_high)
13141     {
13142       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13143       if (attr)
13144         {
13145           low = attr_value_as_address (attr);
13146           high = attr_value_as_address (attr_high);
13147           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13148             high += low;
13149         }
13150       else
13151         /* Found high w/o low attribute.  */
13152         return PC_BOUNDS_INVALID;
13153
13154       /* Found consecutive range of addresses.  */
13155       ret = PC_BOUNDS_HIGH_LOW;
13156     }
13157   else
13158     {
13159       attr = dwarf2_attr (die, DW_AT_ranges, cu);
13160       if (attr != NULL)
13161         {
13162           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13163              We take advantage of the fact that DW_AT_ranges does not appear
13164              in DW_TAG_compile_unit of DWO files.  */
13165           int need_ranges_base = die->tag != DW_TAG_compile_unit;
13166           unsigned int ranges_offset = (DW_UNSND (attr)
13167                                         + (need_ranges_base
13168                                            ? cu->ranges_base
13169                                            : 0));
13170
13171           /* Value of the DW_AT_ranges attribute is the offset in the
13172              .debug_ranges section.  */
13173           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
13174             return PC_BOUNDS_INVALID;
13175           /* Found discontinuous range of addresses.  */
13176           ret = PC_BOUNDS_RANGES;
13177         }
13178       else
13179         return PC_BOUNDS_NOT_PRESENT;
13180     }
13181
13182   /* read_partial_die has also the strict LOW < HIGH requirement.  */
13183   if (high <= low)
13184     return PC_BOUNDS_INVALID;
13185
13186   /* When using the GNU linker, .gnu.linkonce. sections are used to
13187      eliminate duplicate copies of functions and vtables and such.
13188      The linker will arbitrarily choose one and discard the others.
13189      The AT_*_pc values for such functions refer to local labels in
13190      these sections.  If the section from that file was discarded, the
13191      labels are not in the output, so the relocs get a value of 0.
13192      If this is a discarded function, mark the pc bounds as invalid,
13193      so that GDB will ignore it.  */
13194   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
13195     return PC_BOUNDS_INVALID;
13196
13197   *lowpc = low;
13198   if (highpc)
13199     *highpc = high;
13200   return ret;
13201 }
13202
13203 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
13204    its low and high PC addresses.  Do nothing if these addresses could not
13205    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
13206    and HIGHPC to the high address if greater than HIGHPC.  */
13207
13208 static void
13209 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
13210                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
13211                                  struct dwarf2_cu *cu)
13212 {
13213   CORE_ADDR low, high;
13214   struct die_info *child = die->child;
13215
13216   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
13217     {
13218       *lowpc = std::min (*lowpc, low);
13219       *highpc = std::max (*highpc, high);
13220     }
13221
13222   /* If the language does not allow nested subprograms (either inside
13223      subprograms or lexical blocks), we're done.  */
13224   if (cu->language != language_ada)
13225     return;
13226
13227   /* Check all the children of the given DIE.  If it contains nested
13228      subprograms, then check their pc bounds.  Likewise, we need to
13229      check lexical blocks as well, as they may also contain subprogram
13230      definitions.  */
13231   while (child && child->tag)
13232     {
13233       if (child->tag == DW_TAG_subprogram
13234           || child->tag == DW_TAG_lexical_block)
13235         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
13236       child = sibling_die (child);
13237     }
13238 }
13239
13240 /* Get the low and high pc's represented by the scope DIE, and store
13241    them in *LOWPC and *HIGHPC.  If the correct values can't be
13242    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
13243
13244 static void
13245 get_scope_pc_bounds (struct die_info *die,
13246                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
13247                      struct dwarf2_cu *cu)
13248 {
13249   CORE_ADDR best_low = (CORE_ADDR) -1;
13250   CORE_ADDR best_high = (CORE_ADDR) 0;
13251   CORE_ADDR current_low, current_high;
13252
13253   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
13254       >= PC_BOUNDS_RANGES)
13255     {
13256       best_low = current_low;
13257       best_high = current_high;
13258     }
13259   else
13260     {
13261       struct die_info *child = die->child;
13262
13263       while (child && child->tag)
13264         {
13265           switch (child->tag) {
13266           case DW_TAG_subprogram:
13267             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
13268             break;
13269           case DW_TAG_namespace:
13270           case DW_TAG_module:
13271             /* FIXME: carlton/2004-01-16: Should we do this for
13272                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
13273                that current GCC's always emit the DIEs corresponding
13274                to definitions of methods of classes as children of a
13275                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
13276                the DIEs giving the declarations, which could be
13277                anywhere).  But I don't see any reason why the
13278                standards says that they have to be there.  */
13279             get_scope_pc_bounds (child, &current_low, &current_high, cu);
13280
13281             if (current_low != ((CORE_ADDR) -1))
13282               {
13283                 best_low = std::min (best_low, current_low);
13284                 best_high = std::max (best_high, current_high);
13285               }
13286             break;
13287           default:
13288             /* Ignore.  */
13289             break;
13290           }
13291
13292           child = sibling_die (child);
13293         }
13294     }
13295
13296   *lowpc = best_low;
13297   *highpc = best_high;
13298 }
13299
13300 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
13301    in DIE.  */
13302
13303 static void
13304 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
13305                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
13306 {
13307   struct objfile *objfile = cu->objfile;
13308   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13309   struct attribute *attr;
13310   struct attribute *attr_high;
13311
13312   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13313   if (attr_high)
13314     {
13315       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13316       if (attr)
13317         {
13318           CORE_ADDR low = attr_value_as_address (attr);
13319           CORE_ADDR high = attr_value_as_address (attr_high);
13320
13321           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13322             high += low;
13323
13324           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
13325           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
13326           record_block_range (block, low, high - 1);
13327         }
13328     }
13329
13330   attr = dwarf2_attr (die, DW_AT_ranges, cu);
13331   if (attr)
13332     {
13333       bfd *obfd = objfile->obfd;
13334       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13335          We take advantage of the fact that DW_AT_ranges does not appear
13336          in DW_TAG_compile_unit of DWO files.  */
13337       int need_ranges_base = die->tag != DW_TAG_compile_unit;
13338
13339       /* The value of the DW_AT_ranges attribute is the offset of the
13340          address range list in the .debug_ranges section.  */
13341       unsigned long offset = (DW_UNSND (attr)
13342                               + (need_ranges_base ? cu->ranges_base : 0));
13343       const gdb_byte *buffer;
13344
13345       /* For some target architectures, but not others, the
13346          read_address function sign-extends the addresses it returns.
13347          To recognize base address selection entries, we need a
13348          mask.  */
13349       unsigned int addr_size = cu->header.addr_size;
13350       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13351
13352       /* The base address, to which the next pair is relative.  Note
13353          that this 'base' is a DWARF concept: most entries in a range
13354          list are relative, to reduce the number of relocs against the
13355          debugging information.  This is separate from this function's
13356          'baseaddr' argument, which GDB uses to relocate debugging
13357          information from a shared library based on the address at
13358          which the library was loaded.  */
13359       CORE_ADDR base = cu->base_address;
13360       int base_known = cu->base_known;
13361
13362       dwarf2_ranges_process (offset, cu,
13363         [&] (CORE_ADDR start, CORE_ADDR end)
13364         {
13365           start += baseaddr;
13366           end += baseaddr;
13367           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
13368           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
13369           record_block_range (block, start, end - 1);
13370         });
13371     }
13372 }
13373
13374 /* Check whether the producer field indicates either of GCC < 4.6, or the
13375    Intel C/C++ compiler, and cache the result in CU.  */
13376
13377 static void
13378 check_producer (struct dwarf2_cu *cu)
13379 {
13380   int major, minor;
13381
13382   if (cu->producer == NULL)
13383     {
13384       /* For unknown compilers expect their behavior is DWARF version
13385          compliant.
13386
13387          GCC started to support .debug_types sections by -gdwarf-4 since
13388          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
13389          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
13390          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
13391          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
13392     }
13393   else if (producer_is_gcc (cu->producer, &major, &minor))
13394     {
13395       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
13396       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
13397     }
13398   else if (producer_is_icc (cu->producer, &major, &minor))
13399     cu->producer_is_icc_lt_14 = major < 14;
13400   else
13401     {
13402       /* For other non-GCC compilers, expect their behavior is DWARF version
13403          compliant.  */
13404     }
13405
13406   cu->checked_producer = 1;
13407 }
13408
13409 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
13410    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
13411    during 4.6.0 experimental.  */
13412
13413 static int
13414 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
13415 {
13416   if (!cu->checked_producer)
13417     check_producer (cu);
13418
13419   return cu->producer_is_gxx_lt_4_6;
13420 }
13421
13422 /* Return the default accessibility type if it is not overriden by
13423    DW_AT_accessibility.  */
13424
13425 static enum dwarf_access_attribute
13426 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
13427 {
13428   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
13429     {
13430       /* The default DWARF 2 accessibility for members is public, the default
13431          accessibility for inheritance is private.  */
13432
13433       if (die->tag != DW_TAG_inheritance)
13434         return DW_ACCESS_public;
13435       else
13436         return DW_ACCESS_private;
13437     }
13438   else
13439     {
13440       /* DWARF 3+ defines the default accessibility a different way.  The same
13441          rules apply now for DW_TAG_inheritance as for the members and it only
13442          depends on the container kind.  */
13443
13444       if (die->parent->tag == DW_TAG_class_type)
13445         return DW_ACCESS_private;
13446       else
13447         return DW_ACCESS_public;
13448     }
13449 }
13450
13451 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
13452    offset.  If the attribute was not found return 0, otherwise return
13453    1.  If it was found but could not properly be handled, set *OFFSET
13454    to 0.  */
13455
13456 static int
13457 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
13458                              LONGEST *offset)
13459 {
13460   struct attribute *attr;
13461
13462   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
13463   if (attr != NULL)
13464     {
13465       *offset = 0;
13466
13467       /* Note that we do not check for a section offset first here.
13468          This is because DW_AT_data_member_location is new in DWARF 4,
13469          so if we see it, we can assume that a constant form is really
13470          a constant and not a section offset.  */
13471       if (attr_form_is_constant (attr))
13472         *offset = dwarf2_get_attr_constant_value (attr, 0);
13473       else if (attr_form_is_section_offset (attr))
13474         dwarf2_complex_location_expr_complaint ();
13475       else if (attr_form_is_block (attr))
13476         *offset = decode_locdesc (DW_BLOCK (attr), cu);
13477       else
13478         dwarf2_complex_location_expr_complaint ();
13479
13480       return 1;
13481     }
13482
13483   return 0;
13484 }
13485
13486 /* Add an aggregate field to the field list.  */
13487
13488 static void
13489 dwarf2_add_field (struct field_info *fip, struct die_info *die,
13490                   struct dwarf2_cu *cu)
13491 {
13492   struct objfile *objfile = cu->objfile;
13493   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13494   struct nextfield *new_field;
13495   struct attribute *attr;
13496   struct field *fp;
13497   const char *fieldname = "";
13498
13499   /* Allocate a new field list entry and link it in.  */
13500   new_field = XNEW (struct nextfield);
13501   make_cleanup (xfree, new_field);
13502   memset (new_field, 0, sizeof (struct nextfield));
13503
13504   if (die->tag == DW_TAG_inheritance)
13505     {
13506       new_field->next = fip->baseclasses;
13507       fip->baseclasses = new_field;
13508     }
13509   else
13510     {
13511       new_field->next = fip->fields;
13512       fip->fields = new_field;
13513     }
13514   fip->nfields++;
13515
13516   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13517   if (attr)
13518     new_field->accessibility = DW_UNSND (attr);
13519   else
13520     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
13521   if (new_field->accessibility != DW_ACCESS_public)
13522     fip->non_public_fields = 1;
13523
13524   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13525   if (attr)
13526     new_field->virtuality = DW_UNSND (attr);
13527   else
13528     new_field->virtuality = DW_VIRTUALITY_none;
13529
13530   fp = &new_field->field;
13531
13532   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
13533     {
13534       LONGEST offset;
13535
13536       /* Data member other than a C++ static data member.  */
13537
13538       /* Get type of field.  */
13539       fp->type = die_type (die, cu);
13540
13541       SET_FIELD_BITPOS (*fp, 0);
13542
13543       /* Get bit size of field (zero if none).  */
13544       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13545       if (attr)
13546         {
13547           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13548         }
13549       else
13550         {
13551           FIELD_BITSIZE (*fp) = 0;
13552         }
13553
13554       /* Get bit offset of field.  */
13555       if (handle_data_member_location (die, cu, &offset))
13556         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13557       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13558       if (attr)
13559         {
13560           if (gdbarch_bits_big_endian (gdbarch))
13561             {
13562               /* For big endian bits, the DW_AT_bit_offset gives the
13563                  additional bit offset from the MSB of the containing
13564                  anonymous object to the MSB of the field.  We don't
13565                  have to do anything special since we don't need to
13566                  know the size of the anonymous object.  */
13567               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13568             }
13569           else
13570             {
13571               /* For little endian bits, compute the bit offset to the
13572                  MSB of the anonymous object, subtract off the number of
13573                  bits from the MSB of the field to the MSB of the
13574                  object, and then subtract off the number of bits of
13575                  the field itself.  The result is the bit offset of
13576                  the LSB of the field.  */
13577               int anonymous_size;
13578               int bit_offset = DW_UNSND (attr);
13579
13580               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13581               if (attr)
13582                 {
13583                   /* The size of the anonymous object containing
13584                      the bit field is explicit, so use the
13585                      indicated size (in bytes).  */
13586                   anonymous_size = DW_UNSND (attr);
13587                 }
13588               else
13589                 {
13590                   /* The size of the anonymous object containing
13591                      the bit field must be inferred from the type
13592                      attribute of the data member containing the
13593                      bit field.  */
13594                   anonymous_size = TYPE_LENGTH (fp->type);
13595                 }
13596               SET_FIELD_BITPOS (*fp,
13597                                 (FIELD_BITPOS (*fp)
13598                                  + anonymous_size * bits_per_byte
13599                                  - bit_offset - FIELD_BITSIZE (*fp)));
13600             }
13601         }
13602       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13603       if (attr != NULL)
13604         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13605                                 + dwarf2_get_attr_constant_value (attr, 0)));
13606
13607       /* Get name of field.  */
13608       fieldname = dwarf2_name (die, cu);
13609       if (fieldname == NULL)
13610         fieldname = "";
13611
13612       /* The name is already allocated along with this objfile, so we don't
13613          need to duplicate it for the type.  */
13614       fp->name = fieldname;
13615
13616       /* Change accessibility for artificial fields (e.g. virtual table
13617          pointer or virtual base class pointer) to private.  */
13618       if (dwarf2_attr (die, DW_AT_artificial, cu))
13619         {
13620           FIELD_ARTIFICIAL (*fp) = 1;
13621           new_field->accessibility = DW_ACCESS_private;
13622           fip->non_public_fields = 1;
13623         }
13624     }
13625   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13626     {
13627       /* C++ static member.  */
13628
13629       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13630          is a declaration, but all versions of G++ as of this writing
13631          (so through at least 3.2.1) incorrectly generate
13632          DW_TAG_variable tags.  */
13633
13634       const char *physname;
13635
13636       /* Get name of field.  */
13637       fieldname = dwarf2_name (die, cu);
13638       if (fieldname == NULL)
13639         return;
13640
13641       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13642       if (attr
13643           /* Only create a symbol if this is an external value.
13644              new_symbol checks this and puts the value in the global symbol
13645              table, which we want.  If it is not external, new_symbol
13646              will try to put the value in cu->list_in_scope which is wrong.  */
13647           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13648         {
13649           /* A static const member, not much different than an enum as far as
13650              we're concerned, except that we can support more types.  */
13651           new_symbol (die, NULL, cu);
13652         }
13653
13654       /* Get physical name.  */
13655       physname = dwarf2_physname (fieldname, die, cu);
13656
13657       /* The name is already allocated along with this objfile, so we don't
13658          need to duplicate it for the type.  */
13659       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13660       FIELD_TYPE (*fp) = die_type (die, cu);
13661       FIELD_NAME (*fp) = fieldname;
13662     }
13663   else if (die->tag == DW_TAG_inheritance)
13664     {
13665       LONGEST offset;
13666
13667       /* C++ base class field.  */
13668       if (handle_data_member_location (die, cu, &offset))
13669         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13670       FIELD_BITSIZE (*fp) = 0;
13671       FIELD_TYPE (*fp) = die_type (die, cu);
13672       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13673       fip->nbaseclasses++;
13674     }
13675 }
13676
13677 /* Add a typedef defined in the scope of the FIP's class.  */
13678
13679 static void
13680 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13681                     struct dwarf2_cu *cu)
13682 {
13683   struct typedef_field_list *new_field;
13684   struct typedef_field *fp;
13685
13686   /* Allocate a new field list entry and link it in.  */
13687   new_field = XCNEW (struct typedef_field_list);
13688   make_cleanup (xfree, new_field);
13689
13690   gdb_assert (die->tag == DW_TAG_typedef);
13691
13692   fp = &new_field->field;
13693
13694   /* Get name of field.  */
13695   fp->name = dwarf2_name (die, cu);
13696   if (fp->name == NULL)
13697     return;
13698
13699   fp->type = read_type_die (die, cu);
13700
13701   /* Save accessibility.  */
13702   enum dwarf_access_attribute accessibility;
13703   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13704   if (attr != NULL)
13705     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13706   else
13707     accessibility = dwarf2_default_access_attribute (die, cu);
13708   switch (accessibility)
13709     {
13710     case DW_ACCESS_public:
13711       /* The assumed value if neither private nor protected.  */
13712       break;
13713     case DW_ACCESS_private:
13714       fp->is_private = 1;
13715       break;
13716     case DW_ACCESS_protected:
13717       fp->is_protected = 1;
13718       break;
13719     default:
13720       complaint (&symfile_complaints,
13721                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
13722     }
13723
13724   new_field->next = fip->typedef_field_list;
13725   fip->typedef_field_list = new_field;
13726   fip->typedef_field_list_count++;
13727 }
13728
13729 /* Create the vector of fields, and attach it to the type.  */
13730
13731 static void
13732 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13733                               struct dwarf2_cu *cu)
13734 {
13735   int nfields = fip->nfields;
13736
13737   /* Record the field count, allocate space for the array of fields,
13738      and create blank accessibility bitfields if necessary.  */
13739   TYPE_NFIELDS (type) = nfields;
13740   TYPE_FIELDS (type) = (struct field *)
13741     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13742   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13743
13744   if (fip->non_public_fields && cu->language != language_ada)
13745     {
13746       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13747
13748       TYPE_FIELD_PRIVATE_BITS (type) =
13749         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13750       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13751
13752       TYPE_FIELD_PROTECTED_BITS (type) =
13753         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13754       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13755
13756       TYPE_FIELD_IGNORE_BITS (type) =
13757         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13758       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13759     }
13760
13761   /* If the type has baseclasses, allocate and clear a bit vector for
13762      TYPE_FIELD_VIRTUAL_BITS.  */
13763   if (fip->nbaseclasses && cu->language != language_ada)
13764     {
13765       int num_bytes = B_BYTES (fip->nbaseclasses);
13766       unsigned char *pointer;
13767
13768       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13769       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13770       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13771       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13772       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13773     }
13774
13775   /* Copy the saved-up fields into the field vector.  Start from the head of
13776      the list, adding to the tail of the field array, so that they end up in
13777      the same order in the array in which they were added to the list.  */
13778   while (nfields-- > 0)
13779     {
13780       struct nextfield *fieldp;
13781
13782       if (fip->fields)
13783         {
13784           fieldp = fip->fields;
13785           fip->fields = fieldp->next;
13786         }
13787       else
13788         {
13789           fieldp = fip->baseclasses;
13790           fip->baseclasses = fieldp->next;
13791         }
13792
13793       TYPE_FIELD (type, nfields) = fieldp->field;
13794       switch (fieldp->accessibility)
13795         {
13796         case DW_ACCESS_private:
13797           if (cu->language != language_ada)
13798             SET_TYPE_FIELD_PRIVATE (type, nfields);
13799           break;
13800
13801         case DW_ACCESS_protected:
13802           if (cu->language != language_ada)
13803             SET_TYPE_FIELD_PROTECTED (type, nfields);
13804           break;
13805
13806         case DW_ACCESS_public:
13807           break;
13808
13809         default:
13810           /* Unknown accessibility.  Complain and treat it as public.  */
13811           {
13812             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13813                        fieldp->accessibility);
13814           }
13815           break;
13816         }
13817       if (nfields < fip->nbaseclasses)
13818         {
13819           switch (fieldp->virtuality)
13820             {
13821             case DW_VIRTUALITY_virtual:
13822             case DW_VIRTUALITY_pure_virtual:
13823               if (cu->language == language_ada)
13824                 error (_("unexpected virtuality in component of Ada type"));
13825               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13826               break;
13827             }
13828         }
13829     }
13830 }
13831
13832 /* Return true if this member function is a constructor, false
13833    otherwise.  */
13834
13835 static int
13836 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13837 {
13838   const char *fieldname;
13839   const char *type_name;
13840   int len;
13841
13842   if (die->parent == NULL)
13843     return 0;
13844
13845   if (die->parent->tag != DW_TAG_structure_type
13846       && die->parent->tag != DW_TAG_union_type
13847       && die->parent->tag != DW_TAG_class_type)
13848     return 0;
13849
13850   fieldname = dwarf2_name (die, cu);
13851   type_name = dwarf2_name (die->parent, cu);
13852   if (fieldname == NULL || type_name == NULL)
13853     return 0;
13854
13855   len = strlen (fieldname);
13856   return (strncmp (fieldname, type_name, len) == 0
13857           && (type_name[len] == '\0' || type_name[len] == '<'));
13858 }
13859
13860 /* Add a member function to the proper fieldlist.  */
13861
13862 static void
13863 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13864                       struct type *type, struct dwarf2_cu *cu)
13865 {
13866   struct objfile *objfile = cu->objfile;
13867   struct attribute *attr;
13868   struct fnfieldlist *flp;
13869   int i;
13870   struct fn_field *fnp;
13871   const char *fieldname;
13872   struct nextfnfield *new_fnfield;
13873   struct type *this_type;
13874   enum dwarf_access_attribute accessibility;
13875
13876   if (cu->language == language_ada)
13877     error (_("unexpected member function in Ada type"));
13878
13879   /* Get name of member function.  */
13880   fieldname = dwarf2_name (die, cu);
13881   if (fieldname == NULL)
13882     return;
13883
13884   /* Look up member function name in fieldlist.  */
13885   for (i = 0; i < fip->nfnfields; i++)
13886     {
13887       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13888         break;
13889     }
13890
13891   /* Create new list element if necessary.  */
13892   if (i < fip->nfnfields)
13893     flp = &fip->fnfieldlists[i];
13894   else
13895     {
13896       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13897         {
13898           fip->fnfieldlists = (struct fnfieldlist *)
13899             xrealloc (fip->fnfieldlists,
13900                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13901                       * sizeof (struct fnfieldlist));
13902           if (fip->nfnfields == 0)
13903             make_cleanup (free_current_contents, &fip->fnfieldlists);
13904         }
13905       flp = &fip->fnfieldlists[fip->nfnfields];
13906       flp->name = fieldname;
13907       flp->length = 0;
13908       flp->head = NULL;
13909       i = fip->nfnfields++;
13910     }
13911
13912   /* Create a new member function field and chain it to the field list
13913      entry.  */
13914   new_fnfield = XNEW (struct nextfnfield);
13915   make_cleanup (xfree, new_fnfield);
13916   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13917   new_fnfield->next = flp->head;
13918   flp->head = new_fnfield;
13919   flp->length++;
13920
13921   /* Fill in the member function field info.  */
13922   fnp = &new_fnfield->fnfield;
13923
13924   /* Delay processing of the physname until later.  */
13925   if (cu->language == language_cplus)
13926     {
13927       add_to_method_list (type, i, flp->length - 1, fieldname,
13928                           die, cu);
13929     }
13930   else
13931     {
13932       const char *physname = dwarf2_physname (fieldname, die, cu);
13933       fnp->physname = physname ? physname : "";
13934     }
13935
13936   fnp->type = alloc_type (objfile);
13937   this_type = read_type_die (die, cu);
13938   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13939     {
13940       int nparams = TYPE_NFIELDS (this_type);
13941
13942       /* TYPE is the domain of this method, and THIS_TYPE is the type
13943            of the method itself (TYPE_CODE_METHOD).  */
13944       smash_to_method_type (fnp->type, type,
13945                             TYPE_TARGET_TYPE (this_type),
13946                             TYPE_FIELDS (this_type),
13947                             TYPE_NFIELDS (this_type),
13948                             TYPE_VARARGS (this_type));
13949
13950       /* Handle static member functions.
13951          Dwarf2 has no clean way to discern C++ static and non-static
13952          member functions.  G++ helps GDB by marking the first
13953          parameter for non-static member functions (which is the this
13954          pointer) as artificial.  We obtain this information from
13955          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13956       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13957         fnp->voffset = VOFFSET_STATIC;
13958     }
13959   else
13960     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13961                dwarf2_full_name (fieldname, die, cu));
13962
13963   /* Get fcontext from DW_AT_containing_type if present.  */
13964   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13965     fnp->fcontext = die_containing_type (die, cu);
13966
13967   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13968      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13969
13970   /* Get accessibility.  */
13971   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13972   if (attr)
13973     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13974   else
13975     accessibility = dwarf2_default_access_attribute (die, cu);
13976   switch (accessibility)
13977     {
13978     case DW_ACCESS_private:
13979       fnp->is_private = 1;
13980       break;
13981     case DW_ACCESS_protected:
13982       fnp->is_protected = 1;
13983       break;
13984     }
13985
13986   /* Check for artificial methods.  */
13987   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13988   if (attr && DW_UNSND (attr) != 0)
13989     fnp->is_artificial = 1;
13990
13991   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13992
13993   /* Get index in virtual function table if it is a virtual member
13994      function.  For older versions of GCC, this is an offset in the
13995      appropriate virtual table, as specified by DW_AT_containing_type.
13996      For everyone else, it is an expression to be evaluated relative
13997      to the object address.  */
13998
13999   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
14000   if (attr)
14001     {
14002       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
14003         {
14004           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
14005             {
14006               /* Old-style GCC.  */
14007               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
14008             }
14009           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
14010                    || (DW_BLOCK (attr)->size > 1
14011                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
14012                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
14013             {
14014               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
14015               if ((fnp->voffset % cu->header.addr_size) != 0)
14016                 dwarf2_complex_location_expr_complaint ();
14017               else
14018                 fnp->voffset /= cu->header.addr_size;
14019               fnp->voffset += 2;
14020             }
14021           else
14022             dwarf2_complex_location_expr_complaint ();
14023
14024           if (!fnp->fcontext)
14025             {
14026               /* If there is no `this' field and no DW_AT_containing_type,
14027                  we cannot actually find a base class context for the
14028                  vtable!  */
14029               if (TYPE_NFIELDS (this_type) == 0
14030                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
14031                 {
14032                   complaint (&symfile_complaints,
14033                              _("cannot determine context for virtual member "
14034                                "function \"%s\" (offset %d)"),
14035                              fieldname, to_underlying (die->sect_off));
14036                 }
14037               else
14038                 {
14039                   fnp->fcontext
14040                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
14041                 }
14042             }
14043         }
14044       else if (attr_form_is_section_offset (attr))
14045         {
14046           dwarf2_complex_location_expr_complaint ();
14047         }
14048       else
14049         {
14050           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
14051                                                  fieldname);
14052         }
14053     }
14054   else
14055     {
14056       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14057       if (attr && DW_UNSND (attr))
14058         {
14059           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
14060           complaint (&symfile_complaints,
14061                      _("Member function \"%s\" (offset %d) is virtual "
14062                        "but the vtable offset is not specified"),
14063                      fieldname, to_underlying (die->sect_off));
14064           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14065           TYPE_CPLUS_DYNAMIC (type) = 1;
14066         }
14067     }
14068 }
14069
14070 /* Create the vector of member function fields, and attach it to the type.  */
14071
14072 static void
14073 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
14074                                  struct dwarf2_cu *cu)
14075 {
14076   struct fnfieldlist *flp;
14077   int i;
14078
14079   if (cu->language == language_ada)
14080     error (_("unexpected member functions in Ada type"));
14081
14082   ALLOCATE_CPLUS_STRUCT_TYPE (type);
14083   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
14084     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
14085
14086   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
14087     {
14088       struct nextfnfield *nfp = flp->head;
14089       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
14090       int k;
14091
14092       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
14093       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
14094       fn_flp->fn_fields = (struct fn_field *)
14095         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
14096       for (k = flp->length; (k--, nfp); nfp = nfp->next)
14097         fn_flp->fn_fields[k] = nfp->fnfield;
14098     }
14099
14100   TYPE_NFN_FIELDS (type) = fip->nfnfields;
14101 }
14102
14103 /* Returns non-zero if NAME is the name of a vtable member in CU's
14104    language, zero otherwise.  */
14105 static int
14106 is_vtable_name (const char *name, struct dwarf2_cu *cu)
14107 {
14108   static const char vptr[] = "_vptr";
14109   static const char vtable[] = "vtable";
14110
14111   /* Look for the C++ form of the vtable.  */
14112   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
14113     return 1;
14114
14115   return 0;
14116 }
14117
14118 /* GCC outputs unnamed structures that are really pointers to member
14119    functions, with the ABI-specified layout.  If TYPE describes
14120    such a structure, smash it into a member function type.
14121
14122    GCC shouldn't do this; it should just output pointer to member DIEs.
14123    This is GCC PR debug/28767.  */
14124
14125 static void
14126 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
14127 {
14128   struct type *pfn_type, *self_type, *new_type;
14129
14130   /* Check for a structure with no name and two children.  */
14131   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
14132     return;
14133
14134   /* Check for __pfn and __delta members.  */
14135   if (TYPE_FIELD_NAME (type, 0) == NULL
14136       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
14137       || TYPE_FIELD_NAME (type, 1) == NULL
14138       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
14139     return;
14140
14141   /* Find the type of the method.  */
14142   pfn_type = TYPE_FIELD_TYPE (type, 0);
14143   if (pfn_type == NULL
14144       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
14145       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
14146     return;
14147
14148   /* Look for the "this" argument.  */
14149   pfn_type = TYPE_TARGET_TYPE (pfn_type);
14150   if (TYPE_NFIELDS (pfn_type) == 0
14151       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
14152       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
14153     return;
14154
14155   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
14156   new_type = alloc_type (objfile);
14157   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
14158                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
14159                         TYPE_VARARGS (pfn_type));
14160   smash_to_methodptr_type (type, new_type);
14161 }
14162
14163
14164 /* Called when we find the DIE that starts a structure or union scope
14165    (definition) to create a type for the structure or union.  Fill in
14166    the type's name and general properties; the members will not be
14167    processed until process_structure_scope.  A symbol table entry for
14168    the type will also not be done until process_structure_scope (assuming
14169    the type has a name).
14170
14171    NOTE: we need to call these functions regardless of whether or not the
14172    DIE has a DW_AT_name attribute, since it might be an anonymous
14173    structure or union.  This gets the type entered into our set of
14174    user defined types.  */
14175
14176 static struct type *
14177 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
14178 {
14179   struct objfile *objfile = cu->objfile;
14180   struct type *type;
14181   struct attribute *attr;
14182   const char *name;
14183
14184   /* If the definition of this type lives in .debug_types, read that type.
14185      Don't follow DW_AT_specification though, that will take us back up
14186      the chain and we want to go down.  */
14187   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14188   if (attr)
14189     {
14190       type = get_DW_AT_signature_type (die, attr, cu);
14191
14192       /* The type's CU may not be the same as CU.
14193          Ensure TYPE is recorded with CU in die_type_hash.  */
14194       return set_die_type (die, type, cu);
14195     }
14196
14197   type = alloc_type (objfile);
14198   INIT_CPLUS_SPECIFIC (type);
14199
14200   name = dwarf2_name (die, cu);
14201   if (name != NULL)
14202     {
14203       if (cu->language == language_cplus
14204           || cu->language == language_d
14205           || cu->language == language_rust)
14206         {
14207           const char *full_name = dwarf2_full_name (name, die, cu);
14208
14209           /* dwarf2_full_name might have already finished building the DIE's
14210              type.  If so, there is no need to continue.  */
14211           if (get_die_type (die, cu) != NULL)
14212             return get_die_type (die, cu);
14213
14214           TYPE_TAG_NAME (type) = full_name;
14215           if (die->tag == DW_TAG_structure_type
14216               || die->tag == DW_TAG_class_type)
14217             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14218         }
14219       else
14220         {
14221           /* The name is already allocated along with this objfile, so
14222              we don't need to duplicate it for the type.  */
14223           TYPE_TAG_NAME (type) = name;
14224           if (die->tag == DW_TAG_class_type)
14225             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14226         }
14227     }
14228
14229   if (die->tag == DW_TAG_structure_type)
14230     {
14231       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14232     }
14233   else if (die->tag == DW_TAG_union_type)
14234     {
14235       TYPE_CODE (type) = TYPE_CODE_UNION;
14236     }
14237   else
14238     {
14239       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14240     }
14241
14242   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
14243     TYPE_DECLARED_CLASS (type) = 1;
14244
14245   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14246   if (attr)
14247     {
14248       if (attr_form_is_constant (attr))
14249         TYPE_LENGTH (type) = DW_UNSND (attr);
14250       else
14251         {
14252           /* For the moment, dynamic type sizes are not supported
14253              by GDB's struct type.  The actual size is determined
14254              on-demand when resolving the type of a given object,
14255              so set the type's length to zero for now.  Otherwise,
14256              we record an expression as the length, and that expression
14257              could lead to a very large value, which could eventually
14258              lead to us trying to allocate that much memory when creating
14259              a value of that type.  */
14260           TYPE_LENGTH (type) = 0;
14261         }
14262     }
14263   else
14264     {
14265       TYPE_LENGTH (type) = 0;
14266     }
14267
14268   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
14269     {
14270       /* ICC<14 does not output the required DW_AT_declaration on
14271          incomplete types, but gives them a size of zero.  */
14272       TYPE_STUB (type) = 1;
14273     }
14274   else
14275     TYPE_STUB_SUPPORTED (type) = 1;
14276
14277   if (die_is_declaration (die, cu))
14278     TYPE_STUB (type) = 1;
14279   else if (attr == NULL && die->child == NULL
14280            && producer_is_realview (cu->producer))
14281     /* RealView does not output the required DW_AT_declaration
14282        on incomplete types.  */
14283     TYPE_STUB (type) = 1;
14284
14285   /* We need to add the type field to the die immediately so we don't
14286      infinitely recurse when dealing with pointers to the structure
14287      type within the structure itself.  */
14288   set_die_type (die, type, cu);
14289
14290   /* set_die_type should be already done.  */
14291   set_descriptive_type (type, die, cu);
14292
14293   return type;
14294 }
14295
14296 /* Finish creating a structure or union type, including filling in
14297    its members and creating a symbol for it.  */
14298
14299 static void
14300 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
14301 {
14302   struct objfile *objfile = cu->objfile;
14303   struct die_info *child_die;
14304   struct type *type;
14305
14306   type = get_die_type (die, cu);
14307   if (type == NULL)
14308     type = read_structure_type (die, cu);
14309
14310   if (die->child != NULL && ! die_is_declaration (die, cu))
14311     {
14312       struct field_info fi;
14313       std::vector<struct symbol *> template_args;
14314       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
14315
14316       memset (&fi, 0, sizeof (struct field_info));
14317
14318       child_die = die->child;
14319
14320       while (child_die && child_die->tag)
14321         {
14322           if (child_die->tag == DW_TAG_member
14323               || child_die->tag == DW_TAG_variable)
14324             {
14325               /* NOTE: carlton/2002-11-05: A C++ static data member
14326                  should be a DW_TAG_member that is a declaration, but
14327                  all versions of G++ as of this writing (so through at
14328                  least 3.2.1) incorrectly generate DW_TAG_variable
14329                  tags for them instead.  */
14330               dwarf2_add_field (&fi, child_die, cu);
14331             }
14332           else if (child_die->tag == DW_TAG_subprogram)
14333             {
14334               /* Rust doesn't have member functions in the C++ sense.
14335                  However, it does emit ordinary functions as children
14336                  of a struct DIE.  */
14337               if (cu->language == language_rust)
14338                 read_func_scope (child_die, cu);
14339               else
14340                 {
14341                   /* C++ member function.  */
14342                   dwarf2_add_member_fn (&fi, child_die, type, cu);
14343                 }
14344             }
14345           else if (child_die->tag == DW_TAG_inheritance)
14346             {
14347               /* C++ base class field.  */
14348               dwarf2_add_field (&fi, child_die, cu);
14349             }
14350           else if (child_die->tag == DW_TAG_typedef)
14351             dwarf2_add_typedef (&fi, child_die, cu);
14352           else if (child_die->tag == DW_TAG_template_type_param
14353                    || child_die->tag == DW_TAG_template_value_param)
14354             {
14355               struct symbol *arg = new_symbol (child_die, NULL, cu);
14356
14357               if (arg != NULL)
14358                 template_args.push_back (arg);
14359             }
14360
14361           child_die = sibling_die (child_die);
14362         }
14363
14364       /* Attach template arguments to type.  */
14365       if (!template_args.empty ())
14366         {
14367           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14368           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
14369           TYPE_TEMPLATE_ARGUMENTS (type)
14370             = XOBNEWVEC (&objfile->objfile_obstack,
14371                          struct symbol *,
14372                          TYPE_N_TEMPLATE_ARGUMENTS (type));
14373           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
14374                   template_args.data (),
14375                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
14376                    * sizeof (struct symbol *)));
14377         }
14378
14379       /* Attach fields and member functions to the type.  */
14380       if (fi.nfields)
14381         dwarf2_attach_fields_to_type (&fi, type, cu);
14382       if (fi.nfnfields)
14383         {
14384           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
14385
14386           /* Get the type which refers to the base class (possibly this
14387              class itself) which contains the vtable pointer for the current
14388              class from the DW_AT_containing_type attribute.  This use of
14389              DW_AT_containing_type is a GNU extension.  */
14390
14391           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14392             {
14393               struct type *t = die_containing_type (die, cu);
14394
14395               set_type_vptr_basetype (type, t);
14396               if (type == t)
14397                 {
14398                   int i;
14399
14400                   /* Our own class provides vtbl ptr.  */
14401                   for (i = TYPE_NFIELDS (t) - 1;
14402                        i >= TYPE_N_BASECLASSES (t);
14403                        --i)
14404                     {
14405                       const char *fieldname = TYPE_FIELD_NAME (t, i);
14406
14407                       if (is_vtable_name (fieldname, cu))
14408                         {
14409                           set_type_vptr_fieldno (type, i);
14410                           break;
14411                         }
14412                     }
14413
14414                   /* Complain if virtual function table field not found.  */
14415                   if (i < TYPE_N_BASECLASSES (t))
14416                     complaint (&symfile_complaints,
14417                                _("virtual function table pointer "
14418                                  "not found when defining class '%s'"),
14419                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
14420                                "");
14421                 }
14422               else
14423                 {
14424                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
14425                 }
14426             }
14427           else if (cu->producer
14428                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
14429             {
14430               /* The IBM XLC compiler does not provide direct indication
14431                  of the containing type, but the vtable pointer is
14432                  always named __vfp.  */
14433
14434               int i;
14435
14436               for (i = TYPE_NFIELDS (type) - 1;
14437                    i >= TYPE_N_BASECLASSES (type);
14438                    --i)
14439                 {
14440                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
14441                     {
14442                       set_type_vptr_fieldno (type, i);
14443                       set_type_vptr_basetype (type, type);
14444                       break;
14445                     }
14446                 }
14447             }
14448         }
14449
14450       /* Copy fi.typedef_field_list linked list elements content into the
14451          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
14452       if (fi.typedef_field_list)
14453         {
14454           int i = fi.typedef_field_list_count;
14455
14456           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14457           TYPE_TYPEDEF_FIELD_ARRAY (type)
14458             = ((struct typedef_field *)
14459                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
14460           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
14461
14462           /* Reverse the list order to keep the debug info elements order.  */
14463           while (--i >= 0)
14464             {
14465               struct typedef_field *dest, *src;
14466
14467               dest = &TYPE_TYPEDEF_FIELD (type, i);
14468               src = &fi.typedef_field_list->field;
14469               fi.typedef_field_list = fi.typedef_field_list->next;
14470               *dest = *src;
14471             }
14472         }
14473
14474       do_cleanups (back_to);
14475     }
14476
14477   quirk_gcc_member_function_pointer (type, objfile);
14478
14479   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
14480      snapshots) has been known to create a die giving a declaration
14481      for a class that has, as a child, a die giving a definition for a
14482      nested class.  So we have to process our children even if the
14483      current die is a declaration.  Normally, of course, a declaration
14484      won't have any children at all.  */
14485
14486   child_die = die->child;
14487
14488   while (child_die != NULL && child_die->tag)
14489     {
14490       if (child_die->tag == DW_TAG_member
14491           || child_die->tag == DW_TAG_variable
14492           || child_die->tag == DW_TAG_inheritance
14493           || child_die->tag == DW_TAG_template_value_param
14494           || child_die->tag == DW_TAG_template_type_param)
14495         {
14496           /* Do nothing.  */
14497         }
14498       else
14499         process_die (child_die, cu);
14500
14501       child_die = sibling_die (child_die);
14502     }
14503
14504   /* Do not consider external references.  According to the DWARF standard,
14505      these DIEs are identified by the fact that they have no byte_size
14506      attribute, and a declaration attribute.  */
14507   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
14508       || !die_is_declaration (die, cu))
14509     new_symbol (die, type, cu);
14510 }
14511
14512 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
14513    update TYPE using some information only available in DIE's children.  */
14514
14515 static void
14516 update_enumeration_type_from_children (struct die_info *die,
14517                                        struct type *type,
14518                                        struct dwarf2_cu *cu)
14519 {
14520   struct die_info *child_die;
14521   int unsigned_enum = 1;
14522   int flag_enum = 1;
14523   ULONGEST mask = 0;
14524
14525   auto_obstack obstack;
14526
14527   for (child_die = die->child;
14528        child_die != NULL && child_die->tag;
14529        child_die = sibling_die (child_die))
14530     {
14531       struct attribute *attr;
14532       LONGEST value;
14533       const gdb_byte *bytes;
14534       struct dwarf2_locexpr_baton *baton;
14535       const char *name;
14536
14537       if (child_die->tag != DW_TAG_enumerator)
14538         continue;
14539
14540       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
14541       if (attr == NULL)
14542         continue;
14543
14544       name = dwarf2_name (child_die, cu);
14545       if (name == NULL)
14546         name = "<anonymous enumerator>";
14547
14548       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
14549                                &value, &bytes, &baton);
14550       if (value < 0)
14551         {
14552           unsigned_enum = 0;
14553           flag_enum = 0;
14554         }
14555       else if ((mask & value) != 0)
14556         flag_enum = 0;
14557       else
14558         mask |= value;
14559
14560       /* If we already know that the enum type is neither unsigned, nor
14561          a flag type, no need to look at the rest of the enumerates.  */
14562       if (!unsigned_enum && !flag_enum)
14563         break;
14564     }
14565
14566   if (unsigned_enum)
14567     TYPE_UNSIGNED (type) = 1;
14568   if (flag_enum)
14569     TYPE_FLAG_ENUM (type) = 1;
14570 }
14571
14572 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14573    complete the type's fields yet, or create any symbols.  */
14574
14575 static struct type *
14576 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14577 {
14578   struct objfile *objfile = cu->objfile;
14579   struct type *type;
14580   struct attribute *attr;
14581   const char *name;
14582
14583   /* If the definition of this type lives in .debug_types, read that type.
14584      Don't follow DW_AT_specification though, that will take us back up
14585      the chain and we want to go down.  */
14586   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14587   if (attr)
14588     {
14589       type = get_DW_AT_signature_type (die, attr, cu);
14590
14591       /* The type's CU may not be the same as CU.
14592          Ensure TYPE is recorded with CU in die_type_hash.  */
14593       return set_die_type (die, type, cu);
14594     }
14595
14596   type = alloc_type (objfile);
14597
14598   TYPE_CODE (type) = TYPE_CODE_ENUM;
14599   name = dwarf2_full_name (NULL, die, cu);
14600   if (name != NULL)
14601     TYPE_TAG_NAME (type) = name;
14602
14603   attr = dwarf2_attr (die, DW_AT_type, cu);
14604   if (attr != NULL)
14605     {
14606       struct type *underlying_type = die_type (die, cu);
14607
14608       TYPE_TARGET_TYPE (type) = underlying_type;
14609     }
14610
14611   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14612   if (attr)
14613     {
14614       TYPE_LENGTH (type) = DW_UNSND (attr);
14615     }
14616   else
14617     {
14618       TYPE_LENGTH (type) = 0;
14619     }
14620
14621   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14622      declared as private in the package spec, and then defined only
14623      inside the package body.  Such types are known as Taft Amendment
14624      Types.  When another package uses such a type, an incomplete DIE
14625      may be generated by the compiler.  */
14626   if (die_is_declaration (die, cu))
14627     TYPE_STUB (type) = 1;
14628
14629   /* Finish the creation of this type by using the enum's children.
14630      We must call this even when the underlying type has been provided
14631      so that we can determine if we're looking at a "flag" enum.  */
14632   update_enumeration_type_from_children (die, type, cu);
14633
14634   /* If this type has an underlying type that is not a stub, then we
14635      may use its attributes.  We always use the "unsigned" attribute
14636      in this situation, because ordinarily we guess whether the type
14637      is unsigned -- but the guess can be wrong and the underlying type
14638      can tell us the reality.  However, we defer to a local size
14639      attribute if one exists, because this lets the compiler override
14640      the underlying type if needed.  */
14641   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14642     {
14643       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14644       if (TYPE_LENGTH (type) == 0)
14645         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14646     }
14647
14648   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14649
14650   return set_die_type (die, type, cu);
14651 }
14652
14653 /* Given a pointer to a die which begins an enumeration, process all
14654    the dies that define the members of the enumeration, and create the
14655    symbol for the enumeration type.
14656
14657    NOTE: We reverse the order of the element list.  */
14658
14659 static void
14660 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14661 {
14662   struct type *this_type;
14663
14664   this_type = get_die_type (die, cu);
14665   if (this_type == NULL)
14666     this_type = read_enumeration_type (die, cu);
14667
14668   if (die->child != NULL)
14669     {
14670       struct die_info *child_die;
14671       struct symbol *sym;
14672       struct field *fields = NULL;
14673       int num_fields = 0;
14674       const char *name;
14675
14676       child_die = die->child;
14677       while (child_die && child_die->tag)
14678         {
14679           if (child_die->tag != DW_TAG_enumerator)
14680             {
14681               process_die (child_die, cu);
14682             }
14683           else
14684             {
14685               name = dwarf2_name (child_die, cu);
14686               if (name)
14687                 {
14688                   sym = new_symbol (child_die, this_type, cu);
14689
14690                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14691                     {
14692                       fields = (struct field *)
14693                         xrealloc (fields,
14694                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14695                                   * sizeof (struct field));
14696                     }
14697
14698                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14699                   FIELD_TYPE (fields[num_fields]) = NULL;
14700                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14701                   FIELD_BITSIZE (fields[num_fields]) = 0;
14702
14703                   num_fields++;
14704                 }
14705             }
14706
14707           child_die = sibling_die (child_die);
14708         }
14709
14710       if (num_fields)
14711         {
14712           TYPE_NFIELDS (this_type) = num_fields;
14713           TYPE_FIELDS (this_type) = (struct field *)
14714             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14715           memcpy (TYPE_FIELDS (this_type), fields,
14716                   sizeof (struct field) * num_fields);
14717           xfree (fields);
14718         }
14719     }
14720
14721   /* If we are reading an enum from a .debug_types unit, and the enum
14722      is a declaration, and the enum is not the signatured type in the
14723      unit, then we do not want to add a symbol for it.  Adding a
14724      symbol would in some cases obscure the true definition of the
14725      enum, giving users an incomplete type when the definition is
14726      actually available.  Note that we do not want to do this for all
14727      enums which are just declarations, because C++0x allows forward
14728      enum declarations.  */
14729   if (cu->per_cu->is_debug_types
14730       && die_is_declaration (die, cu))
14731     {
14732       struct signatured_type *sig_type;
14733
14734       sig_type = (struct signatured_type *) cu->per_cu;
14735       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14736       if (sig_type->type_offset_in_section != die->sect_off)
14737         return;
14738     }
14739
14740   new_symbol (die, this_type, cu);
14741 }
14742
14743 /* Extract all information from a DW_TAG_array_type DIE and put it in
14744    the DIE's type field.  For now, this only handles one dimensional
14745    arrays.  */
14746
14747 static struct type *
14748 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14749 {
14750   struct objfile *objfile = cu->objfile;
14751   struct die_info *child_die;
14752   struct type *type;
14753   struct type *element_type, *range_type, *index_type;
14754   struct attribute *attr;
14755   const char *name;
14756   unsigned int bit_stride = 0;
14757
14758   element_type = die_type (die, cu);
14759
14760   /* The die_type call above may have already set the type for this DIE.  */
14761   type = get_die_type (die, cu);
14762   if (type)
14763     return type;
14764
14765   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14766   if (attr != NULL)
14767     bit_stride = DW_UNSND (attr) * 8;
14768
14769   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14770   if (attr != NULL)
14771     bit_stride = DW_UNSND (attr);
14772
14773   /* Irix 6.2 native cc creates array types without children for
14774      arrays with unspecified length.  */
14775   if (die->child == NULL)
14776     {
14777       index_type = objfile_type (objfile)->builtin_int;
14778       range_type = create_static_range_type (NULL, index_type, 0, -1);
14779       type = create_array_type_with_stride (NULL, element_type, range_type,
14780                                             bit_stride);
14781       return set_die_type (die, type, cu);
14782     }
14783
14784   std::vector<struct type *> range_types;
14785   child_die = die->child;
14786   while (child_die && child_die->tag)
14787     {
14788       if (child_die->tag == DW_TAG_subrange_type)
14789         {
14790           struct type *child_type = read_type_die (child_die, cu);
14791
14792           if (child_type != NULL)
14793             {
14794               /* The range type was succesfully read.  Save it for the
14795                  array type creation.  */
14796               range_types.push_back (child_type);
14797             }
14798         }
14799       child_die = sibling_die (child_die);
14800     }
14801
14802   /* Dwarf2 dimensions are output from left to right, create the
14803      necessary array types in backwards order.  */
14804
14805   type = element_type;
14806
14807   if (read_array_order (die, cu) == DW_ORD_col_major)
14808     {
14809       int i = 0;
14810
14811       while (i < range_types.size ())
14812         type = create_array_type_with_stride (NULL, type, range_types[i++],
14813                                               bit_stride);
14814     }
14815   else
14816     {
14817       size_t ndim = range_types.size ();
14818       while (ndim-- > 0)
14819         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14820                                               bit_stride);
14821     }
14822
14823   /* Understand Dwarf2 support for vector types (like they occur on
14824      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14825      array type.  This is not part of the Dwarf2/3 standard yet, but a
14826      custom vendor extension.  The main difference between a regular
14827      array and the vector variant is that vectors are passed by value
14828      to functions.  */
14829   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14830   if (attr)
14831     make_vector_type (type);
14832
14833   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14834      implementation may choose to implement triple vectors using this
14835      attribute.  */
14836   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14837   if (attr)
14838     {
14839       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14840         TYPE_LENGTH (type) = DW_UNSND (attr);
14841       else
14842         complaint (&symfile_complaints,
14843                    _("DW_AT_byte_size for array type smaller "
14844                      "than the total size of elements"));
14845     }
14846
14847   name = dwarf2_name (die, cu);
14848   if (name)
14849     TYPE_NAME (type) = name;
14850
14851   /* Install the type in the die.  */
14852   set_die_type (die, type, cu);
14853
14854   /* set_die_type should be already done.  */
14855   set_descriptive_type (type, die, cu);
14856
14857   return type;
14858 }
14859
14860 static enum dwarf_array_dim_ordering
14861 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14862 {
14863   struct attribute *attr;
14864
14865   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14866
14867   if (attr)
14868     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14869
14870   /* GNU F77 is a special case, as at 08/2004 array type info is the
14871      opposite order to the dwarf2 specification, but data is still
14872      laid out as per normal fortran.
14873
14874      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14875      version checking.  */
14876
14877   if (cu->language == language_fortran
14878       && cu->producer && strstr (cu->producer, "GNU F77"))
14879     {
14880       return DW_ORD_row_major;
14881     }
14882
14883   switch (cu->language_defn->la_array_ordering)
14884     {
14885     case array_column_major:
14886       return DW_ORD_col_major;
14887     case array_row_major:
14888     default:
14889       return DW_ORD_row_major;
14890     };
14891 }
14892
14893 /* Extract all information from a DW_TAG_set_type DIE and put it in
14894    the DIE's type field.  */
14895
14896 static struct type *
14897 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14898 {
14899   struct type *domain_type, *set_type;
14900   struct attribute *attr;
14901
14902   domain_type = die_type (die, cu);
14903
14904   /* The die_type call above may have already set the type for this DIE.  */
14905   set_type = get_die_type (die, cu);
14906   if (set_type)
14907     return set_type;
14908
14909   set_type = create_set_type (NULL, domain_type);
14910
14911   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14912   if (attr)
14913     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14914
14915   return set_die_type (die, set_type, cu);
14916 }
14917
14918 /* A helper for read_common_block that creates a locexpr baton.
14919    SYM is the symbol which we are marking as computed.
14920    COMMON_DIE is the DIE for the common block.
14921    COMMON_LOC is the location expression attribute for the common
14922    block itself.
14923    MEMBER_LOC is the location expression attribute for the particular
14924    member of the common block that we are processing.
14925    CU is the CU from which the above come.  */
14926
14927 static void
14928 mark_common_block_symbol_computed (struct symbol *sym,
14929                                    struct die_info *common_die,
14930                                    struct attribute *common_loc,
14931                                    struct attribute *member_loc,
14932                                    struct dwarf2_cu *cu)
14933 {
14934   struct objfile *objfile = dwarf2_per_objfile->objfile;
14935   struct dwarf2_locexpr_baton *baton;
14936   gdb_byte *ptr;
14937   unsigned int cu_off;
14938   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14939   LONGEST offset = 0;
14940
14941   gdb_assert (common_loc && member_loc);
14942   gdb_assert (attr_form_is_block (common_loc));
14943   gdb_assert (attr_form_is_block (member_loc)
14944               || attr_form_is_constant (member_loc));
14945
14946   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14947   baton->per_cu = cu->per_cu;
14948   gdb_assert (baton->per_cu);
14949
14950   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14951
14952   if (attr_form_is_constant (member_loc))
14953     {
14954       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14955       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14956     }
14957   else
14958     baton->size += DW_BLOCK (member_loc)->size;
14959
14960   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14961   baton->data = ptr;
14962
14963   *ptr++ = DW_OP_call4;
14964   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14965   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14966   ptr += 4;
14967
14968   if (attr_form_is_constant (member_loc))
14969     {
14970       *ptr++ = DW_OP_addr;
14971       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14972       ptr += cu->header.addr_size;
14973     }
14974   else
14975     {
14976       /* We have to copy the data here, because DW_OP_call4 will only
14977          use a DW_AT_location attribute.  */
14978       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14979       ptr += DW_BLOCK (member_loc)->size;
14980     }
14981
14982   *ptr++ = DW_OP_plus;
14983   gdb_assert (ptr - baton->data == baton->size);
14984
14985   SYMBOL_LOCATION_BATON (sym) = baton;
14986   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14987 }
14988
14989 /* Create appropriate locally-scoped variables for all the
14990    DW_TAG_common_block entries.  Also create a struct common_block
14991    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14992    is used to sepate the common blocks name namespace from regular
14993    variable names.  */
14994
14995 static void
14996 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14997 {
14998   struct attribute *attr;
14999
15000   attr = dwarf2_attr (die, DW_AT_location, cu);
15001   if (attr)
15002     {
15003       /* Support the .debug_loc offsets.  */
15004       if (attr_form_is_block (attr))
15005         {
15006           /* Ok.  */
15007         }
15008       else if (attr_form_is_section_offset (attr))
15009         {
15010           dwarf2_complex_location_expr_complaint ();
15011           attr = NULL;
15012         }
15013       else
15014         {
15015           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15016                                                  "common block member");
15017           attr = NULL;
15018         }
15019     }
15020
15021   if (die->child != NULL)
15022     {
15023       struct objfile *objfile = cu->objfile;
15024       struct die_info *child_die;
15025       size_t n_entries = 0, size;
15026       struct common_block *common_block;
15027       struct symbol *sym;
15028
15029       for (child_die = die->child;
15030            child_die && child_die->tag;
15031            child_die = sibling_die (child_die))
15032         ++n_entries;
15033
15034       size = (sizeof (struct common_block)
15035               + (n_entries - 1) * sizeof (struct symbol *));
15036       common_block
15037         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
15038                                                  size);
15039       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
15040       common_block->n_entries = 0;
15041
15042       for (child_die = die->child;
15043            child_die && child_die->tag;
15044            child_die = sibling_die (child_die))
15045         {
15046           /* Create the symbol in the DW_TAG_common_block block in the current
15047              symbol scope.  */
15048           sym = new_symbol (child_die, NULL, cu);
15049           if (sym != NULL)
15050             {
15051               struct attribute *member_loc;
15052
15053               common_block->contents[common_block->n_entries++] = sym;
15054
15055               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
15056                                         cu);
15057               if (member_loc)
15058                 {
15059                   /* GDB has handled this for a long time, but it is
15060                      not specified by DWARF.  It seems to have been
15061                      emitted by gfortran at least as recently as:
15062                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
15063                   complaint (&symfile_complaints,
15064                              _("Variable in common block has "
15065                                "DW_AT_data_member_location "
15066                                "- DIE at 0x%x [in module %s]"),
15067                              to_underlying (child_die->sect_off),
15068                              objfile_name (cu->objfile));
15069
15070                   if (attr_form_is_section_offset (member_loc))
15071                     dwarf2_complex_location_expr_complaint ();
15072                   else if (attr_form_is_constant (member_loc)
15073                            || attr_form_is_block (member_loc))
15074                     {
15075                       if (attr)
15076                         mark_common_block_symbol_computed (sym, die, attr,
15077                                                            member_loc, cu);
15078                     }
15079                   else
15080                     dwarf2_complex_location_expr_complaint ();
15081                 }
15082             }
15083         }
15084
15085       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
15086       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
15087     }
15088 }
15089
15090 /* Create a type for a C++ namespace.  */
15091
15092 static struct type *
15093 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
15094 {
15095   struct objfile *objfile = cu->objfile;
15096   const char *previous_prefix, *name;
15097   int is_anonymous;
15098   struct type *type;
15099
15100   /* For extensions, reuse the type of the original namespace.  */
15101   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
15102     {
15103       struct die_info *ext_die;
15104       struct dwarf2_cu *ext_cu = cu;
15105
15106       ext_die = dwarf2_extension (die, &ext_cu);
15107       type = read_type_die (ext_die, ext_cu);
15108
15109       /* EXT_CU may not be the same as CU.
15110          Ensure TYPE is recorded with CU in die_type_hash.  */
15111       return set_die_type (die, type, cu);
15112     }
15113
15114   name = namespace_name (die, &is_anonymous, cu);
15115
15116   /* Now build the name of the current namespace.  */
15117
15118   previous_prefix = determine_prefix (die, cu);
15119   if (previous_prefix[0] != '\0')
15120     name = typename_concat (&objfile->objfile_obstack,
15121                             previous_prefix, name, 0, cu);
15122
15123   /* Create the type.  */
15124   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
15125   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15126
15127   return set_die_type (die, type, cu);
15128 }
15129
15130 /* Read a namespace scope.  */
15131
15132 static void
15133 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
15134 {
15135   struct objfile *objfile = cu->objfile;
15136   int is_anonymous;
15137
15138   /* Add a symbol associated to this if we haven't seen the namespace
15139      before.  Also, add a using directive if it's an anonymous
15140      namespace.  */
15141
15142   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
15143     {
15144       struct type *type;
15145
15146       type = read_type_die (die, cu);
15147       new_symbol (die, type, cu);
15148
15149       namespace_name (die, &is_anonymous, cu);
15150       if (is_anonymous)
15151         {
15152           const char *previous_prefix = determine_prefix (die, cu);
15153
15154           std::vector<const char *> excludes;
15155           add_using_directive (using_directives (cu->language),
15156                                previous_prefix, TYPE_NAME (type), NULL,
15157                                NULL, excludes, 0, &objfile->objfile_obstack);
15158         }
15159     }
15160
15161   if (die->child != NULL)
15162     {
15163       struct die_info *child_die = die->child;
15164
15165       while (child_die && child_die->tag)
15166         {
15167           process_die (child_die, cu);
15168           child_die = sibling_die (child_die);
15169         }
15170     }
15171 }
15172
15173 /* Read a Fortran module as type.  This DIE can be only a declaration used for
15174    imported module.  Still we need that type as local Fortran "use ... only"
15175    declaration imports depend on the created type in determine_prefix.  */
15176
15177 static struct type *
15178 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
15179 {
15180   struct objfile *objfile = cu->objfile;
15181   const char *module_name;
15182   struct type *type;
15183
15184   module_name = dwarf2_name (die, cu);
15185   if (!module_name)
15186     complaint (&symfile_complaints,
15187                _("DW_TAG_module has no name, offset 0x%x"),
15188                to_underlying (die->sect_off));
15189   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
15190
15191   /* determine_prefix uses TYPE_TAG_NAME.  */
15192   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15193
15194   return set_die_type (die, type, cu);
15195 }
15196
15197 /* Read a Fortran module.  */
15198
15199 static void
15200 read_module (struct die_info *die, struct dwarf2_cu *cu)
15201 {
15202   struct die_info *child_die = die->child;
15203   struct type *type;
15204
15205   type = read_type_die (die, cu);
15206   new_symbol (die, type, cu);
15207
15208   while (child_die && child_die->tag)
15209     {
15210       process_die (child_die, cu);
15211       child_die = sibling_die (child_die);
15212     }
15213 }
15214
15215 /* Return the name of the namespace represented by DIE.  Set
15216    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
15217    namespace.  */
15218
15219 static const char *
15220 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
15221 {
15222   struct die_info *current_die;
15223   const char *name = NULL;
15224
15225   /* Loop through the extensions until we find a name.  */
15226
15227   for (current_die = die;
15228        current_die != NULL;
15229        current_die = dwarf2_extension (die, &cu))
15230     {
15231       /* We don't use dwarf2_name here so that we can detect the absence
15232          of a name -> anonymous namespace.  */
15233       name = dwarf2_string_attr (die, DW_AT_name, cu);
15234
15235       if (name != NULL)
15236         break;
15237     }
15238
15239   /* Is it an anonymous namespace?  */
15240
15241   *is_anonymous = (name == NULL);
15242   if (*is_anonymous)
15243     name = CP_ANONYMOUS_NAMESPACE_STR;
15244
15245   return name;
15246 }
15247
15248 /* Extract all information from a DW_TAG_pointer_type DIE and add to
15249    the user defined type vector.  */
15250
15251 static struct type *
15252 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
15253 {
15254   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
15255   struct comp_unit_head *cu_header = &cu->header;
15256   struct type *type;
15257   struct attribute *attr_byte_size;
15258   struct attribute *attr_address_class;
15259   int byte_size, addr_class;
15260   struct type *target_type;
15261
15262   target_type = die_type (die, cu);
15263
15264   /* The die_type call above may have already set the type for this DIE.  */
15265   type = get_die_type (die, cu);
15266   if (type)
15267     return type;
15268
15269   type = lookup_pointer_type (target_type);
15270
15271   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
15272   if (attr_byte_size)
15273     byte_size = DW_UNSND (attr_byte_size);
15274   else
15275     byte_size = cu_header->addr_size;
15276
15277   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
15278   if (attr_address_class)
15279     addr_class = DW_UNSND (attr_address_class);
15280   else
15281     addr_class = DW_ADDR_none;
15282
15283   /* If the pointer size or address class is different than the
15284      default, create a type variant marked as such and set the
15285      length accordingly.  */
15286   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
15287     {
15288       if (gdbarch_address_class_type_flags_p (gdbarch))
15289         {
15290           int type_flags;
15291
15292           type_flags = gdbarch_address_class_type_flags
15293                          (gdbarch, byte_size, addr_class);
15294           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
15295                       == 0);
15296           type = make_type_with_address_space (type, type_flags);
15297         }
15298       else if (TYPE_LENGTH (type) != byte_size)
15299         {
15300           complaint (&symfile_complaints,
15301                      _("invalid pointer size %d"), byte_size);
15302         }
15303       else
15304         {
15305           /* Should we also complain about unhandled address classes?  */
15306         }
15307     }
15308
15309   TYPE_LENGTH (type) = byte_size;
15310   return set_die_type (die, type, cu);
15311 }
15312
15313 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
15314    the user defined type vector.  */
15315
15316 static struct type *
15317 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
15318 {
15319   struct type *type;
15320   struct type *to_type;
15321   struct type *domain;
15322
15323   to_type = die_type (die, cu);
15324   domain = die_containing_type (die, cu);
15325
15326   /* The calls above may have already set the type for this DIE.  */
15327   type = get_die_type (die, cu);
15328   if (type)
15329     return type;
15330
15331   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
15332     type = lookup_methodptr_type (to_type);
15333   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
15334     {
15335       struct type *new_type = alloc_type (cu->objfile);
15336
15337       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
15338                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
15339                             TYPE_VARARGS (to_type));
15340       type = lookup_methodptr_type (new_type);
15341     }
15342   else
15343     type = lookup_memberptr_type (to_type, domain);
15344
15345   return set_die_type (die, type, cu);
15346 }
15347
15348 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
15349    the user defined type vector.  */
15350
15351 static struct type *
15352 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
15353                           enum type_code refcode)
15354 {
15355   struct comp_unit_head *cu_header = &cu->header;
15356   struct type *type, *target_type;
15357   struct attribute *attr;
15358
15359   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
15360
15361   target_type = die_type (die, cu);
15362
15363   /* The die_type call above may have already set the type for this DIE.  */
15364   type = get_die_type (die, cu);
15365   if (type)
15366     return type;
15367
15368   type = lookup_reference_type (target_type, refcode);
15369   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15370   if (attr)
15371     {
15372       TYPE_LENGTH (type) = DW_UNSND (attr);
15373     }
15374   else
15375     {
15376       TYPE_LENGTH (type) = cu_header->addr_size;
15377     }
15378   return set_die_type (die, type, cu);
15379 }
15380
15381 /* Add the given cv-qualifiers to the element type of the array.  GCC
15382    outputs DWARF type qualifiers that apply to an array, not the
15383    element type.  But GDB relies on the array element type to carry
15384    the cv-qualifiers.  This mimics section 6.7.3 of the C99
15385    specification.  */
15386
15387 static struct type *
15388 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
15389                    struct type *base_type, int cnst, int voltl)
15390 {
15391   struct type *el_type, *inner_array;
15392
15393   base_type = copy_type (base_type);
15394   inner_array = base_type;
15395
15396   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
15397     {
15398       TYPE_TARGET_TYPE (inner_array) =
15399         copy_type (TYPE_TARGET_TYPE (inner_array));
15400       inner_array = TYPE_TARGET_TYPE (inner_array);
15401     }
15402
15403   el_type = TYPE_TARGET_TYPE (inner_array);
15404   cnst |= TYPE_CONST (el_type);
15405   voltl |= TYPE_VOLATILE (el_type);
15406   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
15407
15408   return set_die_type (die, base_type, cu);
15409 }
15410
15411 static struct type *
15412 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
15413 {
15414   struct type *base_type, *cv_type;
15415
15416   base_type = die_type (die, cu);
15417
15418   /* The die_type call above may have already set the type for this DIE.  */
15419   cv_type = get_die_type (die, cu);
15420   if (cv_type)
15421     return cv_type;
15422
15423   /* In case the const qualifier is applied to an array type, the element type
15424      is so qualified, not the array type (section 6.7.3 of C99).  */
15425   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15426     return add_array_cv_type (die, cu, base_type, 1, 0);
15427
15428   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
15429   return set_die_type (die, cv_type, cu);
15430 }
15431
15432 static struct type *
15433 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
15434 {
15435   struct type *base_type, *cv_type;
15436
15437   base_type = die_type (die, cu);
15438
15439   /* The die_type call above may have already set the type for this DIE.  */
15440   cv_type = get_die_type (die, cu);
15441   if (cv_type)
15442     return cv_type;
15443
15444   /* In case the volatile qualifier is applied to an array type, the
15445      element type is so qualified, not the array type (section 6.7.3
15446      of C99).  */
15447   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15448     return add_array_cv_type (die, cu, base_type, 0, 1);
15449
15450   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
15451   return set_die_type (die, cv_type, cu);
15452 }
15453
15454 /* Handle DW_TAG_restrict_type.  */
15455
15456 static struct type *
15457 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
15458 {
15459   struct type *base_type, *cv_type;
15460
15461   base_type = die_type (die, cu);
15462
15463   /* The die_type call above may have already set the type for this DIE.  */
15464   cv_type = get_die_type (die, cu);
15465   if (cv_type)
15466     return cv_type;
15467
15468   cv_type = make_restrict_type (base_type);
15469   return set_die_type (die, cv_type, cu);
15470 }
15471
15472 /* Handle DW_TAG_atomic_type.  */
15473
15474 static struct type *
15475 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
15476 {
15477   struct type *base_type, *cv_type;
15478
15479   base_type = die_type (die, cu);
15480
15481   /* The die_type call above may have already set the type for this DIE.  */
15482   cv_type = get_die_type (die, cu);
15483   if (cv_type)
15484     return cv_type;
15485
15486   cv_type = make_atomic_type (base_type);
15487   return set_die_type (die, cv_type, cu);
15488 }
15489
15490 /* Extract all information from a DW_TAG_string_type DIE and add to
15491    the user defined type vector.  It isn't really a user defined type,
15492    but it behaves like one, with other DIE's using an AT_user_def_type
15493    attribute to reference it.  */
15494
15495 static struct type *
15496 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
15497 {
15498   struct objfile *objfile = cu->objfile;
15499   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15500   struct type *type, *range_type, *index_type, *char_type;
15501   struct attribute *attr;
15502   unsigned int length;
15503
15504   attr = dwarf2_attr (die, DW_AT_string_length, cu);
15505   if (attr)
15506     {
15507       length = DW_UNSND (attr);
15508     }
15509   else
15510     {
15511       /* Check for the DW_AT_byte_size attribute.  */
15512       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15513       if (attr)
15514         {
15515           length = DW_UNSND (attr);
15516         }
15517       else
15518         {
15519           length = 1;
15520         }
15521     }
15522
15523   index_type = objfile_type (objfile)->builtin_int;
15524   range_type = create_static_range_type (NULL, index_type, 1, length);
15525   char_type = language_string_char_type (cu->language_defn, gdbarch);
15526   type = create_string_type (NULL, char_type, range_type);
15527
15528   return set_die_type (die, type, cu);
15529 }
15530
15531 /* Assuming that DIE corresponds to a function, returns nonzero
15532    if the function is prototyped.  */
15533
15534 static int
15535 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
15536 {
15537   struct attribute *attr;
15538
15539   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15540   if (attr && (DW_UNSND (attr) != 0))
15541     return 1;
15542
15543   /* The DWARF standard implies that the DW_AT_prototyped attribute
15544      is only meaninful for C, but the concept also extends to other
15545      languages that allow unprototyped functions (Eg: Objective C).
15546      For all other languages, assume that functions are always
15547      prototyped.  */
15548   if (cu->language != language_c
15549       && cu->language != language_objc
15550       && cu->language != language_opencl)
15551     return 1;
15552
15553   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15554      prototyped and unprototyped functions; default to prototyped,
15555      since that is more common in modern code (and RealView warns
15556      about unprototyped functions).  */
15557   if (producer_is_realview (cu->producer))
15558     return 1;
15559
15560   return 0;
15561 }
15562
15563 /* Handle DIES due to C code like:
15564
15565    struct foo
15566    {
15567    int (*funcp)(int a, long l);
15568    int b;
15569    };
15570
15571    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15572
15573 static struct type *
15574 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15575 {
15576   struct objfile *objfile = cu->objfile;
15577   struct type *type;            /* Type that this function returns.  */
15578   struct type *ftype;           /* Function that returns above type.  */
15579   struct attribute *attr;
15580
15581   type = die_type (die, cu);
15582
15583   /* The die_type call above may have already set the type for this DIE.  */
15584   ftype = get_die_type (die, cu);
15585   if (ftype)
15586     return ftype;
15587
15588   ftype = lookup_function_type (type);
15589
15590   if (prototyped_function_p (die, cu))
15591     TYPE_PROTOTYPED (ftype) = 1;
15592
15593   /* Store the calling convention in the type if it's available in
15594      the subroutine die.  Otherwise set the calling convention to
15595      the default value DW_CC_normal.  */
15596   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15597   if (attr)
15598     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15599   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15600     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15601   else
15602     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15603
15604   /* Record whether the function returns normally to its caller or not
15605      if the DWARF producer set that information.  */
15606   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15607   if (attr && (DW_UNSND (attr) != 0))
15608     TYPE_NO_RETURN (ftype) = 1;
15609
15610   /* We need to add the subroutine type to the die immediately so
15611      we don't infinitely recurse when dealing with parameters
15612      declared as the same subroutine type.  */
15613   set_die_type (die, ftype, cu);
15614
15615   if (die->child != NULL)
15616     {
15617       struct type *void_type = objfile_type (objfile)->builtin_void;
15618       struct die_info *child_die;
15619       int nparams, iparams;
15620
15621       /* Count the number of parameters.
15622          FIXME: GDB currently ignores vararg functions, but knows about
15623          vararg member functions.  */
15624       nparams = 0;
15625       child_die = die->child;
15626       while (child_die && child_die->tag)
15627         {
15628           if (child_die->tag == DW_TAG_formal_parameter)
15629             nparams++;
15630           else if (child_die->tag == DW_TAG_unspecified_parameters)
15631             TYPE_VARARGS (ftype) = 1;
15632           child_die = sibling_die (child_die);
15633         }
15634
15635       /* Allocate storage for parameters and fill them in.  */
15636       TYPE_NFIELDS (ftype) = nparams;
15637       TYPE_FIELDS (ftype) = (struct field *)
15638         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15639
15640       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15641          even if we error out during the parameters reading below.  */
15642       for (iparams = 0; iparams < nparams; iparams++)
15643         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15644
15645       iparams = 0;
15646       child_die = die->child;
15647       while (child_die && child_die->tag)
15648         {
15649           if (child_die->tag == DW_TAG_formal_parameter)
15650             {
15651               struct type *arg_type;
15652
15653               /* DWARF version 2 has no clean way to discern C++
15654                  static and non-static member functions.  G++ helps
15655                  GDB by marking the first parameter for non-static
15656                  member functions (which is the this pointer) as
15657                  artificial.  We pass this information to
15658                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15659
15660                  DWARF version 3 added DW_AT_object_pointer, which GCC
15661                  4.5 does not yet generate.  */
15662               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15663               if (attr)
15664                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15665               else
15666                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15667               arg_type = die_type (child_die, cu);
15668
15669               /* RealView does not mark THIS as const, which the testsuite
15670                  expects.  GCC marks THIS as const in method definitions,
15671                  but not in the class specifications (GCC PR 43053).  */
15672               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15673                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15674                 {
15675                   int is_this = 0;
15676                   struct dwarf2_cu *arg_cu = cu;
15677                   const char *name = dwarf2_name (child_die, cu);
15678
15679                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15680                   if (attr)
15681                     {
15682                       /* If the compiler emits this, use it.  */
15683                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15684                         is_this = 1;
15685                     }
15686                   else if (name && strcmp (name, "this") == 0)
15687                     /* Function definitions will have the argument names.  */
15688                     is_this = 1;
15689                   else if (name == NULL && iparams == 0)
15690                     /* Declarations may not have the names, so like
15691                        elsewhere in GDB, assume an artificial first
15692                        argument is "this".  */
15693                     is_this = 1;
15694
15695                   if (is_this)
15696                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15697                                              arg_type, 0);
15698                 }
15699
15700               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15701               iparams++;
15702             }
15703           child_die = sibling_die (child_die);
15704         }
15705     }
15706
15707   return ftype;
15708 }
15709
15710 static struct type *
15711 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15712 {
15713   struct objfile *objfile = cu->objfile;
15714   const char *name = NULL;
15715   struct type *this_type, *target_type;
15716
15717   name = dwarf2_full_name (NULL, die, cu);
15718   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15719   TYPE_TARGET_STUB (this_type) = 1;
15720   set_die_type (die, this_type, cu);
15721   target_type = die_type (die, cu);
15722   if (target_type != this_type)
15723     TYPE_TARGET_TYPE (this_type) = target_type;
15724   else
15725     {
15726       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15727          spec and cause infinite loops in GDB.  */
15728       complaint (&symfile_complaints,
15729                  _("Self-referential DW_TAG_typedef "
15730                    "- DIE at 0x%x [in module %s]"),
15731                  to_underlying (die->sect_off), objfile_name (objfile));
15732       TYPE_TARGET_TYPE (this_type) = NULL;
15733     }
15734   return this_type;
15735 }
15736
15737 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15738    (which may be different from NAME) to the architecture back-end to allow
15739    it to guess the correct format if necessary.  */
15740
15741 static struct type *
15742 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15743                         const char *name_hint)
15744 {
15745   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15746   const struct floatformat **format;
15747   struct type *type;
15748
15749   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15750   if (format)
15751     type = init_float_type (objfile, bits, name, format);
15752   else
15753     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15754
15755   return type;
15756 }
15757
15758 /* Find a representation of a given base type and install
15759    it in the TYPE field of the die.  */
15760
15761 static struct type *
15762 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15763 {
15764   struct objfile *objfile = cu->objfile;
15765   struct type *type;
15766   struct attribute *attr;
15767   int encoding = 0, bits = 0;
15768   const char *name;
15769
15770   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15771   if (attr)
15772     {
15773       encoding = DW_UNSND (attr);
15774     }
15775   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15776   if (attr)
15777     {
15778       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15779     }
15780   name = dwarf2_name (die, cu);
15781   if (!name)
15782     {
15783       complaint (&symfile_complaints,
15784                  _("DW_AT_name missing from DW_TAG_base_type"));
15785     }
15786
15787   switch (encoding)
15788     {
15789       case DW_ATE_address:
15790         /* Turn DW_ATE_address into a void * pointer.  */
15791         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
15792         type = init_pointer_type (objfile, bits, name, type);
15793         break;
15794       case DW_ATE_boolean:
15795         type = init_boolean_type (objfile, bits, 1, name);
15796         break;
15797       case DW_ATE_complex_float:
15798         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15799         type = init_complex_type (objfile, name, type);
15800         break;
15801       case DW_ATE_decimal_float:
15802         type = init_decfloat_type (objfile, bits, name);
15803         break;
15804       case DW_ATE_float:
15805         type = dwarf2_init_float_type (objfile, bits, name, name);
15806         break;
15807       case DW_ATE_signed:
15808         type = init_integer_type (objfile, bits, 0, name);
15809         break;
15810       case DW_ATE_unsigned:
15811         if (cu->language == language_fortran
15812             && name
15813             && startswith (name, "character("))
15814           type = init_character_type (objfile, bits, 1, name);
15815         else
15816           type = init_integer_type (objfile, bits, 1, name);
15817         break;
15818       case DW_ATE_signed_char:
15819         if (cu->language == language_ada || cu->language == language_m2
15820             || cu->language == language_pascal
15821             || cu->language == language_fortran)
15822           type = init_character_type (objfile, bits, 0, name);
15823         else
15824           type = init_integer_type (objfile, bits, 0, name);
15825         break;
15826       case DW_ATE_unsigned_char:
15827         if (cu->language == language_ada || cu->language == language_m2
15828             || cu->language == language_pascal
15829             || cu->language == language_fortran
15830             || cu->language == language_rust)
15831           type = init_character_type (objfile, bits, 1, name);
15832         else
15833           type = init_integer_type (objfile, bits, 1, name);
15834         break;
15835       case DW_ATE_UTF:
15836         {
15837           gdbarch *arch = get_objfile_arch (objfile);
15838
15839           if (bits == 16)
15840             type = builtin_type (arch)->builtin_char16;
15841           else if (bits == 32)
15842             type = builtin_type (arch)->builtin_char32;
15843           else
15844             {
15845               complaint (&symfile_complaints,
15846                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15847                          bits);
15848               type = init_integer_type (objfile, bits, 1, name);
15849             }
15850           return set_die_type (die, type, cu);
15851         }
15852         break;
15853
15854       default:
15855         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15856                    dwarf_type_encoding_name (encoding));
15857         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15858         break;
15859     }
15860
15861   if (name && strcmp (name, "char") == 0)
15862     TYPE_NOSIGN (type) = 1;
15863
15864   return set_die_type (die, type, cu);
15865 }
15866
15867 /* Parse dwarf attribute if it's a block, reference or constant and put the
15868    resulting value of the attribute into struct bound_prop.
15869    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15870
15871 static int
15872 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15873                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15874 {
15875   struct dwarf2_property_baton *baton;
15876   struct obstack *obstack = &cu->objfile->objfile_obstack;
15877
15878   if (attr == NULL || prop == NULL)
15879     return 0;
15880
15881   if (attr_form_is_block (attr))
15882     {
15883       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15884       baton->referenced_type = NULL;
15885       baton->locexpr.per_cu = cu->per_cu;
15886       baton->locexpr.size = DW_BLOCK (attr)->size;
15887       baton->locexpr.data = DW_BLOCK (attr)->data;
15888       prop->data.baton = baton;
15889       prop->kind = PROP_LOCEXPR;
15890       gdb_assert (prop->data.baton != NULL);
15891     }
15892   else if (attr_form_is_ref (attr))
15893     {
15894       struct dwarf2_cu *target_cu = cu;
15895       struct die_info *target_die;
15896       struct attribute *target_attr;
15897
15898       target_die = follow_die_ref (die, attr, &target_cu);
15899       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15900       if (target_attr == NULL)
15901         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15902                                    target_cu);
15903       if (target_attr == NULL)
15904         return 0;
15905
15906       switch (target_attr->name)
15907         {
15908           case DW_AT_location:
15909             if (attr_form_is_section_offset (target_attr))
15910               {
15911                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15912                 baton->referenced_type = die_type (target_die, target_cu);
15913                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15914                 prop->data.baton = baton;
15915                 prop->kind = PROP_LOCLIST;
15916                 gdb_assert (prop->data.baton != NULL);
15917               }
15918             else if (attr_form_is_block (target_attr))
15919               {
15920                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15921                 baton->referenced_type = die_type (target_die, target_cu);
15922                 baton->locexpr.per_cu = cu->per_cu;
15923                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15924                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15925                 prop->data.baton = baton;
15926                 prop->kind = PROP_LOCEXPR;
15927                 gdb_assert (prop->data.baton != NULL);
15928               }
15929             else
15930               {
15931                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15932                                                        "dynamic property");
15933                 return 0;
15934               }
15935             break;
15936           case DW_AT_data_member_location:
15937             {
15938               LONGEST offset;
15939
15940               if (!handle_data_member_location (target_die, target_cu,
15941                                                 &offset))
15942                 return 0;
15943
15944               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15945               baton->referenced_type = read_type_die (target_die->parent,
15946                                                       target_cu);
15947               baton->offset_info.offset = offset;
15948               baton->offset_info.type = die_type (target_die, target_cu);
15949               prop->data.baton = baton;
15950               prop->kind = PROP_ADDR_OFFSET;
15951               break;
15952             }
15953         }
15954     }
15955   else if (attr_form_is_constant (attr))
15956     {
15957       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15958       prop->kind = PROP_CONST;
15959     }
15960   else
15961     {
15962       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15963                                              dwarf2_name (die, cu));
15964       return 0;
15965     }
15966
15967   return 1;
15968 }
15969
15970 /* Read the given DW_AT_subrange DIE.  */
15971
15972 static struct type *
15973 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15974 {
15975   struct type *base_type, *orig_base_type;
15976   struct type *range_type;
15977   struct attribute *attr;
15978   struct dynamic_prop low, high;
15979   int low_default_is_valid;
15980   int high_bound_is_count = 0;
15981   const char *name;
15982   LONGEST negative_mask;
15983
15984   orig_base_type = die_type (die, cu);
15985   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15986      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15987      creating the range type, but we use the result of check_typedef
15988      when examining properties of the type.  */
15989   base_type = check_typedef (orig_base_type);
15990
15991   /* The die_type call above may have already set the type for this DIE.  */
15992   range_type = get_die_type (die, cu);
15993   if (range_type)
15994     return range_type;
15995
15996   low.kind = PROP_CONST;
15997   high.kind = PROP_CONST;
15998   high.data.const_val = 0;
15999
16000   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
16001      omitting DW_AT_lower_bound.  */
16002   switch (cu->language)
16003     {
16004     case language_c:
16005     case language_cplus:
16006       low.data.const_val = 0;
16007       low_default_is_valid = 1;
16008       break;
16009     case language_fortran:
16010       low.data.const_val = 1;
16011       low_default_is_valid = 1;
16012       break;
16013     case language_d:
16014     case language_objc:
16015     case language_rust:
16016       low.data.const_val = 0;
16017       low_default_is_valid = (cu->header.version >= 4);
16018       break;
16019     case language_ada:
16020     case language_m2:
16021     case language_pascal:
16022       low.data.const_val = 1;
16023       low_default_is_valid = (cu->header.version >= 4);
16024       break;
16025     default:
16026       low.data.const_val = 0;
16027       low_default_is_valid = 0;
16028       break;
16029     }
16030
16031   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
16032   if (attr)
16033     attr_to_dynamic_prop (attr, die, cu, &low);
16034   else if (!low_default_is_valid)
16035     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
16036                                       "- DIE at 0x%x [in module %s]"),
16037                to_underlying (die->sect_off), objfile_name (cu->objfile));
16038
16039   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
16040   if (!attr_to_dynamic_prop (attr, die, cu, &high))
16041     {
16042       attr = dwarf2_attr (die, DW_AT_count, cu);
16043       if (attr_to_dynamic_prop (attr, die, cu, &high))
16044         {
16045           /* If bounds are constant do the final calculation here.  */
16046           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
16047             high.data.const_val = low.data.const_val + high.data.const_val - 1;
16048           else
16049             high_bound_is_count = 1;
16050         }
16051     }
16052
16053   /* Dwarf-2 specifications explicitly allows to create subrange types
16054      without specifying a base type.
16055      In that case, the base type must be set to the type of
16056      the lower bound, upper bound or count, in that order, if any of these
16057      three attributes references an object that has a type.
16058      If no base type is found, the Dwarf-2 specifications say that
16059      a signed integer type of size equal to the size of an address should
16060      be used.
16061      For the following C code: `extern char gdb_int [];'
16062      GCC produces an empty range DIE.
16063      FIXME: muller/2010-05-28: Possible references to object for low bound,
16064      high bound or count are not yet handled by this code.  */
16065   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
16066     {
16067       struct objfile *objfile = cu->objfile;
16068       struct gdbarch *gdbarch = get_objfile_arch (objfile);
16069       int addr_size = gdbarch_addr_bit (gdbarch) /8;
16070       struct type *int_type = objfile_type (objfile)->builtin_int;
16071
16072       /* Test "int", "long int", and "long long int" objfile types,
16073          and select the first one having a size above or equal to the
16074          architecture address size.  */
16075       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16076         base_type = int_type;
16077       else
16078         {
16079           int_type = objfile_type (objfile)->builtin_long;
16080           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16081             base_type = int_type;
16082           else
16083             {
16084               int_type = objfile_type (objfile)->builtin_long_long;
16085               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16086                 base_type = int_type;
16087             }
16088         }
16089     }
16090
16091   /* Normally, the DWARF producers are expected to use a signed
16092      constant form (Eg. DW_FORM_sdata) to express negative bounds.
16093      But this is unfortunately not always the case, as witnessed
16094      with GCC, for instance, where the ambiguous DW_FORM_dataN form
16095      is used instead.  To work around that ambiguity, we treat
16096      the bounds as signed, and thus sign-extend their values, when
16097      the base type is signed.  */
16098   negative_mask =
16099     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
16100   if (low.kind == PROP_CONST
16101       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
16102     low.data.const_val |= negative_mask;
16103   if (high.kind == PROP_CONST
16104       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
16105     high.data.const_val |= negative_mask;
16106
16107   range_type = create_range_type (NULL, orig_base_type, &low, &high);
16108
16109   if (high_bound_is_count)
16110     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
16111
16112   /* Ada expects an empty array on no boundary attributes.  */
16113   if (attr == NULL && cu->language != language_ada)
16114     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
16115
16116   name = dwarf2_name (die, cu);
16117   if (name)
16118     TYPE_NAME (range_type) = name;
16119
16120   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16121   if (attr)
16122     TYPE_LENGTH (range_type) = DW_UNSND (attr);
16123
16124   set_die_type (die, range_type, cu);
16125
16126   /* set_die_type should be already done.  */
16127   set_descriptive_type (range_type, die, cu);
16128
16129   return range_type;
16130 }
16131
16132 static struct type *
16133 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
16134 {
16135   struct type *type;
16136
16137   /* For now, we only support the C meaning of an unspecified type: void.  */
16138
16139   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
16140   TYPE_NAME (type) = dwarf2_name (die, cu);
16141
16142   return set_die_type (die, type, cu);
16143 }
16144
16145 /* Read a single die and all its descendents.  Set the die's sibling
16146    field to NULL; set other fields in the die correctly, and set all
16147    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
16148    location of the info_ptr after reading all of those dies.  PARENT
16149    is the parent of the die in question.  */
16150
16151 static struct die_info *
16152 read_die_and_children (const struct die_reader_specs *reader,
16153                        const gdb_byte *info_ptr,
16154                        const gdb_byte **new_info_ptr,
16155                        struct die_info *parent)
16156 {
16157   struct die_info *die;
16158   const gdb_byte *cur_ptr;
16159   int has_children;
16160
16161   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
16162   if (die == NULL)
16163     {
16164       *new_info_ptr = cur_ptr;
16165       return NULL;
16166     }
16167   store_in_ref_table (die, reader->cu);
16168
16169   if (has_children)
16170     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
16171   else
16172     {
16173       die->child = NULL;
16174       *new_info_ptr = cur_ptr;
16175     }
16176
16177   die->sibling = NULL;
16178   die->parent = parent;
16179   return die;
16180 }
16181
16182 /* Read a die, all of its descendents, and all of its siblings; set
16183    all of the fields of all of the dies correctly.  Arguments are as
16184    in read_die_and_children.  */
16185
16186 static struct die_info *
16187 read_die_and_siblings_1 (const struct die_reader_specs *reader,
16188                          const gdb_byte *info_ptr,
16189                          const gdb_byte **new_info_ptr,
16190                          struct die_info *parent)
16191 {
16192   struct die_info *first_die, *last_sibling;
16193   const gdb_byte *cur_ptr;
16194
16195   cur_ptr = info_ptr;
16196   first_die = last_sibling = NULL;
16197
16198   while (1)
16199     {
16200       struct die_info *die
16201         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
16202
16203       if (die == NULL)
16204         {
16205           *new_info_ptr = cur_ptr;
16206           return first_die;
16207         }
16208
16209       if (!first_die)
16210         first_die = die;
16211       else
16212         last_sibling->sibling = die;
16213
16214       last_sibling = die;
16215     }
16216 }
16217
16218 /* Read a die, all of its descendents, and all of its siblings; set
16219    all of the fields of all of the dies correctly.  Arguments are as
16220    in read_die_and_children.
16221    This the main entry point for reading a DIE and all its children.  */
16222
16223 static struct die_info *
16224 read_die_and_siblings (const struct die_reader_specs *reader,
16225                        const gdb_byte *info_ptr,
16226                        const gdb_byte **new_info_ptr,
16227                        struct die_info *parent)
16228 {
16229   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
16230                                                   new_info_ptr, parent);
16231
16232   if (dwarf_die_debug)
16233     {
16234       fprintf_unfiltered (gdb_stdlog,
16235                           "Read die from %s@0x%x of %s:\n",
16236                           get_section_name (reader->die_section),
16237                           (unsigned) (info_ptr - reader->die_section->buffer),
16238                           bfd_get_filename (reader->abfd));
16239       dump_die (die, dwarf_die_debug);
16240     }
16241
16242   return die;
16243 }
16244
16245 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
16246    attributes.
16247    The caller is responsible for filling in the extra attributes
16248    and updating (*DIEP)->num_attrs.
16249    Set DIEP to point to a newly allocated die with its information,
16250    except for its child, sibling, and parent fields.
16251    Set HAS_CHILDREN to tell whether the die has children or not.  */
16252
16253 static const gdb_byte *
16254 read_full_die_1 (const struct die_reader_specs *reader,
16255                  struct die_info **diep, const gdb_byte *info_ptr,
16256                  int *has_children, int num_extra_attrs)
16257 {
16258   unsigned int abbrev_number, bytes_read, i;
16259   struct abbrev_info *abbrev;
16260   struct die_info *die;
16261   struct dwarf2_cu *cu = reader->cu;
16262   bfd *abfd = reader->abfd;
16263
16264   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
16265   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16266   info_ptr += bytes_read;
16267   if (!abbrev_number)
16268     {
16269       *diep = NULL;
16270       *has_children = 0;
16271       return info_ptr;
16272     }
16273
16274   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
16275   if (!abbrev)
16276     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
16277            abbrev_number,
16278            bfd_get_filename (abfd));
16279
16280   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
16281   die->sect_off = sect_off;
16282   die->tag = abbrev->tag;
16283   die->abbrev = abbrev_number;
16284
16285   /* Make the result usable.
16286      The caller needs to update num_attrs after adding the extra
16287      attributes.  */
16288   die->num_attrs = abbrev->num_attrs;
16289
16290   for (i = 0; i < abbrev->num_attrs; ++i)
16291     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
16292                                info_ptr);
16293
16294   *diep = die;
16295   *has_children = abbrev->has_children;
16296   return info_ptr;
16297 }
16298
16299 /* Read a die and all its attributes.
16300    Set DIEP to point to a newly allocated die with its information,
16301    except for its child, sibling, and parent fields.
16302    Set HAS_CHILDREN to tell whether the die has children or not.  */
16303
16304 static const gdb_byte *
16305 read_full_die (const struct die_reader_specs *reader,
16306                struct die_info **diep, const gdb_byte *info_ptr,
16307                int *has_children)
16308 {
16309   const gdb_byte *result;
16310
16311   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
16312
16313   if (dwarf_die_debug)
16314     {
16315       fprintf_unfiltered (gdb_stdlog,
16316                           "Read die from %s@0x%x of %s:\n",
16317                           get_section_name (reader->die_section),
16318                           (unsigned) (info_ptr - reader->die_section->buffer),
16319                           bfd_get_filename (reader->abfd));
16320       dump_die (*diep, dwarf_die_debug);
16321     }
16322
16323   return result;
16324 }
16325 \f
16326 /* Abbreviation tables.
16327
16328    In DWARF version 2, the description of the debugging information is
16329    stored in a separate .debug_abbrev section.  Before we read any
16330    dies from a section we read in all abbreviations and install them
16331    in a hash table.  */
16332
16333 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
16334
16335 static struct abbrev_info *
16336 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
16337 {
16338   struct abbrev_info *abbrev;
16339
16340   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
16341   memset (abbrev, 0, sizeof (struct abbrev_info));
16342
16343   return abbrev;
16344 }
16345
16346 /* Add an abbreviation to the table.  */
16347
16348 static void
16349 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
16350                          unsigned int abbrev_number,
16351                          struct abbrev_info *abbrev)
16352 {
16353   unsigned int hash_number;
16354
16355   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16356   abbrev->next = abbrev_table->abbrevs[hash_number];
16357   abbrev_table->abbrevs[hash_number] = abbrev;
16358 }
16359
16360 /* Look up an abbrev in the table.
16361    Returns NULL if the abbrev is not found.  */
16362
16363 static struct abbrev_info *
16364 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
16365                             unsigned int abbrev_number)
16366 {
16367   unsigned int hash_number;
16368   struct abbrev_info *abbrev;
16369
16370   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16371   abbrev = abbrev_table->abbrevs[hash_number];
16372
16373   while (abbrev)
16374     {
16375       if (abbrev->number == abbrev_number)
16376         return abbrev;
16377       abbrev = abbrev->next;
16378     }
16379   return NULL;
16380 }
16381
16382 /* Read in an abbrev table.  */
16383
16384 static struct abbrev_table *
16385 abbrev_table_read_table (struct dwarf2_section_info *section,
16386                          sect_offset sect_off)
16387 {
16388   struct objfile *objfile = dwarf2_per_objfile->objfile;
16389   bfd *abfd = get_section_bfd_owner (section);
16390   struct abbrev_table *abbrev_table;
16391   const gdb_byte *abbrev_ptr;
16392   struct abbrev_info *cur_abbrev;
16393   unsigned int abbrev_number, bytes_read, abbrev_name;
16394   unsigned int abbrev_form;
16395   struct attr_abbrev *cur_attrs;
16396   unsigned int allocated_attrs;
16397
16398   abbrev_table = XNEW (struct abbrev_table);
16399   abbrev_table->sect_off = sect_off;
16400   obstack_init (&abbrev_table->abbrev_obstack);
16401   abbrev_table->abbrevs =
16402     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
16403                ABBREV_HASH_SIZE);
16404   memset (abbrev_table->abbrevs, 0,
16405           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
16406
16407   dwarf2_read_section (objfile, section);
16408   abbrev_ptr = section->buffer + to_underlying (sect_off);
16409   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16410   abbrev_ptr += bytes_read;
16411
16412   allocated_attrs = ATTR_ALLOC_CHUNK;
16413   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
16414
16415   /* Loop until we reach an abbrev number of 0.  */
16416   while (abbrev_number)
16417     {
16418       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
16419
16420       /* read in abbrev header */
16421       cur_abbrev->number = abbrev_number;
16422       cur_abbrev->tag
16423         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16424       abbrev_ptr += bytes_read;
16425       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
16426       abbrev_ptr += 1;
16427
16428       /* now read in declarations */
16429       for (;;)
16430         {
16431           LONGEST implicit_const;
16432
16433           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16434           abbrev_ptr += bytes_read;
16435           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16436           abbrev_ptr += bytes_read;
16437           if (abbrev_form == DW_FORM_implicit_const)
16438             {
16439               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
16440                                                    &bytes_read);
16441               abbrev_ptr += bytes_read;
16442             }
16443           else
16444             {
16445               /* Initialize it due to a false compiler warning.  */
16446               implicit_const = -1;
16447             }
16448
16449           if (abbrev_name == 0)
16450             break;
16451
16452           if (cur_abbrev->num_attrs == allocated_attrs)
16453             {
16454               allocated_attrs += ATTR_ALLOC_CHUNK;
16455               cur_attrs
16456                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
16457             }
16458
16459           cur_attrs[cur_abbrev->num_attrs].name
16460             = (enum dwarf_attribute) abbrev_name;
16461           cur_attrs[cur_abbrev->num_attrs].form
16462             = (enum dwarf_form) abbrev_form;
16463           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
16464           ++cur_abbrev->num_attrs;
16465         }
16466
16467       cur_abbrev->attrs =
16468         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
16469                    cur_abbrev->num_attrs);
16470       memcpy (cur_abbrev->attrs, cur_attrs,
16471               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
16472
16473       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
16474
16475       /* Get next abbreviation.
16476          Under Irix6 the abbreviations for a compilation unit are not
16477          always properly terminated with an abbrev number of 0.
16478          Exit loop if we encounter an abbreviation which we have
16479          already read (which means we are about to read the abbreviations
16480          for the next compile unit) or if the end of the abbreviation
16481          table is reached.  */
16482       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
16483         break;
16484       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16485       abbrev_ptr += bytes_read;
16486       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
16487         break;
16488     }
16489
16490   xfree (cur_attrs);
16491   return abbrev_table;
16492 }
16493
16494 /* Free the resources held by ABBREV_TABLE.  */
16495
16496 static void
16497 abbrev_table_free (struct abbrev_table *abbrev_table)
16498 {
16499   obstack_free (&abbrev_table->abbrev_obstack, NULL);
16500   xfree (abbrev_table);
16501 }
16502
16503 /* Same as abbrev_table_free but as a cleanup.
16504    We pass in a pointer to the pointer to the table so that we can
16505    set the pointer to NULL when we're done.  It also simplifies
16506    build_type_psymtabs_1.  */
16507
16508 static void
16509 abbrev_table_free_cleanup (void *table_ptr)
16510 {
16511   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
16512
16513   if (*abbrev_table_ptr != NULL)
16514     abbrev_table_free (*abbrev_table_ptr);
16515   *abbrev_table_ptr = NULL;
16516 }
16517
16518 /* Read the abbrev table for CU from ABBREV_SECTION.  */
16519
16520 static void
16521 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
16522                      struct dwarf2_section_info *abbrev_section)
16523 {
16524   cu->abbrev_table =
16525     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
16526 }
16527
16528 /* Release the memory used by the abbrev table for a compilation unit.  */
16529
16530 static void
16531 dwarf2_free_abbrev_table (void *ptr_to_cu)
16532 {
16533   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
16534
16535   if (cu->abbrev_table != NULL)
16536     abbrev_table_free (cu->abbrev_table);
16537   /* Set this to NULL so that we SEGV if we try to read it later,
16538      and also because free_comp_unit verifies this is NULL.  */
16539   cu->abbrev_table = NULL;
16540 }
16541 \f
16542 /* Returns nonzero if TAG represents a type that we might generate a partial
16543    symbol for.  */
16544
16545 static int
16546 is_type_tag_for_partial (int tag)
16547 {
16548   switch (tag)
16549     {
16550 #if 0
16551     /* Some types that would be reasonable to generate partial symbols for,
16552        that we don't at present.  */
16553     case DW_TAG_array_type:
16554     case DW_TAG_file_type:
16555     case DW_TAG_ptr_to_member_type:
16556     case DW_TAG_set_type:
16557     case DW_TAG_string_type:
16558     case DW_TAG_subroutine_type:
16559 #endif
16560     case DW_TAG_base_type:
16561     case DW_TAG_class_type:
16562     case DW_TAG_interface_type:
16563     case DW_TAG_enumeration_type:
16564     case DW_TAG_structure_type:
16565     case DW_TAG_subrange_type:
16566     case DW_TAG_typedef:
16567     case DW_TAG_union_type:
16568       return 1;
16569     default:
16570       return 0;
16571     }
16572 }
16573
16574 /* Load all DIEs that are interesting for partial symbols into memory.  */
16575
16576 static struct partial_die_info *
16577 load_partial_dies (const struct die_reader_specs *reader,
16578                    const gdb_byte *info_ptr, int building_psymtab)
16579 {
16580   struct dwarf2_cu *cu = reader->cu;
16581   struct objfile *objfile = cu->objfile;
16582   struct partial_die_info *part_die;
16583   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16584   struct abbrev_info *abbrev;
16585   unsigned int bytes_read;
16586   unsigned int load_all = 0;
16587   int nesting_level = 1;
16588
16589   parent_die = NULL;
16590   last_die = NULL;
16591
16592   gdb_assert (cu->per_cu != NULL);
16593   if (cu->per_cu->load_all_dies)
16594     load_all = 1;
16595
16596   cu->partial_dies
16597     = htab_create_alloc_ex (cu->header.length / 12,
16598                             partial_die_hash,
16599                             partial_die_eq,
16600                             NULL,
16601                             &cu->comp_unit_obstack,
16602                             hashtab_obstack_allocate,
16603                             dummy_obstack_deallocate);
16604
16605   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16606
16607   while (1)
16608     {
16609       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16610
16611       /* A NULL abbrev means the end of a series of children.  */
16612       if (abbrev == NULL)
16613         {
16614           if (--nesting_level == 0)
16615             {
16616               /* PART_DIE was probably the last thing allocated on the
16617                  comp_unit_obstack, so we could call obstack_free
16618                  here.  We don't do that because the waste is small,
16619                  and will be cleaned up when we're done with this
16620                  compilation unit.  This way, we're also more robust
16621                  against other users of the comp_unit_obstack.  */
16622               return first_die;
16623             }
16624           info_ptr += bytes_read;
16625           last_die = parent_die;
16626           parent_die = parent_die->die_parent;
16627           continue;
16628         }
16629
16630       /* Check for template arguments.  We never save these; if
16631          they're seen, we just mark the parent, and go on our way.  */
16632       if (parent_die != NULL
16633           && cu->language == language_cplus
16634           && (abbrev->tag == DW_TAG_template_type_param
16635               || abbrev->tag == DW_TAG_template_value_param))
16636         {
16637           parent_die->has_template_arguments = 1;
16638
16639           if (!load_all)
16640             {
16641               /* We don't need a partial DIE for the template argument.  */
16642               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16643               continue;
16644             }
16645         }
16646
16647       /* We only recurse into c++ subprograms looking for template arguments.
16648          Skip their other children.  */
16649       if (!load_all
16650           && cu->language == language_cplus
16651           && parent_die != NULL
16652           && parent_die->tag == DW_TAG_subprogram)
16653         {
16654           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16655           continue;
16656         }
16657
16658       /* Check whether this DIE is interesting enough to save.  Normally
16659          we would not be interested in members here, but there may be
16660          later variables referencing them via DW_AT_specification (for
16661          static members).  */
16662       if (!load_all
16663           && !is_type_tag_for_partial (abbrev->tag)
16664           && abbrev->tag != DW_TAG_constant
16665           && abbrev->tag != DW_TAG_enumerator
16666           && abbrev->tag != DW_TAG_subprogram
16667           && abbrev->tag != DW_TAG_lexical_block
16668           && abbrev->tag != DW_TAG_variable
16669           && abbrev->tag != DW_TAG_namespace
16670           && abbrev->tag != DW_TAG_module
16671           && abbrev->tag != DW_TAG_member
16672           && abbrev->tag != DW_TAG_imported_unit
16673           && abbrev->tag != DW_TAG_imported_declaration)
16674         {
16675           /* Otherwise we skip to the next sibling, if any.  */
16676           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16677           continue;
16678         }
16679
16680       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16681                                    info_ptr);
16682
16683       /* This two-pass algorithm for processing partial symbols has a
16684          high cost in cache pressure.  Thus, handle some simple cases
16685          here which cover the majority of C partial symbols.  DIEs
16686          which neither have specification tags in them, nor could have
16687          specification tags elsewhere pointing at them, can simply be
16688          processed and discarded.
16689
16690          This segment is also optional; scan_partial_symbols and
16691          add_partial_symbol will handle these DIEs if we chain
16692          them in normally.  When compilers which do not emit large
16693          quantities of duplicate debug information are more common,
16694          this code can probably be removed.  */
16695
16696       /* Any complete simple types at the top level (pretty much all
16697          of them, for a language without namespaces), can be processed
16698          directly.  */
16699       if (parent_die == NULL
16700           && part_die->has_specification == 0
16701           && part_die->is_declaration == 0
16702           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16703               || part_die->tag == DW_TAG_base_type
16704               || part_die->tag == DW_TAG_subrange_type))
16705         {
16706           if (building_psymtab && part_die->name != NULL)
16707             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16708                                  VAR_DOMAIN, LOC_TYPEDEF,
16709                                  &objfile->static_psymbols,
16710                                  0, cu->language, objfile);
16711           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16712           continue;
16713         }
16714
16715       /* The exception for DW_TAG_typedef with has_children above is
16716          a workaround of GCC PR debug/47510.  In the case of this complaint
16717          type_name_no_tag_or_error will error on such types later.
16718
16719          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16720          it could not find the child DIEs referenced later, this is checked
16721          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16722
16723       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16724         complaint (&symfile_complaints,
16725                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16726                      "- DIE at 0x%x [in module %s]"),
16727                    to_underlying (part_die->sect_off), objfile_name (objfile));
16728
16729       /* If we're at the second level, and we're an enumerator, and
16730          our parent has no specification (meaning possibly lives in a
16731          namespace elsewhere), then we can add the partial symbol now
16732          instead of queueing it.  */
16733       if (part_die->tag == DW_TAG_enumerator
16734           && parent_die != NULL
16735           && parent_die->die_parent == NULL
16736           && parent_die->tag == DW_TAG_enumeration_type
16737           && parent_die->has_specification == 0)
16738         {
16739           if (part_die->name == NULL)
16740             complaint (&symfile_complaints,
16741                        _("malformed enumerator DIE ignored"));
16742           else if (building_psymtab)
16743             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16744                                  VAR_DOMAIN, LOC_CONST,
16745                                  cu->language == language_cplus
16746                                  ? &objfile->global_psymbols
16747                                  : &objfile->static_psymbols,
16748                                  0, cu->language, objfile);
16749
16750           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16751           continue;
16752         }
16753
16754       /* We'll save this DIE so link it in.  */
16755       part_die->die_parent = parent_die;
16756       part_die->die_sibling = NULL;
16757       part_die->die_child = NULL;
16758
16759       if (last_die && last_die == parent_die)
16760         last_die->die_child = part_die;
16761       else if (last_die)
16762         last_die->die_sibling = part_die;
16763
16764       last_die = part_die;
16765
16766       if (first_die == NULL)
16767         first_die = part_die;
16768
16769       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16770          find interesting need to be in the hash table, because we
16771          also have the parent/sibling/child chains; only those that we
16772          might refer to by offset later during partial symbol reading.
16773
16774          For now this means things that might have be the target of a
16775          DW_AT_specification, DW_AT_abstract_origin, or
16776          DW_AT_extension.  DW_AT_extension will refer only to
16777          namespaces; DW_AT_abstract_origin refers to functions (and
16778          many things under the function DIE, but we do not recurse
16779          into function DIEs during partial symbol reading) and
16780          possibly variables as well; DW_AT_specification refers to
16781          declarations.  Declarations ought to have the DW_AT_declaration
16782          flag.  It happens that GCC forgets to put it in sometimes, but
16783          only for functions, not for types.
16784
16785          Adding more things than necessary to the hash table is harmless
16786          except for the performance cost.  Adding too few will result in
16787          wasted time in find_partial_die, when we reread the compilation
16788          unit with load_all_dies set.  */
16789
16790       if (load_all
16791           || abbrev->tag == DW_TAG_constant
16792           || abbrev->tag == DW_TAG_subprogram
16793           || abbrev->tag == DW_TAG_variable
16794           || abbrev->tag == DW_TAG_namespace
16795           || part_die->is_declaration)
16796         {
16797           void **slot;
16798
16799           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16800                                            to_underlying (part_die->sect_off),
16801                                            INSERT);
16802           *slot = part_die;
16803         }
16804
16805       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16806
16807       /* For some DIEs we want to follow their children (if any).  For C
16808          we have no reason to follow the children of structures; for other
16809          languages we have to, so that we can get at method physnames
16810          to infer fully qualified class names, for DW_AT_specification,
16811          and for C++ template arguments.  For C++, we also look one level
16812          inside functions to find template arguments (if the name of the
16813          function does not already contain the template arguments).
16814
16815          For Ada, we need to scan the children of subprograms and lexical
16816          blocks as well because Ada allows the definition of nested
16817          entities that could be interesting for the debugger, such as
16818          nested subprograms for instance.  */
16819       if (last_die->has_children
16820           && (load_all
16821               || last_die->tag == DW_TAG_namespace
16822               || last_die->tag == DW_TAG_module
16823               || last_die->tag == DW_TAG_enumeration_type
16824               || (cu->language == language_cplus
16825                   && last_die->tag == DW_TAG_subprogram
16826                   && (last_die->name == NULL
16827                       || strchr (last_die->name, '<') == NULL))
16828               || (cu->language != language_c
16829                   && (last_die->tag == DW_TAG_class_type
16830                       || last_die->tag == DW_TAG_interface_type
16831                       || last_die->tag == DW_TAG_structure_type
16832                       || last_die->tag == DW_TAG_union_type))
16833               || (cu->language == language_ada
16834                   && (last_die->tag == DW_TAG_subprogram
16835                       || last_die->tag == DW_TAG_lexical_block))))
16836         {
16837           nesting_level++;
16838           parent_die = last_die;
16839           continue;
16840         }
16841
16842       /* Otherwise we skip to the next sibling, if any.  */
16843       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16844
16845       /* Back to the top, do it again.  */
16846     }
16847 }
16848
16849 /* Read a minimal amount of information into the minimal die structure.  */
16850
16851 static const gdb_byte *
16852 read_partial_die (const struct die_reader_specs *reader,
16853                   struct partial_die_info *part_die,
16854                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16855                   const gdb_byte *info_ptr)
16856 {
16857   struct dwarf2_cu *cu = reader->cu;
16858   struct objfile *objfile = cu->objfile;
16859   const gdb_byte *buffer = reader->buffer;
16860   unsigned int i;
16861   struct attribute attr;
16862   int has_low_pc_attr = 0;
16863   int has_high_pc_attr = 0;
16864   int high_pc_relative = 0;
16865
16866   memset (part_die, 0, sizeof (struct partial_die_info));
16867
16868   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16869
16870   info_ptr += abbrev_len;
16871
16872   if (abbrev == NULL)
16873     return info_ptr;
16874
16875   part_die->tag = abbrev->tag;
16876   part_die->has_children = abbrev->has_children;
16877
16878   for (i = 0; i < abbrev->num_attrs; ++i)
16879     {
16880       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16881
16882       /* Store the data if it is of an attribute we want to keep in a
16883          partial symbol table.  */
16884       switch (attr.name)
16885         {
16886         case DW_AT_name:
16887           switch (part_die->tag)
16888             {
16889             case DW_TAG_compile_unit:
16890             case DW_TAG_partial_unit:
16891             case DW_TAG_type_unit:
16892               /* Compilation units have a DW_AT_name that is a filename, not
16893                  a source language identifier.  */
16894             case DW_TAG_enumeration_type:
16895             case DW_TAG_enumerator:
16896               /* These tags always have simple identifiers already; no need
16897                  to canonicalize them.  */
16898               part_die->name = DW_STRING (&attr);
16899               break;
16900             default:
16901               part_die->name
16902                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16903                                             &objfile->per_bfd->storage_obstack);
16904               break;
16905             }
16906           break;
16907         case DW_AT_linkage_name:
16908         case DW_AT_MIPS_linkage_name:
16909           /* Note that both forms of linkage name might appear.  We
16910              assume they will be the same, and we only store the last
16911              one we see.  */
16912           if (cu->language == language_ada)
16913             part_die->name = DW_STRING (&attr);
16914           part_die->linkage_name = DW_STRING (&attr);
16915           break;
16916         case DW_AT_low_pc:
16917           has_low_pc_attr = 1;
16918           part_die->lowpc = attr_value_as_address (&attr);
16919           break;
16920         case DW_AT_high_pc:
16921           has_high_pc_attr = 1;
16922           part_die->highpc = attr_value_as_address (&attr);
16923           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16924                 high_pc_relative = 1;
16925           break;
16926         case DW_AT_location:
16927           /* Support the .debug_loc offsets.  */
16928           if (attr_form_is_block (&attr))
16929             {
16930                part_die->d.locdesc = DW_BLOCK (&attr);
16931             }
16932           else if (attr_form_is_section_offset (&attr))
16933             {
16934               dwarf2_complex_location_expr_complaint ();
16935             }
16936           else
16937             {
16938               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16939                                                      "partial symbol information");
16940             }
16941           break;
16942         case DW_AT_external:
16943           part_die->is_external = DW_UNSND (&attr);
16944           break;
16945         case DW_AT_declaration:
16946           part_die->is_declaration = DW_UNSND (&attr);
16947           break;
16948         case DW_AT_type:
16949           part_die->has_type = 1;
16950           break;
16951         case DW_AT_abstract_origin:
16952         case DW_AT_specification:
16953         case DW_AT_extension:
16954           part_die->has_specification = 1;
16955           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16956           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16957                                    || cu->per_cu->is_dwz);
16958           break;
16959         case DW_AT_sibling:
16960           /* Ignore absolute siblings, they might point outside of
16961              the current compile unit.  */
16962           if (attr.form == DW_FORM_ref_addr)
16963             complaint (&symfile_complaints,
16964                        _("ignoring absolute DW_AT_sibling"));
16965           else
16966             {
16967               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16968               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16969
16970               if (sibling_ptr < info_ptr)
16971                 complaint (&symfile_complaints,
16972                            _("DW_AT_sibling points backwards"));
16973               else if (sibling_ptr > reader->buffer_end)
16974                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16975               else
16976                 part_die->sibling = sibling_ptr;
16977             }
16978           break;
16979         case DW_AT_byte_size:
16980           part_die->has_byte_size = 1;
16981           break;
16982         case DW_AT_const_value:
16983           part_die->has_const_value = 1;
16984           break;
16985         case DW_AT_calling_convention:
16986           /* DWARF doesn't provide a way to identify a program's source-level
16987              entry point.  DW_AT_calling_convention attributes are only meant
16988              to describe functions' calling conventions.
16989
16990              However, because it's a necessary piece of information in
16991              Fortran, and before DWARF 4 DW_CC_program was the only
16992              piece of debugging information whose definition refers to
16993              a 'main program' at all, several compilers marked Fortran
16994              main programs with DW_CC_program --- even when those
16995              functions use the standard calling conventions.
16996
16997              Although DWARF now specifies a way to provide this
16998              information, we support this practice for backward
16999              compatibility.  */
17000           if (DW_UNSND (&attr) == DW_CC_program
17001               && cu->language == language_fortran)
17002             part_die->main_subprogram = 1;
17003           break;
17004         case DW_AT_inline:
17005           if (DW_UNSND (&attr) == DW_INL_inlined
17006               || DW_UNSND (&attr) == DW_INL_declared_inlined)
17007             part_die->may_be_inlined = 1;
17008           break;
17009
17010         case DW_AT_import:
17011           if (part_die->tag == DW_TAG_imported_unit)
17012             {
17013               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
17014               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
17015                                   || cu->per_cu->is_dwz);
17016             }
17017           break;
17018
17019         case DW_AT_main_subprogram:
17020           part_die->main_subprogram = DW_UNSND (&attr);
17021           break;
17022
17023         default:
17024           break;
17025         }
17026     }
17027
17028   if (high_pc_relative)
17029     part_die->highpc += part_die->lowpc;
17030
17031   if (has_low_pc_attr && has_high_pc_attr)
17032     {
17033       /* When using the GNU linker, .gnu.linkonce. sections are used to
17034          eliminate duplicate copies of functions and vtables and such.
17035          The linker will arbitrarily choose one and discard the others.
17036          The AT_*_pc values for such functions refer to local labels in
17037          these sections.  If the section from that file was discarded, the
17038          labels are not in the output, so the relocs get a value of 0.
17039          If this is a discarded function, mark the pc bounds as invalid,
17040          so that GDB will ignore it.  */
17041       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
17042         {
17043           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17044
17045           complaint (&symfile_complaints,
17046                      _("DW_AT_low_pc %s is zero "
17047                        "for DIE at 0x%x [in module %s]"),
17048                      paddress (gdbarch, part_die->lowpc),
17049                      to_underlying (part_die->sect_off), objfile_name (objfile));
17050         }
17051       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
17052       else if (part_die->lowpc >= part_die->highpc)
17053         {
17054           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17055
17056           complaint (&symfile_complaints,
17057                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
17058                        "for DIE at 0x%x [in module %s]"),
17059                      paddress (gdbarch, part_die->lowpc),
17060                      paddress (gdbarch, part_die->highpc),
17061                      to_underlying (part_die->sect_off),
17062                      objfile_name (objfile));
17063         }
17064       else
17065         part_die->has_pc_info = 1;
17066     }
17067
17068   return info_ptr;
17069 }
17070
17071 /* Find a cached partial DIE at OFFSET in CU.  */
17072
17073 static struct partial_die_info *
17074 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
17075 {
17076   struct partial_die_info *lookup_die = NULL;
17077   struct partial_die_info part_die;
17078
17079   part_die.sect_off = sect_off;
17080   lookup_die = ((struct partial_die_info *)
17081                 htab_find_with_hash (cu->partial_dies, &part_die,
17082                                      to_underlying (sect_off)));
17083
17084   return lookup_die;
17085 }
17086
17087 /* Find a partial DIE at OFFSET, which may or may not be in CU,
17088    except in the case of .debug_types DIEs which do not reference
17089    outside their CU (they do however referencing other types via
17090    DW_FORM_ref_sig8).  */
17091
17092 static struct partial_die_info *
17093 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
17094 {
17095   struct objfile *objfile = cu->objfile;
17096   struct dwarf2_per_cu_data *per_cu = NULL;
17097   struct partial_die_info *pd = NULL;
17098
17099   if (offset_in_dwz == cu->per_cu->is_dwz
17100       && offset_in_cu_p (&cu->header, sect_off))
17101     {
17102       pd = find_partial_die_in_comp_unit (sect_off, cu);
17103       if (pd != NULL)
17104         return pd;
17105       /* We missed recording what we needed.
17106          Load all dies and try again.  */
17107       per_cu = cu->per_cu;
17108     }
17109   else
17110     {
17111       /* TUs don't reference other CUs/TUs (except via type signatures).  */
17112       if (cu->per_cu->is_debug_types)
17113         {
17114           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
17115                    " external reference to offset 0x%x [in module %s].\n"),
17116                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
17117                  bfd_get_filename (objfile->obfd));
17118         }
17119       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
17120                                                  objfile);
17121
17122       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
17123         load_partial_comp_unit (per_cu);
17124
17125       per_cu->cu->last_used = 0;
17126       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17127     }
17128
17129   /* If we didn't find it, and not all dies have been loaded,
17130      load them all and try again.  */
17131
17132   if (pd == NULL && per_cu->load_all_dies == 0)
17133     {
17134       per_cu->load_all_dies = 1;
17135
17136       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
17137          THIS_CU->cu may already be in use.  So we can't just free it and
17138          replace its DIEs with the ones we read in.  Instead, we leave those
17139          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
17140          and clobber THIS_CU->cu->partial_dies with the hash table for the new
17141          set.  */
17142       load_partial_comp_unit (per_cu);
17143
17144       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17145     }
17146
17147   if (pd == NULL)
17148     internal_error (__FILE__, __LINE__,
17149                     _("could not find partial DIE 0x%x "
17150                       "in cache [from module %s]\n"),
17151                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
17152   return pd;
17153 }
17154
17155 /* See if we can figure out if the class lives in a namespace.  We do
17156    this by looking for a member function; its demangled name will
17157    contain namespace info, if there is any.  */
17158
17159 static void
17160 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
17161                                   struct dwarf2_cu *cu)
17162 {
17163   /* NOTE: carlton/2003-10-07: Getting the info this way changes
17164      what template types look like, because the demangler
17165      frequently doesn't give the same name as the debug info.  We
17166      could fix this by only using the demangled name to get the
17167      prefix (but see comment in read_structure_type).  */
17168
17169   struct partial_die_info *real_pdi;
17170   struct partial_die_info *child_pdi;
17171
17172   /* If this DIE (this DIE's specification, if any) has a parent, then
17173      we should not do this.  We'll prepend the parent's fully qualified
17174      name when we create the partial symbol.  */
17175
17176   real_pdi = struct_pdi;
17177   while (real_pdi->has_specification)
17178     real_pdi = find_partial_die (real_pdi->spec_offset,
17179                                  real_pdi->spec_is_dwz, cu);
17180
17181   if (real_pdi->die_parent != NULL)
17182     return;
17183
17184   for (child_pdi = struct_pdi->die_child;
17185        child_pdi != NULL;
17186        child_pdi = child_pdi->die_sibling)
17187     {
17188       if (child_pdi->tag == DW_TAG_subprogram
17189           && child_pdi->linkage_name != NULL)
17190         {
17191           char *actual_class_name
17192             = language_class_name_from_physname (cu->language_defn,
17193                                                  child_pdi->linkage_name);
17194           if (actual_class_name != NULL)
17195             {
17196               struct_pdi->name
17197                 = ((const char *)
17198                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17199                                   actual_class_name,
17200                                   strlen (actual_class_name)));
17201               xfree (actual_class_name);
17202             }
17203           break;
17204         }
17205     }
17206 }
17207
17208 /* Adjust PART_DIE before generating a symbol for it.  This function
17209    may set the is_external flag or change the DIE's name.  */
17210
17211 static void
17212 fixup_partial_die (struct partial_die_info *part_die,
17213                    struct dwarf2_cu *cu)
17214 {
17215   /* Once we've fixed up a die, there's no point in doing so again.
17216      This also avoids a memory leak if we were to call
17217      guess_partial_die_structure_name multiple times.  */
17218   if (part_die->fixup_called)
17219     return;
17220
17221   /* If we found a reference attribute and the DIE has no name, try
17222      to find a name in the referred to DIE.  */
17223
17224   if (part_die->name == NULL && part_die->has_specification)
17225     {
17226       struct partial_die_info *spec_die;
17227
17228       spec_die = find_partial_die (part_die->spec_offset,
17229                                    part_die->spec_is_dwz, cu);
17230
17231       fixup_partial_die (spec_die, cu);
17232
17233       if (spec_die->name)
17234         {
17235           part_die->name = spec_die->name;
17236
17237           /* Copy DW_AT_external attribute if it is set.  */
17238           if (spec_die->is_external)
17239             part_die->is_external = spec_die->is_external;
17240         }
17241     }
17242
17243   /* Set default names for some unnamed DIEs.  */
17244
17245   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
17246     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
17247
17248   /* If there is no parent die to provide a namespace, and there are
17249      children, see if we can determine the namespace from their linkage
17250      name.  */
17251   if (cu->language == language_cplus
17252       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17253       && part_die->die_parent == NULL
17254       && part_die->has_children
17255       && (part_die->tag == DW_TAG_class_type
17256           || part_die->tag == DW_TAG_structure_type
17257           || part_die->tag == DW_TAG_union_type))
17258     guess_partial_die_structure_name (part_die, cu);
17259
17260   /* GCC might emit a nameless struct or union that has a linkage
17261      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17262   if (part_die->name == NULL
17263       && (part_die->tag == DW_TAG_class_type
17264           || part_die->tag == DW_TAG_interface_type
17265           || part_die->tag == DW_TAG_structure_type
17266           || part_die->tag == DW_TAG_union_type)
17267       && part_die->linkage_name != NULL)
17268     {
17269       char *demangled;
17270
17271       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
17272       if (demangled)
17273         {
17274           const char *base;
17275
17276           /* Strip any leading namespaces/classes, keep only the base name.
17277              DW_AT_name for named DIEs does not contain the prefixes.  */
17278           base = strrchr (demangled, ':');
17279           if (base && base > demangled && base[-1] == ':')
17280             base++;
17281           else
17282             base = demangled;
17283
17284           part_die->name
17285             = ((const char *)
17286                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17287                               base, strlen (base)));
17288           xfree (demangled);
17289         }
17290     }
17291
17292   part_die->fixup_called = 1;
17293 }
17294
17295 /* Read an attribute value described by an attribute form.  */
17296
17297 static const gdb_byte *
17298 read_attribute_value (const struct die_reader_specs *reader,
17299                       struct attribute *attr, unsigned form,
17300                       LONGEST implicit_const, const gdb_byte *info_ptr)
17301 {
17302   struct dwarf2_cu *cu = reader->cu;
17303   struct objfile *objfile = cu->objfile;
17304   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17305   bfd *abfd = reader->abfd;
17306   struct comp_unit_head *cu_header = &cu->header;
17307   unsigned int bytes_read;
17308   struct dwarf_block *blk;
17309
17310   attr->form = (enum dwarf_form) form;
17311   switch (form)
17312     {
17313     case DW_FORM_ref_addr:
17314       if (cu->header.version == 2)
17315         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17316       else
17317         DW_UNSND (attr) = read_offset (abfd, info_ptr,
17318                                        &cu->header, &bytes_read);
17319       info_ptr += bytes_read;
17320       break;
17321     case DW_FORM_GNU_ref_alt:
17322       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17323       info_ptr += bytes_read;
17324       break;
17325     case DW_FORM_addr:
17326       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17327       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
17328       info_ptr += bytes_read;
17329       break;
17330     case DW_FORM_block2:
17331       blk = dwarf_alloc_block (cu);
17332       blk->size = read_2_bytes (abfd, info_ptr);
17333       info_ptr += 2;
17334       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17335       info_ptr += blk->size;
17336       DW_BLOCK (attr) = blk;
17337       break;
17338     case DW_FORM_block4:
17339       blk = dwarf_alloc_block (cu);
17340       blk->size = read_4_bytes (abfd, info_ptr);
17341       info_ptr += 4;
17342       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17343       info_ptr += blk->size;
17344       DW_BLOCK (attr) = blk;
17345       break;
17346     case DW_FORM_data2:
17347       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
17348       info_ptr += 2;
17349       break;
17350     case DW_FORM_data4:
17351       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
17352       info_ptr += 4;
17353       break;
17354     case DW_FORM_data8:
17355       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
17356       info_ptr += 8;
17357       break;
17358     case DW_FORM_data16:
17359       blk = dwarf_alloc_block (cu);
17360       blk->size = 16;
17361       blk->data = read_n_bytes (abfd, info_ptr, 16);
17362       info_ptr += 16;
17363       DW_BLOCK (attr) = blk;
17364       break;
17365     case DW_FORM_sec_offset:
17366       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17367       info_ptr += bytes_read;
17368       break;
17369     case DW_FORM_string:
17370       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
17371       DW_STRING_IS_CANONICAL (attr) = 0;
17372       info_ptr += bytes_read;
17373       break;
17374     case DW_FORM_strp:
17375       if (!cu->per_cu->is_dwz)
17376         {
17377           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
17378                                                    &bytes_read);
17379           DW_STRING_IS_CANONICAL (attr) = 0;
17380           info_ptr += bytes_read;
17381           break;
17382         }
17383       /* FALLTHROUGH */
17384     case DW_FORM_line_strp:
17385       if (!cu->per_cu->is_dwz)
17386         {
17387           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
17388                                                         cu_header, &bytes_read);
17389           DW_STRING_IS_CANONICAL (attr) = 0;
17390           info_ptr += bytes_read;
17391           break;
17392         }
17393       /* FALLTHROUGH */
17394     case DW_FORM_GNU_strp_alt:
17395       {
17396         struct dwz_file *dwz = dwarf2_get_dwz_file ();
17397         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
17398                                           &bytes_read);
17399
17400         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
17401         DW_STRING_IS_CANONICAL (attr) = 0;
17402         info_ptr += bytes_read;
17403       }
17404       break;
17405     case DW_FORM_exprloc:
17406     case DW_FORM_block:
17407       blk = dwarf_alloc_block (cu);
17408       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17409       info_ptr += bytes_read;
17410       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17411       info_ptr += blk->size;
17412       DW_BLOCK (attr) = blk;
17413       break;
17414     case DW_FORM_block1:
17415       blk = dwarf_alloc_block (cu);
17416       blk->size = read_1_byte (abfd, info_ptr);
17417       info_ptr += 1;
17418       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17419       info_ptr += blk->size;
17420       DW_BLOCK (attr) = blk;
17421       break;
17422     case DW_FORM_data1:
17423       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17424       info_ptr += 1;
17425       break;
17426     case DW_FORM_flag:
17427       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17428       info_ptr += 1;
17429       break;
17430     case DW_FORM_flag_present:
17431       DW_UNSND (attr) = 1;
17432       break;
17433     case DW_FORM_sdata:
17434       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17435       info_ptr += bytes_read;
17436       break;
17437     case DW_FORM_udata:
17438       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17439       info_ptr += bytes_read;
17440       break;
17441     case DW_FORM_ref1:
17442       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17443                          + read_1_byte (abfd, info_ptr));
17444       info_ptr += 1;
17445       break;
17446     case DW_FORM_ref2:
17447       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17448                          + read_2_bytes (abfd, info_ptr));
17449       info_ptr += 2;
17450       break;
17451     case DW_FORM_ref4:
17452       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17453                          + read_4_bytes (abfd, info_ptr));
17454       info_ptr += 4;
17455       break;
17456     case DW_FORM_ref8:
17457       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17458                          + read_8_bytes (abfd, info_ptr));
17459       info_ptr += 8;
17460       break;
17461     case DW_FORM_ref_sig8:
17462       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
17463       info_ptr += 8;
17464       break;
17465     case DW_FORM_ref_udata:
17466       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17467                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
17468       info_ptr += bytes_read;
17469       break;
17470     case DW_FORM_indirect:
17471       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17472       info_ptr += bytes_read;
17473       if (form == DW_FORM_implicit_const)
17474         {
17475           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17476           info_ptr += bytes_read;
17477         }
17478       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
17479                                        info_ptr);
17480       break;
17481     case DW_FORM_implicit_const:
17482       DW_SND (attr) = implicit_const;
17483       break;
17484     case DW_FORM_GNU_addr_index:
17485       if (reader->dwo_file == NULL)
17486         {
17487           /* For now flag a hard error.
17488              Later we can turn this into a complaint.  */
17489           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17490                  dwarf_form_name (form),
17491                  bfd_get_filename (abfd));
17492         }
17493       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
17494       info_ptr += bytes_read;
17495       break;
17496     case DW_FORM_GNU_str_index:
17497       if (reader->dwo_file == NULL)
17498         {
17499           /* For now flag a hard error.
17500              Later we can turn this into a complaint if warranted.  */
17501           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17502                  dwarf_form_name (form),
17503                  bfd_get_filename (abfd));
17504         }
17505       {
17506         ULONGEST str_index =
17507           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17508
17509         DW_STRING (attr) = read_str_index (reader, str_index);
17510         DW_STRING_IS_CANONICAL (attr) = 0;
17511         info_ptr += bytes_read;
17512       }
17513       break;
17514     default:
17515       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
17516              dwarf_form_name (form),
17517              bfd_get_filename (abfd));
17518     }
17519
17520   /* Super hack.  */
17521   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
17522     attr->form = DW_FORM_GNU_ref_alt;
17523
17524   /* We have seen instances where the compiler tried to emit a byte
17525      size attribute of -1 which ended up being encoded as an unsigned
17526      0xffffffff.  Although 0xffffffff is technically a valid size value,
17527      an object of this size seems pretty unlikely so we can relatively
17528      safely treat these cases as if the size attribute was invalid and
17529      treat them as zero by default.  */
17530   if (attr->name == DW_AT_byte_size
17531       && form == DW_FORM_data4
17532       && DW_UNSND (attr) >= 0xffffffff)
17533     {
17534       complaint
17535         (&symfile_complaints,
17536          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
17537          hex_string (DW_UNSND (attr)));
17538       DW_UNSND (attr) = 0;
17539     }
17540
17541   return info_ptr;
17542 }
17543
17544 /* Read an attribute described by an abbreviated attribute.  */
17545
17546 static const gdb_byte *
17547 read_attribute (const struct die_reader_specs *reader,
17548                 struct attribute *attr, struct attr_abbrev *abbrev,
17549                 const gdb_byte *info_ptr)
17550 {
17551   attr->name = abbrev->name;
17552   return read_attribute_value (reader, attr, abbrev->form,
17553                                abbrev->implicit_const, info_ptr);
17554 }
17555
17556 /* Read dwarf information from a buffer.  */
17557
17558 static unsigned int
17559 read_1_byte (bfd *abfd, const gdb_byte *buf)
17560 {
17561   return bfd_get_8 (abfd, buf);
17562 }
17563
17564 static int
17565 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17566 {
17567   return bfd_get_signed_8 (abfd, buf);
17568 }
17569
17570 static unsigned int
17571 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17572 {
17573   return bfd_get_16 (abfd, buf);
17574 }
17575
17576 static int
17577 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17578 {
17579   return bfd_get_signed_16 (abfd, buf);
17580 }
17581
17582 static unsigned int
17583 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17584 {
17585   return bfd_get_32 (abfd, buf);
17586 }
17587
17588 static int
17589 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17590 {
17591   return bfd_get_signed_32 (abfd, buf);
17592 }
17593
17594 static ULONGEST
17595 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17596 {
17597   return bfd_get_64 (abfd, buf);
17598 }
17599
17600 static CORE_ADDR
17601 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17602               unsigned int *bytes_read)
17603 {
17604   struct comp_unit_head *cu_header = &cu->header;
17605   CORE_ADDR retval = 0;
17606
17607   if (cu_header->signed_addr_p)
17608     {
17609       switch (cu_header->addr_size)
17610         {
17611         case 2:
17612           retval = bfd_get_signed_16 (abfd, buf);
17613           break;
17614         case 4:
17615           retval = bfd_get_signed_32 (abfd, buf);
17616           break;
17617         case 8:
17618           retval = bfd_get_signed_64 (abfd, buf);
17619           break;
17620         default:
17621           internal_error (__FILE__, __LINE__,
17622                           _("read_address: bad switch, signed [in module %s]"),
17623                           bfd_get_filename (abfd));
17624         }
17625     }
17626   else
17627     {
17628       switch (cu_header->addr_size)
17629         {
17630         case 2:
17631           retval = bfd_get_16 (abfd, buf);
17632           break;
17633         case 4:
17634           retval = bfd_get_32 (abfd, buf);
17635           break;
17636         case 8:
17637           retval = bfd_get_64 (abfd, buf);
17638           break;
17639         default:
17640           internal_error (__FILE__, __LINE__,
17641                           _("read_address: bad switch, "
17642                             "unsigned [in module %s]"),
17643                           bfd_get_filename (abfd));
17644         }
17645     }
17646
17647   *bytes_read = cu_header->addr_size;
17648   return retval;
17649 }
17650
17651 /* Read the initial length from a section.  The (draft) DWARF 3
17652    specification allows the initial length to take up either 4 bytes
17653    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17654    bytes describe the length and all offsets will be 8 bytes in length
17655    instead of 4.
17656
17657    An older, non-standard 64-bit format is also handled by this
17658    function.  The older format in question stores the initial length
17659    as an 8-byte quantity without an escape value.  Lengths greater
17660    than 2^32 aren't very common which means that the initial 4 bytes
17661    is almost always zero.  Since a length value of zero doesn't make
17662    sense for the 32-bit format, this initial zero can be considered to
17663    be an escape value which indicates the presence of the older 64-bit
17664    format.  As written, the code can't detect (old format) lengths
17665    greater than 4GB.  If it becomes necessary to handle lengths
17666    somewhat larger than 4GB, we could allow other small values (such
17667    as the non-sensical values of 1, 2, and 3) to also be used as
17668    escape values indicating the presence of the old format.
17669
17670    The value returned via bytes_read should be used to increment the
17671    relevant pointer after calling read_initial_length().
17672
17673    [ Note:  read_initial_length() and read_offset() are based on the
17674      document entitled "DWARF Debugging Information Format", revision
17675      3, draft 8, dated November 19, 2001.  This document was obtained
17676      from:
17677
17678         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17679
17680      This document is only a draft and is subject to change.  (So beware.)
17681
17682      Details regarding the older, non-standard 64-bit format were
17683      determined empirically by examining 64-bit ELF files produced by
17684      the SGI toolchain on an IRIX 6.5 machine.
17685
17686      - Kevin, July 16, 2002
17687    ] */
17688
17689 static LONGEST
17690 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17691 {
17692   LONGEST length = bfd_get_32 (abfd, buf);
17693
17694   if (length == 0xffffffff)
17695     {
17696       length = bfd_get_64 (abfd, buf + 4);
17697       *bytes_read = 12;
17698     }
17699   else if (length == 0)
17700     {
17701       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17702       length = bfd_get_64 (abfd, buf);
17703       *bytes_read = 8;
17704     }
17705   else
17706     {
17707       *bytes_read = 4;
17708     }
17709
17710   return length;
17711 }
17712
17713 /* Cover function for read_initial_length.
17714    Returns the length of the object at BUF, and stores the size of the
17715    initial length in *BYTES_READ and stores the size that offsets will be in
17716    *OFFSET_SIZE.
17717    If the initial length size is not equivalent to that specified in
17718    CU_HEADER then issue a complaint.
17719    This is useful when reading non-comp-unit headers.  */
17720
17721 static LONGEST
17722 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17723                                         const struct comp_unit_head *cu_header,
17724                                         unsigned int *bytes_read,
17725                                         unsigned int *offset_size)
17726 {
17727   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17728
17729   gdb_assert (cu_header->initial_length_size == 4
17730               || cu_header->initial_length_size == 8
17731               || cu_header->initial_length_size == 12);
17732
17733   if (cu_header->initial_length_size != *bytes_read)
17734     complaint (&symfile_complaints,
17735                _("intermixed 32-bit and 64-bit DWARF sections"));
17736
17737   *offset_size = (*bytes_read == 4) ? 4 : 8;
17738   return length;
17739 }
17740
17741 /* Read an offset from the data stream.  The size of the offset is
17742    given by cu_header->offset_size.  */
17743
17744 static LONGEST
17745 read_offset (bfd *abfd, const gdb_byte *buf,
17746              const struct comp_unit_head *cu_header,
17747              unsigned int *bytes_read)
17748 {
17749   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17750
17751   *bytes_read = cu_header->offset_size;
17752   return offset;
17753 }
17754
17755 /* Read an offset from the data stream.  */
17756
17757 static LONGEST
17758 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17759 {
17760   LONGEST retval = 0;
17761
17762   switch (offset_size)
17763     {
17764     case 4:
17765       retval = bfd_get_32 (abfd, buf);
17766       break;
17767     case 8:
17768       retval = bfd_get_64 (abfd, buf);
17769       break;
17770     default:
17771       internal_error (__FILE__, __LINE__,
17772                       _("read_offset_1: bad switch [in module %s]"),
17773                       bfd_get_filename (abfd));
17774     }
17775
17776   return retval;
17777 }
17778
17779 static const gdb_byte *
17780 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17781 {
17782   /* If the size of a host char is 8 bits, we can return a pointer
17783      to the buffer, otherwise we have to copy the data to a buffer
17784      allocated on the temporary obstack.  */
17785   gdb_assert (HOST_CHAR_BIT == 8);
17786   return buf;
17787 }
17788
17789 static const char *
17790 read_direct_string (bfd *abfd, const gdb_byte *buf,
17791                     unsigned int *bytes_read_ptr)
17792 {
17793   /* If the size of a host char is 8 bits, we can return a pointer
17794      to the string, otherwise we have to copy the string to a buffer
17795      allocated on the temporary obstack.  */
17796   gdb_assert (HOST_CHAR_BIT == 8);
17797   if (*buf == '\0')
17798     {
17799       *bytes_read_ptr = 1;
17800       return NULL;
17801     }
17802   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17803   return (const char *) buf;
17804 }
17805
17806 /* Return pointer to string at section SECT offset STR_OFFSET with error
17807    reporting strings FORM_NAME and SECT_NAME.  */
17808
17809 static const char *
17810 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17811                                      struct dwarf2_section_info *sect,
17812                                      const char *form_name,
17813                                      const char *sect_name)
17814 {
17815   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17816   if (sect->buffer == NULL)
17817     error (_("%s used without %s section [in module %s]"),
17818            form_name, sect_name, bfd_get_filename (abfd));
17819   if (str_offset >= sect->size)
17820     error (_("%s pointing outside of %s section [in module %s]"),
17821            form_name, sect_name, bfd_get_filename (abfd));
17822   gdb_assert (HOST_CHAR_BIT == 8);
17823   if (sect->buffer[str_offset] == '\0')
17824     return NULL;
17825   return (const char *) (sect->buffer + str_offset);
17826 }
17827
17828 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17829
17830 static const char *
17831 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17832 {
17833   return read_indirect_string_at_offset_from (abfd, str_offset,
17834                                               &dwarf2_per_objfile->str,
17835                                               "DW_FORM_strp", ".debug_str");
17836 }
17837
17838 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17839
17840 static const char *
17841 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17842 {
17843   return read_indirect_string_at_offset_from (abfd, str_offset,
17844                                               &dwarf2_per_objfile->line_str,
17845                                               "DW_FORM_line_strp",
17846                                               ".debug_line_str");
17847 }
17848
17849 /* Read a string at offset STR_OFFSET in the .debug_str section from
17850    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17851    the string consists of a single NUL byte, return NULL; otherwise
17852    return a pointer to the string.  */
17853
17854 static const char *
17855 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17856 {
17857   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17858
17859   if (dwz->str.buffer == NULL)
17860     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17861              "section [in module %s]"),
17862            bfd_get_filename (dwz->dwz_bfd));
17863   if (str_offset >= dwz->str.size)
17864     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17865              ".debug_str section [in module %s]"),
17866            bfd_get_filename (dwz->dwz_bfd));
17867   gdb_assert (HOST_CHAR_BIT == 8);
17868   if (dwz->str.buffer[str_offset] == '\0')
17869     return NULL;
17870   return (const char *) (dwz->str.buffer + str_offset);
17871 }
17872
17873 /* Return pointer to string at .debug_str offset as read from BUF.
17874    BUF is assumed to be in a compilation unit described by CU_HEADER.
17875    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17876
17877 static const char *
17878 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17879                       const struct comp_unit_head *cu_header,
17880                       unsigned int *bytes_read_ptr)
17881 {
17882   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17883
17884   return read_indirect_string_at_offset (abfd, str_offset);
17885 }
17886
17887 /* Return pointer to string at .debug_line_str offset as read from BUF.
17888    BUF is assumed to be in a compilation unit described by CU_HEADER.
17889    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17890
17891 static const char *
17892 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17893                            const struct comp_unit_head *cu_header,
17894                            unsigned int *bytes_read_ptr)
17895 {
17896   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17897
17898   return read_indirect_line_string_at_offset (abfd, str_offset);
17899 }
17900
17901 ULONGEST
17902 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17903                           unsigned int *bytes_read_ptr)
17904 {
17905   ULONGEST result;
17906   unsigned int num_read;
17907   int shift;
17908   unsigned char byte;
17909
17910   result = 0;
17911   shift = 0;
17912   num_read = 0;
17913   while (1)
17914     {
17915       byte = bfd_get_8 (abfd, buf);
17916       buf++;
17917       num_read++;
17918       result |= ((ULONGEST) (byte & 127) << shift);
17919       if ((byte & 128) == 0)
17920         {
17921           break;
17922         }
17923       shift += 7;
17924     }
17925   *bytes_read_ptr = num_read;
17926   return result;
17927 }
17928
17929 static LONGEST
17930 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17931                     unsigned int *bytes_read_ptr)
17932 {
17933   LONGEST result;
17934   int shift, num_read;
17935   unsigned char byte;
17936
17937   result = 0;
17938   shift = 0;
17939   num_read = 0;
17940   while (1)
17941     {
17942       byte = bfd_get_8 (abfd, buf);
17943       buf++;
17944       num_read++;
17945       result |= ((LONGEST) (byte & 127) << shift);
17946       shift += 7;
17947       if ((byte & 128) == 0)
17948         {
17949           break;
17950         }
17951     }
17952   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17953     result |= -(((LONGEST) 1) << shift);
17954   *bytes_read_ptr = num_read;
17955   return result;
17956 }
17957
17958 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17959    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17960    ADDR_SIZE is the size of addresses from the CU header.  */
17961
17962 static CORE_ADDR
17963 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17964 {
17965   struct objfile *objfile = dwarf2_per_objfile->objfile;
17966   bfd *abfd = objfile->obfd;
17967   const gdb_byte *info_ptr;
17968
17969   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17970   if (dwarf2_per_objfile->addr.buffer == NULL)
17971     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17972            objfile_name (objfile));
17973   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17974     error (_("DW_FORM_addr_index pointing outside of "
17975              ".debug_addr section [in module %s]"),
17976            objfile_name (objfile));
17977   info_ptr = (dwarf2_per_objfile->addr.buffer
17978               + addr_base + addr_index * addr_size);
17979   if (addr_size == 4)
17980     return bfd_get_32 (abfd, info_ptr);
17981   else
17982     return bfd_get_64 (abfd, info_ptr);
17983 }
17984
17985 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17986
17987 static CORE_ADDR
17988 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17989 {
17990   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17991 }
17992
17993 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17994
17995 static CORE_ADDR
17996 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17997                              unsigned int *bytes_read)
17998 {
17999   bfd *abfd = cu->objfile->obfd;
18000   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
18001
18002   return read_addr_index (cu, addr_index);
18003 }
18004
18005 /* Data structure to pass results from dwarf2_read_addr_index_reader
18006    back to dwarf2_read_addr_index.  */
18007
18008 struct dwarf2_read_addr_index_data
18009 {
18010   ULONGEST addr_base;
18011   int addr_size;
18012 };
18013
18014 /* die_reader_func for dwarf2_read_addr_index.  */
18015
18016 static void
18017 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
18018                                const gdb_byte *info_ptr,
18019                                struct die_info *comp_unit_die,
18020                                int has_children,
18021                                void *data)
18022 {
18023   struct dwarf2_cu *cu = reader->cu;
18024   struct dwarf2_read_addr_index_data *aidata =
18025     (struct dwarf2_read_addr_index_data *) data;
18026
18027   aidata->addr_base = cu->addr_base;
18028   aidata->addr_size = cu->header.addr_size;
18029 }
18030
18031 /* Given an index in .debug_addr, fetch the value.
18032    NOTE: This can be called during dwarf expression evaluation,
18033    long after the debug information has been read, and thus per_cu->cu
18034    may no longer exist.  */
18035
18036 CORE_ADDR
18037 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
18038                         unsigned int addr_index)
18039 {
18040   struct objfile *objfile = per_cu->objfile;
18041   struct dwarf2_cu *cu = per_cu->cu;
18042   ULONGEST addr_base;
18043   int addr_size;
18044
18045   /* This is intended to be called from outside this file.  */
18046   dw2_setup (objfile);
18047
18048   /* We need addr_base and addr_size.
18049      If we don't have PER_CU->cu, we have to get it.
18050      Nasty, but the alternative is storing the needed info in PER_CU,
18051      which at this point doesn't seem justified: it's not clear how frequently
18052      it would get used and it would increase the size of every PER_CU.
18053      Entry points like dwarf2_per_cu_addr_size do a similar thing
18054      so we're not in uncharted territory here.
18055      Alas we need to be a bit more complicated as addr_base is contained
18056      in the DIE.
18057
18058      We don't need to read the entire CU(/TU).
18059      We just need the header and top level die.
18060
18061      IWBN to use the aging mechanism to let us lazily later discard the CU.
18062      For now we skip this optimization.  */
18063
18064   if (cu != NULL)
18065     {
18066       addr_base = cu->addr_base;
18067       addr_size = cu->header.addr_size;
18068     }
18069   else
18070     {
18071       struct dwarf2_read_addr_index_data aidata;
18072
18073       /* Note: We can't use init_cutu_and_read_dies_simple here,
18074          we need addr_base.  */
18075       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
18076                                dwarf2_read_addr_index_reader, &aidata);
18077       addr_base = aidata.addr_base;
18078       addr_size = aidata.addr_size;
18079     }
18080
18081   return read_addr_index_1 (addr_index, addr_base, addr_size);
18082 }
18083
18084 /* Given a DW_FORM_GNU_str_index, fetch the string.
18085    This is only used by the Fission support.  */
18086
18087 static const char *
18088 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
18089 {
18090   struct objfile *objfile = dwarf2_per_objfile->objfile;
18091   const char *objf_name = objfile_name (objfile);
18092   bfd *abfd = objfile->obfd;
18093   struct dwarf2_cu *cu = reader->cu;
18094   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
18095   struct dwarf2_section_info *str_offsets_section =
18096     &reader->dwo_file->sections.str_offsets;
18097   const gdb_byte *info_ptr;
18098   ULONGEST str_offset;
18099   static const char form_name[] = "DW_FORM_GNU_str_index";
18100
18101   dwarf2_read_section (objfile, str_section);
18102   dwarf2_read_section (objfile, str_offsets_section);
18103   if (str_section->buffer == NULL)
18104     error (_("%s used without .debug_str.dwo section"
18105              " in CU at offset 0x%x [in module %s]"),
18106            form_name, to_underlying (cu->header.sect_off), objf_name);
18107   if (str_offsets_section->buffer == NULL)
18108     error (_("%s used without .debug_str_offsets.dwo section"
18109              " in CU at offset 0x%x [in module %s]"),
18110            form_name, to_underlying (cu->header.sect_off), objf_name);
18111   if (str_index * cu->header.offset_size >= str_offsets_section->size)
18112     error (_("%s pointing outside of .debug_str_offsets.dwo"
18113              " section in CU at offset 0x%x [in module %s]"),
18114            form_name, to_underlying (cu->header.sect_off), objf_name);
18115   info_ptr = (str_offsets_section->buffer
18116               + str_index * cu->header.offset_size);
18117   if (cu->header.offset_size == 4)
18118     str_offset = bfd_get_32 (abfd, info_ptr);
18119   else
18120     str_offset = bfd_get_64 (abfd, info_ptr);
18121   if (str_offset >= str_section->size)
18122     error (_("Offset from %s pointing outside of"
18123              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
18124            form_name, to_underlying (cu->header.sect_off), objf_name);
18125   return (const char *) (str_section->buffer + str_offset);
18126 }
18127
18128 /* Return the length of an LEB128 number in BUF.  */
18129
18130 static int
18131 leb128_size (const gdb_byte *buf)
18132 {
18133   const gdb_byte *begin = buf;
18134   gdb_byte byte;
18135
18136   while (1)
18137     {
18138       byte = *buf++;
18139       if ((byte & 128) == 0)
18140         return buf - begin;
18141     }
18142 }
18143
18144 static void
18145 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
18146 {
18147   switch (lang)
18148     {
18149     case DW_LANG_C89:
18150     case DW_LANG_C99:
18151     case DW_LANG_C11:
18152     case DW_LANG_C:
18153     case DW_LANG_UPC:
18154       cu->language = language_c;
18155       break;
18156     case DW_LANG_Java:
18157     case DW_LANG_C_plus_plus:
18158     case DW_LANG_C_plus_plus_11:
18159     case DW_LANG_C_plus_plus_14:
18160       cu->language = language_cplus;
18161       break;
18162     case DW_LANG_D:
18163       cu->language = language_d;
18164       break;
18165     case DW_LANG_Fortran77:
18166     case DW_LANG_Fortran90:
18167     case DW_LANG_Fortran95:
18168     case DW_LANG_Fortran03:
18169     case DW_LANG_Fortran08:
18170       cu->language = language_fortran;
18171       break;
18172     case DW_LANG_Go:
18173       cu->language = language_go;
18174       break;
18175     case DW_LANG_Mips_Assembler:
18176       cu->language = language_asm;
18177       break;
18178     case DW_LANG_Ada83:
18179     case DW_LANG_Ada95:
18180       cu->language = language_ada;
18181       break;
18182     case DW_LANG_Modula2:
18183       cu->language = language_m2;
18184       break;
18185     case DW_LANG_Pascal83:
18186       cu->language = language_pascal;
18187       break;
18188     case DW_LANG_ObjC:
18189       cu->language = language_objc;
18190       break;
18191     case DW_LANG_Rust:
18192     case DW_LANG_Rust_old:
18193       cu->language = language_rust;
18194       break;
18195     case DW_LANG_Cobol74:
18196     case DW_LANG_Cobol85:
18197     default:
18198       cu->language = language_minimal;
18199       break;
18200     }
18201   cu->language_defn = language_def (cu->language);
18202 }
18203
18204 /* Return the named attribute or NULL if not there.  */
18205
18206 static struct attribute *
18207 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18208 {
18209   for (;;)
18210     {
18211       unsigned int i;
18212       struct attribute *spec = NULL;
18213
18214       for (i = 0; i < die->num_attrs; ++i)
18215         {
18216           if (die->attrs[i].name == name)
18217             return &die->attrs[i];
18218           if (die->attrs[i].name == DW_AT_specification
18219               || die->attrs[i].name == DW_AT_abstract_origin)
18220             spec = &die->attrs[i];
18221         }
18222
18223       if (!spec)
18224         break;
18225
18226       die = follow_die_ref (die, spec, &cu);
18227     }
18228
18229   return NULL;
18230 }
18231
18232 /* Return the named attribute or NULL if not there,
18233    but do not follow DW_AT_specification, etc.
18234    This is for use in contexts where we're reading .debug_types dies.
18235    Following DW_AT_specification, DW_AT_abstract_origin will take us
18236    back up the chain, and we want to go down.  */
18237
18238 static struct attribute *
18239 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
18240 {
18241   unsigned int i;
18242
18243   for (i = 0; i < die->num_attrs; ++i)
18244     if (die->attrs[i].name == name)
18245       return &die->attrs[i];
18246
18247   return NULL;
18248 }
18249
18250 /* Return the string associated with a string-typed attribute, or NULL if it
18251    is either not found or is of an incorrect type.  */
18252
18253 static const char *
18254 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18255 {
18256   struct attribute *attr;
18257   const char *str = NULL;
18258
18259   attr = dwarf2_attr (die, name, cu);
18260
18261   if (attr != NULL)
18262     {
18263       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
18264           || attr->form == DW_FORM_string
18265           || attr->form == DW_FORM_GNU_str_index
18266           || attr->form == DW_FORM_GNU_strp_alt)
18267         str = DW_STRING (attr);
18268       else
18269         complaint (&symfile_complaints,
18270                    _("string type expected for attribute %s for "
18271                      "DIE at 0x%x in module %s"),
18272                    dwarf_attr_name (name), to_underlying (die->sect_off),
18273                    objfile_name (cu->objfile));
18274     }
18275
18276   return str;
18277 }
18278
18279 /* Return non-zero iff the attribute NAME is defined for the given DIE,
18280    and holds a non-zero value.  This function should only be used for
18281    DW_FORM_flag or DW_FORM_flag_present attributes.  */
18282
18283 static int
18284 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
18285 {
18286   struct attribute *attr = dwarf2_attr (die, name, cu);
18287
18288   return (attr && DW_UNSND (attr));
18289 }
18290
18291 static int
18292 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
18293 {
18294   /* A DIE is a declaration if it has a DW_AT_declaration attribute
18295      which value is non-zero.  However, we have to be careful with
18296      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
18297      (via dwarf2_flag_true_p) follows this attribute.  So we may
18298      end up accidently finding a declaration attribute that belongs
18299      to a different DIE referenced by the specification attribute,
18300      even though the given DIE does not have a declaration attribute.  */
18301   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
18302           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
18303 }
18304
18305 /* Return the die giving the specification for DIE, if there is
18306    one.  *SPEC_CU is the CU containing DIE on input, and the CU
18307    containing the return value on output.  If there is no
18308    specification, but there is an abstract origin, that is
18309    returned.  */
18310
18311 static struct die_info *
18312 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
18313 {
18314   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
18315                                              *spec_cu);
18316
18317   if (spec_attr == NULL)
18318     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
18319
18320   if (spec_attr == NULL)
18321     return NULL;
18322   else
18323     return follow_die_ref (die, spec_attr, spec_cu);
18324 }
18325
18326 /* Stub for free_line_header to match void * callback types.  */
18327
18328 static void
18329 free_line_header_voidp (void *arg)
18330 {
18331   struct line_header *lh = (struct line_header *) arg;
18332
18333   delete lh;
18334 }
18335
18336 void
18337 line_header::add_include_dir (const char *include_dir)
18338 {
18339   if (dwarf_line_debug >= 2)
18340     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
18341                         include_dirs.size () + 1, include_dir);
18342
18343   include_dirs.push_back (include_dir);
18344 }
18345
18346 void
18347 line_header::add_file_name (const char *name,
18348                             dir_index d_index,
18349                             unsigned int mod_time,
18350                             unsigned int length)
18351 {
18352   if (dwarf_line_debug >= 2)
18353     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
18354                         (unsigned) file_names.size () + 1, name);
18355
18356   file_names.emplace_back (name, d_index, mod_time, length);
18357 }
18358
18359 /* A convenience function to find the proper .debug_line section for a CU.  */
18360
18361 static struct dwarf2_section_info *
18362 get_debug_line_section (struct dwarf2_cu *cu)
18363 {
18364   struct dwarf2_section_info *section;
18365
18366   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
18367      DWO file.  */
18368   if (cu->dwo_unit && cu->per_cu->is_debug_types)
18369     section = &cu->dwo_unit->dwo_file->sections.line;
18370   else if (cu->per_cu->is_dwz)
18371     {
18372       struct dwz_file *dwz = dwarf2_get_dwz_file ();
18373
18374       section = &dwz->line;
18375     }
18376   else
18377     section = &dwarf2_per_objfile->line;
18378
18379   return section;
18380 }
18381
18382 /* Read directory or file name entry format, starting with byte of
18383    format count entries, ULEB128 pairs of entry formats, ULEB128 of
18384    entries count and the entries themselves in the described entry
18385    format.  */
18386
18387 static void
18388 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
18389                         struct line_header *lh,
18390                         const struct comp_unit_head *cu_header,
18391                         void (*callback) (struct line_header *lh,
18392                                           const char *name,
18393                                           dir_index d_index,
18394                                           unsigned int mod_time,
18395                                           unsigned int length))
18396 {
18397   gdb_byte format_count, formati;
18398   ULONGEST data_count, datai;
18399   const gdb_byte *buf = *bufp;
18400   const gdb_byte *format_header_data;
18401   int i;
18402   unsigned int bytes_read;
18403
18404   format_count = read_1_byte (abfd, buf);
18405   buf += 1;
18406   format_header_data = buf;
18407   for (formati = 0; formati < format_count; formati++)
18408     {
18409       read_unsigned_leb128 (abfd, buf, &bytes_read);
18410       buf += bytes_read;
18411       read_unsigned_leb128 (abfd, buf, &bytes_read);
18412       buf += bytes_read;
18413     }
18414
18415   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
18416   buf += bytes_read;
18417   for (datai = 0; datai < data_count; datai++)
18418     {
18419       const gdb_byte *format = format_header_data;
18420       struct file_entry fe;
18421
18422       for (formati = 0; formati < format_count; formati++)
18423         {
18424           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
18425           format += bytes_read;
18426
18427           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
18428           format += bytes_read;
18429
18430           gdb::optional<const char *> string;
18431           gdb::optional<unsigned int> uint;
18432
18433           switch (form)
18434             {
18435             case DW_FORM_string:
18436               string.emplace (read_direct_string (abfd, buf, &bytes_read));
18437               buf += bytes_read;
18438               break;
18439
18440             case DW_FORM_line_strp:
18441               string.emplace (read_indirect_line_string (abfd, buf,
18442                                                          cu_header,
18443                                                          &bytes_read));
18444               buf += bytes_read;
18445               break;
18446
18447             case DW_FORM_data1:
18448               uint.emplace (read_1_byte (abfd, buf));
18449               buf += 1;
18450               break;
18451
18452             case DW_FORM_data2:
18453               uint.emplace (read_2_bytes (abfd, buf));
18454               buf += 2;
18455               break;
18456
18457             case DW_FORM_data4:
18458               uint.emplace (read_4_bytes (abfd, buf));
18459               buf += 4;
18460               break;
18461
18462             case DW_FORM_data8:
18463               uint.emplace (read_8_bytes (abfd, buf));
18464               buf += 8;
18465               break;
18466
18467             case DW_FORM_udata:
18468               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
18469               buf += bytes_read;
18470               break;
18471
18472             case DW_FORM_block:
18473               /* It is valid only for DW_LNCT_timestamp which is ignored by
18474                  current GDB.  */
18475               break;
18476             }
18477
18478           switch (content_type)
18479             {
18480             case DW_LNCT_path:
18481               if (string.has_value ())
18482                 fe.name = *string;
18483               break;
18484             case DW_LNCT_directory_index:
18485               if (uint.has_value ())
18486                 fe.d_index = (dir_index) *uint;
18487               break;
18488             case DW_LNCT_timestamp:
18489               if (uint.has_value ())
18490                 fe.mod_time = *uint;
18491               break;
18492             case DW_LNCT_size:
18493               if (uint.has_value ())
18494                 fe.length = *uint;
18495               break;
18496             case DW_LNCT_MD5:
18497               break;
18498             default:
18499               complaint (&symfile_complaints,
18500                          _("Unknown format content type %s"),
18501                          pulongest (content_type));
18502             }
18503         }
18504
18505       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
18506     }
18507
18508   *bufp = buf;
18509 }
18510
18511 /* Read the statement program header starting at OFFSET in
18512    .debug_line, or .debug_line.dwo.  Return a pointer
18513    to a struct line_header, allocated using xmalloc.
18514    Returns NULL if there is a problem reading the header, e.g., if it
18515    has a version we don't understand.
18516
18517    NOTE: the strings in the include directory and file name tables of
18518    the returned object point into the dwarf line section buffer,
18519    and must not be freed.  */
18520
18521 static line_header_up
18522 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
18523 {
18524   const gdb_byte *line_ptr;
18525   unsigned int bytes_read, offset_size;
18526   int i;
18527   const char *cur_dir, *cur_file;
18528   struct dwarf2_section_info *section;
18529   bfd *abfd;
18530
18531   section = get_debug_line_section (cu);
18532   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18533   if (section->buffer == NULL)
18534     {
18535       if (cu->dwo_unit && cu->per_cu->is_debug_types)
18536         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
18537       else
18538         complaint (&symfile_complaints, _("missing .debug_line section"));
18539       return 0;
18540     }
18541
18542   /* We can't do this until we know the section is non-empty.
18543      Only then do we know we have such a section.  */
18544   abfd = get_section_bfd_owner (section);
18545
18546   /* Make sure that at least there's room for the total_length field.
18547      That could be 12 bytes long, but we're just going to fudge that.  */
18548   if (to_underlying (sect_off) + 4 >= section->size)
18549     {
18550       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18551       return 0;
18552     }
18553
18554   line_header_up lh (new line_header ());
18555
18556   lh->sect_off = sect_off;
18557   lh->offset_in_dwz = cu->per_cu->is_dwz;
18558
18559   line_ptr = section->buffer + to_underlying (sect_off);
18560
18561   /* Read in the header.  */
18562   lh->total_length =
18563     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18564                                             &bytes_read, &offset_size);
18565   line_ptr += bytes_read;
18566   if (line_ptr + lh->total_length > (section->buffer + section->size))
18567     {
18568       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18569       return 0;
18570     }
18571   lh->statement_program_end = line_ptr + lh->total_length;
18572   lh->version = read_2_bytes (abfd, line_ptr);
18573   line_ptr += 2;
18574   if (lh->version > 5)
18575     {
18576       /* This is a version we don't understand.  The format could have
18577          changed in ways we don't handle properly so just punt.  */
18578       complaint (&symfile_complaints,
18579                  _("unsupported version in .debug_line section"));
18580       return NULL;
18581     }
18582   if (lh->version >= 5)
18583     {
18584       gdb_byte segment_selector_size;
18585
18586       /* Skip address size.  */
18587       read_1_byte (abfd, line_ptr);
18588       line_ptr += 1;
18589
18590       segment_selector_size = read_1_byte (abfd, line_ptr);
18591       line_ptr += 1;
18592       if (segment_selector_size != 0)
18593         {
18594           complaint (&symfile_complaints,
18595                      _("unsupported segment selector size %u "
18596                        "in .debug_line section"),
18597                      segment_selector_size);
18598           return NULL;
18599         }
18600     }
18601   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18602   line_ptr += offset_size;
18603   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18604   line_ptr += 1;
18605   if (lh->version >= 4)
18606     {
18607       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18608       line_ptr += 1;
18609     }
18610   else
18611     lh->maximum_ops_per_instruction = 1;
18612
18613   if (lh->maximum_ops_per_instruction == 0)
18614     {
18615       lh->maximum_ops_per_instruction = 1;
18616       complaint (&symfile_complaints,
18617                  _("invalid maximum_ops_per_instruction "
18618                    "in `.debug_line' section"));
18619     }
18620
18621   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18622   line_ptr += 1;
18623   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18624   line_ptr += 1;
18625   lh->line_range = read_1_byte (abfd, line_ptr);
18626   line_ptr += 1;
18627   lh->opcode_base = read_1_byte (abfd, line_ptr);
18628   line_ptr += 1;
18629   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18630
18631   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18632   for (i = 1; i < lh->opcode_base; ++i)
18633     {
18634       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18635       line_ptr += 1;
18636     }
18637
18638   if (lh->version >= 5)
18639     {
18640       /* Read directory table.  */
18641       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18642                               [] (struct line_header *lh, const char *name,
18643                                   dir_index d_index, unsigned int mod_time,
18644                                   unsigned int length)
18645         {
18646           lh->add_include_dir (name);
18647         });
18648
18649       /* Read file name table.  */
18650       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18651                               [] (struct line_header *lh, const char *name,
18652                                   dir_index d_index, unsigned int mod_time,
18653                                   unsigned int length)
18654         {
18655           lh->add_file_name (name, d_index, mod_time, length);
18656         });
18657     }
18658   else
18659     {
18660       /* Read directory table.  */
18661       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18662         {
18663           line_ptr += bytes_read;
18664           lh->add_include_dir (cur_dir);
18665         }
18666       line_ptr += bytes_read;
18667
18668       /* Read file name table.  */
18669       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18670         {
18671           unsigned int mod_time, length;
18672           dir_index d_index;
18673
18674           line_ptr += bytes_read;
18675           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18676           line_ptr += bytes_read;
18677           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18678           line_ptr += bytes_read;
18679           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18680           line_ptr += bytes_read;
18681
18682           lh->add_file_name (cur_file, d_index, mod_time, length);
18683         }
18684       line_ptr += bytes_read;
18685     }
18686   lh->statement_program_start = line_ptr;
18687
18688   if (line_ptr > (section->buffer + section->size))
18689     complaint (&symfile_complaints,
18690                _("line number info header doesn't "
18691                  "fit in `.debug_line' section"));
18692
18693   return lh;
18694 }
18695
18696 /* Subroutine of dwarf_decode_lines to simplify it.
18697    Return the file name of the psymtab for included file FILE_INDEX
18698    in line header LH of PST.
18699    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18700    If space for the result is malloc'd, it will be freed by a cleanup.
18701    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18702
18703    The function creates dangling cleanup registration.  */
18704
18705 static const char *
18706 psymtab_include_file_name (const struct line_header *lh, int file_index,
18707                            const struct partial_symtab *pst,
18708                            const char *comp_dir)
18709 {
18710   const file_entry &fe = lh->file_names[file_index];
18711   const char *include_name = fe.name;
18712   const char *include_name_to_compare = include_name;
18713   const char *pst_filename;
18714   char *copied_name = NULL;
18715   int file_is_pst;
18716
18717   const char *dir_name = fe.include_dir (lh);
18718
18719   if (!IS_ABSOLUTE_PATH (include_name)
18720       && (dir_name != NULL || comp_dir != NULL))
18721     {
18722       /* Avoid creating a duplicate psymtab for PST.
18723          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18724          Before we do the comparison, however, we need to account
18725          for DIR_NAME and COMP_DIR.
18726          First prepend dir_name (if non-NULL).  If we still don't
18727          have an absolute path prepend comp_dir (if non-NULL).
18728          However, the directory we record in the include-file's
18729          psymtab does not contain COMP_DIR (to match the
18730          corresponding symtab(s)).
18731
18732          Example:
18733
18734          bash$ cd /tmp
18735          bash$ gcc -g ./hello.c
18736          include_name = "hello.c"
18737          dir_name = "."
18738          DW_AT_comp_dir = comp_dir = "/tmp"
18739          DW_AT_name = "./hello.c"
18740
18741       */
18742
18743       if (dir_name != NULL)
18744         {
18745           char *tem = concat (dir_name, SLASH_STRING,
18746                               include_name, (char *)NULL);
18747
18748           make_cleanup (xfree, tem);
18749           include_name = tem;
18750           include_name_to_compare = include_name;
18751         }
18752       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18753         {
18754           char *tem = concat (comp_dir, SLASH_STRING,
18755                               include_name, (char *)NULL);
18756
18757           make_cleanup (xfree, tem);
18758           include_name_to_compare = tem;
18759         }
18760     }
18761
18762   pst_filename = pst->filename;
18763   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18764     {
18765       copied_name = concat (pst->dirname, SLASH_STRING,
18766                             pst_filename, (char *)NULL);
18767       pst_filename = copied_name;
18768     }
18769
18770   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18771
18772   if (copied_name != NULL)
18773     xfree (copied_name);
18774
18775   if (file_is_pst)
18776     return NULL;
18777   return include_name;
18778 }
18779
18780 /* State machine to track the state of the line number program.  */
18781
18782 class lnp_state_machine
18783 {
18784 public:
18785   /* Initialize a machine state for the start of a line number
18786      program.  */
18787   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18788
18789   file_entry *current_file ()
18790   {
18791     /* lh->file_names is 0-based, but the file name numbers in the
18792        statement program are 1-based.  */
18793     return m_line_header->file_name_at (m_file);
18794   }
18795
18796   /* Record the line in the state machine.  END_SEQUENCE is true if
18797      we're processing the end of a sequence.  */
18798   void record_line (bool end_sequence);
18799
18800   /* Check address and if invalid nop-out the rest of the lines in this
18801      sequence.  */
18802   void check_line_address (struct dwarf2_cu *cu,
18803                            const gdb_byte *line_ptr,
18804                            CORE_ADDR lowpc, CORE_ADDR address);
18805
18806   void handle_set_discriminator (unsigned int discriminator)
18807   {
18808     m_discriminator = discriminator;
18809     m_line_has_non_zero_discriminator |= discriminator != 0;
18810   }
18811
18812   /* Handle DW_LNE_set_address.  */
18813   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18814   {
18815     m_op_index = 0;
18816     address += baseaddr;
18817     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18818   }
18819
18820   /* Handle DW_LNS_advance_pc.  */
18821   void handle_advance_pc (CORE_ADDR adjust);
18822
18823   /* Handle a special opcode.  */
18824   void handle_special_opcode (unsigned char op_code);
18825
18826   /* Handle DW_LNS_advance_line.  */
18827   void handle_advance_line (int line_delta)
18828   {
18829     advance_line (line_delta);
18830   }
18831
18832   /* Handle DW_LNS_set_file.  */
18833   void handle_set_file (file_name_index file);
18834
18835   /* Handle DW_LNS_negate_stmt.  */
18836   void handle_negate_stmt ()
18837   {
18838     m_is_stmt = !m_is_stmt;
18839   }
18840
18841   /* Handle DW_LNS_const_add_pc.  */
18842   void handle_const_add_pc ();
18843
18844   /* Handle DW_LNS_fixed_advance_pc.  */
18845   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18846   {
18847     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18848     m_op_index = 0;
18849   }
18850
18851   /* Handle DW_LNS_copy.  */
18852   void handle_copy ()
18853   {
18854     record_line (false);
18855     m_discriminator = 0;
18856   }
18857
18858   /* Handle DW_LNE_end_sequence.  */
18859   void handle_end_sequence ()
18860   {
18861     m_record_line_callback = ::record_line;
18862   }
18863
18864 private:
18865   /* Advance the line by LINE_DELTA.  */
18866   void advance_line (int line_delta)
18867   {
18868     m_line += line_delta;
18869
18870     if (line_delta != 0)
18871       m_line_has_non_zero_discriminator = m_discriminator != 0;
18872   }
18873
18874   gdbarch *m_gdbarch;
18875
18876   /* True if we're recording lines.
18877      Otherwise we're building partial symtabs and are just interested in
18878      finding include files mentioned by the line number program.  */
18879   bool m_record_lines_p;
18880
18881   /* The line number header.  */
18882   line_header *m_line_header;
18883
18884   /* These are part of the standard DWARF line number state machine,
18885      and initialized according to the DWARF spec.  */
18886
18887   unsigned char m_op_index = 0;
18888   /* The line table index (1-based) of the current file.  */
18889   file_name_index m_file = (file_name_index) 1;
18890   unsigned int m_line = 1;
18891
18892   /* These are initialized in the constructor.  */
18893
18894   CORE_ADDR m_address;
18895   bool m_is_stmt;
18896   unsigned int m_discriminator;
18897
18898   /* Additional bits of state we need to track.  */
18899
18900   /* The last file that we called dwarf2_start_subfile for.
18901      This is only used for TLLs.  */
18902   unsigned int m_last_file = 0;
18903   /* The last file a line number was recorded for.  */
18904   struct subfile *m_last_subfile = NULL;
18905
18906   /* The function to call to record a line.  */
18907   record_line_ftype *m_record_line_callback = NULL;
18908
18909   /* The last line number that was recorded, used to coalesce
18910      consecutive entries for the same line.  This can happen, for
18911      example, when discriminators are present.  PR 17276.  */
18912   unsigned int m_last_line = 0;
18913   bool m_line_has_non_zero_discriminator = false;
18914 };
18915
18916 void
18917 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18918 {
18919   CORE_ADDR addr_adj = (((m_op_index + adjust)
18920                          / m_line_header->maximum_ops_per_instruction)
18921                         * m_line_header->minimum_instruction_length);
18922   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18923   m_op_index = ((m_op_index + adjust)
18924                 % m_line_header->maximum_ops_per_instruction);
18925 }
18926
18927 void
18928 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18929 {
18930   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18931   CORE_ADDR addr_adj = (((m_op_index
18932                           + (adj_opcode / m_line_header->line_range))
18933                          / m_line_header->maximum_ops_per_instruction)
18934                         * m_line_header->minimum_instruction_length);
18935   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18936   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18937                 % m_line_header->maximum_ops_per_instruction);
18938
18939   int line_delta = (m_line_header->line_base
18940                     + (adj_opcode % m_line_header->line_range));
18941   advance_line (line_delta);
18942   record_line (false);
18943   m_discriminator = 0;
18944 }
18945
18946 void
18947 lnp_state_machine::handle_set_file (file_name_index file)
18948 {
18949   m_file = file;
18950
18951   const file_entry *fe = current_file ();
18952   if (fe == NULL)
18953     dwarf2_debug_line_missing_file_complaint ();
18954   else if (m_record_lines_p)
18955     {
18956       const char *dir = fe->include_dir (m_line_header);
18957
18958       m_last_subfile = current_subfile;
18959       m_line_has_non_zero_discriminator = m_discriminator != 0;
18960       dwarf2_start_subfile (fe->name, dir);
18961     }
18962 }
18963
18964 void
18965 lnp_state_machine::handle_const_add_pc ()
18966 {
18967   CORE_ADDR adjust
18968     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18969
18970   CORE_ADDR addr_adj
18971     = (((m_op_index + adjust)
18972         / m_line_header->maximum_ops_per_instruction)
18973        * m_line_header->minimum_instruction_length);
18974
18975   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18976   m_op_index = ((m_op_index + adjust)
18977                 % m_line_header->maximum_ops_per_instruction);
18978 }
18979
18980 /* Ignore this record_line request.  */
18981
18982 static void
18983 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18984 {
18985   return;
18986 }
18987
18988 /* Return non-zero if we should add LINE to the line number table.
18989    LINE is the line to add, LAST_LINE is the last line that was added,
18990    LAST_SUBFILE is the subfile for LAST_LINE.
18991    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18992    had a non-zero discriminator.
18993
18994    We have to be careful in the presence of discriminators.
18995    E.g., for this line:
18996
18997      for (i = 0; i < 100000; i++);
18998
18999    clang can emit four line number entries for that one line,
19000    each with a different discriminator.
19001    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
19002
19003    However, we want gdb to coalesce all four entries into one.
19004    Otherwise the user could stepi into the middle of the line and
19005    gdb would get confused about whether the pc really was in the
19006    middle of the line.
19007
19008    Things are further complicated by the fact that two consecutive
19009    line number entries for the same line is a heuristic used by gcc
19010    to denote the end of the prologue.  So we can't just discard duplicate
19011    entries, we have to be selective about it.  The heuristic we use is
19012    that we only collapse consecutive entries for the same line if at least
19013    one of those entries has a non-zero discriminator.  PR 17276.
19014
19015    Note: Addresses in the line number state machine can never go backwards
19016    within one sequence, thus this coalescing is ok.  */
19017
19018 static int
19019 dwarf_record_line_p (unsigned int line, unsigned int last_line,
19020                      int line_has_non_zero_discriminator,
19021                      struct subfile *last_subfile)
19022 {
19023   if (current_subfile != last_subfile)
19024     return 1;
19025   if (line != last_line)
19026     return 1;
19027   /* Same line for the same file that we've seen already.
19028      As a last check, for pr 17276, only record the line if the line
19029      has never had a non-zero discriminator.  */
19030   if (!line_has_non_zero_discriminator)
19031     return 1;
19032   return 0;
19033 }
19034
19035 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
19036    in the line table of subfile SUBFILE.  */
19037
19038 static void
19039 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
19040                      unsigned int line, CORE_ADDR address,
19041                      record_line_ftype p_record_line)
19042 {
19043   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
19044
19045   if (dwarf_line_debug)
19046     {
19047       fprintf_unfiltered (gdb_stdlog,
19048                           "Recording line %u, file %s, address %s\n",
19049                           line, lbasename (subfile->name),
19050                           paddress (gdbarch, address));
19051     }
19052
19053   (*p_record_line) (subfile, line, addr);
19054 }
19055
19056 /* Subroutine of dwarf_decode_lines_1 to simplify it.
19057    Mark the end of a set of line number records.
19058    The arguments are the same as for dwarf_record_line_1.
19059    If SUBFILE is NULL the request is ignored.  */
19060
19061 static void
19062 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
19063                    CORE_ADDR address, record_line_ftype p_record_line)
19064 {
19065   if (subfile == NULL)
19066     return;
19067
19068   if (dwarf_line_debug)
19069     {
19070       fprintf_unfiltered (gdb_stdlog,
19071                           "Finishing current line, file %s, address %s\n",
19072                           lbasename (subfile->name),
19073                           paddress (gdbarch, address));
19074     }
19075
19076   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
19077 }
19078
19079 void
19080 lnp_state_machine::record_line (bool end_sequence)
19081 {
19082   if (dwarf_line_debug)
19083     {
19084       fprintf_unfiltered (gdb_stdlog,
19085                           "Processing actual line %u: file %u,"
19086                           " address %s, is_stmt %u, discrim %u\n",
19087                           m_line, to_underlying (m_file),
19088                           paddress (m_gdbarch, m_address),
19089                           m_is_stmt, m_discriminator);
19090     }
19091
19092   file_entry *fe = current_file ();
19093
19094   if (fe == NULL)
19095     dwarf2_debug_line_missing_file_complaint ();
19096   /* For now we ignore lines not starting on an instruction boundary.
19097      But not when processing end_sequence for compatibility with the
19098      previous version of the code.  */
19099   else if (m_op_index == 0 || end_sequence)
19100     {
19101       fe->included_p = 1;
19102       if (m_record_lines_p && m_is_stmt)
19103         {
19104           if (m_last_subfile != current_subfile || end_sequence)
19105             {
19106               dwarf_finish_line (m_gdbarch, m_last_subfile,
19107                                  m_address, m_record_line_callback);
19108             }
19109
19110           if (!end_sequence)
19111             {
19112               if (dwarf_record_line_p (m_line, m_last_line,
19113                                        m_line_has_non_zero_discriminator,
19114                                        m_last_subfile))
19115                 {
19116                   dwarf_record_line_1 (m_gdbarch, current_subfile,
19117                                        m_line, m_address,
19118                                        m_record_line_callback);
19119                 }
19120               m_last_subfile = current_subfile;
19121               m_last_line = m_line;
19122             }
19123         }
19124     }
19125 }
19126
19127 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
19128                                       bool record_lines_p)
19129 {
19130   m_gdbarch = arch;
19131   m_record_lines_p = record_lines_p;
19132   m_line_header = lh;
19133
19134   m_record_line_callback = ::record_line;
19135
19136   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
19137      was a line entry for it so that the backend has a chance to adjust it
19138      and also record it in case it needs it.  This is currently used by MIPS
19139      code, cf. `mips_adjust_dwarf2_line'.  */
19140   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
19141   m_is_stmt = lh->default_is_stmt;
19142   m_discriminator = 0;
19143 }
19144
19145 void
19146 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
19147                                        const gdb_byte *line_ptr,
19148                                        CORE_ADDR lowpc, CORE_ADDR address)
19149 {
19150   /* If address < lowpc then it's not a usable value, it's outside the
19151      pc range of the CU.  However, we restrict the test to only address
19152      values of zero to preserve GDB's previous behaviour which is to
19153      handle the specific case of a function being GC'd by the linker.  */
19154
19155   if (address == 0 && address < lowpc)
19156     {
19157       /* This line table is for a function which has been
19158          GCd by the linker.  Ignore it.  PR gdb/12528 */
19159
19160       struct objfile *objfile = cu->objfile;
19161       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
19162
19163       complaint (&symfile_complaints,
19164                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
19165                  line_offset, objfile_name (objfile));
19166       m_record_line_callback = noop_record_line;
19167       /* Note: record_line_callback is left as noop_record_line until
19168          we see DW_LNE_end_sequence.  */
19169     }
19170 }
19171
19172 /* Subroutine of dwarf_decode_lines to simplify it.
19173    Process the line number information in LH.
19174    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
19175    program in order to set included_p for every referenced header.  */
19176
19177 static void
19178 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
19179                       const int decode_for_pst_p, CORE_ADDR lowpc)
19180 {
19181   const gdb_byte *line_ptr, *extended_end;
19182   const gdb_byte *line_end;
19183   unsigned int bytes_read, extended_len;
19184   unsigned char op_code, extended_op;
19185   CORE_ADDR baseaddr;
19186   struct objfile *objfile = cu->objfile;
19187   bfd *abfd = objfile->obfd;
19188   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19189   /* True if we're recording line info (as opposed to building partial
19190      symtabs and just interested in finding include files mentioned by
19191      the line number program).  */
19192   bool record_lines_p = !decode_for_pst_p;
19193
19194   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19195
19196   line_ptr = lh->statement_program_start;
19197   line_end = lh->statement_program_end;
19198
19199   /* Read the statement sequences until there's nothing left.  */
19200   while (line_ptr < line_end)
19201     {
19202       /* The DWARF line number program state machine.  Reset the state
19203          machine at the start of each sequence.  */
19204       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
19205       bool end_sequence = false;
19206
19207       if (record_lines_p)
19208         {
19209           /* Start a subfile for the current file of the state
19210              machine.  */
19211           const file_entry *fe = state_machine.current_file ();
19212
19213           if (fe != NULL)
19214             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
19215         }
19216
19217       /* Decode the table.  */
19218       while (line_ptr < line_end && !end_sequence)
19219         {
19220           op_code = read_1_byte (abfd, line_ptr);
19221           line_ptr += 1;
19222
19223           if (op_code >= lh->opcode_base)
19224             {
19225               /* Special opcode.  */
19226               state_machine.handle_special_opcode (op_code);
19227             }
19228           else switch (op_code)
19229             {
19230             case DW_LNS_extended_op:
19231               extended_len = read_unsigned_leb128 (abfd, line_ptr,
19232                                                    &bytes_read);
19233               line_ptr += bytes_read;
19234               extended_end = line_ptr + extended_len;
19235               extended_op = read_1_byte (abfd, line_ptr);
19236               line_ptr += 1;
19237               switch (extended_op)
19238                 {
19239                 case DW_LNE_end_sequence:
19240                   state_machine.handle_end_sequence ();
19241                   end_sequence = true;
19242                   break;
19243                 case DW_LNE_set_address:
19244                   {
19245                     CORE_ADDR address
19246                       = read_address (abfd, line_ptr, cu, &bytes_read);
19247                     line_ptr += bytes_read;
19248
19249                     state_machine.check_line_address (cu, line_ptr,
19250                                                       lowpc, address);
19251                     state_machine.handle_set_address (baseaddr, address);
19252                   }
19253                   break;
19254                 case DW_LNE_define_file:
19255                   {
19256                     const char *cur_file;
19257                     unsigned int mod_time, length;
19258                     dir_index dindex;
19259
19260                     cur_file = read_direct_string (abfd, line_ptr,
19261                                                    &bytes_read);
19262                     line_ptr += bytes_read;
19263                     dindex = (dir_index)
19264                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19265                     line_ptr += bytes_read;
19266                     mod_time =
19267                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19268                     line_ptr += bytes_read;
19269                     length =
19270                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19271                     line_ptr += bytes_read;
19272                     lh->add_file_name (cur_file, dindex, mod_time, length);
19273                   }
19274                   break;
19275                 case DW_LNE_set_discriminator:
19276                   {
19277                     /* The discriminator is not interesting to the
19278                        debugger; just ignore it.  We still need to
19279                        check its value though:
19280                        if there are consecutive entries for the same
19281                        (non-prologue) line we want to coalesce them.
19282                        PR 17276.  */
19283                     unsigned int discr
19284                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19285                     line_ptr += bytes_read;
19286
19287                     state_machine.handle_set_discriminator (discr);
19288                   }
19289                   break;
19290                 default:
19291                   complaint (&symfile_complaints,
19292                              _("mangled .debug_line section"));
19293                   return;
19294                 }
19295               /* Make sure that we parsed the extended op correctly.  If e.g.
19296                  we expected a different address size than the producer used,
19297                  we may have read the wrong number of bytes.  */
19298               if (line_ptr != extended_end)
19299                 {
19300                   complaint (&symfile_complaints,
19301                              _("mangled .debug_line section"));
19302                   return;
19303                 }
19304               break;
19305             case DW_LNS_copy:
19306               state_machine.handle_copy ();
19307               break;
19308             case DW_LNS_advance_pc:
19309               {
19310                 CORE_ADDR adjust
19311                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19312                 line_ptr += bytes_read;
19313
19314                 state_machine.handle_advance_pc (adjust);
19315               }
19316               break;
19317             case DW_LNS_advance_line:
19318               {
19319                 int line_delta
19320                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
19321                 line_ptr += bytes_read;
19322
19323                 state_machine.handle_advance_line (line_delta);
19324               }
19325               break;
19326             case DW_LNS_set_file:
19327               {
19328                 file_name_index file
19329                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
19330                                                             &bytes_read);
19331                 line_ptr += bytes_read;
19332
19333                 state_machine.handle_set_file (file);
19334               }
19335               break;
19336             case DW_LNS_set_column:
19337               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19338               line_ptr += bytes_read;
19339               break;
19340             case DW_LNS_negate_stmt:
19341               state_machine.handle_negate_stmt ();
19342               break;
19343             case DW_LNS_set_basic_block:
19344               break;
19345             /* Add to the address register of the state machine the
19346                address increment value corresponding to special opcode
19347                255.  I.e., this value is scaled by the minimum
19348                instruction length since special opcode 255 would have
19349                scaled the increment.  */
19350             case DW_LNS_const_add_pc:
19351               state_machine.handle_const_add_pc ();
19352               break;
19353             case DW_LNS_fixed_advance_pc:
19354               {
19355                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
19356                 line_ptr += 2;
19357
19358                 state_machine.handle_fixed_advance_pc (addr_adj);
19359               }
19360               break;
19361             default:
19362               {
19363                 /* Unknown standard opcode, ignore it.  */
19364                 int i;
19365
19366                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
19367                   {
19368                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19369                     line_ptr += bytes_read;
19370                   }
19371               }
19372             }
19373         }
19374
19375       if (!end_sequence)
19376         dwarf2_debug_line_missing_end_sequence_complaint ();
19377
19378       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
19379          in which case we still finish recording the last line).  */
19380       state_machine.record_line (true);
19381     }
19382 }
19383
19384 /* Decode the Line Number Program (LNP) for the given line_header
19385    structure and CU.  The actual information extracted and the type
19386    of structures created from the LNP depends on the value of PST.
19387
19388    1. If PST is NULL, then this procedure uses the data from the program
19389       to create all necessary symbol tables, and their linetables.
19390
19391    2. If PST is not NULL, this procedure reads the program to determine
19392       the list of files included by the unit represented by PST, and
19393       builds all the associated partial symbol tables.
19394
19395    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19396    It is used for relative paths in the line table.
19397    NOTE: When processing partial symtabs (pst != NULL),
19398    comp_dir == pst->dirname.
19399
19400    NOTE: It is important that psymtabs have the same file name (via strcmp)
19401    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
19402    symtab we don't use it in the name of the psymtabs we create.
19403    E.g. expand_line_sal requires this when finding psymtabs to expand.
19404    A good testcase for this is mb-inline.exp.
19405
19406    LOWPC is the lowest address in CU (or 0 if not known).
19407
19408    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
19409    for its PC<->lines mapping information.  Otherwise only the filename
19410    table is read in.  */
19411
19412 static void
19413 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
19414                     struct dwarf2_cu *cu, struct partial_symtab *pst,
19415                     CORE_ADDR lowpc, int decode_mapping)
19416 {
19417   struct objfile *objfile = cu->objfile;
19418   const int decode_for_pst_p = (pst != NULL);
19419
19420   if (decode_mapping)
19421     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
19422
19423   if (decode_for_pst_p)
19424     {
19425       int file_index;
19426
19427       /* Now that we're done scanning the Line Header Program, we can
19428          create the psymtab of each included file.  */
19429       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
19430         if (lh->file_names[file_index].included_p == 1)
19431           {
19432             const char *include_name =
19433               psymtab_include_file_name (lh, file_index, pst, comp_dir);
19434             if (include_name != NULL)
19435               dwarf2_create_include_psymtab (include_name, pst, objfile);
19436           }
19437     }
19438   else
19439     {
19440       /* Make sure a symtab is created for every file, even files
19441          which contain only variables (i.e. no code with associated
19442          line numbers).  */
19443       struct compunit_symtab *cust = buildsym_compunit_symtab ();
19444       int i;
19445
19446       for (i = 0; i < lh->file_names.size (); i++)
19447         {
19448           file_entry &fe = lh->file_names[i];
19449
19450           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
19451
19452           if (current_subfile->symtab == NULL)
19453             {
19454               current_subfile->symtab
19455                 = allocate_symtab (cust, current_subfile->name);
19456             }
19457           fe.symtab = current_subfile->symtab;
19458         }
19459     }
19460 }
19461
19462 /* Start a subfile for DWARF.  FILENAME is the name of the file and
19463    DIRNAME the name of the source directory which contains FILENAME
19464    or NULL if not known.
19465    This routine tries to keep line numbers from identical absolute and
19466    relative file names in a common subfile.
19467
19468    Using the `list' example from the GDB testsuite, which resides in
19469    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
19470    of /srcdir/list0.c yields the following debugging information for list0.c:
19471
19472    DW_AT_name:          /srcdir/list0.c
19473    DW_AT_comp_dir:      /compdir
19474    files.files[0].name: list0.h
19475    files.files[0].dir:  /srcdir
19476    files.files[1].name: list0.c
19477    files.files[1].dir:  /srcdir
19478
19479    The line number information for list0.c has to end up in a single
19480    subfile, so that `break /srcdir/list0.c:1' works as expected.
19481    start_subfile will ensure that this happens provided that we pass the
19482    concatenation of files.files[1].dir and files.files[1].name as the
19483    subfile's name.  */
19484
19485 static void
19486 dwarf2_start_subfile (const char *filename, const char *dirname)
19487 {
19488   char *copy = NULL;
19489
19490   /* In order not to lose the line information directory,
19491      we concatenate it to the filename when it makes sense.
19492      Note that the Dwarf3 standard says (speaking of filenames in line
19493      information): ``The directory index is ignored for file names
19494      that represent full path names''.  Thus ignoring dirname in the
19495      `else' branch below isn't an issue.  */
19496
19497   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
19498     {
19499       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
19500       filename = copy;
19501     }
19502
19503   start_subfile (filename);
19504
19505   if (copy != NULL)
19506     xfree (copy);
19507 }
19508
19509 /* Start a symtab for DWARF.
19510    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
19511
19512 static struct compunit_symtab *
19513 dwarf2_start_symtab (struct dwarf2_cu *cu,
19514                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
19515 {
19516   struct compunit_symtab *cust
19517     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
19518
19519   record_debugformat ("DWARF 2");
19520   record_producer (cu->producer);
19521
19522   /* We assume that we're processing GCC output.  */
19523   processing_gcc_compilation = 2;
19524
19525   cu->processing_has_namespace_info = 0;
19526
19527   return cust;
19528 }
19529
19530 static void
19531 var_decode_location (struct attribute *attr, struct symbol *sym,
19532                      struct dwarf2_cu *cu)
19533 {
19534   struct objfile *objfile = cu->objfile;
19535   struct comp_unit_head *cu_header = &cu->header;
19536
19537   /* NOTE drow/2003-01-30: There used to be a comment and some special
19538      code here to turn a symbol with DW_AT_external and a
19539      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19540      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19541      with some versions of binutils) where shared libraries could have
19542      relocations against symbols in their debug information - the
19543      minimal symbol would have the right address, but the debug info
19544      would not.  It's no longer necessary, because we will explicitly
19545      apply relocations when we read in the debug information now.  */
19546
19547   /* A DW_AT_location attribute with no contents indicates that a
19548      variable has been optimized away.  */
19549   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19550     {
19551       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19552       return;
19553     }
19554
19555   /* Handle one degenerate form of location expression specially, to
19556      preserve GDB's previous behavior when section offsets are
19557      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19558      then mark this symbol as LOC_STATIC.  */
19559
19560   if (attr_form_is_block (attr)
19561       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19562            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19563           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19564               && (DW_BLOCK (attr)->size
19565                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19566     {
19567       unsigned int dummy;
19568
19569       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19570         SYMBOL_VALUE_ADDRESS (sym) =
19571           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19572       else
19573         SYMBOL_VALUE_ADDRESS (sym) =
19574           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19575       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19576       fixup_symbol_section (sym, objfile);
19577       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19578                                               SYMBOL_SECTION (sym));
19579       return;
19580     }
19581
19582   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19583      expression evaluator, and use LOC_COMPUTED only when necessary
19584      (i.e. when the value of a register or memory location is
19585      referenced, or a thread-local block, etc.).  Then again, it might
19586      not be worthwhile.  I'm assuming that it isn't unless performance
19587      or memory numbers show me otherwise.  */
19588
19589   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19590
19591   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19592     cu->has_loclist = 1;
19593 }
19594
19595 /* Given a pointer to a DWARF information entry, figure out if we need
19596    to make a symbol table entry for it, and if so, create a new entry
19597    and return a pointer to it.
19598    If TYPE is NULL, determine symbol type from the die, otherwise
19599    used the passed type.
19600    If SPACE is not NULL, use it to hold the new symbol.  If it is
19601    NULL, allocate a new symbol on the objfile's obstack.  */
19602
19603 static struct symbol *
19604 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19605                  struct symbol *space)
19606 {
19607   struct objfile *objfile = cu->objfile;
19608   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19609   struct symbol *sym = NULL;
19610   const char *name;
19611   struct attribute *attr = NULL;
19612   struct attribute *attr2 = NULL;
19613   CORE_ADDR baseaddr;
19614   struct pending **list_to_add = NULL;
19615
19616   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19617
19618   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19619
19620   name = dwarf2_name (die, cu);
19621   if (name)
19622     {
19623       const char *linkagename;
19624       int suppress_add = 0;
19625
19626       if (space)
19627         sym = space;
19628       else
19629         sym = allocate_symbol (objfile);
19630       OBJSTAT (objfile, n_syms++);
19631
19632       /* Cache this symbol's name and the name's demangled form (if any).  */
19633       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19634       linkagename = dwarf2_physname (name, die, cu);
19635       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19636
19637       /* Fortran does not have mangling standard and the mangling does differ
19638          between gfortran, iFort etc.  */
19639       if (cu->language == language_fortran
19640           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19641         symbol_set_demangled_name (&(sym->ginfo),
19642                                    dwarf2_full_name (name, die, cu),
19643                                    NULL);
19644
19645       /* Default assumptions.
19646          Use the passed type or decode it from the die.  */
19647       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19648       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19649       if (type != NULL)
19650         SYMBOL_TYPE (sym) = type;
19651       else
19652         SYMBOL_TYPE (sym) = die_type (die, cu);
19653       attr = dwarf2_attr (die,
19654                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19655                           cu);
19656       if (attr)
19657         {
19658           SYMBOL_LINE (sym) = DW_UNSND (attr);
19659         }
19660
19661       attr = dwarf2_attr (die,
19662                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19663                           cu);
19664       if (attr)
19665         {
19666           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19667           struct file_entry *fe;
19668
19669           if (cu->line_header != NULL)
19670             fe = cu->line_header->file_name_at (file_index);
19671           else
19672             fe = NULL;
19673
19674           if (fe == NULL)
19675             complaint (&symfile_complaints,
19676                        _("file index out of range"));
19677           else
19678             symbol_set_symtab (sym, fe->symtab);
19679         }
19680
19681       switch (die->tag)
19682         {
19683         case DW_TAG_label:
19684           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19685           if (attr)
19686             {
19687               CORE_ADDR addr;
19688
19689               addr = attr_value_as_address (attr);
19690               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19691               SYMBOL_VALUE_ADDRESS (sym) = addr;
19692             }
19693           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19694           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19695           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19696           add_symbol_to_list (sym, cu->list_in_scope);
19697           break;
19698         case DW_TAG_subprogram:
19699           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19700              finish_block.  */
19701           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19702           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19703           if ((attr2 && (DW_UNSND (attr2) != 0))
19704               || cu->language == language_ada)
19705             {
19706               /* Subprograms marked external are stored as a global symbol.
19707                  Ada subprograms, whether marked external or not, are always
19708                  stored as a global symbol, because we want to be able to
19709                  access them globally.  For instance, we want to be able
19710                  to break on a nested subprogram without having to
19711                  specify the context.  */
19712               list_to_add = &global_symbols;
19713             }
19714           else
19715             {
19716               list_to_add = cu->list_in_scope;
19717             }
19718           break;
19719         case DW_TAG_inlined_subroutine:
19720           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19721              finish_block.  */
19722           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19723           SYMBOL_INLINED (sym) = 1;
19724           list_to_add = cu->list_in_scope;
19725           break;
19726         case DW_TAG_template_value_param:
19727           suppress_add = 1;
19728           /* Fall through.  */
19729         case DW_TAG_constant:
19730         case DW_TAG_variable:
19731         case DW_TAG_member:
19732           /* Compilation with minimal debug info may result in
19733              variables with missing type entries.  Change the
19734              misleading `void' type to something sensible.  */
19735           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19736             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19737
19738           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19739           /* In the case of DW_TAG_member, we should only be called for
19740              static const members.  */
19741           if (die->tag == DW_TAG_member)
19742             {
19743               /* dwarf2_add_field uses die_is_declaration,
19744                  so we do the same.  */
19745               gdb_assert (die_is_declaration (die, cu));
19746               gdb_assert (attr);
19747             }
19748           if (attr)
19749             {
19750               dwarf2_const_value (attr, sym, cu);
19751               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19752               if (!suppress_add)
19753                 {
19754                   if (attr2 && (DW_UNSND (attr2) != 0))
19755                     list_to_add = &global_symbols;
19756                   else
19757                     list_to_add = cu->list_in_scope;
19758                 }
19759               break;
19760             }
19761           attr = dwarf2_attr (die, DW_AT_location, cu);
19762           if (attr)
19763             {
19764               var_decode_location (attr, sym, cu);
19765               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19766
19767               /* Fortran explicitly imports any global symbols to the local
19768                  scope by DW_TAG_common_block.  */
19769               if (cu->language == language_fortran && die->parent
19770                   && die->parent->tag == DW_TAG_common_block)
19771                 attr2 = NULL;
19772
19773               if (SYMBOL_CLASS (sym) == LOC_STATIC
19774                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19775                   && !dwarf2_per_objfile->has_section_at_zero)
19776                 {
19777                   /* When a static variable is eliminated by the linker,
19778                      the corresponding debug information is not stripped
19779                      out, but the variable address is set to null;
19780                      do not add such variables into symbol table.  */
19781                 }
19782               else if (attr2 && (DW_UNSND (attr2) != 0))
19783                 {
19784                   /* Workaround gfortran PR debug/40040 - it uses
19785                      DW_AT_location for variables in -fPIC libraries which may
19786                      get overriden by other libraries/executable and get
19787                      a different address.  Resolve it by the minimal symbol
19788                      which may come from inferior's executable using copy
19789                      relocation.  Make this workaround only for gfortran as for
19790                      other compilers GDB cannot guess the minimal symbol
19791                      Fortran mangling kind.  */
19792                   if (cu->language == language_fortran && die->parent
19793                       && die->parent->tag == DW_TAG_module
19794                       && cu->producer
19795                       && startswith (cu->producer, "GNU Fortran"))
19796                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19797
19798                   /* A variable with DW_AT_external is never static,
19799                      but it may be block-scoped.  */
19800                   list_to_add = (cu->list_in_scope == &file_symbols
19801                                  ? &global_symbols : cu->list_in_scope);
19802                 }
19803               else
19804                 list_to_add = cu->list_in_scope;
19805             }
19806           else
19807             {
19808               /* We do not know the address of this symbol.
19809                  If it is an external symbol and we have type information
19810                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19811                  The address of the variable will then be determined from
19812                  the minimal symbol table whenever the variable is
19813                  referenced.  */
19814               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19815
19816               /* Fortran explicitly imports any global symbols to the local
19817                  scope by DW_TAG_common_block.  */
19818               if (cu->language == language_fortran && die->parent
19819                   && die->parent->tag == DW_TAG_common_block)
19820                 {
19821                   /* SYMBOL_CLASS doesn't matter here because
19822                      read_common_block is going to reset it.  */
19823                   if (!suppress_add)
19824                     list_to_add = cu->list_in_scope;
19825                 }
19826               else if (attr2 && (DW_UNSND (attr2) != 0)
19827                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19828                 {
19829                   /* A variable with DW_AT_external is never static, but it
19830                      may be block-scoped.  */
19831                   list_to_add = (cu->list_in_scope == &file_symbols
19832                                  ? &global_symbols : cu->list_in_scope);
19833
19834                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19835                 }
19836               else if (!die_is_declaration (die, cu))
19837                 {
19838                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19839                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19840                   if (!suppress_add)
19841                     list_to_add = cu->list_in_scope;
19842                 }
19843             }
19844           break;
19845         case DW_TAG_formal_parameter:
19846           /* If we are inside a function, mark this as an argument.  If
19847              not, we might be looking at an argument to an inlined function
19848              when we do not have enough information to show inlined frames;
19849              pretend it's a local variable in that case so that the user can
19850              still see it.  */
19851           if (context_stack_depth > 0
19852               && context_stack[context_stack_depth - 1].name != NULL)
19853             SYMBOL_IS_ARGUMENT (sym) = 1;
19854           attr = dwarf2_attr (die, DW_AT_location, cu);
19855           if (attr)
19856             {
19857               var_decode_location (attr, sym, cu);
19858             }
19859           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19860           if (attr)
19861             {
19862               dwarf2_const_value (attr, sym, cu);
19863             }
19864
19865           list_to_add = cu->list_in_scope;
19866           break;
19867         case DW_TAG_unspecified_parameters:
19868           /* From varargs functions; gdb doesn't seem to have any
19869              interest in this information, so just ignore it for now.
19870              (FIXME?) */
19871           break;
19872         case DW_TAG_template_type_param:
19873           suppress_add = 1;
19874           /* Fall through.  */
19875         case DW_TAG_class_type:
19876         case DW_TAG_interface_type:
19877         case DW_TAG_structure_type:
19878         case DW_TAG_union_type:
19879         case DW_TAG_set_type:
19880         case DW_TAG_enumeration_type:
19881           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19882           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19883
19884           {
19885             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19886                really ever be static objects: otherwise, if you try
19887                to, say, break of a class's method and you're in a file
19888                which doesn't mention that class, it won't work unless
19889                the check for all static symbols in lookup_symbol_aux
19890                saves you.  See the OtherFileClass tests in
19891                gdb.c++/namespace.exp.  */
19892
19893             if (!suppress_add)
19894               {
19895                 list_to_add = (cu->list_in_scope == &file_symbols
19896                                && cu->language == language_cplus
19897                                ? &global_symbols : cu->list_in_scope);
19898
19899                 /* The semantics of C++ state that "struct foo {
19900                    ... }" also defines a typedef for "foo".  */
19901                 if (cu->language == language_cplus
19902                     || cu->language == language_ada
19903                     || cu->language == language_d
19904                     || cu->language == language_rust)
19905                   {
19906                     /* The symbol's name is already allocated along
19907                        with this objfile, so we don't need to
19908                        duplicate it for the type.  */
19909                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19910                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19911                   }
19912               }
19913           }
19914           break;
19915         case DW_TAG_typedef:
19916           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19917           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19918           list_to_add = cu->list_in_scope;
19919           break;
19920         case DW_TAG_base_type:
19921         case DW_TAG_subrange_type:
19922           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19923           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19924           list_to_add = cu->list_in_scope;
19925           break;
19926         case DW_TAG_enumerator:
19927           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19928           if (attr)
19929             {
19930               dwarf2_const_value (attr, sym, cu);
19931             }
19932           {
19933             /* NOTE: carlton/2003-11-10: See comment above in the
19934                DW_TAG_class_type, etc. block.  */
19935
19936             list_to_add = (cu->list_in_scope == &file_symbols
19937                            && cu->language == language_cplus
19938                            ? &global_symbols : cu->list_in_scope);
19939           }
19940           break;
19941         case DW_TAG_imported_declaration:
19942         case DW_TAG_namespace:
19943           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19944           list_to_add = &global_symbols;
19945           break;
19946         case DW_TAG_module:
19947           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19948           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19949           list_to_add = &global_symbols;
19950           break;
19951         case DW_TAG_common_block:
19952           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19953           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19954           add_symbol_to_list (sym, cu->list_in_scope);
19955           break;
19956         default:
19957           /* Not a tag we recognize.  Hopefully we aren't processing
19958              trash data, but since we must specifically ignore things
19959              we don't recognize, there is nothing else we should do at
19960              this point.  */
19961           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19962                      dwarf_tag_name (die->tag));
19963           break;
19964         }
19965
19966       if (suppress_add)
19967         {
19968           sym->hash_next = objfile->template_symbols;
19969           objfile->template_symbols = sym;
19970           list_to_add = NULL;
19971         }
19972
19973       if (list_to_add != NULL)
19974         add_symbol_to_list (sym, list_to_add);
19975
19976       /* For the benefit of old versions of GCC, check for anonymous
19977          namespaces based on the demangled name.  */
19978       if (!cu->processing_has_namespace_info
19979           && cu->language == language_cplus)
19980         cp_scan_for_anonymous_namespaces (sym, objfile);
19981     }
19982   return (sym);
19983 }
19984
19985 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19986
19987 static struct symbol *
19988 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19989 {
19990   return new_symbol_full (die, type, cu, NULL);
19991 }
19992
19993 /* Given an attr with a DW_FORM_dataN value in host byte order,
19994    zero-extend it as appropriate for the symbol's type.  The DWARF
19995    standard (v4) is not entirely clear about the meaning of using
19996    DW_FORM_dataN for a constant with a signed type, where the type is
19997    wider than the data.  The conclusion of a discussion on the DWARF
19998    list was that this is unspecified.  We choose to always zero-extend
19999    because that is the interpretation long in use by GCC.  */
20000
20001 static gdb_byte *
20002 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
20003                          struct dwarf2_cu *cu, LONGEST *value, int bits)
20004 {
20005   struct objfile *objfile = cu->objfile;
20006   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
20007                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
20008   LONGEST l = DW_UNSND (attr);
20009
20010   if (bits < sizeof (*value) * 8)
20011     {
20012       l &= ((LONGEST) 1 << bits) - 1;
20013       *value = l;
20014     }
20015   else if (bits == sizeof (*value) * 8)
20016     *value = l;
20017   else
20018     {
20019       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
20020       store_unsigned_integer (bytes, bits / 8, byte_order, l);
20021       return bytes;
20022     }
20023
20024   return NULL;
20025 }
20026
20027 /* Read a constant value from an attribute.  Either set *VALUE, or if
20028    the value does not fit in *VALUE, set *BYTES - either already
20029    allocated on the objfile obstack, or newly allocated on OBSTACK,
20030    or, set *BATON, if we translated the constant to a location
20031    expression.  */
20032
20033 static void
20034 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
20035                          const char *name, struct obstack *obstack,
20036                          struct dwarf2_cu *cu,
20037                          LONGEST *value, const gdb_byte **bytes,
20038                          struct dwarf2_locexpr_baton **baton)
20039 {
20040   struct objfile *objfile = cu->objfile;
20041   struct comp_unit_head *cu_header = &cu->header;
20042   struct dwarf_block *blk;
20043   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
20044                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20045
20046   *value = 0;
20047   *bytes = NULL;
20048   *baton = NULL;
20049
20050   switch (attr->form)
20051     {
20052     case DW_FORM_addr:
20053     case DW_FORM_GNU_addr_index:
20054       {
20055         gdb_byte *data;
20056
20057         if (TYPE_LENGTH (type) != cu_header->addr_size)
20058           dwarf2_const_value_length_mismatch_complaint (name,
20059                                                         cu_header->addr_size,
20060                                                         TYPE_LENGTH (type));
20061         /* Symbols of this form are reasonably rare, so we just
20062            piggyback on the existing location code rather than writing
20063            a new implementation of symbol_computed_ops.  */
20064         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
20065         (*baton)->per_cu = cu->per_cu;
20066         gdb_assert ((*baton)->per_cu);
20067
20068         (*baton)->size = 2 + cu_header->addr_size;
20069         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
20070         (*baton)->data = data;
20071
20072         data[0] = DW_OP_addr;
20073         store_unsigned_integer (&data[1], cu_header->addr_size,
20074                                 byte_order, DW_ADDR (attr));
20075         data[cu_header->addr_size + 1] = DW_OP_stack_value;
20076       }
20077       break;
20078     case DW_FORM_string:
20079     case DW_FORM_strp:
20080     case DW_FORM_GNU_str_index:
20081     case DW_FORM_GNU_strp_alt:
20082       /* DW_STRING is already allocated on the objfile obstack, point
20083          directly to it.  */
20084       *bytes = (const gdb_byte *) DW_STRING (attr);
20085       break;
20086     case DW_FORM_block1:
20087     case DW_FORM_block2:
20088     case DW_FORM_block4:
20089     case DW_FORM_block:
20090     case DW_FORM_exprloc:
20091     case DW_FORM_data16:
20092       blk = DW_BLOCK (attr);
20093       if (TYPE_LENGTH (type) != blk->size)
20094         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
20095                                                       TYPE_LENGTH (type));
20096       *bytes = blk->data;
20097       break;
20098
20099       /* The DW_AT_const_value attributes are supposed to carry the
20100          symbol's value "represented as it would be on the target
20101          architecture."  By the time we get here, it's already been
20102          converted to host endianness, so we just need to sign- or
20103          zero-extend it as appropriate.  */
20104     case DW_FORM_data1:
20105       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
20106       break;
20107     case DW_FORM_data2:
20108       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
20109       break;
20110     case DW_FORM_data4:
20111       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
20112       break;
20113     case DW_FORM_data8:
20114       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
20115       break;
20116
20117     case DW_FORM_sdata:
20118     case DW_FORM_implicit_const:
20119       *value = DW_SND (attr);
20120       break;
20121
20122     case DW_FORM_udata:
20123       *value = DW_UNSND (attr);
20124       break;
20125
20126     default:
20127       complaint (&symfile_complaints,
20128                  _("unsupported const value attribute form: '%s'"),
20129                  dwarf_form_name (attr->form));
20130       *value = 0;
20131       break;
20132     }
20133 }
20134
20135
20136 /* Copy constant value from an attribute to a symbol.  */
20137
20138 static void
20139 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
20140                     struct dwarf2_cu *cu)
20141 {
20142   struct objfile *objfile = cu->objfile;
20143   LONGEST value;
20144   const gdb_byte *bytes;
20145   struct dwarf2_locexpr_baton *baton;
20146
20147   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
20148                            SYMBOL_PRINT_NAME (sym),
20149                            &objfile->objfile_obstack, cu,
20150                            &value, &bytes, &baton);
20151
20152   if (baton != NULL)
20153     {
20154       SYMBOL_LOCATION_BATON (sym) = baton;
20155       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
20156     }
20157   else if (bytes != NULL)
20158      {
20159       SYMBOL_VALUE_BYTES (sym) = bytes;
20160       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
20161     }
20162   else
20163     {
20164       SYMBOL_VALUE (sym) = value;
20165       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
20166     }
20167 }
20168
20169 /* Return the type of the die in question using its DW_AT_type attribute.  */
20170
20171 static struct type *
20172 die_type (struct die_info *die, struct dwarf2_cu *cu)
20173 {
20174   struct attribute *type_attr;
20175
20176   type_attr = dwarf2_attr (die, DW_AT_type, cu);
20177   if (!type_attr)
20178     {
20179       /* A missing DW_AT_type represents a void type.  */
20180       return objfile_type (cu->objfile)->builtin_void;
20181     }
20182
20183   return lookup_die_type (die, type_attr, cu);
20184 }
20185
20186 /* True iff CU's producer generates GNAT Ada auxiliary information
20187    that allows to find parallel types through that information instead
20188    of having to do expensive parallel lookups by type name.  */
20189
20190 static int
20191 need_gnat_info (struct dwarf2_cu *cu)
20192 {
20193   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
20194      of GNAT produces this auxiliary information, without any indication
20195      that it is produced.  Part of enhancing the FSF version of GNAT
20196      to produce that information will be to put in place an indicator
20197      that we can use in order to determine whether the descriptive type
20198      info is available or not.  One suggestion that has been made is
20199      to use a new attribute, attached to the CU die.  For now, assume
20200      that the descriptive type info is not available.  */
20201   return 0;
20202 }
20203
20204 /* Return the auxiliary type of the die in question using its
20205    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
20206    attribute is not present.  */
20207
20208 static struct type *
20209 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
20210 {
20211   struct attribute *type_attr;
20212
20213   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
20214   if (!type_attr)
20215     return NULL;
20216
20217   return lookup_die_type (die, type_attr, cu);
20218 }
20219
20220 /* If DIE has a descriptive_type attribute, then set the TYPE's
20221    descriptive type accordingly.  */
20222
20223 static void
20224 set_descriptive_type (struct type *type, struct die_info *die,
20225                       struct dwarf2_cu *cu)
20226 {
20227   struct type *descriptive_type = die_descriptive_type (die, cu);
20228
20229   if (descriptive_type)
20230     {
20231       ALLOCATE_GNAT_AUX_TYPE (type);
20232       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
20233     }
20234 }
20235
20236 /* Return the containing type of the die in question using its
20237    DW_AT_containing_type attribute.  */
20238
20239 static struct type *
20240 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
20241 {
20242   struct attribute *type_attr;
20243
20244   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
20245   if (!type_attr)
20246     error (_("Dwarf Error: Problem turning containing type into gdb type "
20247              "[in module %s]"), objfile_name (cu->objfile));
20248
20249   return lookup_die_type (die, type_attr, cu);
20250 }
20251
20252 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
20253
20254 static struct type *
20255 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
20256 {
20257   struct objfile *objfile = dwarf2_per_objfile->objfile;
20258   char *message, *saved;
20259
20260   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
20261                         objfile_name (objfile),
20262                         to_underlying (cu->header.sect_off),
20263                         to_underlying (die->sect_off));
20264   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
20265                                   message, strlen (message));
20266   xfree (message);
20267
20268   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
20269 }
20270
20271 /* Look up the type of DIE in CU using its type attribute ATTR.
20272    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
20273    DW_AT_containing_type.
20274    If there is no type substitute an error marker.  */
20275
20276 static struct type *
20277 lookup_die_type (struct die_info *die, const struct attribute *attr,
20278                  struct dwarf2_cu *cu)
20279 {
20280   struct objfile *objfile = cu->objfile;
20281   struct type *this_type;
20282
20283   gdb_assert (attr->name == DW_AT_type
20284               || attr->name == DW_AT_GNAT_descriptive_type
20285               || attr->name == DW_AT_containing_type);
20286
20287   /* First see if we have it cached.  */
20288
20289   if (attr->form == DW_FORM_GNU_ref_alt)
20290     {
20291       struct dwarf2_per_cu_data *per_cu;
20292       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20293
20294       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
20295       this_type = get_die_type_at_offset (sect_off, per_cu);
20296     }
20297   else if (attr_form_is_ref (attr))
20298     {
20299       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20300
20301       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
20302     }
20303   else if (attr->form == DW_FORM_ref_sig8)
20304     {
20305       ULONGEST signature = DW_SIGNATURE (attr);
20306
20307       return get_signatured_type (die, signature, cu);
20308     }
20309   else
20310     {
20311       complaint (&symfile_complaints,
20312                  _("Dwarf Error: Bad type attribute %s in DIE"
20313                    " at 0x%x [in module %s]"),
20314                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
20315                  objfile_name (objfile));
20316       return build_error_marker_type (cu, die);
20317     }
20318
20319   /* If not cached we need to read it in.  */
20320
20321   if (this_type == NULL)
20322     {
20323       struct die_info *type_die = NULL;
20324       struct dwarf2_cu *type_cu = cu;
20325
20326       if (attr_form_is_ref (attr))
20327         type_die = follow_die_ref (die, attr, &type_cu);
20328       if (type_die == NULL)
20329         return build_error_marker_type (cu, die);
20330       /* If we find the type now, it's probably because the type came
20331          from an inter-CU reference and the type's CU got expanded before
20332          ours.  */
20333       this_type = read_type_die (type_die, type_cu);
20334     }
20335
20336   /* If we still don't have a type use an error marker.  */
20337
20338   if (this_type == NULL)
20339     return build_error_marker_type (cu, die);
20340
20341   return this_type;
20342 }
20343
20344 /* Return the type in DIE, CU.
20345    Returns NULL for invalid types.
20346
20347    This first does a lookup in die_type_hash,
20348    and only reads the die in if necessary.
20349
20350    NOTE: This can be called when reading in partial or full symbols.  */
20351
20352 static struct type *
20353 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
20354 {
20355   struct type *this_type;
20356
20357   this_type = get_die_type (die, cu);
20358   if (this_type)
20359     return this_type;
20360
20361   return read_type_die_1 (die, cu);
20362 }
20363
20364 /* Read the type in DIE, CU.
20365    Returns NULL for invalid types.  */
20366
20367 static struct type *
20368 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
20369 {
20370   struct type *this_type = NULL;
20371
20372   switch (die->tag)
20373     {
20374     case DW_TAG_class_type:
20375     case DW_TAG_interface_type:
20376     case DW_TAG_structure_type:
20377     case DW_TAG_union_type:
20378       this_type = read_structure_type (die, cu);
20379       break;
20380     case DW_TAG_enumeration_type:
20381       this_type = read_enumeration_type (die, cu);
20382       break;
20383     case DW_TAG_subprogram:
20384     case DW_TAG_subroutine_type:
20385     case DW_TAG_inlined_subroutine:
20386       this_type = read_subroutine_type (die, cu);
20387       break;
20388     case DW_TAG_array_type:
20389       this_type = read_array_type (die, cu);
20390       break;
20391     case DW_TAG_set_type:
20392       this_type = read_set_type (die, cu);
20393       break;
20394     case DW_TAG_pointer_type:
20395       this_type = read_tag_pointer_type (die, cu);
20396       break;
20397     case DW_TAG_ptr_to_member_type:
20398       this_type = read_tag_ptr_to_member_type (die, cu);
20399       break;
20400     case DW_TAG_reference_type:
20401       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
20402       break;
20403     case DW_TAG_rvalue_reference_type:
20404       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
20405       break;
20406     case DW_TAG_const_type:
20407       this_type = read_tag_const_type (die, cu);
20408       break;
20409     case DW_TAG_volatile_type:
20410       this_type = read_tag_volatile_type (die, cu);
20411       break;
20412     case DW_TAG_restrict_type:
20413       this_type = read_tag_restrict_type (die, cu);
20414       break;
20415     case DW_TAG_string_type:
20416       this_type = read_tag_string_type (die, cu);
20417       break;
20418     case DW_TAG_typedef:
20419       this_type = read_typedef (die, cu);
20420       break;
20421     case DW_TAG_subrange_type:
20422       this_type = read_subrange_type (die, cu);
20423       break;
20424     case DW_TAG_base_type:
20425       this_type = read_base_type (die, cu);
20426       break;
20427     case DW_TAG_unspecified_type:
20428       this_type = read_unspecified_type (die, cu);
20429       break;
20430     case DW_TAG_namespace:
20431       this_type = read_namespace_type (die, cu);
20432       break;
20433     case DW_TAG_module:
20434       this_type = read_module_type (die, cu);
20435       break;
20436     case DW_TAG_atomic_type:
20437       this_type = read_tag_atomic_type (die, cu);
20438       break;
20439     default:
20440       complaint (&symfile_complaints,
20441                  _("unexpected tag in read_type_die: '%s'"),
20442                  dwarf_tag_name (die->tag));
20443       break;
20444     }
20445
20446   return this_type;
20447 }
20448
20449 /* See if we can figure out if the class lives in a namespace.  We do
20450    this by looking for a member function; its demangled name will
20451    contain namespace info, if there is any.
20452    Return the computed name or NULL.
20453    Space for the result is allocated on the objfile's obstack.
20454    This is the full-die version of guess_partial_die_structure_name.
20455    In this case we know DIE has no useful parent.  */
20456
20457 static char *
20458 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
20459 {
20460   struct die_info *spec_die;
20461   struct dwarf2_cu *spec_cu;
20462   struct die_info *child;
20463
20464   spec_cu = cu;
20465   spec_die = die_specification (die, &spec_cu);
20466   if (spec_die != NULL)
20467     {
20468       die = spec_die;
20469       cu = spec_cu;
20470     }
20471
20472   for (child = die->child;
20473        child != NULL;
20474        child = child->sibling)
20475     {
20476       if (child->tag == DW_TAG_subprogram)
20477         {
20478           const char *linkage_name = dw2_linkage_name (child, cu);
20479
20480           if (linkage_name != NULL)
20481             {
20482               char *actual_name
20483                 = language_class_name_from_physname (cu->language_defn,
20484                                                      linkage_name);
20485               char *name = NULL;
20486
20487               if (actual_name != NULL)
20488                 {
20489                   const char *die_name = dwarf2_name (die, cu);
20490
20491                   if (die_name != NULL
20492                       && strcmp (die_name, actual_name) != 0)
20493                     {
20494                       /* Strip off the class name from the full name.
20495                          We want the prefix.  */
20496                       int die_name_len = strlen (die_name);
20497                       int actual_name_len = strlen (actual_name);
20498
20499                       /* Test for '::' as a sanity check.  */
20500                       if (actual_name_len > die_name_len + 2
20501                           && actual_name[actual_name_len
20502                                          - die_name_len - 1] == ':')
20503                         name = (char *) obstack_copy0 (
20504                           &cu->objfile->per_bfd->storage_obstack,
20505                           actual_name, actual_name_len - die_name_len - 2);
20506                     }
20507                 }
20508               xfree (actual_name);
20509               return name;
20510             }
20511         }
20512     }
20513
20514   return NULL;
20515 }
20516
20517 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
20518    prefix part in such case.  See
20519    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20520
20521 static const char *
20522 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
20523 {
20524   struct attribute *attr;
20525   const char *base;
20526
20527   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
20528       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
20529     return NULL;
20530
20531   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
20532     return NULL;
20533
20534   attr = dw2_linkage_name_attr (die, cu);
20535   if (attr == NULL || DW_STRING (attr) == NULL)
20536     return NULL;
20537
20538   /* dwarf2_name had to be already called.  */
20539   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20540
20541   /* Strip the base name, keep any leading namespaces/classes.  */
20542   base = strrchr (DW_STRING (attr), ':');
20543   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20544     return "";
20545
20546   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20547                                  DW_STRING (attr),
20548                                  &base[-1] - DW_STRING (attr));
20549 }
20550
20551 /* Return the name of the namespace/class that DIE is defined within,
20552    or "" if we can't tell.  The caller should not xfree the result.
20553
20554    For example, if we're within the method foo() in the following
20555    code:
20556
20557    namespace N {
20558      class C {
20559        void foo () {
20560        }
20561      };
20562    }
20563
20564    then determine_prefix on foo's die will return "N::C".  */
20565
20566 static const char *
20567 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20568 {
20569   struct die_info *parent, *spec_die;
20570   struct dwarf2_cu *spec_cu;
20571   struct type *parent_type;
20572   const char *retval;
20573
20574   if (cu->language != language_cplus
20575       && cu->language != language_fortran && cu->language != language_d
20576       && cu->language != language_rust)
20577     return "";
20578
20579   retval = anonymous_struct_prefix (die, cu);
20580   if (retval)
20581     return retval;
20582
20583   /* We have to be careful in the presence of DW_AT_specification.
20584      For example, with GCC 3.4, given the code
20585
20586      namespace N {
20587        void foo() {
20588          // Definition of N::foo.
20589        }
20590      }
20591
20592      then we'll have a tree of DIEs like this:
20593
20594      1: DW_TAG_compile_unit
20595        2: DW_TAG_namespace        // N
20596          3: DW_TAG_subprogram     // declaration of N::foo
20597        4: DW_TAG_subprogram       // definition of N::foo
20598             DW_AT_specification   // refers to die #3
20599
20600      Thus, when processing die #4, we have to pretend that we're in
20601      the context of its DW_AT_specification, namely the contex of die
20602      #3.  */
20603   spec_cu = cu;
20604   spec_die = die_specification (die, &spec_cu);
20605   if (spec_die == NULL)
20606     parent = die->parent;
20607   else
20608     {
20609       parent = spec_die->parent;
20610       cu = spec_cu;
20611     }
20612
20613   if (parent == NULL)
20614     return "";
20615   else if (parent->building_fullname)
20616     {
20617       const char *name;
20618       const char *parent_name;
20619
20620       /* It has been seen on RealView 2.2 built binaries,
20621          DW_TAG_template_type_param types actually _defined_ as
20622          children of the parent class:
20623
20624          enum E {};
20625          template class <class Enum> Class{};
20626          Class<enum E> class_e;
20627
20628          1: DW_TAG_class_type (Class)
20629            2: DW_TAG_enumeration_type (E)
20630              3: DW_TAG_enumerator (enum1:0)
20631              3: DW_TAG_enumerator (enum2:1)
20632              ...
20633            2: DW_TAG_template_type_param
20634               DW_AT_type  DW_FORM_ref_udata (E)
20635
20636          Besides being broken debug info, it can put GDB into an
20637          infinite loop.  Consider:
20638
20639          When we're building the full name for Class<E>, we'll start
20640          at Class, and go look over its template type parameters,
20641          finding E.  We'll then try to build the full name of E, and
20642          reach here.  We're now trying to build the full name of E,
20643          and look over the parent DIE for containing scope.  In the
20644          broken case, if we followed the parent DIE of E, we'd again
20645          find Class, and once again go look at its template type
20646          arguments, etc., etc.  Simply don't consider such parent die
20647          as source-level parent of this die (it can't be, the language
20648          doesn't allow it), and break the loop here.  */
20649       name = dwarf2_name (die, cu);
20650       parent_name = dwarf2_name (parent, cu);
20651       complaint (&symfile_complaints,
20652                  _("template param type '%s' defined within parent '%s'"),
20653                  name ? name : "<unknown>",
20654                  parent_name ? parent_name : "<unknown>");
20655       return "";
20656     }
20657   else
20658     switch (parent->tag)
20659       {
20660       case DW_TAG_namespace:
20661         parent_type = read_type_die (parent, cu);
20662         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20663            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20664            Work around this problem here.  */
20665         if (cu->language == language_cplus
20666             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20667           return "";
20668         /* We give a name to even anonymous namespaces.  */
20669         return TYPE_TAG_NAME (parent_type);
20670       case DW_TAG_class_type:
20671       case DW_TAG_interface_type:
20672       case DW_TAG_structure_type:
20673       case DW_TAG_union_type:
20674       case DW_TAG_module:
20675         parent_type = read_type_die (parent, cu);
20676         if (TYPE_TAG_NAME (parent_type) != NULL)
20677           return TYPE_TAG_NAME (parent_type);
20678         else
20679           /* An anonymous structure is only allowed non-static data
20680              members; no typedefs, no member functions, et cetera.
20681              So it does not need a prefix.  */
20682           return "";
20683       case DW_TAG_compile_unit:
20684       case DW_TAG_partial_unit:
20685         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20686         if (cu->language == language_cplus
20687             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20688             && die->child != NULL
20689             && (die->tag == DW_TAG_class_type
20690                 || die->tag == DW_TAG_structure_type
20691                 || die->tag == DW_TAG_union_type))
20692           {
20693             char *name = guess_full_die_structure_name (die, cu);
20694             if (name != NULL)
20695               return name;
20696           }
20697         return "";
20698       case DW_TAG_enumeration_type:
20699         parent_type = read_type_die (parent, cu);
20700         if (TYPE_DECLARED_CLASS (parent_type))
20701           {
20702             if (TYPE_TAG_NAME (parent_type) != NULL)
20703               return TYPE_TAG_NAME (parent_type);
20704             return "";
20705           }
20706         /* Fall through.  */
20707       default:
20708         return determine_prefix (parent, cu);
20709       }
20710 }
20711
20712 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20713    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20714    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20715    an obconcat, otherwise allocate storage for the result.  The CU argument is
20716    used to determine the language and hence, the appropriate separator.  */
20717
20718 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20719
20720 static char *
20721 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20722                  int physname, struct dwarf2_cu *cu)
20723 {
20724   const char *lead = "";
20725   const char *sep;
20726
20727   if (suffix == NULL || suffix[0] == '\0'
20728       || prefix == NULL || prefix[0] == '\0')
20729     sep = "";
20730   else if (cu->language == language_d)
20731     {
20732       /* For D, the 'main' function could be defined in any module, but it
20733          should never be prefixed.  */
20734       if (strcmp (suffix, "D main") == 0)
20735         {
20736           prefix = "";
20737           sep = "";
20738         }
20739       else
20740         sep = ".";
20741     }
20742   else if (cu->language == language_fortran && physname)
20743     {
20744       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20745          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20746
20747       lead = "__";
20748       sep = "_MOD_";
20749     }
20750   else
20751     sep = "::";
20752
20753   if (prefix == NULL)
20754     prefix = "";
20755   if (suffix == NULL)
20756     suffix = "";
20757
20758   if (obs == NULL)
20759     {
20760       char *retval
20761         = ((char *)
20762            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20763
20764       strcpy (retval, lead);
20765       strcat (retval, prefix);
20766       strcat (retval, sep);
20767       strcat (retval, suffix);
20768       return retval;
20769     }
20770   else
20771     {
20772       /* We have an obstack.  */
20773       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20774     }
20775 }
20776
20777 /* Return sibling of die, NULL if no sibling.  */
20778
20779 static struct die_info *
20780 sibling_die (struct die_info *die)
20781 {
20782   return die->sibling;
20783 }
20784
20785 /* Get name of a die, return NULL if not found.  */
20786
20787 static const char *
20788 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20789                           struct obstack *obstack)
20790 {
20791   if (name && cu->language == language_cplus)
20792     {
20793       std::string canon_name = cp_canonicalize_string (name);
20794
20795       if (!canon_name.empty ())
20796         {
20797           if (canon_name != name)
20798             name = (const char *) obstack_copy0 (obstack,
20799                                                  canon_name.c_str (),
20800                                                  canon_name.length ());
20801         }
20802     }
20803
20804   return name;
20805 }
20806
20807 /* Get name of a die, return NULL if not found.
20808    Anonymous namespaces are converted to their magic string.  */
20809
20810 static const char *
20811 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20812 {
20813   struct attribute *attr;
20814
20815   attr = dwarf2_attr (die, DW_AT_name, cu);
20816   if ((!attr || !DW_STRING (attr))
20817       && die->tag != DW_TAG_namespace
20818       && die->tag != DW_TAG_class_type
20819       && die->tag != DW_TAG_interface_type
20820       && die->tag != DW_TAG_structure_type
20821       && die->tag != DW_TAG_union_type)
20822     return NULL;
20823
20824   switch (die->tag)
20825     {
20826     case DW_TAG_compile_unit:
20827     case DW_TAG_partial_unit:
20828       /* Compilation units have a DW_AT_name that is a filename, not
20829          a source language identifier.  */
20830     case DW_TAG_enumeration_type:
20831     case DW_TAG_enumerator:
20832       /* These tags always have simple identifiers already; no need
20833          to canonicalize them.  */
20834       return DW_STRING (attr);
20835
20836     case DW_TAG_namespace:
20837       if (attr != NULL && DW_STRING (attr) != NULL)
20838         return DW_STRING (attr);
20839       return CP_ANONYMOUS_NAMESPACE_STR;
20840
20841     case DW_TAG_class_type:
20842     case DW_TAG_interface_type:
20843     case DW_TAG_structure_type:
20844     case DW_TAG_union_type:
20845       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20846          structures or unions.  These were of the form "._%d" in GCC 4.1,
20847          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20848          and GCC 4.4.  We work around this problem by ignoring these.  */
20849       if (attr && DW_STRING (attr)
20850           && (startswith (DW_STRING (attr), "._")
20851               || startswith (DW_STRING (attr), "<anonymous")))
20852         return NULL;
20853
20854       /* GCC might emit a nameless typedef that has a linkage name.  See
20855          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20856       if (!attr || DW_STRING (attr) == NULL)
20857         {
20858           char *demangled = NULL;
20859
20860           attr = dw2_linkage_name_attr (die, cu);
20861           if (attr == NULL || DW_STRING (attr) == NULL)
20862             return NULL;
20863
20864           /* Avoid demangling DW_STRING (attr) the second time on a second
20865              call for the same DIE.  */
20866           if (!DW_STRING_IS_CANONICAL (attr))
20867             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20868
20869           if (demangled)
20870             {
20871               const char *base;
20872
20873               /* FIXME: we already did this for the partial symbol... */
20874               DW_STRING (attr)
20875                 = ((const char *)
20876                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20877                                   demangled, strlen (demangled)));
20878               DW_STRING_IS_CANONICAL (attr) = 1;
20879               xfree (demangled);
20880
20881               /* Strip any leading namespaces/classes, keep only the base name.
20882                  DW_AT_name for named DIEs does not contain the prefixes.  */
20883               base = strrchr (DW_STRING (attr), ':');
20884               if (base && base > DW_STRING (attr) && base[-1] == ':')
20885                 return &base[1];
20886               else
20887                 return DW_STRING (attr);
20888             }
20889         }
20890       break;
20891
20892     default:
20893       break;
20894     }
20895
20896   if (!DW_STRING_IS_CANONICAL (attr))
20897     {
20898       DW_STRING (attr)
20899         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20900                                     &cu->objfile->per_bfd->storage_obstack);
20901       DW_STRING_IS_CANONICAL (attr) = 1;
20902     }
20903   return DW_STRING (attr);
20904 }
20905
20906 /* Return the die that this die in an extension of, or NULL if there
20907    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20908    containing the return value on output.  */
20909
20910 static struct die_info *
20911 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20912 {
20913   struct attribute *attr;
20914
20915   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20916   if (attr == NULL)
20917     return NULL;
20918
20919   return follow_die_ref (die, attr, ext_cu);
20920 }
20921
20922 /* Convert a DIE tag into its string name.  */
20923
20924 static const char *
20925 dwarf_tag_name (unsigned tag)
20926 {
20927   const char *name = get_DW_TAG_name (tag);
20928
20929   if (name == NULL)
20930     return "DW_TAG_<unknown>";
20931
20932   return name;
20933 }
20934
20935 /* Convert a DWARF attribute code into its string name.  */
20936
20937 static const char *
20938 dwarf_attr_name (unsigned attr)
20939 {
20940   const char *name;
20941
20942 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20943   if (attr == DW_AT_MIPS_fde)
20944     return "DW_AT_MIPS_fde";
20945 #else
20946   if (attr == DW_AT_HP_block_index)
20947     return "DW_AT_HP_block_index";
20948 #endif
20949
20950   name = get_DW_AT_name (attr);
20951
20952   if (name == NULL)
20953     return "DW_AT_<unknown>";
20954
20955   return name;
20956 }
20957
20958 /* Convert a DWARF value form code into its string name.  */
20959
20960 static const char *
20961 dwarf_form_name (unsigned form)
20962 {
20963   const char *name = get_DW_FORM_name (form);
20964
20965   if (name == NULL)
20966     return "DW_FORM_<unknown>";
20967
20968   return name;
20969 }
20970
20971 static const char *
20972 dwarf_bool_name (unsigned mybool)
20973 {
20974   if (mybool)
20975     return "TRUE";
20976   else
20977     return "FALSE";
20978 }
20979
20980 /* Convert a DWARF type code into its string name.  */
20981
20982 static const char *
20983 dwarf_type_encoding_name (unsigned enc)
20984 {
20985   const char *name = get_DW_ATE_name (enc);
20986
20987   if (name == NULL)
20988     return "DW_ATE_<unknown>";
20989
20990   return name;
20991 }
20992
20993 static void
20994 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20995 {
20996   unsigned int i;
20997
20998   print_spaces (indent, f);
20999   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
21000                       dwarf_tag_name (die->tag), die->abbrev,
21001                       to_underlying (die->sect_off));
21002
21003   if (die->parent != NULL)
21004     {
21005       print_spaces (indent, f);
21006       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
21007                           to_underlying (die->parent->sect_off));
21008     }
21009
21010   print_spaces (indent, f);
21011   fprintf_unfiltered (f, "  has children: %s\n",
21012            dwarf_bool_name (die->child != NULL));
21013
21014   print_spaces (indent, f);
21015   fprintf_unfiltered (f, "  attributes:\n");
21016
21017   for (i = 0; i < die->num_attrs; ++i)
21018     {
21019       print_spaces (indent, f);
21020       fprintf_unfiltered (f, "    %s (%s) ",
21021                dwarf_attr_name (die->attrs[i].name),
21022                dwarf_form_name (die->attrs[i].form));
21023
21024       switch (die->attrs[i].form)
21025         {
21026         case DW_FORM_addr:
21027         case DW_FORM_GNU_addr_index:
21028           fprintf_unfiltered (f, "address: ");
21029           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
21030           break;
21031         case DW_FORM_block2:
21032         case DW_FORM_block4:
21033         case DW_FORM_block:
21034         case DW_FORM_block1:
21035           fprintf_unfiltered (f, "block: size %s",
21036                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21037           break;
21038         case DW_FORM_exprloc:
21039           fprintf_unfiltered (f, "expression: size %s",
21040                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21041           break;
21042         case DW_FORM_data16:
21043           fprintf_unfiltered (f, "constant of 16 bytes");
21044           break;
21045         case DW_FORM_ref_addr:
21046           fprintf_unfiltered (f, "ref address: ");
21047           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21048           break;
21049         case DW_FORM_GNU_ref_alt:
21050           fprintf_unfiltered (f, "alt ref address: ");
21051           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21052           break;
21053         case DW_FORM_ref1:
21054         case DW_FORM_ref2:
21055         case DW_FORM_ref4:
21056         case DW_FORM_ref8:
21057         case DW_FORM_ref_udata:
21058           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
21059                               (long) (DW_UNSND (&die->attrs[i])));
21060           break;
21061         case DW_FORM_data1:
21062         case DW_FORM_data2:
21063         case DW_FORM_data4:
21064         case DW_FORM_data8:
21065         case DW_FORM_udata:
21066         case DW_FORM_sdata:
21067           fprintf_unfiltered (f, "constant: %s",
21068                               pulongest (DW_UNSND (&die->attrs[i])));
21069           break;
21070         case DW_FORM_sec_offset:
21071           fprintf_unfiltered (f, "section offset: %s",
21072                               pulongest (DW_UNSND (&die->attrs[i])));
21073           break;
21074         case DW_FORM_ref_sig8:
21075           fprintf_unfiltered (f, "signature: %s",
21076                               hex_string (DW_SIGNATURE (&die->attrs[i])));
21077           break;
21078         case DW_FORM_string:
21079         case DW_FORM_strp:
21080         case DW_FORM_line_strp:
21081         case DW_FORM_GNU_str_index:
21082         case DW_FORM_GNU_strp_alt:
21083           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
21084                    DW_STRING (&die->attrs[i])
21085                    ? DW_STRING (&die->attrs[i]) : "",
21086                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
21087           break;
21088         case DW_FORM_flag:
21089           if (DW_UNSND (&die->attrs[i]))
21090             fprintf_unfiltered (f, "flag: TRUE");
21091           else
21092             fprintf_unfiltered (f, "flag: FALSE");
21093           break;
21094         case DW_FORM_flag_present:
21095           fprintf_unfiltered (f, "flag: TRUE");
21096           break;
21097         case DW_FORM_indirect:
21098           /* The reader will have reduced the indirect form to
21099              the "base form" so this form should not occur.  */
21100           fprintf_unfiltered (f, 
21101                               "unexpected attribute form: DW_FORM_indirect");
21102           break;
21103         case DW_FORM_implicit_const:
21104           fprintf_unfiltered (f, "constant: %s",
21105                               plongest (DW_SND (&die->attrs[i])));
21106           break;
21107         default:
21108           fprintf_unfiltered (f, "unsupported attribute form: %d.",
21109                    die->attrs[i].form);
21110           break;
21111         }
21112       fprintf_unfiltered (f, "\n");
21113     }
21114 }
21115
21116 static void
21117 dump_die_for_error (struct die_info *die)
21118 {
21119   dump_die_shallow (gdb_stderr, 0, die);
21120 }
21121
21122 static void
21123 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
21124 {
21125   int indent = level * 4;
21126
21127   gdb_assert (die != NULL);
21128
21129   if (level >= max_level)
21130     return;
21131
21132   dump_die_shallow (f, indent, die);
21133
21134   if (die->child != NULL)
21135     {
21136       print_spaces (indent, f);
21137       fprintf_unfiltered (f, "  Children:");
21138       if (level + 1 < max_level)
21139         {
21140           fprintf_unfiltered (f, "\n");
21141           dump_die_1 (f, level + 1, max_level, die->child);
21142         }
21143       else
21144         {
21145           fprintf_unfiltered (f,
21146                               " [not printed, max nesting level reached]\n");
21147         }
21148     }
21149
21150   if (die->sibling != NULL && level > 0)
21151     {
21152       dump_die_1 (f, level, max_level, die->sibling);
21153     }
21154 }
21155
21156 /* This is called from the pdie macro in gdbinit.in.
21157    It's not static so gcc will keep a copy callable from gdb.  */
21158
21159 void
21160 dump_die (struct die_info *die, int max_level)
21161 {
21162   dump_die_1 (gdb_stdlog, 0, max_level, die);
21163 }
21164
21165 static void
21166 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
21167 {
21168   void **slot;
21169
21170   slot = htab_find_slot_with_hash (cu->die_hash, die,
21171                                    to_underlying (die->sect_off),
21172                                    INSERT);
21173
21174   *slot = die;
21175 }
21176
21177 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
21178    required kind.  */
21179
21180 static sect_offset
21181 dwarf2_get_ref_die_offset (const struct attribute *attr)
21182 {
21183   if (attr_form_is_ref (attr))
21184     return (sect_offset) DW_UNSND (attr);
21185
21186   complaint (&symfile_complaints,
21187              _("unsupported die ref attribute form: '%s'"),
21188              dwarf_form_name (attr->form));
21189   return {};
21190 }
21191
21192 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
21193  * the value held by the attribute is not constant.  */
21194
21195 static LONGEST
21196 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
21197 {
21198   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
21199     return DW_SND (attr);
21200   else if (attr->form == DW_FORM_udata
21201            || attr->form == DW_FORM_data1
21202            || attr->form == DW_FORM_data2
21203            || attr->form == DW_FORM_data4
21204            || attr->form == DW_FORM_data8)
21205     return DW_UNSND (attr);
21206   else
21207     {
21208       /* For DW_FORM_data16 see attr_form_is_constant.  */
21209       complaint (&symfile_complaints,
21210                  _("Attribute value is not a constant (%s)"),
21211                  dwarf_form_name (attr->form));
21212       return default_value;
21213     }
21214 }
21215
21216 /* Follow reference or signature attribute ATTR of SRC_DIE.
21217    On entry *REF_CU is the CU of SRC_DIE.
21218    On exit *REF_CU is the CU of the result.  */
21219
21220 static struct die_info *
21221 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
21222                        struct dwarf2_cu **ref_cu)
21223 {
21224   struct die_info *die;
21225
21226   if (attr_form_is_ref (attr))
21227     die = follow_die_ref (src_die, attr, ref_cu);
21228   else if (attr->form == DW_FORM_ref_sig8)
21229     die = follow_die_sig (src_die, attr, ref_cu);
21230   else
21231     {
21232       dump_die_for_error (src_die);
21233       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
21234              objfile_name ((*ref_cu)->objfile));
21235     }
21236
21237   return die;
21238 }
21239
21240 /* Follow reference OFFSET.
21241    On entry *REF_CU is the CU of the source die referencing OFFSET.
21242    On exit *REF_CU is the CU of the result.
21243    Returns NULL if OFFSET is invalid.  */
21244
21245 static struct die_info *
21246 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
21247                    struct dwarf2_cu **ref_cu)
21248 {
21249   struct die_info temp_die;
21250   struct dwarf2_cu *target_cu, *cu = *ref_cu;
21251
21252   gdb_assert (cu->per_cu != NULL);
21253
21254   target_cu = cu;
21255
21256   if (cu->per_cu->is_debug_types)
21257     {
21258       /* .debug_types CUs cannot reference anything outside their CU.
21259          If they need to, they have to reference a signatured type via
21260          DW_FORM_ref_sig8.  */
21261       if (!offset_in_cu_p (&cu->header, sect_off))
21262         return NULL;
21263     }
21264   else if (offset_in_dwz != cu->per_cu->is_dwz
21265            || !offset_in_cu_p (&cu->header, sect_off))
21266     {
21267       struct dwarf2_per_cu_data *per_cu;
21268
21269       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
21270                                                  cu->objfile);
21271
21272       /* If necessary, add it to the queue and load its DIEs.  */
21273       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
21274         load_full_comp_unit (per_cu, cu->language);
21275
21276       target_cu = per_cu->cu;
21277     }
21278   else if (cu->dies == NULL)
21279     {
21280       /* We're loading full DIEs during partial symbol reading.  */
21281       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
21282       load_full_comp_unit (cu->per_cu, language_minimal);
21283     }
21284
21285   *ref_cu = target_cu;
21286   temp_die.sect_off = sect_off;
21287   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
21288                                                   &temp_die,
21289                                                   to_underlying (sect_off));
21290 }
21291
21292 /* Follow reference attribute ATTR of SRC_DIE.
21293    On entry *REF_CU is the CU of SRC_DIE.
21294    On exit *REF_CU is the CU of the result.  */
21295
21296 static struct die_info *
21297 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
21298                 struct dwarf2_cu **ref_cu)
21299 {
21300   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21301   struct dwarf2_cu *cu = *ref_cu;
21302   struct die_info *die;
21303
21304   die = follow_die_offset (sect_off,
21305                            (attr->form == DW_FORM_GNU_ref_alt
21306                             || cu->per_cu->is_dwz),
21307                            ref_cu);
21308   if (!die)
21309     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
21310            "at 0x%x [in module %s]"),
21311            to_underlying (sect_off), to_underlying (src_die->sect_off),
21312            objfile_name (cu->objfile));
21313
21314   return die;
21315 }
21316
21317 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
21318    Returned value is intended for DW_OP_call*.  Returned
21319    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
21320
21321 struct dwarf2_locexpr_baton
21322 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
21323                                struct dwarf2_per_cu_data *per_cu,
21324                                CORE_ADDR (*get_frame_pc) (void *baton),
21325                                void *baton)
21326 {
21327   struct dwarf2_cu *cu;
21328   struct die_info *die;
21329   struct attribute *attr;
21330   struct dwarf2_locexpr_baton retval;
21331
21332   dw2_setup (per_cu->objfile);
21333
21334   if (per_cu->cu == NULL)
21335     load_cu (per_cu);
21336   cu = per_cu->cu;
21337   if (cu == NULL)
21338     {
21339       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21340          Instead just throw an error, not much else we can do.  */
21341       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21342              to_underlying (sect_off), objfile_name (per_cu->objfile));
21343     }
21344
21345   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21346   if (!die)
21347     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21348            to_underlying (sect_off), objfile_name (per_cu->objfile));
21349
21350   attr = dwarf2_attr (die, DW_AT_location, cu);
21351   if (!attr)
21352     {
21353       /* DWARF: "If there is no such attribute, then there is no effect.".
21354          DATA is ignored if SIZE is 0.  */
21355
21356       retval.data = NULL;
21357       retval.size = 0;
21358     }
21359   else if (attr_form_is_section_offset (attr))
21360     {
21361       struct dwarf2_loclist_baton loclist_baton;
21362       CORE_ADDR pc = (*get_frame_pc) (baton);
21363       size_t size;
21364
21365       fill_in_loclist_baton (cu, &loclist_baton, attr);
21366
21367       retval.data = dwarf2_find_location_expression (&loclist_baton,
21368                                                      &size, pc);
21369       retval.size = size;
21370     }
21371   else
21372     {
21373       if (!attr_form_is_block (attr))
21374         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
21375                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
21376                to_underlying (sect_off), objfile_name (per_cu->objfile));
21377
21378       retval.data = DW_BLOCK (attr)->data;
21379       retval.size = DW_BLOCK (attr)->size;
21380     }
21381   retval.per_cu = cu->per_cu;
21382
21383   age_cached_comp_units ();
21384
21385   return retval;
21386 }
21387
21388 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
21389    offset.  */
21390
21391 struct dwarf2_locexpr_baton
21392 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
21393                              struct dwarf2_per_cu_data *per_cu,
21394                              CORE_ADDR (*get_frame_pc) (void *baton),
21395                              void *baton)
21396 {
21397   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
21398
21399   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
21400 }
21401
21402 /* Write a constant of a given type as target-ordered bytes into
21403    OBSTACK.  */
21404
21405 static const gdb_byte *
21406 write_constant_as_bytes (struct obstack *obstack,
21407                          enum bfd_endian byte_order,
21408                          struct type *type,
21409                          ULONGEST value,
21410                          LONGEST *len)
21411 {
21412   gdb_byte *result;
21413
21414   *len = TYPE_LENGTH (type);
21415   result = (gdb_byte *) obstack_alloc (obstack, *len);
21416   store_unsigned_integer (result, *len, byte_order, value);
21417
21418   return result;
21419 }
21420
21421 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
21422    pointer to the constant bytes and set LEN to the length of the
21423    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
21424    does not have a DW_AT_const_value, return NULL.  */
21425
21426 const gdb_byte *
21427 dwarf2_fetch_constant_bytes (sect_offset sect_off,
21428                              struct dwarf2_per_cu_data *per_cu,
21429                              struct obstack *obstack,
21430                              LONGEST *len)
21431 {
21432   struct dwarf2_cu *cu;
21433   struct die_info *die;
21434   struct attribute *attr;
21435   const gdb_byte *result = NULL;
21436   struct type *type;
21437   LONGEST value;
21438   enum bfd_endian byte_order;
21439
21440   dw2_setup (per_cu->objfile);
21441
21442   if (per_cu->cu == NULL)
21443     load_cu (per_cu);
21444   cu = per_cu->cu;
21445   if (cu == NULL)
21446     {
21447       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21448          Instead just throw an error, not much else we can do.  */
21449       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21450              to_underlying (sect_off), objfile_name (per_cu->objfile));
21451     }
21452
21453   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21454   if (!die)
21455     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21456            to_underlying (sect_off), objfile_name (per_cu->objfile));
21457
21458
21459   attr = dwarf2_attr (die, DW_AT_const_value, cu);
21460   if (attr == NULL)
21461     return NULL;
21462
21463   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
21464                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21465
21466   switch (attr->form)
21467     {
21468     case DW_FORM_addr:
21469     case DW_FORM_GNU_addr_index:
21470       {
21471         gdb_byte *tem;
21472
21473         *len = cu->header.addr_size;
21474         tem = (gdb_byte *) obstack_alloc (obstack, *len);
21475         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
21476         result = tem;
21477       }
21478       break;
21479     case DW_FORM_string:
21480     case DW_FORM_strp:
21481     case DW_FORM_GNU_str_index:
21482     case DW_FORM_GNU_strp_alt:
21483       /* DW_STRING is already allocated on the objfile obstack, point
21484          directly to it.  */
21485       result = (const gdb_byte *) DW_STRING (attr);
21486       *len = strlen (DW_STRING (attr));
21487       break;
21488     case DW_FORM_block1:
21489     case DW_FORM_block2:
21490     case DW_FORM_block4:
21491     case DW_FORM_block:
21492     case DW_FORM_exprloc:
21493     case DW_FORM_data16:
21494       result = DW_BLOCK (attr)->data;
21495       *len = DW_BLOCK (attr)->size;
21496       break;
21497
21498       /* The DW_AT_const_value attributes are supposed to carry the
21499          symbol's value "represented as it would be on the target
21500          architecture."  By the time we get here, it's already been
21501          converted to host endianness, so we just need to sign- or
21502          zero-extend it as appropriate.  */
21503     case DW_FORM_data1:
21504       type = die_type (die, cu);
21505       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
21506       if (result == NULL)
21507         result = write_constant_as_bytes (obstack, byte_order,
21508                                           type, value, len);
21509       break;
21510     case DW_FORM_data2:
21511       type = die_type (die, cu);
21512       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
21513       if (result == NULL)
21514         result = write_constant_as_bytes (obstack, byte_order,
21515                                           type, value, len);
21516       break;
21517     case DW_FORM_data4:
21518       type = die_type (die, cu);
21519       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
21520       if (result == NULL)
21521         result = write_constant_as_bytes (obstack, byte_order,
21522                                           type, value, len);
21523       break;
21524     case DW_FORM_data8:
21525       type = die_type (die, cu);
21526       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
21527       if (result == NULL)
21528         result = write_constant_as_bytes (obstack, byte_order,
21529                                           type, value, len);
21530       break;
21531
21532     case DW_FORM_sdata:
21533     case DW_FORM_implicit_const:
21534       type = die_type (die, cu);
21535       result = write_constant_as_bytes (obstack, byte_order,
21536                                         type, DW_SND (attr), len);
21537       break;
21538
21539     case DW_FORM_udata:
21540       type = die_type (die, cu);
21541       result = write_constant_as_bytes (obstack, byte_order,
21542                                         type, DW_UNSND (attr), len);
21543       break;
21544
21545     default:
21546       complaint (&symfile_complaints,
21547                  _("unsupported const value attribute form: '%s'"),
21548                  dwarf_form_name (attr->form));
21549       break;
21550     }
21551
21552   return result;
21553 }
21554
21555 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21556    valid type for this die is found.  */
21557
21558 struct type *
21559 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21560                                 struct dwarf2_per_cu_data *per_cu)
21561 {
21562   struct dwarf2_cu *cu;
21563   struct die_info *die;
21564
21565   dw2_setup (per_cu->objfile);
21566
21567   if (per_cu->cu == NULL)
21568     load_cu (per_cu);
21569   cu = per_cu->cu;
21570   if (!cu)
21571     return NULL;
21572
21573   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21574   if (!die)
21575     return NULL;
21576
21577   return die_type (die, cu);
21578 }
21579
21580 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21581    PER_CU.  */
21582
21583 struct type *
21584 dwarf2_get_die_type (cu_offset die_offset,
21585                      struct dwarf2_per_cu_data *per_cu)
21586 {
21587   dw2_setup (per_cu->objfile);
21588
21589   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21590   return get_die_type_at_offset (die_offset_sect, per_cu);
21591 }
21592
21593 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21594    On entry *REF_CU is the CU of SRC_DIE.
21595    On exit *REF_CU is the CU of the result.
21596    Returns NULL if the referenced DIE isn't found.  */
21597
21598 static struct die_info *
21599 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21600                   struct dwarf2_cu **ref_cu)
21601 {
21602   struct die_info temp_die;
21603   struct dwarf2_cu *sig_cu;
21604   struct die_info *die;
21605
21606   /* While it might be nice to assert sig_type->type == NULL here,
21607      we can get here for DW_AT_imported_declaration where we need
21608      the DIE not the type.  */
21609
21610   /* If necessary, add it to the queue and load its DIEs.  */
21611
21612   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21613     read_signatured_type (sig_type);
21614
21615   sig_cu = sig_type->per_cu.cu;
21616   gdb_assert (sig_cu != NULL);
21617   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21618   temp_die.sect_off = sig_type->type_offset_in_section;
21619   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21620                                                  to_underlying (temp_die.sect_off));
21621   if (die)
21622     {
21623       /* For .gdb_index version 7 keep track of included TUs.
21624          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21625       if (dwarf2_per_objfile->index_table != NULL
21626           && dwarf2_per_objfile->index_table->version <= 7)
21627         {
21628           VEC_safe_push (dwarf2_per_cu_ptr,
21629                          (*ref_cu)->per_cu->imported_symtabs,
21630                          sig_cu->per_cu);
21631         }
21632
21633       *ref_cu = sig_cu;
21634       return die;
21635     }
21636
21637   return NULL;
21638 }
21639
21640 /* Follow signatured type referenced by ATTR in SRC_DIE.
21641    On entry *REF_CU is the CU of SRC_DIE.
21642    On exit *REF_CU is the CU of the result.
21643    The result is the DIE of the type.
21644    If the referenced type cannot be found an error is thrown.  */
21645
21646 static struct die_info *
21647 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21648                 struct dwarf2_cu **ref_cu)
21649 {
21650   ULONGEST signature = DW_SIGNATURE (attr);
21651   struct signatured_type *sig_type;
21652   struct die_info *die;
21653
21654   gdb_assert (attr->form == DW_FORM_ref_sig8);
21655
21656   sig_type = lookup_signatured_type (*ref_cu, signature);
21657   /* sig_type will be NULL if the signatured type is missing from
21658      the debug info.  */
21659   if (sig_type == NULL)
21660     {
21661       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21662                " from DIE at 0x%x [in module %s]"),
21663              hex_string (signature), to_underlying (src_die->sect_off),
21664              objfile_name ((*ref_cu)->objfile));
21665     }
21666
21667   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21668   if (die == NULL)
21669     {
21670       dump_die_for_error (src_die);
21671       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21672                " from DIE at 0x%x [in module %s]"),
21673              hex_string (signature), to_underlying (src_die->sect_off),
21674              objfile_name ((*ref_cu)->objfile));
21675     }
21676
21677   return die;
21678 }
21679
21680 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21681    reading in and processing the type unit if necessary.  */
21682
21683 static struct type *
21684 get_signatured_type (struct die_info *die, ULONGEST signature,
21685                      struct dwarf2_cu *cu)
21686 {
21687   struct signatured_type *sig_type;
21688   struct dwarf2_cu *type_cu;
21689   struct die_info *type_die;
21690   struct type *type;
21691
21692   sig_type = lookup_signatured_type (cu, signature);
21693   /* sig_type will be NULL if the signatured type is missing from
21694      the debug info.  */
21695   if (sig_type == NULL)
21696     {
21697       complaint (&symfile_complaints,
21698                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21699                    " from DIE at 0x%x [in module %s]"),
21700                  hex_string (signature), to_underlying (die->sect_off),
21701                  objfile_name (dwarf2_per_objfile->objfile));
21702       return build_error_marker_type (cu, die);
21703     }
21704
21705   /* If we already know the type we're done.  */
21706   if (sig_type->type != NULL)
21707     return sig_type->type;
21708
21709   type_cu = cu;
21710   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21711   if (type_die != NULL)
21712     {
21713       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21714          is created.  This is important, for example, because for c++ classes
21715          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21716       type = read_type_die (type_die, type_cu);
21717       if (type == NULL)
21718         {
21719           complaint (&symfile_complaints,
21720                      _("Dwarf Error: Cannot build signatured type %s"
21721                        " referenced from DIE at 0x%x [in module %s]"),
21722                      hex_string (signature), to_underlying (die->sect_off),
21723                      objfile_name (dwarf2_per_objfile->objfile));
21724           type = build_error_marker_type (cu, die);
21725         }
21726     }
21727   else
21728     {
21729       complaint (&symfile_complaints,
21730                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21731                    " from DIE at 0x%x [in module %s]"),
21732                  hex_string (signature), to_underlying (die->sect_off),
21733                  objfile_name (dwarf2_per_objfile->objfile));
21734       type = build_error_marker_type (cu, die);
21735     }
21736   sig_type->type = type;
21737
21738   return type;
21739 }
21740
21741 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21742    reading in and processing the type unit if necessary.  */
21743
21744 static struct type *
21745 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21746                           struct dwarf2_cu *cu) /* ARI: editCase function */
21747 {
21748   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21749   if (attr_form_is_ref (attr))
21750     {
21751       struct dwarf2_cu *type_cu = cu;
21752       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21753
21754       return read_type_die (type_die, type_cu);
21755     }
21756   else if (attr->form == DW_FORM_ref_sig8)
21757     {
21758       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21759     }
21760   else
21761     {
21762       complaint (&symfile_complaints,
21763                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21764                    " at 0x%x [in module %s]"),
21765                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21766                  objfile_name (dwarf2_per_objfile->objfile));
21767       return build_error_marker_type (cu, die);
21768     }
21769 }
21770
21771 /* Load the DIEs associated with type unit PER_CU into memory.  */
21772
21773 static void
21774 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21775 {
21776   struct signatured_type *sig_type;
21777
21778   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21779   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21780
21781   /* We have the per_cu, but we need the signatured_type.
21782      Fortunately this is an easy translation.  */
21783   gdb_assert (per_cu->is_debug_types);
21784   sig_type = (struct signatured_type *) per_cu;
21785
21786   gdb_assert (per_cu->cu == NULL);
21787
21788   read_signatured_type (sig_type);
21789
21790   gdb_assert (per_cu->cu != NULL);
21791 }
21792
21793 /* die_reader_func for read_signatured_type.
21794    This is identical to load_full_comp_unit_reader,
21795    but is kept separate for now.  */
21796
21797 static void
21798 read_signatured_type_reader (const struct die_reader_specs *reader,
21799                              const gdb_byte *info_ptr,
21800                              struct die_info *comp_unit_die,
21801                              int has_children,
21802                              void *data)
21803 {
21804   struct dwarf2_cu *cu = reader->cu;
21805
21806   gdb_assert (cu->die_hash == NULL);
21807   cu->die_hash =
21808     htab_create_alloc_ex (cu->header.length / 12,
21809                           die_hash,
21810                           die_eq,
21811                           NULL,
21812                           &cu->comp_unit_obstack,
21813                           hashtab_obstack_allocate,
21814                           dummy_obstack_deallocate);
21815
21816   if (has_children)
21817     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21818                                                   &info_ptr, comp_unit_die);
21819   cu->dies = comp_unit_die;
21820   /* comp_unit_die is not stored in die_hash, no need.  */
21821
21822   /* We try not to read any attributes in this function, because not
21823      all CUs needed for references have been loaded yet, and symbol
21824      table processing isn't initialized.  But we have to set the CU language,
21825      or we won't be able to build types correctly.
21826      Similarly, if we do not read the producer, we can not apply
21827      producer-specific interpretation.  */
21828   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21829 }
21830
21831 /* Read in a signatured type and build its CU and DIEs.
21832    If the type is a stub for the real type in a DWO file,
21833    read in the real type from the DWO file as well.  */
21834
21835 static void
21836 read_signatured_type (struct signatured_type *sig_type)
21837 {
21838   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21839
21840   gdb_assert (per_cu->is_debug_types);
21841   gdb_assert (per_cu->cu == NULL);
21842
21843   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21844                            read_signatured_type_reader, NULL);
21845   sig_type->per_cu.tu_read = 1;
21846 }
21847
21848 /* Decode simple location descriptions.
21849    Given a pointer to a dwarf block that defines a location, compute
21850    the location and return the value.
21851
21852    NOTE drow/2003-11-18: This function is called in two situations
21853    now: for the address of static or global variables (partial symbols
21854    only) and for offsets into structures which are expected to be
21855    (more or less) constant.  The partial symbol case should go away,
21856    and only the constant case should remain.  That will let this
21857    function complain more accurately.  A few special modes are allowed
21858    without complaint for global variables (for instance, global
21859    register values and thread-local values).
21860
21861    A location description containing no operations indicates that the
21862    object is optimized out.  The return value is 0 for that case.
21863    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21864    callers will only want a very basic result and this can become a
21865    complaint.
21866
21867    Note that stack[0] is unused except as a default error return.  */
21868
21869 static CORE_ADDR
21870 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21871 {
21872   struct objfile *objfile = cu->objfile;
21873   size_t i;
21874   size_t size = blk->size;
21875   const gdb_byte *data = blk->data;
21876   CORE_ADDR stack[64];
21877   int stacki;
21878   unsigned int bytes_read, unsnd;
21879   gdb_byte op;
21880
21881   i = 0;
21882   stacki = 0;
21883   stack[stacki] = 0;
21884   stack[++stacki] = 0;
21885
21886   while (i < size)
21887     {
21888       op = data[i++];
21889       switch (op)
21890         {
21891         case DW_OP_lit0:
21892         case DW_OP_lit1:
21893         case DW_OP_lit2:
21894         case DW_OP_lit3:
21895         case DW_OP_lit4:
21896         case DW_OP_lit5:
21897         case DW_OP_lit6:
21898         case DW_OP_lit7:
21899         case DW_OP_lit8:
21900         case DW_OP_lit9:
21901         case DW_OP_lit10:
21902         case DW_OP_lit11:
21903         case DW_OP_lit12:
21904         case DW_OP_lit13:
21905         case DW_OP_lit14:
21906         case DW_OP_lit15:
21907         case DW_OP_lit16:
21908         case DW_OP_lit17:
21909         case DW_OP_lit18:
21910         case DW_OP_lit19:
21911         case DW_OP_lit20:
21912         case DW_OP_lit21:
21913         case DW_OP_lit22:
21914         case DW_OP_lit23:
21915         case DW_OP_lit24:
21916         case DW_OP_lit25:
21917         case DW_OP_lit26:
21918         case DW_OP_lit27:
21919         case DW_OP_lit28:
21920         case DW_OP_lit29:
21921         case DW_OP_lit30:
21922         case DW_OP_lit31:
21923           stack[++stacki] = op - DW_OP_lit0;
21924           break;
21925
21926         case DW_OP_reg0:
21927         case DW_OP_reg1:
21928         case DW_OP_reg2:
21929         case DW_OP_reg3:
21930         case DW_OP_reg4:
21931         case DW_OP_reg5:
21932         case DW_OP_reg6:
21933         case DW_OP_reg7:
21934         case DW_OP_reg8:
21935         case DW_OP_reg9:
21936         case DW_OP_reg10:
21937         case DW_OP_reg11:
21938         case DW_OP_reg12:
21939         case DW_OP_reg13:
21940         case DW_OP_reg14:
21941         case DW_OP_reg15:
21942         case DW_OP_reg16:
21943         case DW_OP_reg17:
21944         case DW_OP_reg18:
21945         case DW_OP_reg19:
21946         case DW_OP_reg20:
21947         case DW_OP_reg21:
21948         case DW_OP_reg22:
21949         case DW_OP_reg23:
21950         case DW_OP_reg24:
21951         case DW_OP_reg25:
21952         case DW_OP_reg26:
21953         case DW_OP_reg27:
21954         case DW_OP_reg28:
21955         case DW_OP_reg29:
21956         case DW_OP_reg30:
21957         case DW_OP_reg31:
21958           stack[++stacki] = op - DW_OP_reg0;
21959           if (i < size)
21960             dwarf2_complex_location_expr_complaint ();
21961           break;
21962
21963         case DW_OP_regx:
21964           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21965           i += bytes_read;
21966           stack[++stacki] = unsnd;
21967           if (i < size)
21968             dwarf2_complex_location_expr_complaint ();
21969           break;
21970
21971         case DW_OP_addr:
21972           stack[++stacki] = read_address (objfile->obfd, &data[i],
21973                                           cu, &bytes_read);
21974           i += bytes_read;
21975           break;
21976
21977         case DW_OP_const1u:
21978           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21979           i += 1;
21980           break;
21981
21982         case DW_OP_const1s:
21983           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21984           i += 1;
21985           break;
21986
21987         case DW_OP_const2u:
21988           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21989           i += 2;
21990           break;
21991
21992         case DW_OP_const2s:
21993           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21994           i += 2;
21995           break;
21996
21997         case DW_OP_const4u:
21998           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21999           i += 4;
22000           break;
22001
22002         case DW_OP_const4s:
22003           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
22004           i += 4;
22005           break;
22006
22007         case DW_OP_const8u:
22008           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
22009           i += 8;
22010           break;
22011
22012         case DW_OP_constu:
22013           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
22014                                                   &bytes_read);
22015           i += bytes_read;
22016           break;
22017
22018         case DW_OP_consts:
22019           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
22020           i += bytes_read;
22021           break;
22022
22023         case DW_OP_dup:
22024           stack[stacki + 1] = stack[stacki];
22025           stacki++;
22026           break;
22027
22028         case DW_OP_plus:
22029           stack[stacki - 1] += stack[stacki];
22030           stacki--;
22031           break;
22032
22033         case DW_OP_plus_uconst:
22034           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
22035                                                  &bytes_read);
22036           i += bytes_read;
22037           break;
22038
22039         case DW_OP_minus:
22040           stack[stacki - 1] -= stack[stacki];
22041           stacki--;
22042           break;
22043
22044         case DW_OP_deref:
22045           /* If we're not the last op, then we definitely can't encode
22046              this using GDB's address_class enum.  This is valid for partial
22047              global symbols, although the variable's address will be bogus
22048              in the psymtab.  */
22049           if (i < size)
22050             dwarf2_complex_location_expr_complaint ();
22051           break;
22052
22053         case DW_OP_GNU_push_tls_address:
22054         case DW_OP_form_tls_address:
22055           /* The top of the stack has the offset from the beginning
22056              of the thread control block at which the variable is located.  */
22057           /* Nothing should follow this operator, so the top of stack would
22058              be returned.  */
22059           /* This is valid for partial global symbols, but the variable's
22060              address will be bogus in the psymtab.  Make it always at least
22061              non-zero to not look as a variable garbage collected by linker
22062              which have DW_OP_addr 0.  */
22063           if (i < size)
22064             dwarf2_complex_location_expr_complaint ();
22065           stack[stacki]++;
22066           break;
22067
22068         case DW_OP_GNU_uninit:
22069           break;
22070
22071         case DW_OP_GNU_addr_index:
22072         case DW_OP_GNU_const_index:
22073           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
22074                                                          &bytes_read);
22075           i += bytes_read;
22076           break;
22077
22078         default:
22079           {
22080             const char *name = get_DW_OP_name (op);
22081
22082             if (name)
22083               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
22084                          name);
22085             else
22086               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
22087                          op);
22088           }
22089
22090           return (stack[stacki]);
22091         }
22092
22093       /* Enforce maximum stack depth of SIZE-1 to avoid writing
22094          outside of the allocated space.  Also enforce minimum>0.  */
22095       if (stacki >= ARRAY_SIZE (stack) - 1)
22096         {
22097           complaint (&symfile_complaints,
22098                      _("location description stack overflow"));
22099           return 0;
22100         }
22101
22102       if (stacki <= 0)
22103         {
22104           complaint (&symfile_complaints,
22105                      _("location description stack underflow"));
22106           return 0;
22107         }
22108     }
22109   return (stack[stacki]);
22110 }
22111
22112 /* memory allocation interface */
22113
22114 static struct dwarf_block *
22115 dwarf_alloc_block (struct dwarf2_cu *cu)
22116 {
22117   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
22118 }
22119
22120 static struct die_info *
22121 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
22122 {
22123   struct die_info *die;
22124   size_t size = sizeof (struct die_info);
22125
22126   if (num_attrs > 1)
22127     size += (num_attrs - 1) * sizeof (struct attribute);
22128
22129   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
22130   memset (die, 0, sizeof (struct die_info));
22131   return (die);
22132 }
22133
22134 \f
22135 /* Macro support.  */
22136
22137 /* Return file name relative to the compilation directory of file number I in
22138    *LH's file name table.  The result is allocated using xmalloc; the caller is
22139    responsible for freeing it.  */
22140
22141 static char *
22142 file_file_name (int file, struct line_header *lh)
22143 {
22144   /* Is the file number a valid index into the line header's file name
22145      table?  Remember that file numbers start with one, not zero.  */
22146   if (1 <= file && file <= lh->file_names.size ())
22147     {
22148       const file_entry &fe = lh->file_names[file - 1];
22149
22150       if (!IS_ABSOLUTE_PATH (fe.name))
22151         {
22152           const char *dir = fe.include_dir (lh);
22153           if (dir != NULL)
22154             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
22155         }
22156       return xstrdup (fe.name);
22157     }
22158   else
22159     {
22160       /* The compiler produced a bogus file number.  We can at least
22161          record the macro definitions made in the file, even if we
22162          won't be able to find the file by name.  */
22163       char fake_name[80];
22164
22165       xsnprintf (fake_name, sizeof (fake_name),
22166                  "<bad macro file number %d>", file);
22167
22168       complaint (&symfile_complaints,
22169                  _("bad file number in macro information (%d)"),
22170                  file);
22171
22172       return xstrdup (fake_name);
22173     }
22174 }
22175
22176 /* Return the full name of file number I in *LH's file name table.
22177    Use COMP_DIR as the name of the current directory of the
22178    compilation.  The result is allocated using xmalloc; the caller is
22179    responsible for freeing it.  */
22180 static char *
22181 file_full_name (int file, struct line_header *lh, const char *comp_dir)
22182 {
22183   /* Is the file number a valid index into the line header's file name
22184      table?  Remember that file numbers start with one, not zero.  */
22185   if (1 <= file && file <= lh->file_names.size ())
22186     {
22187       char *relative = file_file_name (file, lh);
22188
22189       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
22190         return relative;
22191       return reconcat (relative, comp_dir, SLASH_STRING,
22192                        relative, (char *) NULL);
22193     }
22194   else
22195     return file_file_name (file, lh);
22196 }
22197
22198
22199 static struct macro_source_file *
22200 macro_start_file (int file, int line,
22201                   struct macro_source_file *current_file,
22202                   struct line_header *lh)
22203 {
22204   /* File name relative to the compilation directory of this source file.  */
22205   char *file_name = file_file_name (file, lh);
22206
22207   if (! current_file)
22208     {
22209       /* Note: We don't create a macro table for this compilation unit
22210          at all until we actually get a filename.  */
22211       struct macro_table *macro_table = get_macro_table ();
22212
22213       /* If we have no current file, then this must be the start_file
22214          directive for the compilation unit's main source file.  */
22215       current_file = macro_set_main (macro_table, file_name);
22216       macro_define_special (macro_table);
22217     }
22218   else
22219     current_file = macro_include (current_file, line, file_name);
22220
22221   xfree (file_name);
22222
22223   return current_file;
22224 }
22225
22226 static const char *
22227 consume_improper_spaces (const char *p, const char *body)
22228 {
22229   if (*p == ' ')
22230     {
22231       complaint (&symfile_complaints,
22232                  _("macro definition contains spaces "
22233                    "in formal argument list:\n`%s'"),
22234                  body);
22235
22236       while (*p == ' ')
22237         p++;
22238     }
22239
22240   return p;
22241 }
22242
22243
22244 static void
22245 parse_macro_definition (struct macro_source_file *file, int line,
22246                         const char *body)
22247 {
22248   const char *p;
22249
22250   /* The body string takes one of two forms.  For object-like macro
22251      definitions, it should be:
22252
22253         <macro name> " " <definition>
22254
22255      For function-like macro definitions, it should be:
22256
22257         <macro name> "() " <definition>
22258      or
22259         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
22260
22261      Spaces may appear only where explicitly indicated, and in the
22262      <definition>.
22263
22264      The Dwarf 2 spec says that an object-like macro's name is always
22265      followed by a space, but versions of GCC around March 2002 omit
22266      the space when the macro's definition is the empty string.
22267
22268      The Dwarf 2 spec says that there should be no spaces between the
22269      formal arguments in a function-like macro's formal argument list,
22270      but versions of GCC around March 2002 include spaces after the
22271      commas.  */
22272
22273
22274   /* Find the extent of the macro name.  The macro name is terminated
22275      by either a space or null character (for an object-like macro) or
22276      an opening paren (for a function-like macro).  */
22277   for (p = body; *p; p++)
22278     if (*p == ' ' || *p == '(')
22279       break;
22280
22281   if (*p == ' ' || *p == '\0')
22282     {
22283       /* It's an object-like macro.  */
22284       int name_len = p - body;
22285       char *name = savestring (body, name_len);
22286       const char *replacement;
22287
22288       if (*p == ' ')
22289         replacement = body + name_len + 1;
22290       else
22291         {
22292           dwarf2_macro_malformed_definition_complaint (body);
22293           replacement = body + name_len;
22294         }
22295
22296       macro_define_object (file, line, name, replacement);
22297
22298       xfree (name);
22299     }
22300   else if (*p == '(')
22301     {
22302       /* It's a function-like macro.  */
22303       char *name = savestring (body, p - body);
22304       int argc = 0;
22305       int argv_size = 1;
22306       char **argv = XNEWVEC (char *, argv_size);
22307
22308       p++;
22309
22310       p = consume_improper_spaces (p, body);
22311
22312       /* Parse the formal argument list.  */
22313       while (*p && *p != ')')
22314         {
22315           /* Find the extent of the current argument name.  */
22316           const char *arg_start = p;
22317
22318           while (*p && *p != ',' && *p != ')' && *p != ' ')
22319             p++;
22320
22321           if (! *p || p == arg_start)
22322             dwarf2_macro_malformed_definition_complaint (body);
22323           else
22324             {
22325               /* Make sure argv has room for the new argument.  */
22326               if (argc >= argv_size)
22327                 {
22328                   argv_size *= 2;
22329                   argv = XRESIZEVEC (char *, argv, argv_size);
22330                 }
22331
22332               argv[argc++] = savestring (arg_start, p - arg_start);
22333             }
22334
22335           p = consume_improper_spaces (p, body);
22336
22337           /* Consume the comma, if present.  */
22338           if (*p == ',')
22339             {
22340               p++;
22341
22342               p = consume_improper_spaces (p, body);
22343             }
22344         }
22345
22346       if (*p == ')')
22347         {
22348           p++;
22349
22350           if (*p == ' ')
22351             /* Perfectly formed definition, no complaints.  */
22352             macro_define_function (file, line, name,
22353                                    argc, (const char **) argv,
22354                                    p + 1);
22355           else if (*p == '\0')
22356             {
22357               /* Complain, but do define it.  */
22358               dwarf2_macro_malformed_definition_complaint (body);
22359               macro_define_function (file, line, name,
22360                                      argc, (const char **) argv,
22361                                      p);
22362             }
22363           else
22364             /* Just complain.  */
22365             dwarf2_macro_malformed_definition_complaint (body);
22366         }
22367       else
22368         /* Just complain.  */
22369         dwarf2_macro_malformed_definition_complaint (body);
22370
22371       xfree (name);
22372       {
22373         int i;
22374
22375         for (i = 0; i < argc; i++)
22376           xfree (argv[i]);
22377       }
22378       xfree (argv);
22379     }
22380   else
22381     dwarf2_macro_malformed_definition_complaint (body);
22382 }
22383
22384 /* Skip some bytes from BYTES according to the form given in FORM.
22385    Returns the new pointer.  */
22386
22387 static const gdb_byte *
22388 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
22389                  enum dwarf_form form,
22390                  unsigned int offset_size,
22391                  struct dwarf2_section_info *section)
22392 {
22393   unsigned int bytes_read;
22394
22395   switch (form)
22396     {
22397     case DW_FORM_data1:
22398     case DW_FORM_flag:
22399       ++bytes;
22400       break;
22401
22402     case DW_FORM_data2:
22403       bytes += 2;
22404       break;
22405
22406     case DW_FORM_data4:
22407       bytes += 4;
22408       break;
22409
22410     case DW_FORM_data8:
22411       bytes += 8;
22412       break;
22413
22414     case DW_FORM_data16:
22415       bytes += 16;
22416       break;
22417
22418     case DW_FORM_string:
22419       read_direct_string (abfd, bytes, &bytes_read);
22420       bytes += bytes_read;
22421       break;
22422
22423     case DW_FORM_sec_offset:
22424     case DW_FORM_strp:
22425     case DW_FORM_GNU_strp_alt:
22426       bytes += offset_size;
22427       break;
22428
22429     case DW_FORM_block:
22430       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
22431       bytes += bytes_read;
22432       break;
22433
22434     case DW_FORM_block1:
22435       bytes += 1 + read_1_byte (abfd, bytes);
22436       break;
22437     case DW_FORM_block2:
22438       bytes += 2 + read_2_bytes (abfd, bytes);
22439       break;
22440     case DW_FORM_block4:
22441       bytes += 4 + read_4_bytes (abfd, bytes);
22442       break;
22443
22444     case DW_FORM_sdata:
22445     case DW_FORM_udata:
22446     case DW_FORM_GNU_addr_index:
22447     case DW_FORM_GNU_str_index:
22448       bytes = gdb_skip_leb128 (bytes, buffer_end);
22449       if (bytes == NULL)
22450         {
22451           dwarf2_section_buffer_overflow_complaint (section);
22452           return NULL;
22453         }
22454       break;
22455
22456     case DW_FORM_implicit_const:
22457       break;
22458
22459     default:
22460       {
22461       complain:
22462         complaint (&symfile_complaints,
22463                    _("invalid form 0x%x in `%s'"),
22464                    form, get_section_name (section));
22465         return NULL;
22466       }
22467     }
22468
22469   return bytes;
22470 }
22471
22472 /* A helper for dwarf_decode_macros that handles skipping an unknown
22473    opcode.  Returns an updated pointer to the macro data buffer; or,
22474    on error, issues a complaint and returns NULL.  */
22475
22476 static const gdb_byte *
22477 skip_unknown_opcode (unsigned int opcode,
22478                      const gdb_byte **opcode_definitions,
22479                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22480                      bfd *abfd,
22481                      unsigned int offset_size,
22482                      struct dwarf2_section_info *section)
22483 {
22484   unsigned int bytes_read, i;
22485   unsigned long arg;
22486   const gdb_byte *defn;
22487
22488   if (opcode_definitions[opcode] == NULL)
22489     {
22490       complaint (&symfile_complaints,
22491                  _("unrecognized DW_MACFINO opcode 0x%x"),
22492                  opcode);
22493       return NULL;
22494     }
22495
22496   defn = opcode_definitions[opcode];
22497   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
22498   defn += bytes_read;
22499
22500   for (i = 0; i < arg; ++i)
22501     {
22502       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
22503                                  (enum dwarf_form) defn[i], offset_size,
22504                                  section);
22505       if (mac_ptr == NULL)
22506         {
22507           /* skip_form_bytes already issued the complaint.  */
22508           return NULL;
22509         }
22510     }
22511
22512   return mac_ptr;
22513 }
22514
22515 /* A helper function which parses the header of a macro section.
22516    If the macro section is the extended (for now called "GNU") type,
22517    then this updates *OFFSET_SIZE.  Returns a pointer to just after
22518    the header, or issues a complaint and returns NULL on error.  */
22519
22520 static const gdb_byte *
22521 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
22522                           bfd *abfd,
22523                           const gdb_byte *mac_ptr,
22524                           unsigned int *offset_size,
22525                           int section_is_gnu)
22526 {
22527   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
22528
22529   if (section_is_gnu)
22530     {
22531       unsigned int version, flags;
22532
22533       version = read_2_bytes (abfd, mac_ptr);
22534       if (version != 4 && version != 5)
22535         {
22536           complaint (&symfile_complaints,
22537                      _("unrecognized version `%d' in .debug_macro section"),
22538                      version);
22539           return NULL;
22540         }
22541       mac_ptr += 2;
22542
22543       flags = read_1_byte (abfd, mac_ptr);
22544       ++mac_ptr;
22545       *offset_size = (flags & 1) ? 8 : 4;
22546
22547       if ((flags & 2) != 0)
22548         /* We don't need the line table offset.  */
22549         mac_ptr += *offset_size;
22550
22551       /* Vendor opcode descriptions.  */
22552       if ((flags & 4) != 0)
22553         {
22554           unsigned int i, count;
22555
22556           count = read_1_byte (abfd, mac_ptr);
22557           ++mac_ptr;
22558           for (i = 0; i < count; ++i)
22559             {
22560               unsigned int opcode, bytes_read;
22561               unsigned long arg;
22562
22563               opcode = read_1_byte (abfd, mac_ptr);
22564               ++mac_ptr;
22565               opcode_definitions[opcode] = mac_ptr;
22566               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22567               mac_ptr += bytes_read;
22568               mac_ptr += arg;
22569             }
22570         }
22571     }
22572
22573   return mac_ptr;
22574 }
22575
22576 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22577    including DW_MACRO_import.  */
22578
22579 static void
22580 dwarf_decode_macro_bytes (bfd *abfd,
22581                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22582                           struct macro_source_file *current_file,
22583                           struct line_header *lh,
22584                           struct dwarf2_section_info *section,
22585                           int section_is_gnu, int section_is_dwz,
22586                           unsigned int offset_size,
22587                           htab_t include_hash)
22588 {
22589   struct objfile *objfile = dwarf2_per_objfile->objfile;
22590   enum dwarf_macro_record_type macinfo_type;
22591   int at_commandline;
22592   const gdb_byte *opcode_definitions[256];
22593
22594   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22595                                       &offset_size, section_is_gnu);
22596   if (mac_ptr == NULL)
22597     {
22598       /* We already issued a complaint.  */
22599       return;
22600     }
22601
22602   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22603      GDB is still reading the definitions from command line.  First
22604      DW_MACINFO_start_file will need to be ignored as it was already executed
22605      to create CURRENT_FILE for the main source holding also the command line
22606      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22607      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22608
22609   at_commandline = 1;
22610
22611   do
22612     {
22613       /* Do we at least have room for a macinfo type byte?  */
22614       if (mac_ptr >= mac_end)
22615         {
22616           dwarf2_section_buffer_overflow_complaint (section);
22617           break;
22618         }
22619
22620       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22621       mac_ptr++;
22622
22623       /* Note that we rely on the fact that the corresponding GNU and
22624          DWARF constants are the same.  */
22625       switch (macinfo_type)
22626         {
22627           /* A zero macinfo type indicates the end of the macro
22628              information.  */
22629         case 0:
22630           break;
22631
22632         case DW_MACRO_define:
22633         case DW_MACRO_undef:
22634         case DW_MACRO_define_strp:
22635         case DW_MACRO_undef_strp:
22636         case DW_MACRO_define_sup:
22637         case DW_MACRO_undef_sup:
22638           {
22639             unsigned int bytes_read;
22640             int line;
22641             const char *body;
22642             int is_define;
22643
22644             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22645             mac_ptr += bytes_read;
22646
22647             if (macinfo_type == DW_MACRO_define
22648                 || macinfo_type == DW_MACRO_undef)
22649               {
22650                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22651                 mac_ptr += bytes_read;
22652               }
22653             else
22654               {
22655                 LONGEST str_offset;
22656
22657                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22658                 mac_ptr += offset_size;
22659
22660                 if (macinfo_type == DW_MACRO_define_sup
22661                     || macinfo_type == DW_MACRO_undef_sup
22662                     || section_is_dwz)
22663                   {
22664                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22665
22666                     body = read_indirect_string_from_dwz (dwz, str_offset);
22667                   }
22668                 else
22669                   body = read_indirect_string_at_offset (abfd, str_offset);
22670               }
22671
22672             is_define = (macinfo_type == DW_MACRO_define
22673                          || macinfo_type == DW_MACRO_define_strp
22674                          || macinfo_type == DW_MACRO_define_sup);
22675             if (! current_file)
22676               {
22677                 /* DWARF violation as no main source is present.  */
22678                 complaint (&symfile_complaints,
22679                            _("debug info with no main source gives macro %s "
22680                              "on line %d: %s"),
22681                            is_define ? _("definition") : _("undefinition"),
22682                            line, body);
22683                 break;
22684               }
22685             if ((line == 0 && !at_commandline)
22686                 || (line != 0 && at_commandline))
22687               complaint (&symfile_complaints,
22688                          _("debug info gives %s macro %s with %s line %d: %s"),
22689                          at_commandline ? _("command-line") : _("in-file"),
22690                          is_define ? _("definition") : _("undefinition"),
22691                          line == 0 ? _("zero") : _("non-zero"), line, body);
22692
22693             if (is_define)
22694               parse_macro_definition (current_file, line, body);
22695             else
22696               {
22697                 gdb_assert (macinfo_type == DW_MACRO_undef
22698                             || macinfo_type == DW_MACRO_undef_strp
22699                             || macinfo_type == DW_MACRO_undef_sup);
22700                 macro_undef (current_file, line, body);
22701               }
22702           }
22703           break;
22704
22705         case DW_MACRO_start_file:
22706           {
22707             unsigned int bytes_read;
22708             int line, file;
22709
22710             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22711             mac_ptr += bytes_read;
22712             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22713             mac_ptr += bytes_read;
22714
22715             if ((line == 0 && !at_commandline)
22716                 || (line != 0 && at_commandline))
22717               complaint (&symfile_complaints,
22718                          _("debug info gives source %d included "
22719                            "from %s at %s line %d"),
22720                          file, at_commandline ? _("command-line") : _("file"),
22721                          line == 0 ? _("zero") : _("non-zero"), line);
22722
22723             if (at_commandline)
22724               {
22725                 /* This DW_MACRO_start_file was executed in the
22726                    pass one.  */
22727                 at_commandline = 0;
22728               }
22729             else
22730               current_file = macro_start_file (file, line, current_file, lh);
22731           }
22732           break;
22733
22734         case DW_MACRO_end_file:
22735           if (! current_file)
22736             complaint (&symfile_complaints,
22737                        _("macro debug info has an unmatched "
22738                          "`close_file' directive"));
22739           else
22740             {
22741               current_file = current_file->included_by;
22742               if (! current_file)
22743                 {
22744                   enum dwarf_macro_record_type next_type;
22745
22746                   /* GCC circa March 2002 doesn't produce the zero
22747                      type byte marking the end of the compilation
22748                      unit.  Complain if it's not there, but exit no
22749                      matter what.  */
22750
22751                   /* Do we at least have room for a macinfo type byte?  */
22752                   if (mac_ptr >= mac_end)
22753                     {
22754                       dwarf2_section_buffer_overflow_complaint (section);
22755                       return;
22756                     }
22757
22758                   /* We don't increment mac_ptr here, so this is just
22759                      a look-ahead.  */
22760                   next_type
22761                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22762                                                                   mac_ptr);
22763                   if (next_type != 0)
22764                     complaint (&symfile_complaints,
22765                                _("no terminating 0-type entry for "
22766                                  "macros in `.debug_macinfo' section"));
22767
22768                   return;
22769                 }
22770             }
22771           break;
22772
22773         case DW_MACRO_import:
22774         case DW_MACRO_import_sup:
22775           {
22776             LONGEST offset;
22777             void **slot;
22778             bfd *include_bfd = abfd;
22779             struct dwarf2_section_info *include_section = section;
22780             const gdb_byte *include_mac_end = mac_end;
22781             int is_dwz = section_is_dwz;
22782             const gdb_byte *new_mac_ptr;
22783
22784             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22785             mac_ptr += offset_size;
22786
22787             if (macinfo_type == DW_MACRO_import_sup)
22788               {
22789                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22790
22791                 dwarf2_read_section (objfile, &dwz->macro);
22792
22793                 include_section = &dwz->macro;
22794                 include_bfd = get_section_bfd_owner (include_section);
22795                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22796                 is_dwz = 1;
22797               }
22798
22799             new_mac_ptr = include_section->buffer + offset;
22800             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22801
22802             if (*slot != NULL)
22803               {
22804                 /* This has actually happened; see
22805                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22806                 complaint (&symfile_complaints,
22807                            _("recursive DW_MACRO_import in "
22808                              ".debug_macro section"));
22809               }
22810             else
22811               {
22812                 *slot = (void *) new_mac_ptr;
22813
22814                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22815                                           include_mac_end, current_file, lh,
22816                                           section, section_is_gnu, is_dwz,
22817                                           offset_size, include_hash);
22818
22819                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22820               }
22821           }
22822           break;
22823
22824         case DW_MACINFO_vendor_ext:
22825           if (!section_is_gnu)
22826             {
22827               unsigned int bytes_read;
22828
22829               /* This reads the constant, but since we don't recognize
22830                  any vendor extensions, we ignore it.  */
22831               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22832               mac_ptr += bytes_read;
22833               read_direct_string (abfd, mac_ptr, &bytes_read);
22834               mac_ptr += bytes_read;
22835
22836               /* We don't recognize any vendor extensions.  */
22837               break;
22838             }
22839           /* FALLTHROUGH */
22840
22841         default:
22842           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22843                                          mac_ptr, mac_end, abfd, offset_size,
22844                                          section);
22845           if (mac_ptr == NULL)
22846             return;
22847           break;
22848         }
22849     } while (macinfo_type != 0);
22850 }
22851
22852 static void
22853 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22854                      int section_is_gnu)
22855 {
22856   struct objfile *objfile = dwarf2_per_objfile->objfile;
22857   struct line_header *lh = cu->line_header;
22858   bfd *abfd;
22859   const gdb_byte *mac_ptr, *mac_end;
22860   struct macro_source_file *current_file = 0;
22861   enum dwarf_macro_record_type macinfo_type;
22862   unsigned int offset_size = cu->header.offset_size;
22863   const gdb_byte *opcode_definitions[256];
22864   void **slot;
22865   struct dwarf2_section_info *section;
22866   const char *section_name;
22867
22868   if (cu->dwo_unit != NULL)
22869     {
22870       if (section_is_gnu)
22871         {
22872           section = &cu->dwo_unit->dwo_file->sections.macro;
22873           section_name = ".debug_macro.dwo";
22874         }
22875       else
22876         {
22877           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22878           section_name = ".debug_macinfo.dwo";
22879         }
22880     }
22881   else
22882     {
22883       if (section_is_gnu)
22884         {
22885           section = &dwarf2_per_objfile->macro;
22886           section_name = ".debug_macro";
22887         }
22888       else
22889         {
22890           section = &dwarf2_per_objfile->macinfo;
22891           section_name = ".debug_macinfo";
22892         }
22893     }
22894
22895   dwarf2_read_section (objfile, section);
22896   if (section->buffer == NULL)
22897     {
22898       complaint (&symfile_complaints, _("missing %s section"), section_name);
22899       return;
22900     }
22901   abfd = get_section_bfd_owner (section);
22902
22903   /* First pass: Find the name of the base filename.
22904      This filename is needed in order to process all macros whose definition
22905      (or undefinition) comes from the command line.  These macros are defined
22906      before the first DW_MACINFO_start_file entry, and yet still need to be
22907      associated to the base file.
22908
22909      To determine the base file name, we scan the macro definitions until we
22910      reach the first DW_MACINFO_start_file entry.  We then initialize
22911      CURRENT_FILE accordingly so that any macro definition found before the
22912      first DW_MACINFO_start_file can still be associated to the base file.  */
22913
22914   mac_ptr = section->buffer + offset;
22915   mac_end = section->buffer + section->size;
22916
22917   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22918                                       &offset_size, section_is_gnu);
22919   if (mac_ptr == NULL)
22920     {
22921       /* We already issued a complaint.  */
22922       return;
22923     }
22924
22925   do
22926     {
22927       /* Do we at least have room for a macinfo type byte?  */
22928       if (mac_ptr >= mac_end)
22929         {
22930           /* Complaint is printed during the second pass as GDB will probably
22931              stop the first pass earlier upon finding
22932              DW_MACINFO_start_file.  */
22933           break;
22934         }
22935
22936       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22937       mac_ptr++;
22938
22939       /* Note that we rely on the fact that the corresponding GNU and
22940          DWARF constants are the same.  */
22941       switch (macinfo_type)
22942         {
22943           /* A zero macinfo type indicates the end of the macro
22944              information.  */
22945         case 0:
22946           break;
22947
22948         case DW_MACRO_define:
22949         case DW_MACRO_undef:
22950           /* Only skip the data by MAC_PTR.  */
22951           {
22952             unsigned int bytes_read;
22953
22954             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22955             mac_ptr += bytes_read;
22956             read_direct_string (abfd, mac_ptr, &bytes_read);
22957             mac_ptr += bytes_read;
22958           }
22959           break;
22960
22961         case DW_MACRO_start_file:
22962           {
22963             unsigned int bytes_read;
22964             int line, file;
22965
22966             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22967             mac_ptr += bytes_read;
22968             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22969             mac_ptr += bytes_read;
22970
22971             current_file = macro_start_file (file, line, current_file, lh);
22972           }
22973           break;
22974
22975         case DW_MACRO_end_file:
22976           /* No data to skip by MAC_PTR.  */
22977           break;
22978
22979         case DW_MACRO_define_strp:
22980         case DW_MACRO_undef_strp:
22981         case DW_MACRO_define_sup:
22982         case DW_MACRO_undef_sup:
22983           {
22984             unsigned int bytes_read;
22985
22986             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22987             mac_ptr += bytes_read;
22988             mac_ptr += offset_size;
22989           }
22990           break;
22991
22992         case DW_MACRO_import:
22993         case DW_MACRO_import_sup:
22994           /* Note that, according to the spec, a transparent include
22995              chain cannot call DW_MACRO_start_file.  So, we can just
22996              skip this opcode.  */
22997           mac_ptr += offset_size;
22998           break;
22999
23000         case DW_MACINFO_vendor_ext:
23001           /* Only skip the data by MAC_PTR.  */
23002           if (!section_is_gnu)
23003             {
23004               unsigned int bytes_read;
23005
23006               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23007               mac_ptr += bytes_read;
23008               read_direct_string (abfd, mac_ptr, &bytes_read);
23009               mac_ptr += bytes_read;
23010             }
23011           /* FALLTHROUGH */
23012
23013         default:
23014           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23015                                          mac_ptr, mac_end, abfd, offset_size,
23016                                          section);
23017           if (mac_ptr == NULL)
23018             return;
23019           break;
23020         }
23021     } while (macinfo_type != 0 && current_file == NULL);
23022
23023   /* Second pass: Process all entries.
23024
23025      Use the AT_COMMAND_LINE flag to determine whether we are still processing
23026      command-line macro definitions/undefinitions.  This flag is unset when we
23027      reach the first DW_MACINFO_start_file entry.  */
23028
23029   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
23030                                            htab_eq_pointer,
23031                                            NULL, xcalloc, xfree));
23032   mac_ptr = section->buffer + offset;
23033   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
23034   *slot = (void *) mac_ptr;
23035   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
23036                             current_file, lh, section,
23037                             section_is_gnu, 0, offset_size,
23038                             include_hash.get ());
23039 }
23040
23041 /* Check if the attribute's form is a DW_FORM_block*
23042    if so return true else false.  */
23043
23044 static int
23045 attr_form_is_block (const struct attribute *attr)
23046 {
23047   return (attr == NULL ? 0 :
23048       attr->form == DW_FORM_block1
23049       || attr->form == DW_FORM_block2
23050       || attr->form == DW_FORM_block4
23051       || attr->form == DW_FORM_block
23052       || attr->form == DW_FORM_exprloc);
23053 }
23054
23055 /* Return non-zero if ATTR's value is a section offset --- classes
23056    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
23057    You may use DW_UNSND (attr) to retrieve such offsets.
23058
23059    Section 7.5.4, "Attribute Encodings", explains that no attribute
23060    may have a value that belongs to more than one of these classes; it
23061    would be ambiguous if we did, because we use the same forms for all
23062    of them.  */
23063
23064 static int
23065 attr_form_is_section_offset (const struct attribute *attr)
23066 {
23067   return (attr->form == DW_FORM_data4
23068           || attr->form == DW_FORM_data8
23069           || attr->form == DW_FORM_sec_offset);
23070 }
23071
23072 /* Return non-zero if ATTR's value falls in the 'constant' class, or
23073    zero otherwise.  When this function returns true, you can apply
23074    dwarf2_get_attr_constant_value to it.
23075
23076    However, note that for some attributes you must check
23077    attr_form_is_section_offset before using this test.  DW_FORM_data4
23078    and DW_FORM_data8 are members of both the constant class, and of
23079    the classes that contain offsets into other debug sections
23080    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
23081    that, if an attribute's can be either a constant or one of the
23082    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
23083    taken as section offsets, not constants.
23084
23085    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
23086    cannot handle that.  */
23087
23088 static int
23089 attr_form_is_constant (const struct attribute *attr)
23090 {
23091   switch (attr->form)
23092     {
23093     case DW_FORM_sdata:
23094     case DW_FORM_udata:
23095     case DW_FORM_data1:
23096     case DW_FORM_data2:
23097     case DW_FORM_data4:
23098     case DW_FORM_data8:
23099     case DW_FORM_implicit_const:
23100       return 1;
23101     default:
23102       return 0;
23103     }
23104 }
23105
23106
23107 /* DW_ADDR is always stored already as sect_offset; despite for the forms
23108    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
23109
23110 static int
23111 attr_form_is_ref (const struct attribute *attr)
23112 {
23113   switch (attr->form)
23114     {
23115     case DW_FORM_ref_addr:
23116     case DW_FORM_ref1:
23117     case DW_FORM_ref2:
23118     case DW_FORM_ref4:
23119     case DW_FORM_ref8:
23120     case DW_FORM_ref_udata:
23121     case DW_FORM_GNU_ref_alt:
23122       return 1;
23123     default:
23124       return 0;
23125     }
23126 }
23127
23128 /* Return the .debug_loc section to use for CU.
23129    For DWO files use .debug_loc.dwo.  */
23130
23131 static struct dwarf2_section_info *
23132 cu_debug_loc_section (struct dwarf2_cu *cu)
23133 {
23134   if (cu->dwo_unit)
23135     {
23136       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
23137       
23138       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
23139     }
23140   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
23141                                   : &dwarf2_per_objfile->loc);
23142 }
23143
23144 /* A helper function that fills in a dwarf2_loclist_baton.  */
23145
23146 static void
23147 fill_in_loclist_baton (struct dwarf2_cu *cu,
23148                        struct dwarf2_loclist_baton *baton,
23149                        const struct attribute *attr)
23150 {
23151   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23152
23153   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
23154
23155   baton->per_cu = cu->per_cu;
23156   gdb_assert (baton->per_cu);
23157   /* We don't know how long the location list is, but make sure we
23158      don't run off the edge of the section.  */
23159   baton->size = section->size - DW_UNSND (attr);
23160   baton->data = section->buffer + DW_UNSND (attr);
23161   baton->base_address = cu->base_address;
23162   baton->from_dwo = cu->dwo_unit != NULL;
23163 }
23164
23165 static void
23166 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
23167                              struct dwarf2_cu *cu, int is_block)
23168 {
23169   struct objfile *objfile = dwarf2_per_objfile->objfile;
23170   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23171
23172   if (attr_form_is_section_offset (attr)
23173       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
23174          the section.  If so, fall through to the complaint in the
23175          other branch.  */
23176       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
23177     {
23178       struct dwarf2_loclist_baton *baton;
23179
23180       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
23181
23182       fill_in_loclist_baton (cu, baton, attr);
23183
23184       if (cu->base_known == 0)
23185         complaint (&symfile_complaints,
23186                    _("Location list used without "
23187                      "specifying the CU base address."));
23188
23189       SYMBOL_ACLASS_INDEX (sym) = (is_block
23190                                    ? dwarf2_loclist_block_index
23191                                    : dwarf2_loclist_index);
23192       SYMBOL_LOCATION_BATON (sym) = baton;
23193     }
23194   else
23195     {
23196       struct dwarf2_locexpr_baton *baton;
23197
23198       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
23199       baton->per_cu = cu->per_cu;
23200       gdb_assert (baton->per_cu);
23201
23202       if (attr_form_is_block (attr))
23203         {
23204           /* Note that we're just copying the block's data pointer
23205              here, not the actual data.  We're still pointing into the
23206              info_buffer for SYM's objfile; right now we never release
23207              that buffer, but when we do clean up properly this may
23208              need to change.  */
23209           baton->size = DW_BLOCK (attr)->size;
23210           baton->data = DW_BLOCK (attr)->data;
23211         }
23212       else
23213         {
23214           dwarf2_invalid_attrib_class_complaint ("location description",
23215                                                  SYMBOL_NATURAL_NAME (sym));
23216           baton->size = 0;
23217         }
23218
23219       SYMBOL_ACLASS_INDEX (sym) = (is_block
23220                                    ? dwarf2_locexpr_block_index
23221                                    : dwarf2_locexpr_index);
23222       SYMBOL_LOCATION_BATON (sym) = baton;
23223     }
23224 }
23225
23226 /* Return the OBJFILE associated with the compilation unit CU.  If CU
23227    came from a separate debuginfo file, then the master objfile is
23228    returned.  */
23229
23230 struct objfile *
23231 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
23232 {
23233   struct objfile *objfile = per_cu->objfile;
23234
23235   /* Return the master objfile, so that we can report and look up the
23236      correct file containing this variable.  */
23237   if (objfile->separate_debug_objfile_backlink)
23238     objfile = objfile->separate_debug_objfile_backlink;
23239
23240   return objfile;
23241 }
23242
23243 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
23244    (CU_HEADERP is unused in such case) or prepare a temporary copy at
23245    CU_HEADERP first.  */
23246
23247 static const struct comp_unit_head *
23248 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
23249                        struct dwarf2_per_cu_data *per_cu)
23250 {
23251   const gdb_byte *info_ptr;
23252
23253   if (per_cu->cu)
23254     return &per_cu->cu->header;
23255
23256   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
23257
23258   memset (cu_headerp, 0, sizeof (*cu_headerp));
23259   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
23260                        rcuh_kind::COMPILE);
23261
23262   return cu_headerp;
23263 }
23264
23265 /* Return the address size given in the compilation unit header for CU.  */
23266
23267 int
23268 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
23269 {
23270   struct comp_unit_head cu_header_local;
23271   const struct comp_unit_head *cu_headerp;
23272
23273   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23274
23275   return cu_headerp->addr_size;
23276 }
23277
23278 /* Return the offset size given in the compilation unit header for CU.  */
23279
23280 int
23281 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
23282 {
23283   struct comp_unit_head cu_header_local;
23284   const struct comp_unit_head *cu_headerp;
23285
23286   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23287
23288   return cu_headerp->offset_size;
23289 }
23290
23291 /* See its dwarf2loc.h declaration.  */
23292
23293 int
23294 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
23295 {
23296   struct comp_unit_head cu_header_local;
23297   const struct comp_unit_head *cu_headerp;
23298
23299   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23300
23301   if (cu_headerp->version == 2)
23302     return cu_headerp->addr_size;
23303   else
23304     return cu_headerp->offset_size;
23305 }
23306
23307 /* Return the text offset of the CU.  The returned offset comes from
23308    this CU's objfile.  If this objfile came from a separate debuginfo
23309    file, then the offset may be different from the corresponding
23310    offset in the parent objfile.  */
23311
23312 CORE_ADDR
23313 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
23314 {
23315   struct objfile *objfile = per_cu->objfile;
23316
23317   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23318 }
23319
23320 /* Return DWARF version number of PER_CU.  */
23321
23322 short
23323 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
23324 {
23325   return per_cu->dwarf_version;
23326 }
23327
23328 /* Locate the .debug_info compilation unit from CU's objfile which contains
23329    the DIE at OFFSET.  Raises an error on failure.  */
23330
23331 static struct dwarf2_per_cu_data *
23332 dwarf2_find_containing_comp_unit (sect_offset sect_off,
23333                                   unsigned int offset_in_dwz,
23334                                   struct objfile *objfile)
23335 {
23336   struct dwarf2_per_cu_data *this_cu;
23337   int low, high;
23338   const sect_offset *cu_off;
23339
23340   low = 0;
23341   high = dwarf2_per_objfile->n_comp_units - 1;
23342   while (high > low)
23343     {
23344       struct dwarf2_per_cu_data *mid_cu;
23345       int mid = low + (high - low) / 2;
23346
23347       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
23348       cu_off = &mid_cu->sect_off;
23349       if (mid_cu->is_dwz > offset_in_dwz
23350           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
23351         high = mid;
23352       else
23353         low = mid + 1;
23354     }
23355   gdb_assert (low == high);
23356   this_cu = dwarf2_per_objfile->all_comp_units[low];
23357   cu_off = &this_cu->sect_off;
23358   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
23359     {
23360       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
23361         error (_("Dwarf Error: could not find partial DIE containing "
23362                "offset 0x%x [in module %s]"),
23363                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
23364
23365       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
23366                   <= sect_off);
23367       return dwarf2_per_objfile->all_comp_units[low-1];
23368     }
23369   else
23370     {
23371       this_cu = dwarf2_per_objfile->all_comp_units[low];
23372       if (low == dwarf2_per_objfile->n_comp_units - 1
23373           && sect_off >= this_cu->sect_off + this_cu->length)
23374         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
23375       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
23376       return this_cu;
23377     }
23378 }
23379
23380 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
23381
23382 static void
23383 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
23384 {
23385   memset (cu, 0, sizeof (*cu));
23386   per_cu->cu = cu;
23387   cu->per_cu = per_cu;
23388   cu->objfile = per_cu->objfile;
23389   obstack_init (&cu->comp_unit_obstack);
23390 }
23391
23392 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
23393
23394 static void
23395 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
23396                        enum language pretend_language)
23397 {
23398   struct attribute *attr;
23399
23400   /* Set the language we're debugging.  */
23401   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
23402   if (attr)
23403     set_cu_language (DW_UNSND (attr), cu);
23404   else
23405     {
23406       cu->language = pretend_language;
23407       cu->language_defn = language_def (cu->language);
23408     }
23409
23410   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
23411 }
23412
23413 /* Release one cached compilation unit, CU.  We unlink it from the tree
23414    of compilation units, but we don't remove it from the read_in_chain;
23415    the caller is responsible for that.
23416    NOTE: DATA is a void * because this function is also used as a
23417    cleanup routine.  */
23418
23419 static void
23420 free_heap_comp_unit (void *data)
23421 {
23422   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23423
23424   gdb_assert (cu->per_cu != NULL);
23425   cu->per_cu->cu = NULL;
23426   cu->per_cu = NULL;
23427
23428   obstack_free (&cu->comp_unit_obstack, NULL);
23429
23430   xfree (cu);
23431 }
23432
23433 /* This cleanup function is passed the address of a dwarf2_cu on the stack
23434    when we're finished with it.  We can't free the pointer itself, but be
23435    sure to unlink it from the cache.  Also release any associated storage.  */
23436
23437 static void
23438 free_stack_comp_unit (void *data)
23439 {
23440   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23441
23442   gdb_assert (cu->per_cu != NULL);
23443   cu->per_cu->cu = NULL;
23444   cu->per_cu = NULL;
23445
23446   obstack_free (&cu->comp_unit_obstack, NULL);
23447   cu->partial_dies = NULL;
23448 }
23449
23450 /* Free all cached compilation units.  */
23451
23452 static void
23453 free_cached_comp_units (void *data)
23454 {
23455   dwarf2_per_objfile->free_cached_comp_units ();
23456 }
23457
23458 /* Increase the age counter on each cached compilation unit, and free
23459    any that are too old.  */
23460
23461 static void
23462 age_cached_comp_units (void)
23463 {
23464   struct dwarf2_per_cu_data *per_cu, **last_chain;
23465
23466   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
23467   per_cu = dwarf2_per_objfile->read_in_chain;
23468   while (per_cu != NULL)
23469     {
23470       per_cu->cu->last_used ++;
23471       if (per_cu->cu->last_used <= dwarf_max_cache_age)
23472         dwarf2_mark (per_cu->cu);
23473       per_cu = per_cu->cu->read_in_chain;
23474     }
23475
23476   per_cu = dwarf2_per_objfile->read_in_chain;
23477   last_chain = &dwarf2_per_objfile->read_in_chain;
23478   while (per_cu != NULL)
23479     {
23480       struct dwarf2_per_cu_data *next_cu;
23481
23482       next_cu = per_cu->cu->read_in_chain;
23483
23484       if (!per_cu->cu->mark)
23485         {
23486           free_heap_comp_unit (per_cu->cu);
23487           *last_chain = next_cu;
23488         }
23489       else
23490         last_chain = &per_cu->cu->read_in_chain;
23491
23492       per_cu = next_cu;
23493     }
23494 }
23495
23496 /* Remove a single compilation unit from the cache.  */
23497
23498 static void
23499 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
23500 {
23501   struct dwarf2_per_cu_data *per_cu, **last_chain;
23502
23503   per_cu = dwarf2_per_objfile->read_in_chain;
23504   last_chain = &dwarf2_per_objfile->read_in_chain;
23505   while (per_cu != NULL)
23506     {
23507       struct dwarf2_per_cu_data *next_cu;
23508
23509       next_cu = per_cu->cu->read_in_chain;
23510
23511       if (per_cu == target_per_cu)
23512         {
23513           free_heap_comp_unit (per_cu->cu);
23514           per_cu->cu = NULL;
23515           *last_chain = next_cu;
23516           break;
23517         }
23518       else
23519         last_chain = &per_cu->cu->read_in_chain;
23520
23521       per_cu = next_cu;
23522     }
23523 }
23524
23525 /* Release all extra memory associated with OBJFILE.  */
23526
23527 void
23528 dwarf2_free_objfile (struct objfile *objfile)
23529 {
23530   dwarf2_per_objfile
23531     = (struct dwarf2_per_objfile *) objfile_data (objfile,
23532                                                   dwarf2_objfile_data_key);
23533
23534   if (dwarf2_per_objfile == NULL)
23535     return;
23536
23537   dwarf2_per_objfile->~dwarf2_per_objfile ();
23538 }
23539
23540 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23541    We store these in a hash table separate from the DIEs, and preserve them
23542    when the DIEs are flushed out of cache.
23543
23544    The CU "per_cu" pointer is needed because offset alone is not enough to
23545    uniquely identify the type.  A file may have multiple .debug_types sections,
23546    or the type may come from a DWO file.  Furthermore, while it's more logical
23547    to use per_cu->section+offset, with Fission the section with the data is in
23548    the DWO file but we don't know that section at the point we need it.
23549    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23550    because we can enter the lookup routine, get_die_type_at_offset, from
23551    outside this file, and thus won't necessarily have PER_CU->cu.
23552    Fortunately, PER_CU is stable for the life of the objfile.  */
23553
23554 struct dwarf2_per_cu_offset_and_type
23555 {
23556   const struct dwarf2_per_cu_data *per_cu;
23557   sect_offset sect_off;
23558   struct type *type;
23559 };
23560
23561 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23562
23563 static hashval_t
23564 per_cu_offset_and_type_hash (const void *item)
23565 {
23566   const struct dwarf2_per_cu_offset_and_type *ofs
23567     = (const struct dwarf2_per_cu_offset_and_type *) item;
23568
23569   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23570 }
23571
23572 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23573
23574 static int
23575 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23576 {
23577   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23578     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23579   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23580     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23581
23582   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23583           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23584 }
23585
23586 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23587    table if necessary.  For convenience, return TYPE.
23588
23589    The DIEs reading must have careful ordering to:
23590     * Not cause infite loops trying to read in DIEs as a prerequisite for
23591       reading current DIE.
23592     * Not trying to dereference contents of still incompletely read in types
23593       while reading in other DIEs.
23594     * Enable referencing still incompletely read in types just by a pointer to
23595       the type without accessing its fields.
23596
23597    Therefore caller should follow these rules:
23598      * Try to fetch any prerequisite types we may need to build this DIE type
23599        before building the type and calling set_die_type.
23600      * After building type call set_die_type for current DIE as soon as
23601        possible before fetching more types to complete the current type.
23602      * Make the type as complete as possible before fetching more types.  */
23603
23604 static struct type *
23605 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23606 {
23607   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23608   struct objfile *objfile = cu->objfile;
23609   struct attribute *attr;
23610   struct dynamic_prop prop;
23611
23612   /* For Ada types, make sure that the gnat-specific data is always
23613      initialized (if not already set).  There are a few types where
23614      we should not be doing so, because the type-specific area is
23615      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23616      where the type-specific area is used to store the floatformat).
23617      But this is not a problem, because the gnat-specific information
23618      is actually not needed for these types.  */
23619   if (need_gnat_info (cu)
23620       && TYPE_CODE (type) != TYPE_CODE_FUNC
23621       && TYPE_CODE (type) != TYPE_CODE_FLT
23622       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23623       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23624       && TYPE_CODE (type) != TYPE_CODE_METHOD
23625       && !HAVE_GNAT_AUX_INFO (type))
23626     INIT_GNAT_SPECIFIC (type);
23627
23628   /* Read DW_AT_allocated and set in type.  */
23629   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23630   if (attr_form_is_block (attr))
23631     {
23632       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23633         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23634     }
23635   else if (attr != NULL)
23636     {
23637       complaint (&symfile_complaints,
23638                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23639                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23640                  to_underlying (die->sect_off));
23641     }
23642
23643   /* Read DW_AT_associated and set in type.  */
23644   attr = dwarf2_attr (die, DW_AT_associated, cu);
23645   if (attr_form_is_block (attr))
23646     {
23647       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23648         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23649     }
23650   else if (attr != NULL)
23651     {
23652       complaint (&symfile_complaints,
23653                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23654                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23655                  to_underlying (die->sect_off));
23656     }
23657
23658   /* Read DW_AT_data_location and set in type.  */
23659   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23660   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23661     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23662
23663   if (dwarf2_per_objfile->die_type_hash == NULL)
23664     {
23665       dwarf2_per_objfile->die_type_hash =
23666         htab_create_alloc_ex (127,
23667                               per_cu_offset_and_type_hash,
23668                               per_cu_offset_and_type_eq,
23669                               NULL,
23670                               &objfile->objfile_obstack,
23671                               hashtab_obstack_allocate,
23672                               dummy_obstack_deallocate);
23673     }
23674
23675   ofs.per_cu = cu->per_cu;
23676   ofs.sect_off = die->sect_off;
23677   ofs.type = type;
23678   slot = (struct dwarf2_per_cu_offset_and_type **)
23679     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23680   if (*slot)
23681     complaint (&symfile_complaints,
23682                _("A problem internal to GDB: DIE 0x%x has type already set"),
23683                to_underlying (die->sect_off));
23684   *slot = XOBNEW (&objfile->objfile_obstack,
23685                   struct dwarf2_per_cu_offset_and_type);
23686   **slot = ofs;
23687   return type;
23688 }
23689
23690 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23691    or return NULL if the die does not have a saved type.  */
23692
23693 static struct type *
23694 get_die_type_at_offset (sect_offset sect_off,
23695                         struct dwarf2_per_cu_data *per_cu)
23696 {
23697   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23698
23699   if (dwarf2_per_objfile->die_type_hash == NULL)
23700     return NULL;
23701
23702   ofs.per_cu = per_cu;
23703   ofs.sect_off = sect_off;
23704   slot = ((struct dwarf2_per_cu_offset_and_type *)
23705           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23706   if (slot)
23707     return slot->type;
23708   else
23709     return NULL;
23710 }
23711
23712 /* Look up the type for DIE in CU in die_type_hash,
23713    or return NULL if DIE does not have a saved type.  */
23714
23715 static struct type *
23716 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23717 {
23718   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23719 }
23720
23721 /* Add a dependence relationship from CU to REF_PER_CU.  */
23722
23723 static void
23724 dwarf2_add_dependence (struct dwarf2_cu *cu,
23725                        struct dwarf2_per_cu_data *ref_per_cu)
23726 {
23727   void **slot;
23728
23729   if (cu->dependencies == NULL)
23730     cu->dependencies
23731       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23732                               NULL, &cu->comp_unit_obstack,
23733                               hashtab_obstack_allocate,
23734                               dummy_obstack_deallocate);
23735
23736   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23737   if (*slot == NULL)
23738     *slot = ref_per_cu;
23739 }
23740
23741 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23742    Set the mark field in every compilation unit in the
23743    cache that we must keep because we are keeping CU.  */
23744
23745 static int
23746 dwarf2_mark_helper (void **slot, void *data)
23747 {
23748   struct dwarf2_per_cu_data *per_cu;
23749
23750   per_cu = (struct dwarf2_per_cu_data *) *slot;
23751
23752   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23753      reading of the chain.  As such dependencies remain valid it is not much
23754      useful to track and undo them during QUIT cleanups.  */
23755   if (per_cu->cu == NULL)
23756     return 1;
23757
23758   if (per_cu->cu->mark)
23759     return 1;
23760   per_cu->cu->mark = 1;
23761
23762   if (per_cu->cu->dependencies != NULL)
23763     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23764
23765   return 1;
23766 }
23767
23768 /* Set the mark field in CU and in every other compilation unit in the
23769    cache that we must keep because we are keeping CU.  */
23770
23771 static void
23772 dwarf2_mark (struct dwarf2_cu *cu)
23773 {
23774   if (cu->mark)
23775     return;
23776   cu->mark = 1;
23777   if (cu->dependencies != NULL)
23778     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23779 }
23780
23781 static void
23782 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23783 {
23784   while (per_cu)
23785     {
23786       per_cu->cu->mark = 0;
23787       per_cu = per_cu->cu->read_in_chain;
23788     }
23789 }
23790
23791 /* Trivial hash function for partial_die_info: the hash value of a DIE
23792    is its offset in .debug_info for this objfile.  */
23793
23794 static hashval_t
23795 partial_die_hash (const void *item)
23796 {
23797   const struct partial_die_info *part_die
23798     = (const struct partial_die_info *) item;
23799
23800   return to_underlying (part_die->sect_off);
23801 }
23802
23803 /* Trivial comparison function for partial_die_info structures: two DIEs
23804    are equal if they have the same offset.  */
23805
23806 static int
23807 partial_die_eq (const void *item_lhs, const void *item_rhs)
23808 {
23809   const struct partial_die_info *part_die_lhs
23810     = (const struct partial_die_info *) item_lhs;
23811   const struct partial_die_info *part_die_rhs
23812     = (const struct partial_die_info *) item_rhs;
23813
23814   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23815 }
23816
23817 static struct cmd_list_element *set_dwarf_cmdlist;
23818 static struct cmd_list_element *show_dwarf_cmdlist;
23819
23820 static void
23821 set_dwarf_cmd (const char *args, int from_tty)
23822 {
23823   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23824              gdb_stdout);
23825 }
23826
23827 static void
23828 show_dwarf_cmd (const char *args, int from_tty)
23829 {
23830   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23831 }
23832
23833 /* Free data associated with OBJFILE, if necessary.  */
23834
23835 static void
23836 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23837 {
23838   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23839   int ix;
23840
23841   /* Make sure we don't accidentally use dwarf2_per_objfile while
23842      cleaning up.  */
23843   dwarf2_per_objfile = NULL;
23844
23845   for (ix = 0; ix < data->n_comp_units; ++ix)
23846    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23847
23848   for (ix = 0; ix < data->n_type_units; ++ix)
23849     VEC_free (dwarf2_per_cu_ptr,
23850               data->all_type_units[ix]->per_cu.imported_symtabs);
23851   xfree (data->all_type_units);
23852
23853   VEC_free (dwarf2_section_info_def, data->types);
23854
23855   if (data->dwo_files)
23856     free_dwo_files (data->dwo_files, objfile);
23857   if (data->dwp_file)
23858     gdb_bfd_unref (data->dwp_file->dbfd);
23859
23860   if (data->dwz_file && data->dwz_file->dwz_bfd)
23861     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23862
23863   if (data->index_table != NULL)
23864     data->index_table->~mapped_index ();
23865 }
23866
23867 \f
23868 /* The "save gdb-index" command.  */
23869
23870 /* In-memory buffer to prepare data to be written later to a file.  */
23871 class data_buf
23872 {
23873 public:
23874   /* Copy DATA to the end of the buffer.  */
23875   template<typename T>
23876   void append_data (const T &data)
23877   {
23878     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23879                reinterpret_cast<const gdb_byte *> (&data + 1),
23880                grow (sizeof (data)));
23881   }
23882
23883   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23884      terminating zero is appended too.  */
23885   void append_cstr0 (const char *cstr)
23886   {
23887     const size_t size = strlen (cstr) + 1;
23888     std::copy (cstr, cstr + size, grow (size));
23889   }
23890
23891   /* Accept a host-format integer in VAL and append it to the buffer
23892      as a target-format integer which is LEN bytes long.  */
23893   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23894   {
23895     ::store_unsigned_integer (grow (len), len, byte_order, val);
23896   }
23897
23898   /* Return the size of the buffer.  */
23899   size_t size () const
23900   {
23901     return m_vec.size ();
23902   }
23903
23904   /* Write the buffer to FILE.  */
23905   void file_write (FILE *file) const
23906   {
23907     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23908       error (_("couldn't write data to file"));
23909   }
23910
23911 private:
23912   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23913      the start of the new block.  */
23914   gdb_byte *grow (size_t size)
23915   {
23916     m_vec.resize (m_vec.size () + size);
23917     return &*m_vec.end () - size;
23918   }
23919
23920   gdb::byte_vector m_vec;
23921 };
23922
23923 /* An entry in the symbol table.  */
23924 struct symtab_index_entry
23925 {
23926   /* The name of the symbol.  */
23927   const char *name;
23928   /* The offset of the name in the constant pool.  */
23929   offset_type index_offset;
23930   /* A sorted vector of the indices of all the CUs that hold an object
23931      of this name.  */
23932   std::vector<offset_type> cu_indices;
23933 };
23934
23935 /* The symbol table.  This is a power-of-2-sized hash table.  */
23936 struct mapped_symtab
23937 {
23938   mapped_symtab ()
23939   {
23940     data.resize (1024);
23941   }
23942
23943   offset_type n_elements = 0;
23944   std::vector<symtab_index_entry> data;
23945 };
23946
23947 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23948    the slot.
23949    
23950    Function is used only during write_hash_table so no index format backward
23951    compatibility is needed.  */
23952
23953 static symtab_index_entry &
23954 find_slot (struct mapped_symtab *symtab, const char *name)
23955 {
23956   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23957
23958   index = hash & (symtab->data.size () - 1);
23959   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23960
23961   for (;;)
23962     {
23963       if (symtab->data[index].name == NULL
23964           || strcmp (name, symtab->data[index].name) == 0)
23965         return symtab->data[index];
23966       index = (index + step) & (symtab->data.size () - 1);
23967     }
23968 }
23969
23970 /* Expand SYMTAB's hash table.  */
23971
23972 static void
23973 hash_expand (struct mapped_symtab *symtab)
23974 {
23975   auto old_entries = std::move (symtab->data);
23976
23977   symtab->data.clear ();
23978   symtab->data.resize (old_entries.size () * 2);
23979
23980   for (auto &it : old_entries)
23981     if (it.name != NULL)
23982       {
23983         auto &ref = find_slot (symtab, it.name);
23984         ref = std::move (it);
23985       }
23986 }
23987
23988 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23989    CU_INDEX is the index of the CU in which the symbol appears.
23990    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23991
23992 static void
23993 add_index_entry (struct mapped_symtab *symtab, const char *name,
23994                  int is_static, gdb_index_symbol_kind kind,
23995                  offset_type cu_index)
23996 {
23997   offset_type cu_index_and_attrs;
23998
23999   ++symtab->n_elements;
24000   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
24001     hash_expand (symtab);
24002
24003   symtab_index_entry &slot = find_slot (symtab, name);
24004   if (slot.name == NULL)
24005     {
24006       slot.name = name;
24007       /* index_offset is set later.  */
24008     }
24009
24010   cu_index_and_attrs = 0;
24011   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
24012   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
24013   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
24014
24015   /* We don't want to record an index value twice as we want to avoid the
24016      duplication.
24017      We process all global symbols and then all static symbols
24018      (which would allow us to avoid the duplication by only having to check
24019      the last entry pushed), but a symbol could have multiple kinds in one CU.
24020      To keep things simple we don't worry about the duplication here and
24021      sort and uniqufy the list after we've processed all symbols.  */
24022   slot.cu_indices.push_back (cu_index_and_attrs);
24023 }
24024
24025 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
24026
24027 static void
24028 uniquify_cu_indices (struct mapped_symtab *symtab)
24029 {
24030   for (auto &entry : symtab->data)
24031     {
24032       if (entry.name != NULL && !entry.cu_indices.empty ())
24033         {
24034           auto &cu_indices = entry.cu_indices;
24035           std::sort (cu_indices.begin (), cu_indices.end ());
24036           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
24037           cu_indices.erase (from, cu_indices.end ());
24038         }
24039     }
24040 }
24041
24042 /* A form of 'const char *' suitable for container keys.  Only the
24043    pointer is stored.  The strings themselves are compared, not the
24044    pointers.  */
24045 class c_str_view
24046 {
24047 public:
24048   c_str_view (const char *cstr)
24049     : m_cstr (cstr)
24050   {}
24051
24052   bool operator== (const c_str_view &other) const
24053   {
24054     return strcmp (m_cstr, other.m_cstr) == 0;
24055   }
24056
24057 private:
24058   friend class c_str_view_hasher;
24059   const char *const m_cstr;
24060 };
24061
24062 /* A std::unordered_map::hasher for c_str_view that uses the right
24063    hash function for strings in a mapped index.  */
24064 class c_str_view_hasher
24065 {
24066 public:
24067   size_t operator () (const c_str_view &x) const
24068   {
24069     return mapped_index_string_hash (INT_MAX, x.m_cstr);
24070   }
24071 };
24072
24073 /* A std::unordered_map::hasher for std::vector<>.  */
24074 template<typename T>
24075 class vector_hasher
24076 {
24077 public:
24078   size_t operator () (const std::vector<T> &key) const
24079   {
24080     return iterative_hash (key.data (),
24081                            sizeof (key.front ()) * key.size (), 0);
24082   }
24083 };
24084
24085 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
24086    constant pool entries going into the data buffer CPOOL.  */
24087
24088 static void
24089 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
24090 {
24091   {
24092     /* Elements are sorted vectors of the indices of all the CUs that
24093        hold an object of this name.  */
24094     std::unordered_map<std::vector<offset_type>, offset_type,
24095                        vector_hasher<offset_type>>
24096       symbol_hash_table;
24097
24098     /* We add all the index vectors to the constant pool first, to
24099        ensure alignment is ok.  */
24100     for (symtab_index_entry &entry : symtab->data)
24101       {
24102         if (entry.name == NULL)
24103           continue;
24104         gdb_assert (entry.index_offset == 0);
24105
24106         /* Finding before inserting is faster than always trying to
24107            insert, because inserting always allocates a node, does the
24108            lookup, and then destroys the new node if another node
24109            already had the same key.  C++17 try_emplace will avoid
24110            this.  */
24111         const auto found
24112           = symbol_hash_table.find (entry.cu_indices);
24113         if (found != symbol_hash_table.end ())
24114           {
24115             entry.index_offset = found->second;
24116             continue;
24117           }
24118
24119         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
24120         entry.index_offset = cpool.size ();
24121         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
24122         for (const auto index : entry.cu_indices)
24123           cpool.append_data (MAYBE_SWAP (index));
24124       }
24125   }
24126
24127   /* Now write out the hash table.  */
24128   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
24129   for (const auto &entry : symtab->data)
24130     {
24131       offset_type str_off, vec_off;
24132
24133       if (entry.name != NULL)
24134         {
24135           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
24136           if (insertpair.second)
24137             cpool.append_cstr0 (entry.name);
24138           str_off = insertpair.first->second;
24139           vec_off = entry.index_offset;
24140         }
24141       else
24142         {
24143           /* While 0 is a valid constant pool index, it is not valid
24144              to have 0 for both offsets.  */
24145           str_off = 0;
24146           vec_off = 0;
24147         }
24148
24149       output.append_data (MAYBE_SWAP (str_off));
24150       output.append_data (MAYBE_SWAP (vec_off));
24151     }
24152 }
24153
24154 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
24155
24156 /* Helper struct for building the address table.  */
24157 struct addrmap_index_data
24158 {
24159   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
24160     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
24161   {}
24162
24163   struct objfile *objfile;
24164   data_buf &addr_vec;
24165   psym_index_map &cu_index_htab;
24166
24167   /* Non-zero if the previous_* fields are valid.
24168      We can't write an entry until we see the next entry (since it is only then
24169      that we know the end of the entry).  */
24170   int previous_valid;
24171   /* Index of the CU in the table of all CUs in the index file.  */
24172   unsigned int previous_cu_index;
24173   /* Start address of the CU.  */
24174   CORE_ADDR previous_cu_start;
24175 };
24176
24177 /* Write an address entry to ADDR_VEC.  */
24178
24179 static void
24180 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
24181                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
24182 {
24183   CORE_ADDR baseaddr;
24184
24185   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24186
24187   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
24188   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
24189   addr_vec.append_data (MAYBE_SWAP (cu_index));
24190 }
24191
24192 /* Worker function for traversing an addrmap to build the address table.  */
24193
24194 static int
24195 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
24196 {
24197   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
24198   struct partial_symtab *pst = (struct partial_symtab *) obj;
24199
24200   if (data->previous_valid)
24201     add_address_entry (data->objfile, data->addr_vec,
24202                        data->previous_cu_start, start_addr,
24203                        data->previous_cu_index);
24204
24205   data->previous_cu_start = start_addr;
24206   if (pst != NULL)
24207     {
24208       const auto it = data->cu_index_htab.find (pst);
24209       gdb_assert (it != data->cu_index_htab.cend ());
24210       data->previous_cu_index = it->second;
24211       data->previous_valid = 1;
24212     }
24213   else
24214     data->previous_valid = 0;
24215
24216   return 0;
24217 }
24218
24219 /* Write OBJFILE's address map to ADDR_VEC.
24220    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
24221    in the index file.  */
24222
24223 static void
24224 write_address_map (struct objfile *objfile, data_buf &addr_vec,
24225                    psym_index_map &cu_index_htab)
24226 {
24227   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
24228
24229   /* When writing the address table, we have to cope with the fact that
24230      the addrmap iterator only provides the start of a region; we have to
24231      wait until the next invocation to get the start of the next region.  */
24232
24233   addrmap_index_data.objfile = objfile;
24234   addrmap_index_data.previous_valid = 0;
24235
24236   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
24237                    &addrmap_index_data);
24238
24239   /* It's highly unlikely the last entry (end address = 0xff...ff)
24240      is valid, but we should still handle it.
24241      The end address is recorded as the start of the next region, but that
24242      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
24243      anyway.  */
24244   if (addrmap_index_data.previous_valid)
24245     add_address_entry (objfile, addr_vec,
24246                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
24247                        addrmap_index_data.previous_cu_index);
24248 }
24249
24250 /* Return the symbol kind of PSYM.  */
24251
24252 static gdb_index_symbol_kind
24253 symbol_kind (struct partial_symbol *psym)
24254 {
24255   domain_enum domain = PSYMBOL_DOMAIN (psym);
24256   enum address_class aclass = PSYMBOL_CLASS (psym);
24257
24258   switch (domain)
24259     {
24260     case VAR_DOMAIN:
24261       switch (aclass)
24262         {
24263         case LOC_BLOCK:
24264           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
24265         case LOC_TYPEDEF:
24266           return GDB_INDEX_SYMBOL_KIND_TYPE;
24267         case LOC_COMPUTED:
24268         case LOC_CONST_BYTES:
24269         case LOC_OPTIMIZED_OUT:
24270         case LOC_STATIC:
24271           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24272         case LOC_CONST:
24273           /* Note: It's currently impossible to recognize psyms as enum values
24274              short of reading the type info.  For now punt.  */
24275           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24276         default:
24277           /* There are other LOC_FOO values that one might want to classify
24278              as variables, but dwarf2read.c doesn't currently use them.  */
24279           return GDB_INDEX_SYMBOL_KIND_OTHER;
24280         }
24281     case STRUCT_DOMAIN:
24282       return GDB_INDEX_SYMBOL_KIND_TYPE;
24283     default:
24284       return GDB_INDEX_SYMBOL_KIND_OTHER;
24285     }
24286 }
24287
24288 /* Add a list of partial symbols to SYMTAB.  */
24289
24290 static void
24291 write_psymbols (struct mapped_symtab *symtab,
24292                 std::unordered_set<partial_symbol *> &psyms_seen,
24293                 struct partial_symbol **psymp,
24294                 int count,
24295                 offset_type cu_index,
24296                 int is_static)
24297 {
24298   for (; count-- > 0; ++psymp)
24299     {
24300       struct partial_symbol *psym = *psymp;
24301
24302       if (SYMBOL_LANGUAGE (psym) == language_ada)
24303         error (_("Ada is not currently supported by the index"));
24304
24305       /* Only add a given psymbol once.  */
24306       if (psyms_seen.insert (psym).second)
24307         {
24308           gdb_index_symbol_kind kind = symbol_kind (psym);
24309
24310           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
24311                            is_static, kind, cu_index);
24312         }
24313     }
24314 }
24315
24316 /* A helper struct used when iterating over debug_types.  */
24317 struct signatured_type_index_data
24318 {
24319   signatured_type_index_data (data_buf &types_list_,
24320                               std::unordered_set<partial_symbol *> &psyms_seen_)
24321     : types_list (types_list_), psyms_seen (psyms_seen_)
24322   {}
24323
24324   struct objfile *objfile;
24325   struct mapped_symtab *symtab;
24326   data_buf &types_list;
24327   std::unordered_set<partial_symbol *> &psyms_seen;
24328   int cu_index;
24329 };
24330
24331 /* A helper function that writes a single signatured_type to an
24332    obstack.  */
24333
24334 static int
24335 write_one_signatured_type (void **slot, void *d)
24336 {
24337   struct signatured_type_index_data *info
24338     = (struct signatured_type_index_data *) d;
24339   struct signatured_type *entry = (struct signatured_type *) *slot;
24340   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
24341
24342   write_psymbols (info->symtab,
24343                   info->psyms_seen,
24344                   &info->objfile->global_psymbols[psymtab->globals_offset],
24345                   psymtab->n_global_syms, info->cu_index,
24346                   0);
24347   write_psymbols (info->symtab,
24348                   info->psyms_seen,
24349                   &info->objfile->static_psymbols[psymtab->statics_offset],
24350                   psymtab->n_static_syms, info->cu_index,
24351                   1);
24352
24353   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24354                                 to_underlying (entry->per_cu.sect_off));
24355   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24356                                 to_underlying (entry->type_offset_in_tu));
24357   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
24358
24359   ++info->cu_index;
24360
24361   return 1;
24362 }
24363
24364 /* Recurse into all "included" dependencies and count their symbols as
24365    if they appeared in this psymtab.  */
24366
24367 static void
24368 recursively_count_psymbols (struct partial_symtab *psymtab,
24369                             size_t &psyms_seen)
24370 {
24371   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
24372     if (psymtab->dependencies[i]->user != NULL)
24373       recursively_count_psymbols (psymtab->dependencies[i],
24374                                   psyms_seen);
24375
24376   psyms_seen += psymtab->n_global_syms;
24377   psyms_seen += psymtab->n_static_syms;
24378 }
24379
24380 /* Recurse into all "included" dependencies and write their symbols as
24381    if they appeared in this psymtab.  */
24382
24383 static void
24384 recursively_write_psymbols (struct objfile *objfile,
24385                             struct partial_symtab *psymtab,
24386                             struct mapped_symtab *symtab,
24387                             std::unordered_set<partial_symbol *> &psyms_seen,
24388                             offset_type cu_index)
24389 {
24390   int i;
24391
24392   for (i = 0; i < psymtab->number_of_dependencies; ++i)
24393     if (psymtab->dependencies[i]->user != NULL)
24394       recursively_write_psymbols (objfile, psymtab->dependencies[i],
24395                                   symtab, psyms_seen, cu_index);
24396
24397   write_psymbols (symtab,
24398                   psyms_seen,
24399                   &objfile->global_psymbols[psymtab->globals_offset],
24400                   psymtab->n_global_syms, cu_index,
24401                   0);
24402   write_psymbols (symtab,
24403                   psyms_seen,
24404                   &objfile->static_psymbols[psymtab->statics_offset],
24405                   psymtab->n_static_syms, cu_index,
24406                   1);
24407 }
24408
24409 /* Create an index file for OBJFILE in the directory DIR.  */
24410
24411 static void
24412 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
24413 {
24414   if (dwarf2_per_objfile->using_index)
24415     error (_("Cannot use an index to create the index"));
24416
24417   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
24418     error (_("Cannot make an index when the file has multiple .debug_types sections"));
24419
24420   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
24421     return;
24422
24423   struct stat st;
24424   if (stat (objfile_name (objfile), &st) < 0)
24425     perror_with_name (objfile_name (objfile));
24426
24427   std::string filename (std::string (dir) + SLASH_STRING
24428                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
24429
24430   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
24431   if (!out_file)
24432     error (_("Can't open `%s' for writing"), filename.c_str ());
24433
24434   /* Order matters here; we want FILE to be closed before FILENAME is
24435      unlinked, because on MS-Windows one cannot delete a file that is
24436      still open.  (Don't call anything here that might throw until
24437      file_closer is created.)  */
24438   gdb::unlinker unlink_file (filename.c_str ());
24439   gdb_file_up close_out_file (out_file);
24440
24441   mapped_symtab symtab;
24442   data_buf cu_list;
24443
24444   /* While we're scanning CU's create a table that maps a psymtab pointer
24445      (which is what addrmap records) to its index (which is what is recorded
24446      in the index file).  This will later be needed to write the address
24447      table.  */
24448   psym_index_map cu_index_htab;
24449   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
24450
24451   /* The CU list is already sorted, so we don't need to do additional
24452      work here.  Also, the debug_types entries do not appear in
24453      all_comp_units, but only in their own hash table.  */
24454
24455   /* The psyms_seen set is potentially going to be largish (~40k
24456      elements when indexing a -g3 build of GDB itself).  Estimate the
24457      number of elements in order to avoid too many rehashes, which
24458      require rebuilding buckets and thus many trips to
24459      malloc/free.  */
24460   size_t psyms_count = 0;
24461   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24462     {
24463       struct dwarf2_per_cu_data *per_cu
24464         = dwarf2_per_objfile->all_comp_units[i];
24465       struct partial_symtab *psymtab = per_cu->v.psymtab;
24466
24467       if (psymtab != NULL && psymtab->user == NULL)
24468         recursively_count_psymbols (psymtab, psyms_count);
24469     }
24470   /* Generating an index for gdb itself shows a ratio of
24471      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
24472   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
24473   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24474     {
24475       struct dwarf2_per_cu_data *per_cu
24476         = dwarf2_per_objfile->all_comp_units[i];
24477       struct partial_symtab *psymtab = per_cu->v.psymtab;
24478
24479       /* CU of a shared file from 'dwz -m' may be unused by this main file.
24480          It may be referenced from a local scope but in such case it does not
24481          need to be present in .gdb_index.  */
24482       if (psymtab == NULL)
24483         continue;
24484
24485       if (psymtab->user == NULL)
24486         recursively_write_psymbols (objfile, psymtab, &symtab,
24487                                     psyms_seen, i);
24488
24489       const auto insertpair = cu_index_htab.emplace (psymtab, i);
24490       gdb_assert (insertpair.second);
24491
24492       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
24493                            to_underlying (per_cu->sect_off));
24494       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
24495     }
24496
24497   /* Dump the address map.  */
24498   data_buf addr_vec;
24499   write_address_map (objfile, addr_vec, cu_index_htab);
24500
24501   /* Write out the .debug_type entries, if any.  */
24502   data_buf types_cu_list;
24503   if (dwarf2_per_objfile->signatured_types)
24504     {
24505       signatured_type_index_data sig_data (types_cu_list,
24506                                            psyms_seen);
24507
24508       sig_data.objfile = objfile;
24509       sig_data.symtab = &symtab;
24510       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
24511       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
24512                               write_one_signatured_type, &sig_data);
24513     }
24514
24515   /* Now that we've processed all symbols we can shrink their cu_indices
24516      lists.  */
24517   uniquify_cu_indices (&symtab);
24518
24519   data_buf symtab_vec, constant_pool;
24520   write_hash_table (&symtab, symtab_vec, constant_pool);
24521
24522   data_buf contents;
24523   const offset_type size_of_contents = 6 * sizeof (offset_type);
24524   offset_type total_len = size_of_contents;
24525
24526   /* The version number.  */
24527   contents.append_data (MAYBE_SWAP (8));
24528
24529   /* The offset of the CU list from the start of the file.  */
24530   contents.append_data (MAYBE_SWAP (total_len));
24531   total_len += cu_list.size ();
24532
24533   /* The offset of the types CU list from the start of the file.  */
24534   contents.append_data (MAYBE_SWAP (total_len));
24535   total_len += types_cu_list.size ();
24536
24537   /* The offset of the address table from the start of the file.  */
24538   contents.append_data (MAYBE_SWAP (total_len));
24539   total_len += addr_vec.size ();
24540
24541   /* The offset of the symbol table from the start of the file.  */
24542   contents.append_data (MAYBE_SWAP (total_len));
24543   total_len += symtab_vec.size ();
24544
24545   /* The offset of the constant pool from the start of the file.  */
24546   contents.append_data (MAYBE_SWAP (total_len));
24547   total_len += constant_pool.size ();
24548
24549   gdb_assert (contents.size () == size_of_contents);
24550
24551   contents.file_write (out_file);
24552   cu_list.file_write (out_file);
24553   types_cu_list.file_write (out_file);
24554   addr_vec.file_write (out_file);
24555   symtab_vec.file_write (out_file);
24556   constant_pool.file_write (out_file);
24557
24558   /* We want to keep the file.  */
24559   unlink_file.keep ();
24560 }
24561
24562 /* Implementation of the `save gdb-index' command.
24563    
24564    Note that the file format used by this command is documented in the
24565    GDB manual.  Any changes here must be documented there.  */
24566
24567 static void
24568 save_gdb_index_command (const char *arg, int from_tty)
24569 {
24570   struct objfile *objfile;
24571
24572   if (!arg || !*arg)
24573     error (_("usage: save gdb-index DIRECTORY"));
24574
24575   ALL_OBJFILES (objfile)
24576   {
24577     struct stat st;
24578
24579     /* If the objfile does not correspond to an actual file, skip it.  */
24580     if (stat (objfile_name (objfile), &st) < 0)
24581       continue;
24582
24583     dwarf2_per_objfile
24584       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24585                                                     dwarf2_objfile_data_key);
24586     if (dwarf2_per_objfile)
24587       {
24588
24589         TRY
24590           {
24591             write_psymtabs_to_index (objfile, arg);
24592           }
24593         CATCH (except, RETURN_MASK_ERROR)
24594           {
24595             exception_fprintf (gdb_stderr, except,
24596                                _("Error while writing index for `%s': "),
24597                                objfile_name (objfile));
24598           }
24599         END_CATCH
24600       }
24601   }
24602 }
24603
24604 \f
24605
24606 int dwarf_always_disassemble;
24607
24608 static void
24609 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24610                                struct cmd_list_element *c, const char *value)
24611 {
24612   fprintf_filtered (file,
24613                     _("Whether to always disassemble "
24614                       "DWARF expressions is %s.\n"),
24615                     value);
24616 }
24617
24618 static void
24619 show_check_physname (struct ui_file *file, int from_tty,
24620                      struct cmd_list_element *c, const char *value)
24621 {
24622   fprintf_filtered (file,
24623                     _("Whether to check \"physname\" is %s.\n"),
24624                     value);
24625 }
24626
24627 void
24628 _initialize_dwarf2_read (void)
24629 {
24630   struct cmd_list_element *c;
24631
24632   dwarf2_objfile_data_key
24633     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24634
24635   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24636 Set DWARF specific variables.\n\
24637 Configure DWARF variables such as the cache size"),
24638                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24639                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24640
24641   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24642 Show DWARF specific variables\n\
24643 Show DWARF variables such as the cache size"),
24644                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24645                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24646
24647   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24648                             &dwarf_max_cache_age, _("\
24649 Set the upper bound on the age of cached DWARF compilation units."), _("\
24650 Show the upper bound on the age of cached DWARF compilation units."), _("\
24651 A higher limit means that cached compilation units will be stored\n\
24652 in memory longer, and more total memory will be used.  Zero disables\n\
24653 caching, which can slow down startup."),
24654                             NULL,
24655                             show_dwarf_max_cache_age,
24656                             &set_dwarf_cmdlist,
24657                             &show_dwarf_cmdlist);
24658
24659   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24660                            &dwarf_always_disassemble, _("\
24661 Set whether `info address' always disassembles DWARF expressions."), _("\
24662 Show whether `info address' always disassembles DWARF expressions."), _("\
24663 When enabled, DWARF expressions are always printed in an assembly-like\n\
24664 syntax.  When disabled, expressions will be printed in a more\n\
24665 conversational style, when possible."),
24666                            NULL,
24667                            show_dwarf_always_disassemble,
24668                            &set_dwarf_cmdlist,
24669                            &show_dwarf_cmdlist);
24670
24671   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24672 Set debugging of the DWARF reader."), _("\
24673 Show debugging of the DWARF reader."), _("\
24674 When enabled (non-zero), debugging messages are printed during DWARF\n\
24675 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24676 information.  A value greater than 1 provides more verbose information."),
24677                             NULL,
24678                             NULL,
24679                             &setdebuglist, &showdebuglist);
24680
24681   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24682 Set debugging of the DWARF DIE reader."), _("\
24683 Show debugging of the DWARF DIE reader."), _("\
24684 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24685 The value is the maximum depth to print."),
24686                              NULL,
24687                              NULL,
24688                              &setdebuglist, &showdebuglist);
24689
24690   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24691 Set debugging of the dwarf line reader."), _("\
24692 Show debugging of the dwarf line reader."), _("\
24693 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24694 A value of 1 (one) provides basic information.\n\
24695 A value greater than 1 provides more verbose information."),
24696                              NULL,
24697                              NULL,
24698                              &setdebuglist, &showdebuglist);
24699
24700   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24701 Set cross-checking of \"physname\" code against demangler."), _("\
24702 Show cross-checking of \"physname\" code against demangler."), _("\
24703 When enabled, GDB's internal \"physname\" code is checked against\n\
24704 the demangler."),
24705                            NULL, show_check_physname,
24706                            &setdebuglist, &showdebuglist);
24707
24708   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24709                            no_class, &use_deprecated_index_sections, _("\
24710 Set whether to use deprecated gdb_index sections."), _("\
24711 Show whether to use deprecated gdb_index sections."), _("\
24712 When enabled, deprecated .gdb_index sections are used anyway.\n\
24713 Normally they are ignored either because of a missing feature or\n\
24714 performance issue.\n\
24715 Warning: This option must be enabled before gdb reads the file."),
24716                            NULL,
24717                            NULL,
24718                            &setlist, &showlist);
24719
24720   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24721                _("\
24722 Save a gdb-index file.\n\
24723 Usage: save gdb-index DIRECTORY"),
24724                &save_cmdlist);
24725   set_cmd_completer (c, filename_completer);
24726
24727   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24728                                                         &dwarf2_locexpr_funcs);
24729   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24730                                                         &dwarf2_loclist_funcs);
24731
24732   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24733                                         &dwarf2_block_frame_base_locexpr_funcs);
24734   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24735                                         &dwarf2_block_frame_base_loclist_funcs);
24736
24737 #if GDB_SELF_TEST
24738   selftests::register_test ("dw2_expand_symtabs_matching",
24739                             selftests::dw2_expand_symtabs_matching::run_test);
24740 #endif
24741 }